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
21 January 2010 07:04 [Source: ICIS news] GUANGZHOU (ICIS news)--?xml:namespace> The world’s third-largest economy grew by a higher-than-expected 8.7% in 2009 while industrial growth reached 11.0%, according to official data released by the National Bureau of Statistics of China on Thursday. The raw chemical and chemical manufacturing sector registered a 14.6% year-on-year increase, based on the official data. Analysts estimate a double-digit GDP growth this year as the global economic recovery firms up. "We predict that GDP would grow by a faster 10.6% this year. Demand of fuel and petrochemical products will obviously increase along with galloping economy," said Xue Hua, a macro economy analyst at Shenzhen-based brokerage house China Merchants Securities. Dr Ba Shusong, deputy director general of Financial Research Institute, development research centre of the State Council or China’s cabinet, said the country's GDP had entered a new-round of growth cycle in 2010 and "we expect that overall growth will be 9-10% for the year". Analysts also said the government could gradually withdraw stimulus packages and attempt to curb inflation as consumption improved and overseas demand rose. The consumer price index (CPI), a price gauge for retail, rose 1.9% year on year in December, higher than the 0.6% in November. The production price index (PPI), a gauge for wholesale, grew by 1.7% on year in the December, the first rise in last 13 months. "Improvements on overseas demand will spike Chinese exports and therefore relieve Interest rates could be hiked in the first quarter of the year, X.
http://www.icis.com/Articles/2010/01/21/9327596/chinas+petrochemical+industry+to+flourish+-+analysts.html
CC-MAIN-2013-20
refinedweb
272
57.37
A constructor is a special Java method that is used to initialize some data whenever you instantiate a class. This method is automatically called when you create an object. By default, all Java objects have a no-arg constructor. That is, a constructor that takes in no arguments. Programmers can also define their own constructor. In this Java programming tutorial, you will learn how to create and define constructors. Read: The Top Tools for Remote Developers How to Create a Constructor in Java A constructor is similar to normal Java methods; however, a constructor does not have any return type. To create a constructor, simply use the same name as that of your class, as shown in the code example below: class Fruits { // this method below is the constructor Fruits (){ // some code here } } Within the curly brackets { }of a constructor, you can define the parameters that it will take. These parameters can be primitive data types (such as int or float), or they can even be reference types (such as arrays or Objects). How to Use Constructors in Java Once you instantiate a class, the code in your constructor automatically runs. This is specifically true if you have defined a no-arg constructor. In the event your constructor has a parameter list, then you will need to provide the necessary arguments when instantiating the class, as is the case in the follow Java code example: MyClass instance1 = new MyClass(arg1, arg2); The passed arguments will be used to initialize the constructor for the created object. See the sample code below. It demonstrates the concepts that have just been discussed: class MyConstructor { public MyConstructor(int x, String s1){ int height = x; String name = s1; } public static void main(String args[]) { MyConstructor mycont = new MyConstructor(8, "Jay"); } } Just like with methods, the accessibility of constructors can be restricted using visibility modifiers, including: public, private, protected. For example, if you tried to access a constructor with private visibility in a subclass, you would get a compilation error. Read: Tips to Improve Performance in Java Using the Java Keyword: this It is possible that your constructor’s parameter list may have variable names similar to the ones of your class’ instance variables. Java allows shadowing of the class variables inside your constructor, so that you can be able to use the same variable names. Developers can access the shadowed variables (or any member of the class) using the Java keyword this. The keyword this is used to refer to the current object. See the example below, demonstrating how to use the this keyword in Java: class MyConstructor { int x = 0; String s1; private MyConstructor(int x, String s1){ x = this.x; s1 = this.s1; } public static void main(String args[]) { MyConstructor mycont = new MyConstructor(5, "Jack"); } } What is Constructor Chaining in Java? Note that the keyword this is not just for accessing instance members. It can also be used to call constructors inside other constructors. This is known as constructor chaining. Programmers can have as many constructors in their classes as they want, so long as they have differing method signatures. When the this keyword is used to call another constructor inside the current constructor, it must be the first expression in the calling constructor. It is important to note that at least one of the chained constructors should not be using the this keyword. See the code example below showing how to chain constructors in Java: public class ConstructorUsingThis{ ConstructorUsingThis(){ System.out.println("\nThis msg is from the no-arg constructor."); } ConstructorUsingThis(int y){ this(); int num = y; System.out.println("This msg is from the constructor with one argument: " + num); } public static void main(String[] args){ ConstructorUsingThis Obj = new ConstructorUsingThis(85); } } Final Thoughts on Constructors in Java By now, you should be comfortable creating constructors on your own. As mentioned earlier, constructors are used to initialize values at object creation. A good example of values that are usually initialized are database entries. Read more Java programming tutorials and software development guides.
https://www.developer.com/java/java-constructors/
CC-MAIN-2022-33
refinedweb
669
52.7
11 December 2012 08:06 [Source: ICIS news] SINGAPORE (ICIS)--China’s output of major petrochemical products in October has seen a large increase as producers had built up their stocks in advance because of a previously upbeat outlook, industry sources said on Tuesday. The output of ethylene in the country increased by 2.5% year on year to 1.27m tonnes in October, according to data, which was released later than usual by China Petroleum and Chemical Industry Federation (CPCIF). However, the total ethylene output between January and October dropped by 2.4% to 12.3m tonnes, compared with the same period a year earlier, CPCIF data showed. The country’s naphtha output rose by 0.4% year on year to 2.27m tonnes in October. However, the total output of naphtha in the first 10 months of this year decreased by 2.5% year on year to 23m tonnes. China’s polyethylene (PE) output gained by 1.7% year on year to 867,000 tonnes in October, while its total output for January-October rose by 0.9% to 8.42m tonnes compared with the same period a year earlier. Domestic crude oil output in October rose by 8.4% year on year to 17.9m tonnes, while total output in January-October saw a 1.4% year-on-year increase at 172m tonnes. The output of benzene, however, decreased by 21.2% from a year ago to 571,000 tonnes in October because some domestic plants were shut. As a result, the total output of benzene in January-October fell by 1.3% to 5.41m tonnes, compared with the first 10 months of last year, CPCIF said. The prices of 65 petrochemical products covered by Chemease, an ICIS service in China, were mixed in the fourth week of October. Prices of butyl rubber (BR), butyl acrylate and crude benzene rose by 3%, while glycerin prices saw a 2% gain, Chemease data showed. Acrylonitrile (ACN) prices saw the largest decrease among the products at 7%, followed by a 6% price fall for methylene diphenyl diisocyanate (MDI). Table: China’s petrochemical output in October 2012?xml:namespace> Source: CPCIFSource: CPC
http://www.icis.com/Articles/2012/12/11/9622922/chinas-october-output-for-petrochemical-products-largely.html
CC-MAIN-2014-42
refinedweb
362
68.77
A framework for WebProgramming. Masthead - URL - Version 0.4.1 (2004-09-13) - Licence - LGPL (will consider BSD-Style or Python if LGPL is a problem) - Platforms - Windows, Linux, UNIX (not tested on MacOS but should work) - Python versions - Python 2.2 and above - Status - Beta (although the author uses it in commercial applications) Introduction These modules used to be known as the lemon modules. The CVS is still hosted at "It is better to have a flexible module that can be used intuitively than an all-singing, all-dancing framework that no-one can be bothered to learn." The Python Web Modules are a suite of simple and easy to use Python components desinged to allow developers to write Python CGI scripts or web applications with SQL databases, sessions, templates, email and authorisation functionality. The modules can easily be used on shared web hosting accounts running Apache and Python for example. Getting Started First you need to download the latest relase from and then read the getting started guide at Session, Identification and Authentication Session handling is done through the web.session module as follows: import web.session session = web.session.start( options... ) session['myVariable'] = 'This will be available at each request' The module supports cookies or cgi variables. The use of the term "session" on its own can be confusing, especially in the context of the terminology of particular Web frameworks. Therefore, this document uses the following terms: Identity and identification handling is achieved through the web.auth module which uses the web.session module to store its information. Users may have multiple access levels to multiple applicaitons. Login handling and password reminder code is handled automatically. Both modules can either use a database supported by web.database or a file store to store the information between requests. Forms and Fields One of the more tedious tasks of web programing is creating HTML forms and validating field input. The web.form module allows you to create forms from Field objects. There are Field objects for all the standard HTML fields. HTML generation and user input validation and requesting the user to correct errors are all handled by the Form object. Fields also exist for the common Python objects such integers, string, datetime objects etc as well as email and URL fields. These fields convert the value chosen by the user in the form directly to the appropriate Python type so no conversion is required. A DateTime field returns a datetime.datetime object, an Integer field returns an integer. a StringSelect field allows the user to choose one string from a choice and an EmailCheckBoxGroup allows the choice of one or more Email addresses. Database Support A major part of the project are the database modules. The web.database module is a simple SQL abstraction layer which sits on top of a DB-API 2.0 cursor to implement data type conversions, provide database independance and offer a more Python-like interface to the data returned from queries. Here are the main features of the module: - 100% compatible with the underlying DB-API 2.0 cursor. A web.database cursor is also a DB-API 2.0 cursor. - Provides methods including select(), insert(), update(), delete(), create(), alter() and drop() which build and customise the SQL depending on the database being used providing database independance. - Provides strong typing for the data being used. No need to deal with SQL strings, the module automatically encodes and decodes data for the approriate column. The web.database.object module is an object-relational mapper. It allows you to simply define complex database structures in Python code and then create the necessary tables automatically. It then allows you to manipulate the Python objects you have defined to transparently manipulate the underlying database including the facility to use multiple joins without knowing any SQL. The feature which sets the web.database.object apart from rivals like SQLObject is that the Table column classes are derived from web.form.field objects which means you can transparently create HTML interfaces to edit the data structures through a web browser using the Table object's form() method with all validation handled for you. This makes web.database.object module ideal as a middle layer for writing data-driver websites although it has broader uses as well. A database object can in theory have any storage driver (text, XML, SQL Datbase, DBM) although currently only a driver for the web.database module has been written. This means that any storage system with a driver for web.database can be used with web.database.object. This currently includes MySQL, ODBC, SQLite and, to an extent, Gadlfy. More information is available in the module reference at Presentation Support The modules support a number of presentation options including Dreamweaver MX, XYAPTU and simple '%(value)' style replacements. The preferred method of producing output is perhaps using Cheetah. All templating using the parse() function. One example is: import web.template html = web.template.parse(type='cheetah', file='test.tmpl', dict={'title':'Web Modules'}) Documentation Full documentation on the latest version of the software is availble at Other Features Other features which make these modules stand out are plain and HTML email support, simple graph creation, full error handling and datetime compatibity classes for Python 2.2. Deployment Platforms The Web Modules were written because although there are quite a few web application frameworks available they are either too simplistic, or require adminster rights to install and so cannot be used with most shared hosting accounts. The modules provide everything needed to write data-driven websites without needing installation or superuser rights. Included are database drivers and even a webserver so they should run on any computer or server which runs Python 2.2 or above. Currently the only pure-Python database supported is Gadfly and this has some limitations so ideally users should use MySQL or SQLite instead. Developers can use the modules with other servers such as Zope or on their own but the author tends to use them in CGI scripts on Apache running on FreeBSD or Linux servers. Development Interfaces The modules are desinged to be used in any way you like. They do not tie you to a CGI way of working or a servlet architecture. You can use them as building blocks to create your own way of doing things. If you prefer some help though the examples in the documentation assume for simplicity you are using a CGI approach. The examples are listed at Hosting Most UNIX hosts which support Python 2.2 or above and include a web.database supported driver such as MySQLdb will be an ideal platform for using these modules. I use and would reccomend If you are after cheap hosting to have a play with that might break at any moment try Future Future releases will also conform to the WSGI being discussed on the WEB-SIG mailing list at the moment. Read the project plan. InTheirOwnWords Although much of the functionality of these modules is replicated elsewhere, I believe this is the most complete set of modules available that doesn't tie you into using a particular architecture. In each component I have tried to go one stage further than other sofware available. I would appreciate feedback, encouragement or comments if you have any to author <at> pythonweb.org. This area is for comments and discussion with other Python Web Developers.. I'd appreciate your thoughts.
https://wiki.python.org/moin/PythonWebModules?highlight=DateTime
CC-MAIN-2016-50
refinedweb
1,244
55.44
Python String question using string libraries python string exercises write a python function to insert a string in the middle of a string. python 3 string methods python get string reverse a string in python string slicing in python string operators in python Consider the pattern %at% where % can have zero or any number of occurrences of an alphabetical character. For example, the string `"BAT, FAT, LATER, HABIT" has three words that match the pattern. How can this be done in Python? import re str_list = ['BAT', 'FAT', 'LATER', 'HABIT'] counter = 0 for strr in str_list: if re.search('at', strr, re.IGNORECASE): counter += 1 print(counter) OUTPUT: 3 Python Data Type: String - Exercises, Practice, Solution, Strings in Python can be created using single quotes or double quotes or String with the use of Single Quotes: Welcome to the Geeks World String with the use� Strings in Python are objects, and Python provides a no. of built-in/library functions to modify them. Also, you would agree that each one of us uses Python Strings very frequently in regular programming activities. Considering this fact, we’ve tried to cover all the Python String Operators and Functions under this single post. mylist = ['BAT', 'FAT', 'LATER', 'HABIT'] count = 0 for pattern in mylist: if 'at' in pattern.lower(): count = count + 1 print(count) Python String, 8. What is an f-string and how do you use it? New in python 3.6, f-strings make string interpolation really easy. Using�. Use Counter to make the codes shorter: from collections import Counter str_list = ['BAT', 'FAT', 'LATER', 'HABIT'] my_counter = Counter('at' in word.lower() for word in str_list) # 3 print(my_counter[True]) Python Strings (With Examples), Learn the four main approaches to string formatting in Python, as well as their Strings in Python have a unique built-in operation that can be accessed with the it ") 8 LOAD_FAST 1 (question) 10 FORMAT_VALUE 0 12 LOAD_CONST 3 ('? What. 41 Questions to Test your Knowledge of Python Strings, String of ASCII characters which are considered punctuation characters your own string formatting behaviors using the same implementation as the to in the format string (integers for positional arguments, and strings for� First, get a set of all English words. I expect there are many libraries that can do this, but recommendations for software libraries are off-topic for Stack Overflow, so just use whatever you can find. Then, iterate through all substrings of the string, and see if any of them are in the collection. Python String Formatting Best Practices – Real Python, This String exercise covers questions on topics such as String operations, manipulations, slicing, and String functions. This Python String� I generated a long and ugly XML string with Python and I need to filter it through pretty printer to look nicer. I found this post for python pretty printers, but I have to write the XML string to a file to be read back to use the tools, which I want to avoid if possible. string — Common string operations — Python 3.8.4rc1 documentation, Along with array, binary tree, and linked list data structures, the string is another Algorithms and Data Structures in Python for those who love Python easily solve string-based problems because strings are nothing but a character array. asked string coding questions from programming job interviews:. In Python, individual characters of a String can be accessed by using the method of Indexing. Indexing allows negative address references to access characters from the back of the String, e.g. -1 refers to the last character, -2 refers to the second last character and so on. - Still not crystal, so in your example HAT CAT MATTER, we should be able to just print uhm 3? since ATcame thrice? - @santosh Have you tried to code it? - @planet260 i am not able to get the logic - @user5173426 yes AT came thrice so i should print 3 - Okay, does it have to be a pattern or just a searching for a substring?
http://thetopsites.net/article/54360203.shtml
CC-MAIN-2020-50
refinedweb
665
68.6
Red Hat Bugzilla – Bug 595043 Fedora 12 x86_64 KVM libvirtd Nokia USB connection kernel panic crash on reboot Last modified: 2010-10-02 20:02:42 EDT Created attachment 415910 [details] Contents of abrt kerneloops directory after crash Description of problem: Fedora 12 crashes on boot when starting KVM (libvirtd --daemon) whilst Nokia USB interface cable is connected. Version-Release number of selected component (if applicable): Fedora 12 x86_64 server with any of at least the following kernels: * kernel 2.6.32.12-115.fc12.x86_64 * kernel 2.6.32.11-99.fc12.x86_64 * kernel 2.6.32.10-90.fc12.x86_64 How reproducible: ALWAYS Steps to Reproduce: 1. Connect Nokia 6303 Classic (or similar) mobile phone via USB cable 2. Have libvirtd set to start (chkconfig libvirtd on) 3. Reboot server Alternate method to reproduce: 1. Connect Nokia as before 2. Disable libvirtd auto-start (chkconfig libvirtd off) 3. Reboot server 4. Login to server 5. execute "service libvirtd start" Actual results: System crash with references to various "net" related routines or entry-points. Expected results: System should start libvirtd/KVM services without crashing. Additional info: Plugging the Nokia USB cable in *AFTER* the KVM/libvirtd services have loaded and stabilised does not cause a crash - the crash only occurs when booting with the Nokia cable connected. "ifconfig -a" after reboot with Nokia connected reports a "usbpn0" device. This device seems to be transient as a later "ifconfig -a" no longer reports its presence. It is very likely that it is the presence of this device (or possible usb network devices in general) that is causing libvirtd/KVM to "chuck its guts". Created attachment 415911 [details] BZ2 Tarball containing various configuration information output To assist in investigation I've also included a tarball containing configuration information such as list of installed packages, "dmesg" results, network configuration and output from "lsusb". Oh, for those wondering why the Nokia phone is connected? It's being used by Nagios to send SMS messages when certain critical events occur. The problem still occurs after updating to: libvirt-client-0.7.1-16.fc12.x86_64 libvirt-0.7.1-16.fc12.x86_64 libvirt-python-0.7.1-16.fc12.x86_64 net-tools-1.60-100.fc12.x86_64 Here's the ifconfig output pertaining to the mysterious usbpn0: usbpn0 Link encap:UNSPEC HWaddr 1B-00-00-00-00-00-80-4E-00-00-00-00-00-00-00-00 POINTOPOINT NOARP MTU:65541 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:3 RX bytes:0 (0.0 b) TX bytes:0 (0.0 b) Created attachment 421205 [details] Updated configuration information text files (tarballed) Created attachment 421207 [details] Most recent abrt Kerneloops data (crash #1) Created attachment 421208 [details] Most recent abrt Kerneloops data (crash #2) Smolt profile for system: Smolt wiki page for Nokia USB connection in above system: Have updated to kernel 2.6.32.14-127.fc12.x86_64, however the crash still occurs. Sequence is: Have the Nokia USB interface connected *BEFORE* starting libvirtd, and the system crashes. If you start libvirtd and *THEN* plug in the Nokia USB cable, everything works fine. This means that any sort of restart will cause a kernel crash if libvirtd is set to execute at system start and the Nokia USB cable is connected. Unfortunately, it appears that due to the nature of the crash, abrt/kerneloops is unable to actually the traceback. What I could record from some quick scribbling was: raw_notifier_call_chain call_netdevice_notifiers rollback_registered unregister_netdevice unregister_netdev loopback_net_exit cleanup_net worker_thread ? cleanup_net ? aubremove_wake_function ? worker_thread kthread child_rip ? kthread ? child_rip __phonet_get [phonet] Fatal exc in interrupt Pid=37 comm. netns Tainted G D W Changed Bugzilla component entry from "kernel" to "libvirt". It's hard to choose the right component here people, as we have three choices, all of which are correct at some level. I initially thought it should be part of KVM, as we're using kvm_XXXX modules. Then, given the fact that the entire kernel gets clagged, I thought maybe it should be "kernel". I've now changed it to "libvirt" as it's likely that it's the interaction between the virtualisation libraries and the associated kernel loadable modules that's causing the crash. It would be nice to be able to somehow mark a bug as impacting (or associated with) all 3 (or more) components. That may help in assigning the bug to the correct team after review. Also, why can't we change the priority when editing the bug details? For me, this is a HIGH priority, not the default of "low". Now that libvirt-0.7.1-18.fc12 has been pushed to Fedora 12 stable repository, I hope to test it this weekend. Created attachment 430949 [details] Screen shot of kernel panic traceback libvirt-0.7.1-18.fc12 has been installed. Unfortunately, the situation has not improved. When the Nokia USB cable is left connected, and libvirtd is started, we get a kernel panic (screenshot of "panic" screen attached). Start libvirtd WITHOUT the USB cable, and everything is fine. Plug the USB cable in AFTER libvirtd is started, everything continues to operate correctly. Created attachment 430950 [details] Currently installed package list (sorted) I've attached the (sorted) output from 'rpm -qa' to help provide a more complete picture of the installation environment. We really need to see the entire oops report. Try starting the kernel with the option "vga=1" to put the console in 50-line mode, or "vga=791" for VESA mode. Or scroll back if you can do that. Created attachment 431691 [details] Updated oops/kernel panic screen shot This is screen shot of the kernel panic after executing "service libvirtd start" with the Nokia USB cable connected. Kernel video mode set to vga=1 at boot load. Screen captured via browser to HP iLO2 remote console facility. I hope this helps more! Cheers, Scott I suspect that the screen buffer in the iLO2 card got a little mangled (evidenced by the repeating sections of text from "phonedeon" on the far right side of the screen shot I just attached). I suspect that "phonedeon" is actually "phonet" and "radeon" squished over each other. Unfortunately, it's the best I can offer. However, the code call traces appear to be complete. I see that kernel-2.6.32.16-141.fc12 has been released to the stable "updates" repository. I am arranging another outage to install and activate the new kernel. Once the new kernel is active, I'll try starting libvirtd again with the Nokia USB cable attached. I should have the results in some 16 hours from time of this update. Created attachment 432000 [details] Another clipboard grab of remote console kernel panic traceback This is the panic after starting libvirtd with the new kernel. Whilst my caveat about the screen buffer in my previous note still holds true, the traceback sequences definitely point to some interaction between "phonet", "netns". I will attach the output from dmesg which shows the USB/cdc_phonet activity when plugging in the Nokia USB cable *after* libvirtd has started. Created attachment 432001 [details] "dmesg" output from kernel-2.6.32.16-141.fc12.x86_64 Here's the output from dmesg as promised. Possibly fixed by:;a=commitdiff_plain;h=7dfde179c38056b91d51e60f3d50902387f27c84 (In reply to comment #20) > Possibly fixed by: > >;a=commitdiff_plain;h=7dfde179c38056b91d51e60f3d50902387f27c84 Not sure when this patch will make it into the kernel, or even if it will remedy the problem. We're now running kernel 2.6.32.21-166.fc12.x86_64 (with 4 older kernels available as boot time alternatives) and libvirt 0.8.2-1.fc12.x86_64 however the problem still exists. When I can organise another outage, I'll try to get an up-to-date crash/trace for the forum. <hr> kernel-2.6.32.11-99.fc12.x86_64 kernel-2.6.32.12-115.fc12.x86_64 kernel-2.6.32.14-127.fc12.x86_64 kernel-2.6.32.16-141.fc12.x86_64 kernel-2.6.32.21-166.fc12.x86_64 kernel-devel-2.6.32.11-99.fc12.x86_64 kernel-devel-2.6.32.12-115.fc12.x86_64 kernel-devel-2.6.32.14-127.fc12.x86_64 kernel-devel-2.6.32.16-141.fc12.x86_64 kernel-devel-2.6.32.21-166.fc12.x86_64 kernel-firmware-2.6.32.21-166.fc12.noarch kernel-headers-2.6.32.21-166.fc12.x86_64 libvirt-0.8.2-1.fc12.x86_64 libvirt-client-0.8.2-1.fc12.x86_64 libvirt-python-0.8.2-1.fc12.x86_64 <hr> Cheers! There's a patch here you may want to try btw.: The stack trace in comment #25 of the chromium bug is very similar to comment #18 here. Lemme know if it works please. (In reply to comment #22) > There's a patch here you may want to try btw.: > > > > The stack trace in comment #25 of the chromium bug is very similar to comment > #18 here. > > Lemme know if it works please. Hi Craig - very interesting reading, and thanks for providing the very useful link. Yes, I suspect that this would indeed resolve the issue as I *know* that libvirtd definitely interacts with the kernel network namespace functions during initialisation, as it needs to setup & provide the bridge between the physical host network interface(s) and the network interface(s) of the virtual machine. Unfortunately, I won't be able to try patching the kernel until 02-Oct. It's interesting the comment from Nokia saying that it's difficult (impossible?) to fix in kernels <= 2.6.32. Hopefully the Fedora upstream kernel maintainers can integrate this patch too, at least in the 2.6.32 series, otherwise I may have to wait for a kernel version > 2.6.32. I've just run a quick query against the "rawhide" Fedora repository, and there's a kernel 2.6.36 available there (based on the 0.21.rc4.git1.fc15 release). By the time I'm in a position to try this patch out, this new kernel may even be released as a stable update. If not, I will try it out before attempting to integrate the Nokia patch to the current kernel. I'll keep people posted here. Cheers! It appears that the boys & girls over in the Google chromium bug tracker have tested the v2.6.35 kernel, and aren't having any issues with system crashes with the Nokia connected (refer). I see too that the "rawhide" repository has updated the release of the 2.6.36 kernel to 0.22.rc4.git2.fc15, so hopefully the v2.6.36 kernel should resolve this issue once it's officially released (based upon the fact that 2.6.35 appears to be okay with Nokia). It would be nice to have this annoying problem resolved. This bug will never get fixed in Fedora 12, since it's staying on 2.6.32 until EOL. So we can close it as CANTFIX, or you can update to Fedora 13 or 14 and we can change the version it's reported against to one of those. Hmm - I strongly disagree with the attitude regarding the maintenance of kernel levels for FC12, given that Fedora 14 has not yet been officially released, however there's not much that I can do about it out here in user-land. I have upgraded to the FC13 versions of the Fedora kernel & libvirt packages (versions 2.6.34.7-56.fc13.x86_64 & 0.8.2-1.fc13.x86_64 respectively) and am happy to advise that the bug appears to have been removed/resolved in those versions. Thanks to all for their time in reviewing this issue, along with the various suggestions offered. Cheers! (I draw the attention of people to the following link: And I quote: "This translates into: * Fedora 12 will be maintained until 1 month after the release of Fedora 14. * Fedora 13 will be maintained until 1 month after the release of Fedora 15." Given that Fedora 14 is not scheduled for release until November 2010 [], I would have expected that Fedora 12 would enjoy complete support, including kernel updates, until December 2010. )
https://bugzilla.redhat.com/show_bug.cgi?id=595043
CC-MAIN-2018-26
refinedweb
2,045
56.15
When a class is designed a new data type is being added to the C++ language. The ability to overload a C++ operator allows the programmer to define the meaning of operators relative to the class being defined. Operators are overloaded and selected based on the signature- matching algorithm for finding overloaded functions. The keyword operator is used to define a type conversion member function. It is also used to overload the built-in C operators. Just as a function name can be given a variety of meanings, with each meaning being different depending upon the arguments being passed, so can an operator, such as +, be given additional meanings. Overloading operators allows infix expressions of both ADTs and built-in types to be written. It is an important notational convenience and in many instances leads to shorter and more readable programs. Defining operators for a class is easy once you know how the application of an operator is translated to a function call. For a unary operator such as &, when you write the following: where X is an instance of some class, the C++ compiler applies the operator by calling this function: X.operator&() The compiler automatically passes a pointer to the class instance to the function. For binary operators such as +, an expression such as this: X + Y where X and Y are class instances, the compiler calls the function: X.operator+(Y) As you can see, the C++ compiler reduces the application of operators to function calls. Thus, you can overload an operator by defining a function whose name begins with the keyword operator followed by the symbolic notation of that operator. Like all member functions, operator functions receive a pointer to the class instance in the hidden argument named this. Because this argument is implicit, unary operator functions are defined with no arguments at all. Binary operator functions that are members of the class take a single argument, which is the right- hand side of the operator expression. The ternary operator, ?:, cannot be overloaded. However, you can define an operator function as a friend instead of as a member function of the class. By defining an operator overload function as a friend, the class instance pointer is not passed to the function. There are times when the programmer needs to define friend operator functions. When declared as a friend, the operator function requires all arguments explicitly. Thus, to declare operator+ as a friend function of class X, the following would be written: friend X operator+(X&, Y&); // assume X is a class and thereafter, to evaluate the expression x1 + x2 for two instances of class X, the C++ compiler will call the function operator+(x1, x2). All C++ operators can be overloaded except for the following: Member access operator x.y Dereferencing pointer to member x.*y Scope resolution operator x::y Conditional operator x?y:z Those that can be overloaded are: + - * / % ^ & | - ! , = < > <= >= ++ -- << >> == != && || += -= /= %= ^= &= |= <<= >>= [] () -> new delete Although C++ enables the programmer to redefine the meaning of most of the built-in operator symbols for a class, there is no ability to change the precedence rules that dictate the order in which operators are evaluated. C++ operators have the same precedence as those of their ANSI C counterparts. Even if, for some class, the programmer were to define operators + and * to have entirely different meanings from addition and multiplication, in an expression such as this: a + b * c // a, b, c are some class instances the C++ compiler will still invoke the operator* function to evaluate b * c before calling operator+. The following tips will help in designing classes with overloaded operators (assume that a and b are instances of appropriate class types). #. C++ does not “understand” the meaning of an overloaded operator. It’s the programmer’s responsibility to provide meaningful overloaded functions. #. C++ is not able to derive complex operators from simple ones. For instance, if you define overloaded operator functions operator* and operator=, C++ cannot evaluate the expression a *= b correctly. #. The programmer may never change the syntax of an overloaded operator. Operators that are binary must remain binary. Unary operators must remain unary. #. The programmer cannot invent new operators for use in expressions. Only those operators listed for the syntax of the language can be overloaded. However, the programmer can always write functions for special cases. #. The programmer may overload the operators ++ and –. As an example of operator overloading, consider the + operator, the binary version, for the CString class. A good interpretation of this operator for the CString class would be to concatenate two CString objects. A typical use of the + operator for CString might be this: CString s1("This "), s2("and that"), s3; s3 = s1+s2; The programmer can get this functionality by defining the following function as a member of the CString class; // ********************************************************* // overload + // Member function to concatenate two String objects CString& CString::operator+( const CString& str ) { size_t lgth = len + str.len; char *t = new char[lgth + 1]; strcpy( t, s ); strcat( t, str.s ); return CString(t); } Because this version of the operator+ is a member function of the CString class, it takes only one argument, a reference to the CString on the right-hand side of the + operator. The function returns a new CString object that is a concatenation of the two CString items that are being added. Although the member function operator+ works well when adding CString items, it cannot handle another type of use for the operator. Because a CString is meant to model a dynamic array of characters, it is natural to allow the use of the operator in expressions such as this: CString str = "World!". CString s2 = "Hello, "+ str; // expecting "Hello, World!" In this case, the C++ compiler will interpret the right-hand side of the expression as the following: "Hello".operator+(str) This is an error, because “Hello” is not an instance of a class and therefore has no member operator+ function that can be applied to “Hello”. One might think that a solution would be to convert “Hello” to a CString and then apply the operator+ function of the CString class. But, this does not happen because the C++ compiler does not automatically convert the left-hand operand of any member operator functions. However, if the programmer were to define a nonmember friend operator+ function in the CString class: friend CString operator+(const char *s1, const String& s2); the compiler would convert the expression call this function with the pointer to “Hello” as the first argument and str as the second argument. This would evaluate to the following function call: operator+("Hello", str) The definition of the friend operator+ function is similar to the member function, except that it does not take an implied pointer to the current instance of the class as the first argument, and the body of the function has to refer to each argument explicitly. Following is a definition of the function: //*********************************************************** // CString concatenation operator, declared as "friend" CString operator+(const char *a, CString ) // overload { CString temp; strcpy( temp.s, a ); if( (strlen(a) + b.len ) < MAXLEN ) { strcat( temp.s, b.s ); temp.len = strlen( temp.s ); } else cerr << "Max length exceeded in concatenation.\n"; return temp; } When copying one class instance to another instance of a compatible type, the results can be unexpected. C++ makes copies of instances not only in assignment expressions but at other times. So you must be aware of the consequences of copying class instances, even if you do not explicitly assign them with the = operator. There are four times when a copy of a class instance will be made: #. When one instance is used to initialize a newly defined instance of the same class. #. When an instance is passed to a function’s value parameter of the class type. #. When a function returns a class instance (not a reference or pointer to the class). #. When a statement assigns one instance to another. The first three of these cases initialize new copies of class instances using the value of an existing instance. The fourth case assigns the value of an existing instance to another instance that was previously defined. In all cases, the result is an object that contains copies of the data fields of another object. After making such copies, all may seem well, but trouble lurks unseen when the class instances contain pointer fields that address variables allocated space on the heap. Problems can also arise when creating copies of instances that contain fields of other class types, which may contain their own pointer fields. If two or more pointers happen to address the same location in memory, deleting one of those pointers will cause the others to address invalid data. Worse, deleting the same space more than once can corrupt the heap and cause a major bug. Because classes often inherit properties of many other classes, a simple assignment or function call might create dozens of duplicate pointers. And if those pointers address instances were allocated by new, class destructors might deallocate the same memory spaces multiple times, which will almost always corrupt the heap. To avoid such problems, the programmer should always provide a copy constructor for any class that includes dynamically allocated members. // ********************************************************* // CString(const String&) // Create a new CString as a copy of another CString // This is called the "copy constructor" CString::CString( const CString& str ) { len = s.len; maxlen = s.maxlen; s = new char[maxlen]; strcpy( s, str.s ); } When the programmer starts to define his/her own classes such as the CString class, he/she might want to overload the definitions of the << and >> operators so that they work with the class. For example, once the >> operator is overloaded, it is possible to read characters from an input stream into a CString object by writing: CString user_input; cin >> user_input; // accept user's input Similarly, to display a CString, the programmer would write the following: CString greetings = "Hello, World!"; cout << greetings << endl; The stream extraction operator, >>, is easy to implement. The following version assumes a maximum string length of 256 characters including the null byte and uses the get function of the input stream to read in the characters into an internal array. Then it creates a new CString object from that character array and returns the CString. //*********************************************************** // Stream extraction operator for CString class istream& operator>>(istream& is, CString& str) { char buf[MAXLEN]; if( is.get(buf,MAXLEN) ) str = String( buf ); return is; } To overload the insertion operator, <<, a public member function is needed for the class that can handle the actual output. For the CString class, a print function is defined that performs the output as follows: //*********************************************************** // Output the CString to the specified output stream void CString::print( ostream& os ) const { os << s ; } Once the print function is defined, you can overload the << operator for a CString argument as follows: //*********************************************************** // Stream insertion operator for CString class ostream& operator<<(ostream& os, String& str) { str.print( os ); return os; } As can be seen, this operator function does its work by calling the member function named print within the Cstring class. Note that the ostream class declares operator<< as a friend function. Templates, also called generics or parameterized types, allow the programmer to construct a family of related functions or classes. Consider a function max(x,y) that returns the larger of its two arguments, x and y can be of any type that has the ability to be ordered. But, since C++ is a strongly typed language, it expects the types of the parameters x and y to be declared at compile time. Without using templates, many overloaded versions of max() are required, one for each data type to be supported, even though the code for each version is essentially identical. Each version compares the arguments and returns the larger. For example, int max( int x, int y ) { return ( x < y) ? x : y ; } long max( long x, long y ) { return ( x > y) ? x : y; } One way around this problem is to use a macro: it is not desired: class Foo { public: int max(int, int); // syntax error; this gets expanded }; By using a template instead, the programmer generated the appropriate that the call to max can be used with arguments of any type for which operator>() is defined. A class template (also called a generic class or class generator) allows the programmer to define a pattern for class definitions. Generic container classes are good examples. Consider the following example of a stack class. Whether the stack is for integers, character strings or of any other type, the basic operations performed on the type are the same (insert, delete, index, and so on). With the element type treated as a type parameter to the class, the system will generate type-safe class definitions on the fly: // ************************************************************* // Interface File : CStack.h // Implementation File : CStack.cpp // Description : A template class that implements // : a stack. // ************************************************************* // #pragma interface #ifndef _CSTACK_H #define _CSTACK_H #include <string.h> // #ifndef _BOOL // #define _BOOL // enum bool { false, true }; // #endif template<class T> class CStack { protected: // // Structure that describes each Node of the linked list // struct StackNode { T nodeData; StackNode *next; }; unsigned _cnt; // count of nodes in the stack bool _newErr; // error indicator for new StackNode *_tos; // pointer to the top of the stack CStack& copy( CStack& ); public: // // Constructors // CStack(); // // Destructors // ~CStack(); // // Accessors // bool isempty() const { return ( _cnt == 0 ) ? true : false; } bool getNewErr() const { return _newErr; } // // Mutators // void push( T ); bool pop( T& ); void clean( void ); CStack& operator=( CStack& item ) { copy( item ); return *this; } }; #endif // ************************************************************* // Interface File : CStack.h // Implementation File : CStack.h // Description : Contructs a template class for a // : stack; // ************************************************************* // #pragma implementation // #include "cstack.h" template CStack::CStack() { _cnt = 0; _newErr = false; _tos = NULL; } template CStack::~CStack() { clean(); } template CStack& CStack::copy( CStack& item ) { StackNode *current, *nextNode, *temp; // // clear the stack if not already empty // if( _tos ) clean(); // // copy the data members across // _cnt = item._cnt; _newErr = item._newErr; // // assign NULL to the top of stack pointer // _tos = NULL; // // exit if the source is empty // if( !item._tos ) return *this; // // allocate a new stack element // _tos = new StackNode; // // exit if error in allocation // if( !_tos ) { _newErr = true; return *this; } // // initialize pointers to copy all of stack // _tos->next = NULL; _tos->nodeData = item._tos->nodeData; nextNode = item._tos->next; current = _tos; // // duplicate the source stack elements // while( nextNode ) { // // create a new stack // temp = new StackNode; if( !temp ) { _newErr = true; return *this; } // // copy data // temp->nodeData = nextNode->nodeData; temp->next = NULL; current->next = temp; current = current->next; nextNode = nextNode->next; } return *this; } template void CStack::clean() { T temp; // // pop everything from the stack // while( pop(temp) ); } template void CStack::push( T item ) { StackNode *temp; _newErr = false; // // first node on the stack? // if( _tos ) // no { // // get a new stack node // temp = new StackNode; if( !temp ) { _newErr = true; return; } temp->nodeData = item; temp->next = _tos; _tos = temp; } else // yes { _tos = new StackNode; if( _tos == NULL ) { _newErr = true; return; } _tos->nodeData = item; _tos->next = NULL; } ++_cnt; } template bool CStack::pop( T& item ) { StackNode *temp; // // anything in the stack? // if( _cnt ) { // // save the data being popped into the reference // data item // item = _tos->nodeData; // // save the current top of stack address // temp = _tos; // // move top of stack to the next node on the list // _tos = _tos->next; // // delete the old top of stack // delete temp; // // decrement the count of nodes // --_cnt; return true; } else return false; } Notice that in the above example that both the interface and the implementation appear in the header file. There is no separate .cpp file that holds the implementation. Most compilers require that both the interface code and the implementation be in one file for templates. // ************************************************************ // Source File : tstack.cpp // Description : Test program to exercise the parametric // : class CStack. // ************************************************************ #include #include "cstack.h" #include "cstring.h" int main() { CStack myData; int values[5]; int ch; cout << "Enter 5 integers: "; cin >> values[0] >> values[1] >> values[2] >> values[3] >> values[4]; for( int i = 0; i < 5; ++i ) myData.push( values[i] ); for( i = 0; i < 5; ++i ) { myData.pop( values[i] ); cout << "Value at[ " << i << " ]= " << values[i] << endl; } cout << "End of integer Stack Demo"; CString list[5]; char buf[80]; CStack names; for( i = 0; i < 5; ++i ) { cout << "\nEnter a name: "; cin >> buf; list[i] = buf; names.push( list[i] ); } for( i = 0; i < 5; ++i ) { names.pop( list[i] ); cout << "Value at[ " << i << " ]= " << (const char *)list[i] << endl; } cout << "End of CString Stack Demo - Press RETURN: "; cin >> ch; return 0; } As with function templates, an explicit template class definition may be provided to override the automatic definition for a given type: class CStack {...}; The symbol CStack must always be accompanied by a data type in angle brackets. It cannot appear alone, except in some cases in the original template definition. Another method available for handling out of memory conditions and other exceptions appears only in the latest versions of C++. As of this writing only the Borland C++ version 4.xx compiler and the GNU C++ version 2.7.0 compiler implements the specifications of the ANSI/ISO C++ committee on exception handling. Exception handling involves three keywords in C++, throw, try , and catch. Throwing an exception lets you gather information at the throw point that could be used in troubleshooting the causes that led to the program failure. The throw keyword is analogous to using raise() with signal(). A C++ program can directly raise an exception in a try block by using the throw expression. The trying of code that may result in an exception is protected by having a catch routine. The catching of an exception allows the program to take actions that could led to a graceful program termination. Only synchronous exceptions are handled, meaning that the failure is generated from within the program, not from an external source, such an pressing CTRL-C or CTRL-BREAK. If asynchronous exceptions are to be handled then the signal() function must still be used along with, possibly, the raise() function. Array::Array( int elements ) { if( elements < 1 ) throw ( elements ); pArray = new int[elements]; if( pArray == (int *)NULL ) throw( "NO SPACE on the FREE store" ); } void foo() { try { Array first( 10000 ), b( -5 ); .... } catch( int x ) { ... // code to handle incorrect number of elements ... // in an Array type } catch( char *errMsg ) { ... // code to handle no more free store } } The try-block specified by try must be followed immediately by the handler specified by catch. If an exception is thrown in the try- block, program control is transferred to the appropriate exception handler. The throw keyword comes in two syntactic forms: (1) throw (2) throw expression The second format, throw expression, will cause an exception to be raised. The innermost try block in which an exception is raised is used to select the catch **throw, causes the current exception to be rethrown. It is used when a second handler is needed to complete processing of an exception. With the second format, the expression thrown is a static, temporary item that persists until the catch handler is exited. The catch handler may use this expression in its processing. void sample() { int x; ... throw x; } main() { try { sample(); } catch( int value ) { ... } } The value thrown by throw in the sample() function persists until the handler with the signature catch( int value ) exits. The argument value is available for use within the catch routine as would any argument being passed to a function. When a function called from another function throws an exception, the process stack is unwound until an exception handler is found. This means that by exiting from the local function, any local automatic storage class variables will be destroyed. void func2() { int local_2A, local_2B; ... throw local_2A; } void func1() { int local_1A; ... func2(); } main() { try { func1(); // func2() is exited with local_2A and // local_2B destroyed } catch( int value ) { ... throw; // exception is re-thrown, possibly due to // some condition within this catch() function } If the thrown expression was of integer type, the rethrown exception is of the same integer value and will be handled by the nearest handler suitable for that type, but not by the handler that re-threw the exception. Although C++ allows an exception to be of almost any type, it is useful to make exception classes. The exception object is treated exactly the way any object would be treated. An exception carries information from the point where the exception is caught. enum ErrorType { BOUNDS, HEAP, OTHER }; class CArrayError { public: CArrayError( ErrorType, int, int ); // for out of BOUNDS CArrayError( ErrorType, int ); // for out of HEAP CArrayError( ErrorType ); // for OTHER ... private: ErrorType _errType; int _upperBound , _index , _size ; }; Now a throw expression using an object of type CArrayError can be more informative to a handler than just throwing simple expressions. ... throw CArrayError( BOUNDS, i, _upperBound ); ... The try keyword has the form try compound statement handler list The try block is where the decision is made as to what handler is called to handle a raised exception. The order in which handlers are defined determines the order in which the handlers with matching argument lists are tried. A throw expression matches the catch argument if it is It is unwise to list handlers in an order that prevents them from being called. For example: catch( void * ); // would also catch any "char *" arguments catch( char * ); catch( BaseClass& ); // would also catch any "DerivedClass&" calls catch( DerivedClass& ); try blocks can be nested. If no matching handler is available in the immediate try block, a handler is selected from its immediately surrounding try block. If no handler can be found that matches, then a default behavior is used. The catch keyword has the following form catch( formal argument ) compound statement The catch appears to be a function declaration of one argument without a return type. catch routines do not accept more than one argument, because that would imply that more than one exception was being handled at once. The catch routine may have an argument list of ellipses, ..., which matches any argument. In addition, the formal argument can be an abstract declaration, which means it can have a type without a variable name. The catch handler is called by an appropriate throw expression. At that point the try block, which was in effect when the exception was thrown, is exited. Upon exit from the try block, the destructors for any objects that are local to the try block are invoked. An exception specification can be part of the syntax of a function declaration function_header throw( type list ) The type list is the list of types that a throw expression within the function can have. If no type list is specified, the compiler can assume that no throw will be executed by the function. void func1() throw( int, CArrayError ); void func2( int x ) throw(); If an exception specification is left off, then the assumption is that an arbitrary exception can be thrown by the function. It is recommended that those exceptions that will be handled in a function be specified with the function declaration. Violations of the specifications are a run-time error. When no other handler has been specified to deal with an exception, the system provides the terminate() handler as a default. Within the terminate() handler, the abort() function is called. The programmer can use the set_terminate() **abort(), by the default termination handler. When a function throws an exception that was not in its exception specification list, the system provides the handler unexpected() which will be called. By default the abort() function is called by the unexpected() handler. The programmer can use the set_unexpected() function to change the function called by the handler. The predefined exceptions in the C++ language are as follows: Exception Type Header file ---------------------------------------------------------------- Bad_cast class typeinfo.h Bad_typeid class typeinfo.h set_new_handler function new.h set_terminate function except.h set_unexpected function except.h terminate function except.h Type_info class typeinfo.h unexpected function except.h xalloc class except.h xmsg class except.h In the following example, an allocation failure will result in the predefined exception xalloc being thrown. Your program should always be prepared to catch the xalloc exception before trying to access the new object. To handle the catching of an exception you must implement a try {} and catch {} pair of operations. // // LINES.CPP - dynamically allocate space from the free store // using try and catch for exceptions. This will only work // with the most recent BorlandC++ v4.xx or Microsoft Visual C++ // v2.x or Microsoft Visual C++ v4.0 compilers. // #include <iostream.h> #include <except.h> int main() { char **buf; int height, width, i; // // acquire parameters concerning data to be input // cout << "Enter number of lines: "; cin >> height; cout << "Enter width of lines: " ; cin >> width; // // allocate array of buffers for text // try // test for exceptions { buf = new char *[height]; for( i = 0; i < height; ++i ) buf[i] = new char[width]; } catch( xalloc ) // enter this only if xalloc is // thrown { cout << "ERROR: Could not allocate space." << endl; return 1; } // //; }
https://docs.aakashlabs.org/apl/cphelp/chap11.html
CC-MAIN-2020-45
refinedweb
4,136
53.31
Hi again, I know I've asked a lot of questions, and you guys have been a really big help, so sorry for all the trouble. XD But, I've got another problem. :X I've been making a reflective program, and it's more or less working right now except of couple of casting/wrapping problems. My program keeps crashing whenever I try to run a reflective method using anything other then Strings. When I do a small test using a method that requires integers, I get the following error: java.lang.NoSuchMethodException: Example.intint(java.lang.Integer, java.lang.Integer) Below is my test class Example: public class Example { public static void output() { System.out.println("Running output"); } [B] public int intint(int var1, int var2) { return (var1 + var2);[/B] } public String stringint(String x, int y) { System.out.println(x); System.out.println(y); return null; } public String stringstring (String x, String y) { return x.concat(y); } } What I don't get is that I have an intint method that requires 2 int variables. How come my program can't seem to catch it? I'm currently using Integer.class; as my way of using intst as the class parameter, and String.class for Strings. Does anyone the proper way I should cast/wrap it?
https://www.daniweb.com/programming/software-development/threads/30087/classes
CC-MAIN-2018-05
refinedweb
218
58.08
Opened 2 years ago Last modified 12 months ago #5824 enhancement new Add automatic detection of the number of CPU core to trial -j Description It'd be nice if trial -j auto twisted detected the number of available cores and used that as the number of local workers. Attachments (3) Change History (20) comment:1 Changed 2 years ago by DefaultCC Plugin - Cc jml added comment:2 Changed 17 months ago by itamar - Keywords easy added comment:3 Changed 17 months ago by racheesingh - Owner set to racheesingh - Status changed from new to assigned comment:4 Changed 17 months ago by racheesingh I looked at the Python docs for multiprocessing. multiprocessing.cpu_count() seems like something we could use to get the number of CPUs. But the docs also mention this: Return the number of CPUs in the system. May raise NotImplementedError. Apparently, on Windows machines cpu_count may result in a NotImplementedError. So should we use this at all? comment:5 Changed 17 months ago by racheesingh Does this seem like a reasonable thing to do? [I tried out multiprocessing.cpu_count and modified the opt_jobs method like so.] def opt_jobs(self, number): """ Number of local workers to run, a strictly positive integer. """ # Case insensitive check if jobs was "auto" if number.lower() == "auto": try: number = multiprocessing.cpu_count() except NotImplementedError: # Windows might raise NotImplementedError while accessing cpu_count raise usage.UsageError( "-j AUTO option not supported for your system.") else: try: number = int(number) except ValueError: raise usage.UsageError( "Expecting integer argument to jobs, got '%s'" % number) if number <= 0: raise usage.UsageError( "Argument to jobs must be a strictly positive integer") self["jobs"] = number comment:6 Changed 17 months ago by racheesingh - Cc rachee.singh@… added Changed 17 months ago by racheesingh comment:7 Changed 17 months ago by racheesingh - Keywords review added - Owner racheesingh deleted - Status changed from assigned to new comment:8 Changed 17 months ago by Julian - Keywords review removed - Owner set to racheesingh Hey! Thanks for working on this. The solution you submitted looks like it's headed in the right direction, but all patches submitted to Twisted have to have accompanying tests. Take a gander at if you haven't already. You'll need to test the new behavior that this ticket is proposing. Thanks again for looking at this! comment:9 Changed 17 months ago by racheesingh Thanks for the pointers! I followed the links about how to add tests and I added a test in what seemed like the place where tests for trial located. After adding the test case I ran trial --testmodule twisted/scripts/trial.py to check if my test case was running at all. But I found that it was not being run. Is there something I am missing here? I am attaching the patch file which has the test case I was trying to add. Changed 17 months ago by racheesingh Proposed fix along with test case. comment:10 Changed 17 months ago by thijs Thanks for your patch. - you should run trial twisted.trial.test.test_script since you placed your test there - the docstring should also mention it can raise a NotImplementedError - or perhaps it should simply return 1 for platforms like win32 and print a warning instead? comment:11 Changed 17 months ago by itamar Thanks for that patch! I'm not sure what thijs is referring to in items 2 and 3. Here are my review comments: - "trial --help" should indicate auto is a possible option for --jobs, otherwise no one will know about the cool new feature you added! - You should provide a test for the error case where NotImplementedError is raised. - "-j AUTO option not supported for your system." would better read as "'-j auto option not supported for your system."` - You should provide a news file () - "svn add" it and then "svn diff" will include it. Please resubmit after addressing these issues. comment:12 Changed 17 months ago by racheesingh Thanks for the review comments. I have incorporated the comments from thijs and itamar and am attaching the diff. Please do tell me if I have missed something out (or misunderstood your feedback). Changed 17 months ago by racheesingh Proposed fix along with test case, incorporating review comments. comment:13 Changed 17 months ago by racheesingh - Keywords review added - Owner racheesingh deleted comment:14 Changed 16 months ago by jonathanj - Keywords review removed - Owner set to racheesingh Thanks for working on this and your continued effort! I have a few review points: - Please use two newlines around methods as per the Twisted Coding Standard. - I think raising SkipTest, with an appropriate message, is better than passing the test in the case where NotImplementedError is raised. - It seems like your test case should be split into two test cases: one testing that NotImplementedError causes the expected UsageError (without depending on multiprocessing.cpu_count to raise this exception) from parseOptions; and one testing (and potentially being skipped on platforms that do not support it) that the runner worker count is auto-detected. comment:15 Changed 12 months ago by Julian comment:16 Changed 12 months ago by exarkun Thanks for the work on this so far, everyone. "trial --help" should indicate auto is a possible option for --jobs, otherwise no one will know about the cool new feature you added! Also, there's a man page for trial. It should be updated as well. comment:17 Changed 12 months ago by exarkun - Keywords easy removed The Python standard library multiprocessing module has a function that exposes the number of available CPUs.
http://twistedmatrix.com/trac/ticket/5824
CC-MAIN-2014-41
refinedweb
925
64.2
Accessing S3 and Redshift via API Gateway (using AWS Lambda) Today I am going to talk about how to get data from your website aand store it in redshift using AWS server-less architecture. This is probably the easiest and fastest way to start processing your data and build your backend quickly. Let’s start with building a simple GET restpoint. - Open the AWS console and go to API Gateway. - Select the HTTP API and select BUILD. The HTTP api supports lambda and gives CORS support out of the box. - Now give your api a name and we are good to go. For this tutorial, i will name it “test”. - It will give you an option to have an auto-deploy route that deploys all your changes automatically. you can give it your own name or leave it as $default. - Now just click create and an api will be created for you. Now let's create the lambda function which we will integrate with our api gateway. - Create a function from scratch. - I chose language as python but you can chose any language you are comfortable with. - Create an IAM role and give write and read permissions for — API Gateway, S3, Redshift, Cloudwatch. - Lambda will automatically create a log group for you and upload all logs to cloudwatch. Now lets create a route in your api. - Click on routes on the left pane. - Click create and choose “GET” api. now that we have an endpoint, let’s integrate it with our backend(lambda). 3. Go to your routes now and click “GET”. 4. Click “attach integration”, select Lambda function and copy the arn of your lambda function here. 5. Click — Grant API gateway permission to invoke your lambda. AAANNNDDD!!!.. you are good to go. 6. lambda by default returns “‘Hello from Lambda!” . So now lets go the code and change that to “testing testing 1 2 3” and save it. Your api should be automatically deployed to default stage. 7. Now lets configure CORS, so we can hit our API from any web browser. Now that we have everything configured let’s try to hit the API. You will find the url for your stage in STAGES on the left panel. Let’s go to this url and you will see your “testing” msg 🥳🥳🥳🥳. Now that we have set up our connection between lambda and apigateway, Lets start with saving our data in S3 and redshift. Create a “POST” route similar to how we created our “GET” and integrate it with the same lambda. Lets also create and S3 bucket and redshift table to store our data. S3 bucket — - Just give your bucket a unique name and you should be good to go. You dont need any more configurations. I named my bucket — ‘test-medium-ankita’. - Now in your lambda , add this S3 bucket as a trigger, so that whenever any data is added to the bucket, it flows to redshift. Redshift table - Let our schema be. — String name, String age, String fav_cartoon - Now open Redshift from the AWS console and lets create our table. (I am assuming you already have redshift setup. If not you can follow this tutorial. - Run the following command to create a table. Create table public.medium ( name VARCHAR(max), age VARCHAR(max), fav_cartoon VARCHAR(max) ) 4. Now when you do — select * from public.medium; You should see your table. For my tutorial, whenever data is inserted into S3 bucket — “test-medium-ankita” , it should automatically populate your redshift table. Once we have all our configurations ready, lets start with creating our lambda function. You will need the following packages: - psycopg2 - boto3 You will need to configure AWS on your local machine (create a user for this with all the required permissions mentioned earlier). - Now create a virtual env. (We will need this to upload our code as a zip file to lambda. You can also follow this tutorial). Code: import json import psycopg2 import boto3def redshiftputdata(loc): con = psycopg2.connect(dbname='***', host='***', port='***', user='***', password='***') cur = conn.cursor() # Begin your transaction cur.execute("begin;") cur.execute( "COPY public.executed_user_rules FROM" + loc + "CREDENTIALS 'aws_iam_role=arn:aws:iam::***' json 'auto';") # Commit your transaction cur.execute("commit;") print("executed user rules copy executed fine!")def put_data_into_s3(data, bucket): putbucket = bucket key = "medium" client = boto3.client('s3') client.put_object(Body=data, Bucket=putbucket, Key=key) return datadef lambda_handler(event, context): print(event) # For api gateway post. response = "default" if ("rawPath" in event and event.get("rawPath") == "/postnames"): body = event.get("body") dict = json.loads(body) dict = json.dumps(dict) print(dict) response = put_data_into_s3(dict, "test-medium-ankita") # handle data coming from s3. if("Records" in event): records = event["Records"] for record in records: s3_name = record["s3"]["bucket"]["name"] key = record["s3"]["object"]["key"] output = "" if (s3_name == "test-medium-ankita" and key.find(".json") != -1): loc = "'s3://test-medium-ankita/%s'" % (key) output = redshiftputdata(loc) print("output: ", output) # TODO implement return { 'statusCode': 200, 'body': json.dumps(response) } The function — “ redshiftputdata” — is used to COPY the json file received from S3 to our redshift table. And the function “put_data_into_s3” is used to put your data into S3 in a json format. Now let’s do a post call and we should directly see data populated in our redshift table: Body for call : {"name":"Ankita Sinha","age": "15","fav_cartoon": "tom and jerry"} Let’s now see the data in our table — P.S. You can get lambda executable psycopg2 from here — . You just need to put this file in your code and zip it.
https://medium.com/nerd-for-tech/accessing-s3-and-redshift-via-api-gateway-using-aws-lambda-aad4d1915587?source=user_profile---------7----------------------------
CC-MAIN-2021-43
refinedweb
923
68.26
I have written a plugin that sends a signal to activate my code. However, it doesn't send the user-request object to my code. I am looking for a way to retrieve the current request without modifying the main application. I cannot find any documentation related to global request (like $_SERVER['REMOTE_ADDR'] As I know it, you define your Django view using a number of methods like: def detail(request, some_param): # [...] The parameter request contains information about the HTTP request. request.META['HTTP_X_FORWARDED_FOR'] for example, returns the client's IP address. If your plugin has something to do with requests, its classes and function probably will be instantiated/called from your view. This means you need to pass it the current request object, as it makes no sense to have a global request object around. In PHP, this is possible, as every request causes the whole code to be executed from scratch, but in Django requests are dispatched by a server and passed around in the framework using HttpRequest objects. Also refer to this part of the Django documentation for more information.
https://codedump.io/share/fO9Olxk7gvxd/1/is-the-global-request-variable-in-pythondjango-available
CC-MAIN-2018-05
refinedweb
183
53.71
BIP Extensions By Tim Dexter-Oracle on Sep 26, 2007 I have recently seen a spate of requests for new functions to be built into BIP - we have enhancements coming out of our ears. For those of you that can not wait and have a little java experience or even have access to a java resource read on. Before I get into the meat of this entry - Oracle will not support you if you choose to use the following methods described. At least I dont think they will - please dont log a TAR if you get stuck :o) As many of you know, that RTF template you develop is converted to an XSLFO stylesheet and the Oracle XSL transformation engine is then used to apply said template to XML data - so at the heart of the whole engine is an XSL transformer. The Oracle implementation provides a framework that allows you to extend the XSLT engine to create your own functions. We even make use of it in our xdoxslt: functions. I have mounted a cut down version of the XDK dev guide here - it just contains the java section. Useful to understand whats going on in the XSLT engine - check out the 'Programming with Oracle XSLT Extensions' section. So how do I do it? From a high level, you create a java class with a method that will process the incoming data and return a result to the transformation engine to be rendered. To then use the new function, your extensions need to be declared in the template as a namespace and the new function name called using the namespace prefix. For example bipext:welcomeMsg('Tim') where 'bipext' is the namespace and welcomeMsg is method to be called. Of course your java class needs to be in the classpath of the publisher engine to be picked up. Let's keep it simple to start with, I have created a very simple class that has only a single method: package oracle.bip.extensions; public class BIPExtensions { public BIPExtensions() { } public static final String welcomeMsg(String name) { return("Hello " + name+" !"); } } The welcomeMsg method takes a string input value and returns a string, 'Hello <<name>> !' to be rendered in the output - yes, its very simple - not Hello World thou you have to admit :0) Couple of other points to notice: - The package path is important - we'll use this in the namespace declaration. - The 'welcomeMsg' method is 'static' - the Oracle XDK can handle both static and non-static methods - they explain further in their documentation here. We now have our java class and method, it needs to be placed into the classpath for the engine - I'll come back to this, so lets assume its done. Now we need to declare that we want to use our new extensions in our template. We just declare these as a namespace: <?namespace:bipext=?> notice that 'bipext' is going to be the prefix we'll use, you can have your own. In the URI we must have : followed by the package path using period (.) separators and then the class name that holds the extension method(s). Once, that is done we can call the function in the template. <?bipext:welcomeMsg('Tim')?> of course 'Tim' could be replaced with an element name - just so long as its a string or can be interpreted as such. When the template is applied and the extension is called we get back 'Welcome Tim !' and its inserted into our output. Being able to test your functions relies on your class being in that all important classpath - if you are using JDeveloper or similar its simple enough to get your class archive in - just ensure its above the xmlparserv2XXX.jar and xdoparser.jar in the list. Using Template Builder for MSWord is a little more tricky and requires what can only be described as 'a bit of hacking' - but with some care you can test them. Template Builder does not support setting a classpath or registering new java functions - yet. The only way around it is to get you class into the xdocore.jar in the /jlib directory under the plugin install. If you are up for it ... - Make a copy and back up the original xdocore.jar and rename it - Using winzip or similar open the jar up - Now you need to merge the extension class into the jar(zip) file - just make sure you preserve that directory path in the archive. In our case, 'oracle.bip.extensions.BIPExtensions.class'. In the visual zippers this is drag an drop but you may need to work out the command line syntax - sorry, Im lazy and use a UI. - Close the archive Hacking done - you're now ready to test the function using the Template Builder. Now remember, you get into a mess, just back up to step 1 again - remember support do not want a ticket asking about how to unhack Template Builder and dont tell em Tim told you to do it :o) Once you're happy with the template, deploy it and your class to the server and you're good to go. Now, here we tackled the simple stuff - you, Im sure will get very creative - got common functions all your templates need and can not be satisfied in a sub template? build an extension - the possibilities are endless and I can hear the cogs whirring from here. If you come up with a hot extension and want to share it, send it in and I'll post it here. Posted by Frank Menne on November 22, 2007 at 08:27 PM MST # Posted by Tung Ho on March 22, 2009 at 10:02 PM MDT # Posted by Brett on June 10, 2009 at 04:04 AM MDT # Posted by guest on May 17, 2011 at 05:28 PM MDT #
https://blogs.oracle.com/xmlpublisher/entry/bip_extensions
CC-MAIN-2015-32
refinedweb
971
67.69
How to Do Simple Arithmetic with C Programming Math in your C source code is brought to you by the +, –, *, and / operators. These are the basic math symbols, with the exception of * and /, mostly because the × and ÷ characters aren’t found on the typical computer keyboard. Calculations in C are made by placing values on either side of a math operator, just as you did all throughout school, but with the benefit of the computer making the calculations. Here is a sample: THE COMPUTER DOES THE MATH #include <stdio.h> int main() { puts("Values 8 and 2:"); printf("Addition is %d\n",8+2); printf("Subtraction is %d\n",8-2); printf("Multiplication is %d\n",8*2); printf("Division is %d\n",8/2); return(0); } Exercise 1: Create a project named ex0504 using the source code shown in Listing 5-2. Save. Build. Run. The output looks something like this: Values 8 and 2: Addition is 10 Subtraction is 6 Multiplication is 16 Division is 4 What you see in this code are immediate calculations. That is, the value that’s calculated, the result, isn’t stored. Instead, the program does the math and deals with the result, which is stuffed into the %d conversion character in the printf() function’s formatting text. Exercise 2: Write a program that displays the result of adding 456.98 and 213.4. Exercise 3: Write a program that displays the result of multiplying the values 8, 14, and 25. Exercise 4: Write a program that solves one of those stupid riddles on Facebook: What’s the result of 0+50*1–60–60*0+10? Solve the equation yourself before you run the program to see the computer’s result.
http://www.dummies.com/how-to/content/how-to-do-simple-arithmetic-with-c-programming.html
CC-MAIN-2015-22
refinedweb
289
60.04
Yes, I'd like to drop those two options. auto_now can be accomplished with "default=datetime.datetime.now", and auto_now_add can be accomplished with a custom save() method. Adrian Adrian Holovaty holovaty.com | djangoproject.com Oh, please, yes! I'd be inclined just to remove 'em wholesale and let things fail loudly, but if someone wants to work up a patch that issues a validation warning (and otherwise does nothing when those params are there) that's probably the right approach. Jacob What about LazyDate? It seems to me that given "default=datetime.datetime.now" is legal, LazyDate can be deprecated as well. Yours Russ Magee %-) Yeah, I'd like to get rid of LazyDate, too. Jacob Is there an easy way to say "today - 3 days" just using the datetime module? I can't think of one off the top of my head that isn't as complex as LazyDate(), but that may be because it's Monday. At the moment LazyDate is useful in limit_choices_to and as a default value. I'd vote to move it into django/utils/dates.py so that it's more visible (it feels wrong in models/__init__.py, but that may just be my bad taste), but I'd like to keep it. Otherwise I'm pretty sure I'm going to end up rewriting it for myself. Cheers, Malcolm How about: lambda : datetime.now() + datetime.timedelta(days=3) Yours, Russ Magee %-) Scrub that last part. Wishful thinking on my part. It can't really be used as a default at the moment, because it doesn't have a __call__ method. Malcolm Yep, you're right. Must be Monday. :-( I withdraw my objection. Nuke it. Malcolm well, if I see this correctly, both have to be implemented in save(). Default will only be used if you don't supply a value, where auto_now is used every time and cannot be overridden. that said, I would be happy without them as well ;) +1 on removing those options > Adrian > > -- > Adrian Holovaty > holovaty.com | djangoproject.com > > > > -- Honza Král ICQ#: 107471613 Phone: +420 606 678585 It could be just me, but although i don't mind losing auto_*, it don't look very DRY in save. I know it's only a few lines (like 4 ? for both options, not using default= for sake of keeping the logic together) but when lots of models have a cre_date and mod_date, those lines are repeated over and over again in save(). Maybe a decorator or the dispatcher can help for all the models with automaticly filled cre and mod_date's. This could also be combined with things like last_modified_by_user and created_by_user. Cause to me it seems these are all standard (housekeeping) tasks which you would like to associate with a model and not repeat the code for it in every model. But i could be missing the point entirely :) Malcolm's 'It's Monday' comment could apply to me too ;) I agree. Using default= in place of auto_now_add is fine, but writing a save() for every model that needs auto_now is just annoying. A shortcut would be nice. I agree with Brian. Regards, David What about a new attribute for all fields, something like: default_condition, where: - The default is set if default_condition(current_value) is True. - By default, default_condition is `lambda value: value is None`, this mimicks current behavior. So: # default_condition is True when created_date is None created_date = models.DateTimeField(default=datetime.now) # default_condition is always True, equivalent to auto_now=True updated_date = models.DateTimeField(default=datetime.now, default_condition=lambda value: True) And it's useful for other fields: minimum_of_zero = models.IntegerField(default=0, default_condition=lambda value: value < 0) seems like it should be as easy as a function in contrib somewhere: def auto_now(amodel): if not amodel.id: amodel.created = datetime.datetime.now() else: amodel.modified = datetime.datetime.now() super(type(amodel), amodel).save() and in your model you have: save = contrib.auto_now When you have to add code to your save() method you could still call auto_now(self). Another option is a trivial field subclass:: class AutoDateTimeField(models.DateTimeField): def pre_save(self, model_instance, add): return datetime.datetime.now() Jacob @auto_now('updatted_on') @auto_add_now('submitted_date') def save(self): super(MyModel).save() I even have started coding it as I need SOME solution that is simple. One problem I have had is with edit_inline and auto_now where the entries are always updated in teh admin even if nothing was changed. Also there are sometimes when I want an auto_now on condition. So this all boils down to something like def auto_now(save, *field_names, **options): condition = None if 'condition' in options: condition = options['condition'] if not len(field_names): raise InvalidArgument, "Something..." save = save field_names = field_names def auto_now_decorator(object): if condition is not None: if not condition(object): return for name in field_names: setattr(object, name, datetime.datetime.now()) save(object) return auto_now_decorator def auto_add_now(save, *field_names, **options): base_condition = None if 'condition' in options: base_condition = options['condition'] def new_condition(object): ## add code to get models PK field from type(object). pk = 'id' if getattr(object, pk) is None: if base_condition is not None: return base_condition(object) return True return False options['condition'] = new_condition return auto_now(save, *field_names, **options) This would allow for things like: @auto_now('last_saved_on', 'other_field') @auto_now('updated_on', condition = lambda obj: fields_have_changed(object)) ## only set the datetime on new objects if the field is not already set... @auto_add_now('submitted_date', condition=lambda obj: obj.submitted_date is None) def save(self): ## some other custom code.... super(MyModel, self).save() To be honest this could be abstracted further where the dynamic value could be set lazy, (like in the previous post has on the model fields). I perfer having these as decorators so they can be added to ANY save 'like' method or on the form it's self. I also used the term 'dynamic' on purpose, as this is not a default value, but could be set to anything based on any of the other fields or any outside influence. There are problems with the above code, the PK issue is mentioned, but there are also issued with time vs data vs datetime vs strings, and giving proper errors for fields which do not exist. I would also want another option for doing backoff validation but that is for a separate post. I would love any feedback anyone has on this Idea. There are a number of projects I am working on that will need this (PyCon, python Jobs board, and 3 others), so I plan on doing a formal implementation starting soon. -Doug
https://groups.google.com/g/Django-developers/c/TNYxwiXLTlI
CC-MAIN-2022-21
refinedweb
1,090
56.35
I am just a student who have a programming class that is not related to my course. So I am helping for your help guys. This is the needed output: Enter Amount Borrowed: 5000 Payment # 1: 1000 Current Balance: 4000 Payment # 2: 2000 Current Balance: 2000 Payment # 3: 1000 Current Balance: 1000 Payment # 4: 100 Current Balance: 900 Payment # 5: 500 Current Balance: 400 Payment # 6: 400 Current Balance: 0 YOU ARE PAID! I try my best to answer this. When i insert the code below, its not adding the input value while loop. For example, The amount borrowed is 5000, i enter 1000. So the current balance is 4000, when i enter 500, it must be 3500, right ? but its still 4500 on the screen. So its not adding while loop. here's my code: Code:// HARD.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <conio.h> using namespace std; void main() { int num=0, //input value ab, //Amount Borrowed p=0, //payment number counter cb=0; //Current Balance float sum=0; //add cout<<"Enter Amount Borrowed:"; cin>>ab; while(ab!=0) { sum+=num; p=p+1; cout<<"Payment#"<<p<<":"; cin>>num; cb=ab-num; cout<<"Current Balance:"<<cb<<endl; } cout<<"You are Paid"; getch(); }
https://cboard.cprogramming.com/cplusplus-programming/139274-help-event-controlled-loop.html
CC-MAIN-2017-30
refinedweb
213
74.69
This blog post was hosted in the Datadog Engineering Blog, you can read it here. If you look at the new Datadog Agent, you might notice most of the codebase is written in Go, although the checks we use to gather metrics are still written in Python. This is possible because the Datadog Agent, a regular Go binary, embeds a CPython interpreter that can be called whenever it needs to execute Python code. This process can be made transparent using an abstraction layer so that you can still write idiomatic Go code even when there’s Python running under the hood. There are a number of reasons why you might want to embed Python in a Go application: The list could go on, but for the Datadog Agent the last point is crucial: we want you to be able to execute custom checks or change existing ones without forcing you to recompile the Agent, or in general, to compile anything. Embedding CPython is quite easy and well documented. The interpreter itself is written in C and a C API is provided to programmatically perform operations at a very low level, like creating objects, importing modules, and calling functions. In this article we’ll show some code examples, and we’ll focus on keeping the Go code idiomatic while interacting with Python at the same time, but before we proceed we need to address a small gap: the embedding API is C but our main application is Go, how can this possibly work? There are a number of good reasons why you might not want to introduce cgo in your stack, but embedding CPython is one of those cases where you must. Cgo is not a language nor a compiler. It’s a Foreign Function Interface (FFI), a mechanism we can use in Go to invoke functions and services written in a different language, specifically C. When we say “cgo” we’re actually referring to a set of tools, libraries, functions, and types that are used by the go toolchain under the hood so we can keep doing go build to get our Go binaries. An absolutely minimal example of a program using cgo looks like this: package main // #include <float.h> import "C" import "fmt" func main() { fmt.Println("Max float value of float is", C.FLT_MAX) } The comment block right above the import "C" instruction is called a “preamble” and can contain actual C code, in this case an header inclusion. Once imported, the “C” pseudo-package lets us “jump” to the foreign code, accessing the FLT_MAX constant. You can build the example by invoking go build, the same as if it was plain Go. If you want to have a look at all the work cgo does under the hood, run go build -x. You’ll see the “cgo” tool will be invoked to generate some C and Go modules, then the C and Go compilers will be invoked to build the object modules and finally the linker will put everything together. You can read more about cgo on the Go blog. The article contains more examples and few useful links to get further into details. Now that we have an idea of what cgo can do for us, let’s see how we can run some Python code using this mechanism. A Go program that, technically speaking, embeds CPython is not as complicated as you might expect. In fact, at the bare minimum, all we have to do is initialize the interpreter before running any Python code and finalize it when we’re done. Please note that we’re going to use Python 2.x throughout all the examples but everything we’ll see can be applied to Python 3.x as well with very little adaptation. Let’s look at an example: package main // #cgo pkg-config: python-2.7 // #include <Python.h> import "C" import "fmt" func main() { C.Py_Initialize() fmt.Println(C.GoString(C.Py_GetVersion())) C.Py_Finalize() } The example above does exactly what the following Python code would do: import sys print(sys.version) You can see we put a #cgo directive in the preamble; those directives are passed to the toolchain to let you change the build workflow. In this case, we tell cgo to invoke “pkg-config” to gather the flags needed to build and link against a library called “python-2.7” and pass those flags to the C compiler. If you have the CPython development libraries installed in your system along with pkg-config, this would let you keep using a plain go build to compile the example above. Back to the code, we use Py_Initialize() and Py_Finalize() to set up and shut down the interpreter and the Py_GetVersion C function to retrieve the string containing the version information for the embedded interpreter. If you’re wondering, all the cgo bits we need to put together to invoke the C Python API are boilerplate code. This is why the Datadog Agent relies on go-python for all the embedding operations; the library provides a Go friendly thin wrapper around the C API and hides the cgo details. This is another basic embedding example, this time using go-python: package main import ( python "github.com/sbinet/go-python" ) func main() { python.Initialize() python.PyRun_SimpleString("print 'hello, world!'") python.Finalize() } This looks closer to regular Go code, no more cgo exposed and we can use Go strings back and forth while accessing the Python API. Embedding looks powerful and developer friendly. Time to put the interpreter to good use: let’s try to load a Python module from disk. We don’t need anything complex on the Python side, the ubiquitous “hello world” will serve the purpose: # foo.py def hello(): """ Print hello world for fun and profit. """ print "hello, world!" The Go code is slightly()) } Once built, we need to set the PYTHONPATH environment variable to the current working dir so that the import statement will be able to find the foo.py module. From a shell, the command would look like this: $ go build main.go && PYTHONPATH=. ./main hello, world! Having to bring in cgo in order to embed Python is a tradeoff: builds will be slower, the Garbage Collector won’t help us managing memory used by the foreign system, and cross compilation will be non-trivial. Whether or not these are concerns for a specific project can be debated, but there’s something I deem not negotiable: the Go concurrency model. If we couldn’t run Python from a goroutine, using Go altogether would make very little sense. Before playing with concurrency, Python, and cgo, there’s something we need to know: it’s the Global Interpreter Lock, also known as the GIL. The GIL is a mechanism widely adopted in language interpreters (CPython is one of those) preventing more than one thread from running at the same time. This means that no Python program executed by CPython will be ever able to run in parallel within the same process. Concurrency is still possible and in the end, the lock is a good tradeoff between speed, security, and implementation simplicity. So why should this pose a problem when it comes to embedding? When a regular, non-embedded Python program starts, there’s no GIL involved to avoid useless overhead in locking operations; the GIL starts the first time some Python code requests to spawn a thread. For each thread, the interpreter creates a data structure to store information about the current state and locks the GIL. When the thread has finished, the state is restored and the GIL unlocked, ready to be used by other threads. When we run Python from a Go program, none of the above happens automatically. Without the GIL, multiple Python threads could be created by our Go program. This could cause a race condition leading to fatal runtime errors, and most likely a segmentation fault bringing down the whole Go application. The solution to this problem is to explicitly invoke the GIL whenever we run multithreaded code from Go; the code is not complex because the C API provides all the tools we need. To better expose the problem, we need to do something CPU bounded from Python. Let’s add these functions to our foo.py module from the previous example: #)) We’ll try to print odd and even numbers concurrently from Go, using two different goroutines (thus involving threads):() } While reading the example you might note a pattern, the pattern that will become our mantra to run embedded Python code: The code should be straightforward but there’s a subtle detail we want to point out: notice that despite seconding the GIL mantra, in one case we operate the GIL by calling PyEval_SaveThread() and PyEval_RestoreThread(), in another (look inside the goroutines) we do the same with PyGILState_Ensure() and PyGILState_Release(). We said when multithreading is operated from Python, the interpreter takes care of creating the data structure needed to store the current state, but when the same happens from the C API, we’re responsible for that. When we initialize the interpreter with go-python, we’re operating in a Python context. So when PyEval_InitThreads() is called it initializes the data structure and locks the GIL. We can use PyEval_SaveThread() and PyEval_RestoreThread() to operate on already existing state. Inside the goroutines, we’re operating from a Go context and we need to explicitly create the state and remove it when done, which is what PyGILState_Ensure() and PyGILState_Release() do for us. At this point we know how to deal with multithreading Go code executing Python in an embedded interpreter but after the GIL, another challenge is right around the corner: the Go scheduler. When a goroutine starts, it’s scheduled for execution on one of the GOMAXPROCS threads available—see here for more details on the topic. If a goroutine happens to perform a syscall or call C code, the current thread hands over the other goroutines waiting to run in the thread queue to another thread so they can have better chances to run; the current goroutine is paused, waiting for the syscall or the C function to return. When this happens, the thread tries to resume the paused goroutine, but if this is not possible, it asks the Go runtime to find another thread to complete the goroutine and goes to sleep. The goroutine is finally scheduled to another thread and it finishes. With this in mind, let’s see what can happen to a goroutine running some Python code when a goroutine is moved to a new thread:: Luckily for us, we can force the Go runtime to always keep our goroutine running on the same thread by calling the LockOSThread function from the runtime package from within a goroutine: go func() { runtime.LockOSThread() _gstate := python.PyGILState_Ensure() odds.Call(python.PyTuple_New(0), python.PyDict_New()) python.PyGILState_Release(_gstate) wg.Done() }() This will interfere with the scheduler and might introduce some overhead, but it’s a price that we’re willing to pay to avoid random panics. In order to embed Python, the Datadog Agent has to accept a few tradeoffs: We’re happy to accept each of these for the convenience of running Python checks in Go. But by being conscious of the tradeoffs, we’re able to minimize their effect. Regarding other limitations introduced to support Python, we have few countermeasures to contain potential issues: go build. We’ll re-evaluate our options in the future and decide whether keeping around cgo is still worth it; we could even reconsider whether Python as a whole is still worth it, waiting for the Go plugin package to be mature enough to support our use case. But for now the embedded Python is working well and transitioning from the old Agent to the new one couldn’t be easier.
https://dev.pippi.im/writing/cgo-and-python/
CC-MAIN-2018-47
refinedweb
1,977
66.37
Home > Products > deep well pumps Suppliers Home > Products > deep well pumps Suppliers > Compare Suppliers Company List Product List < Back to list items Page:1/1 Taiwan Our major export products are oil free mini air compressor, magnetic diaphragm air pump, roots blower, ring blower, jet aerator, membrane diffus... We manufacture complete line water systems accessories. Our full line accessory products check valves, foot valves, tank tees, available in engi... AC Induction Motors manufacturer. Porducts include AC motor,submersible pump,on land pump,Deep Well Pump,Multi-storey Building Pump,Blower,Fan... China (mainland) Tianjin Gan Quan (submersible pump) Group Corporation is an important base of manufacturing water industry products and corresponding control pr... We are professional in producing water pump and looking forward to establish a long lasting relation with you. Zhejiang Xunduo Pump Co., Ltd., is a professional manufacturer of submersible pump in China. Our products include: Stainless steel submersibl... Taizhou Sunny Bright Industry Co., Ltd. brands as "SBT", which is founded in October 1994. We have an area of 40,000 square meters with 20,000... Grand Hardware Manufacturing Co., Ltd is Precision metal parts supplier. --Professional OEM CNC Machining parts and CNC turned parts supplier ... Zhejiang Kesheng Mechanical&Electrical Co.,Ltd is manufacturer specialized in AC Submersible Pump,AC Motor and DC Solar Water Pump. Our DC Solar... FuJian YinJia electromechanical co., ltd is a professional enterprise which has production of pumps, castings, plastic products. Founded in 1990... SEMC(SMC) Shanghai Electrical Machinery Group Co., Ltd. We have been specializing in manufacturing,export and import electrical machinery, metal... Ningbo Sandio Tools Co.,Ltd locates in Ningbo City, is a manufacturer specializes in auto accessories, pumps and air compressors includes vortex... Taizhou Happy Water Pump Co.,Ltd was founded in 1997, with more than fifty million assets. It covers an occupied area of 13,000 square meters, c... Zhejiang Big Century Pump Co., Ltd is a modernized pump manufacturing corporation which integrates production, R&D, sales and service. The lead... Zhejiang Redbud Pump Co., Ltd is an professional pump manufacturer which integrates with scientific research, production and sales as a whole. W... We are a leading manufacturer in producing different kinds of Cables with 60 years' working experience from China. Voltage range:30V--35KV. IE... Zhejiang Xiandai Pump Co., LTD is a professional multistage pump manufacturer. We have been involving in multistage centrifugal pump producing m... Shine Drilltech is a thriving and growing 100% Chinese owned company serving the oilfield drilling and service rig equipment needs since 2006. ... ZhengZhou Shenlong Submersible Pump CO,Ltd is a company specialized in manufacturing all kinds of electric submersible pumps and water supply pl... Hello my friend, Good day! This is Sunshine. Zhejiang Sunshine' Pump manufacturing Co., Ltd is one of the leading suppliers for all kinds o... Changsha Zoomlian Pump Co., Ltd, established in 1989, is an enterprise which engages in the production and sales of multistage pumps, centrifuga... Zhengzhou Shenlong Pump Industry Co., Ltd is located at the beautiful shore of the Yellow River and at the foot of the mountains of Mangshan, Zh... The world’s top variable frequency installation manufacture The world’s top variable frequency control installation manufacture DOOCH CO., LTD... Colin Petroleum Equipment Co., Ltd is mainly engaged in designing, manufacturing and selling petroleum drilling equipment and spare parts, inclu... Founded In 1975, Henan Dalin Rubber Co., Ltd, The Former State-Owned Huixian Rubber Works. Specializing In Pneumatic Clutch Air Tube(Bag), Disc... Zhengzhou Dragon Dream Pump Valve Equipment Co., Ltd. is located in the south of Yellow River, at the foot of beautiful Mangshan Mountain. Drago... ZHEJIANG AQUAROYAL INDUSTRIAL CO., LTD was established in 2006, which specialized on the research and development, manufacture and sales of the ... Xi’an Landau Mechanical & Electrical Co., Ltd. was established in1993,Taizhou, Zhejiang has a construction area of more than 100 thousand square... Established in 1981, Huanggong Machinery Group, China covers a floor area of 30 thousand square meters for its industry park, in which the const... Show: 20 30 40 Showing 1 - 29 items Supplier Name Year Established Business Certification Sun Mines Electrics Co., Ltd. Lee Products Co., Ltd. Hsin Tai Jeo Electric Machinery Co., Ltd. Tianjin GanQuan Group Corporation Lingxiao Pump Co., Ltd. Zhejiang Xunduo Pump Co., Ltd. Taizhou Sunny Bright Industry Co., Ltd. Grand Hardware Manufacturing Co., Ltd. Zhejiang Kesheng Mechanica l& Electrical Co.,Ltd. Fujian Yinjia Electromechanical Co.,Ltd. Shanghai Electrical Machinery Group Co., Ltd Ningbo Sandio Tools Co.,Ltd Taizhou Happy Water Pump Co.,Ltd Zhejiang Big Century Pump Co.,Ltd Zhejiang Redbud Pump Co., Ltd. Qingdao cable Co.,Ltd Zhejiang Xiandai Pump Co., Ltd Shine Drilling Equipment Manufacturing Co., Ltd Zhengzhou Shenlong Submersible Pump Co.,Ltd Zhejiang Sunshine Pump Manufacturing Co., Ltd Changsha Zoomlian Pump Co., Ltd. Zhengzhou Shenlong Pump Industry Co., Ltd Shanghai Dooch Pump Co., Ltd Colin Petroleum Equipment Co., Ltd Henan Dalin Rubber And Telecommunications Apparatus Co., Ltd. Zhengzhou Dragon Dream Pump Valve Equipment Co., Ltd Zhejiang Aquaroyal Pump Co., Ltd Xian Landau Mechanical Electrical Co., Ltd. Huanggong Machinery Group Co., Ltd
https://www.ttnet.net/hot-search/suppliers-deep-well-pumps.html
CC-MAIN-2018-51
refinedweb
842
53.68
Question What are stocks? How are stocks beneficial to corporations? Why do investors invest in stocks? Answer to relevant QuestionsDescribe common investment mistakes made by individuals. Discuss the differences between common stock and preferred stock. What is the dollar amount of Joel’s return (see problem 1)? In Problem 1. Joel purchased 100 shares of stock for $ 20 per share. During the year, he received dividend checks amounting to $ 150. Joel recently sold the stock ...Compare the returns from investing in bank CDs to the possible returns from stock over the next 12 years by filling in the following worksheet. Savings Accumulated over the Next 12 Years What is inflation? How is inflation measured? How does inflation affect stock prices? Post your question
http://www.solutioninn.com/what-are-stocks-how-are-stocks-beneficial-to-corporations-why
CC-MAIN-2017-13
refinedweb
123
71.71
challongerankingchallongeranking challongeranking is a Python-module for ranking players in tournaments hosted in Challonge. The rating algorithm is a basic Elo rating with a constant K value of 32. Players are identified by an email hash provided by the Challonge API. This means that in order for a match to be ranked, both players must have been registered to the processed tournament(s) with their Challonge-accounts. InstallingInstalling pip install iso8601 pip install -e git+ pip install challongeranking UsageUsage To import, use from challongeranking import challongeranking. Please see the examples directory for example code. Using the stored dataUsing the stored data challongeranking stores ratings in a SQL database (or any other store that provides the Python DB-API interface (described in PEP 249). See README-database for details.
https://libraries.io/pypi/challongeranking
CC-MAIN-2021-10
refinedweb
128
55.84
I was interviewing with few companies a couple of months back for a Frontend/Fullstack position. One of the most interesting questions I faced in one of the coding exams was to Write a function in JavaScript that takes an input 'n' and return all the prime numbers until 'n'. The question is simple and straight forward as you see it. I quickly wrote the following code and it worked perfectly! BOOM! I’m done. I felt happy and ran the test cases. Of course, they failed. Happiness is a myth in Javascript. There was a trick here and this was the provided main method that calls my function… function main() { const primeNumberGenerator = getAllPrimeNumbers(23); let primeNumber; while ((primeNumber = primeNumberGenerator.next().value) !== undefined) { console.log(primeNumber); } } I observed some new keywords like next(), I remember to have seen something similar to this in RxJS but this was a pure Javascript code so this should mean something different. I googled and found something new in Javascript that I have rarely used/heard before - Generators in Javascript. It was a timed test, so I quickly read through articles, examples and fixed my code. It worked and all tests passed! Generators can return (“yield”) multiple values, one after another, on-demand. They work great with [iterables](), allowing to create data streams with ease. I don’t want to talk more about generators as there are better articles that do this. I have attached a few at the end that helped me in this course of learning. This was one of the most interesting things I got to solve as part of the interviews. I wrote code to solve a simple problem but with lazy evaluation and memory efficiency. This was fun. Few Articles that helped me to quickly understand Generators and Iterators - - - I hope this was helpful to you to explore how we can use generators in our everyday code. Discussion (1) ! == undefined check is redundant here, no?
https://practicaldev-herokuapp-com.global.ssl.fastly.net/devcer/log-all-prime-numbers-until-n-using-javascript-generators-121e
CC-MAIN-2021-31
refinedweb
325
64.71
Further Challenges in Generating C Bindings After parsing the output from gcc, there were more challenges in generating such bindings that work well for my language. C headers files are really inaccessible description for an API, despite being standardized and plain text. Macros need some parsing too, and then some more In C file it's not unusual to store important constants in macros. The macro is an expression which folds into the correct constant. The macros are defined as rewriting rules into C, so it would be very difficult to convert all of them. I were able to parse some of these macros by parsing them with the same parser I used for constants appearing in arrays and enumerations. GCC doesn't retain the order of the macros in the debug output, so I needed separate parsing and evaluation stages for retrieving the constants. Macro constants depended on the enumerated constants, so macroparsing happens after the actual parsing. Partial Evaluation Most of the time I tried to evaluatee constants as soon as I encountered them. Some C headers represent constants as size of an another structure. The problem is that I can't force the size of structures at this point, as the API specification should be portable, if possible. I decided to produce partial evaluation whenever I hit these constructs. I drop lot of the constants and type definitions I parse, so partial evaluation lets me acknowledge the constructs but I don't need to deal with them right yet. Namespace Restriction Once parsed the header files contain lot more than the API. I solved it by shuffling through the functions, using a regex to select the functions I generate bindings for. It'd be also quite goofy to hold separate namespaces for unions and structures. I solved this by scanning through every function and a structure I'm writing out. If there's a typedef that produces the alias for the structure in the global space, then I coalesce the structure to hold that name. If there's no structure of same name in the global space, I drop the structure from the struct space. Otherwise I prefix it with 'struct_' -name. Namespace Reconstruction Namespace prefixes helped me to recognise the functions part of the API, but it would be frustrating having to write sdl.SDL_Init instead of just sdl.Init. I rewrite every name using a regex substitution. I have to do some verification to make sure the substitution doesn't produce namespace collision. Finally Linus Tolvards makes sure to not break ABI and userspace of linux. Library API definitions written as C/C++ headers makes sure we don't need negligence from Linus to break the userspace. I hope C wouldn't be a standard for describing how to interface with shared libraries. Considering the effort required to generate bindings it is nearly unreadable for non-C programmers. For similar reason it is also easy to design a C API which doesn't stay consistent across platforms. We are bullying ourselves here.
http://boxbase.org/entries/2014/dec/15/further-challenges-in-generating-c-bindings/
CC-MAIN-2018-34
refinedweb
507
63.29
Linux in a Windows World/Additional Server Programs/Managing a Network with Linux From WikiContent Current revision Linux can run several protocols that can provide important background functionality on networks. These protocols seldom make themselves obvious to users—except if the servers that manage them malfunction. Although most of them are major protocols in the sense that they provide many features and have even spawned entire books, they aren't tricky enough to configure to deserve entire chapters in this book. Therefore, I cover all of them in this chapter. These protocols are the Dynamic Host Configuration Protocol, which delivers IP addresses and other basic network configuration information to clients; the Domain Name System, which converts hostnames to IP addresses and vice versa; and the Network Time Protocol, which helps keep clocks synchronized on multiple computers. Although all these protocols can be handled by Windows, doing so with Linux gives you all of Linux's advantages. The servers that handle these protocols are all small enough and require little enough in the way of CPU time, memory, and other resources that they can be run on a very modest Linux system—perhaps an old 80486 or Pentium system that's been retired. You can move one or more of these services onto such a Linux system, obviating the need to upgrade your software and hardware to enable the latest version of Windows to do the job. Delivering IP Addresses with DHCP Networks of all sizes use DHCP to simplify configuration of most computers on the network. A computer configured to use DHCP for basic network configuration tries to locate a DHCP server at startup and, if one is found, sets its basic network options to those specified by the DHCP server. This task may sound impossible because basic network configuration information is delivered via the network before the DHCP client is configured, but it is possible, and understanding the basics of how it's possible is the first order of business. Next up is an overview of DHCP configuration files. You can use DHCP to assign addresses either so that the same computer is or isn't guaranteed the same address on each boot, and understanding how to do both is important. Finally, knowing how to tell clients to use DHCP is critically important to this protocol's successful deployment. The Role of DHCP DHCP is an unusual protocol because it uses very low-level network protocols to help a computer "bootstrap" a more sophisticated configuration. When a DHCP client boots or starts its TCP/IP network stack, the client has no IP address, but it does have working hardware, and it can send data over the network wire. The DHCP client therefore sends a network broadcast with a query directed at any DHCP server that might be listening. Although the DHCP client has no IP address, it does have a working low-level hardware address, and the DHCP server is able to direct its reply to this address. The DHCP server's reply includes information on basic network settings—most importantly, the client's IP address and network mask, as well as the IP addresses of the subnet's router and the DNS servers the client should use. Additional information can be delivered, as well, such as the IP addresses of NBNS computers, but this information isn't delivered by all DHCP servers or used by all clients. DHCP works by issuing leases on IP addresses. The idea is that, should the client crash or otherwise become inaccessible, the IP address will revert back to the pool of available addresses after a limited time. In this way, a DHCP server can continue delivering addresses from a fixed set of addresses. Clients can also give up their leases voluntarily—say, when they're shut down. Not all clients do this, though. Leases have fixed terms, and when a lease expires, a client must renew that lease. (Typically, clients attempt to renew their leases halfway through their terms. If the initial renewal attempt fails, subsequent attempts are made.) Considered on the network as a whole, DHCP simplifies configuration. Instead of entering several IP addresses on each client (for the client itself, including its netmask, the router, DNS servers, and perhaps more), DHCP enables you to set a single option to use DHCP on each client. The details of IP address assignment can then be handled by the server, either automatically or by assigning one address to each computer. This centralized control has a certain appeal by itself, but it's also helpful because it reduces the risk of a typo causing problems, and it makes it easier to change your network's configuration. For instance, if you need to change your network's DNS server address for some reason, you can do so by implementing a change in the DHCP server configuration. Tip Because DHCP works by providing leases of fixed length, changes to network features such as DNS and router IP addresses won't immediately propagate to all DHCP clients. Most clients should update their settings by half the DHCP lease time, though. You can adjust the lease time from the DHCP server. Because DHCP can assign IP addresses arbitrarily to any computer that asks for one, it can be particularly handy on networks on which computers are frequently added and removed. For instance, if your office hosts a number of notebook computers that are frequently removed and taken on business trips, these computers might not have permanent IP address assignments. A DHCP server can assign addresses to them as they're used. Furthermore, if a notebook computer is used on two networks, and if both networks use DHCP, the notebook computer can adjust itself automatically to the settings needed by both networks. Warning Although enabling DHCP to deliver IP addresses to any new computer it sees, and using notebook computers with any network's DHCP server are both useful procedures, they're also both potentially risky. If a new computer on your network is infected with a worm or virus, it might be able to spread locally, bypassing any firewall controls you have on your router. Likewise, a notebook computer can come under attack from worms or viruses if connected to a foreign network. To reduce risk in a security-conscious environment, you might configure DHCP to deliver IP addresses only to known computers. You can do so by referencing specific hardware addresses, as described in the Section 15.1.4.2. In the Linux world, the Internet Software Consortium's (ISC;) DHCP server is the standard one. Most Linux distributions ship with this server under the package name dhcpd or dhcp-server. ISC also produces a DHCP client, which is frequently installed as dhcpcd. Other DHCP clients, such as pump and dhcp-client, are also available. Kernel and Routing Requirements for DHCP Because the DHCP server must communicate with clients that are not yet fully configured for TCP/IP, the server needs support for packet sockets. This is a way for programs to communicate over the network without using an intervening network protocol, such as TCP/IP. It's usually enabled by default, but if you've rebuilt your kernel yourself, you might want to check for it. In 2.6.x kernels, check Networking Support → Networking Options → Packet Socket. If this option isn't enabled, enable it and recompile your kernel. This option is also needed by some DHCP clients. DHCP servers send their responses to clients using a broadcast address. This can be either a global broadcast (255.255.255.255) or a broadcast that reaches all the computers on a particular subnet (such as 172.24.255.255 to reach all the computers on the 172.24.0.0/16 subnet). Unfortunately, some DHCP clients (such as some versions of Windows) expect DHCP servers to deliver global broadcasts, but some Linux configurations convert global broadcasts into local broadcasts. The usual symptom of this problem is that some Windows clients (particularly Windows 9x/Me systems) can't obtain IP addresses via DHCP, but others (such as Linux clients) can. If this happens, try typing this command on the Linux DHCP server: # route add -host 255.255.255.255 dev eth0 If the DHCP server is delivering addresses on a device other than eth0, change that part of the command appropriately. After making this change, try restarting an affected Windows system; it should now work. If so, add this line to a local Linux startup script or to the SysV startup script for your DHCP server. Tip This route command adds an explicit route for traffic destined to 255.255.255.255; without it, Linux changes the IP address to conform to existing routes. You can check your existing routing table by typing route -n. After adding the route as just described, it should appear as the first entry in the routing table. DHCP Configuration Files The DHCP server's configuration file is /etc/dhcpd.conf . Some package distributions include this file in this location, but some packages instead provide a sample file in another location. For instance, SuSE's dhcp-server package stores a sample file in /usr/share/doc/packages/dhcp-server/. The ISC DHCP server also creates a file to track its leases, often called /var/lib/dhcp/dhcpd.leases. You shouldn't need to adjust this file, although examining it can sometimes be a good way to check the server's operation. Warning Don't confuse the DHCP server's dhcpd.conf file with dhcpcd.conf, which some DHCP client packages use as a configuration file! Aside from comments, which are denoted by hash marks (#), dhcpd.conf contains two broad types of statements: - Parameters - These are relatively simple statements that provide information for clients (such as a router's IP address) or that tell the server whether or how to do something (such as how long leases should be). Many parameters begin with the keyword option. - Declarations - These statements describe the network topology, assign IP addresses to clients, or create a grouping of related parameters. Declarations often span multiple lines, in which case the grouped lines are denoted by curly braces ({ }). Most dhcpd.conf files begin with a set of parameters and then move on to declarations. A simple network may contain just one declaration, which in turn contains multiple parameters. A more complex network might contain multiple declarations. Assigning Addresses The bulk of DHCP server configuration is in assigning IP addresses. A full configuration file, though, sets assorted other parameters, and it's best to consider them together. I therefore describe two complete configurations as examples: assigning dynamic IP addresses and assigning fixed IP addresses. Dynamic address assignment In a dynamic IP address assignment configuration, the DHCP server hands out IP addresses to any computer that asks for them but doesn't go to any great lengths to track computers and match them with the same IP address every time they boot. Thus, a single computer might receive four different IP addresses over the course of a week, depending on factors such as the lease time, the number of addresses available, the number of computers on the network, and how often the computer reboots or is shut down for an extended period. Tip Even when a network uses dynamic IP addresses, a computer's IP address is unlikely to change unless the computer is shut down for an extended period of time, such that its lease expires and another computer grabs the address. Even when a computer reboots, it typically asks for its old address back, and will probably receive that address if the lease hasn't expired yet. When the computer stays up continuously, it renews its lease before the lease expires and so keeps the same IP address continuously. Example 15-1 shows a typical dhcpd.conf file for assigning dynamic IP addresses. Although this example is simple, something like it should be adequate for many small networks or even simple large networks. Most lines in this file end in semicolons (;), and omitting that character is an easy way to create a nonfunctional configuration file, so be sure to check that detail. Multiline declarations, however, don't use a semicolon on lines that end in either an open or a close curly brace. Example 15-1. Sample dynamic DHCP server configuration allow bootp; default-lease-time 86400; max-lease-time 172800; option subnet-mask 255.255.255.0; option domain-name-servers 192.168.1.7, 172.24.21.7; option domain-name "example.com"; option netbios-node-type 8; option netbios-name-servers 192.168.1.7 option ntp-servers 192.168.1.7; option x-display-manager 192.168.1.3; option tftp-server-name "mango.example.com"; subnet 192.168.1.0 netmask 255.255.255.0 { option routers 192.168.1.1; range 192.168.1.50 192.168.1.254; } This example begins with several lines that set assorted parameters. Most of these have fairly descriptive names, such as default-lease-time or option subnet-mask. However, some options require some elaboration: - allow bootp - This option tells DHCP to respond to BootP requests, which are similar to DHCP requests but designed to be used by computers that boot off the network. Such configurations are often used with thin clients, as described in Chapter 12. - default-lease-time - You set the default lease time, in seconds, with this option. The lease time is actually determined by negotiation between the client and the server, so you may end up delivering longer leases than you specify with this file, depending on the client's options. - max-lease-time - This parameter sets the maximum lease time the server delivers. Even if the client requests a longer time, the server won't comply. Tip When testing a DHCP configuration, or sometime before making important changes such as altering a router or NTP server IP address, you may want to reduce the default-lease-time and max-lease-time values to something short—possibly as short as a few minutes (say, 300—five minutes). This action reduces the amount of time that clients have invalid information, which can speed up DHCP testing. Using lease times in the range of several minutes to a few hours can be good on networks that see lots of coming and going, such as a network to which users frequently attach laptops for a few minutes at a time. Note that using short lease times will increase network traffic and load on the DHCP server. Setting lease times in the range of many hours or days (such as the 86400, or one day, default lease time in Example 15-1), is a better policy for a stable and working DHCP server on a network that sees few changes to its clients. - option subnet-mask - As you might guess, this option sets the subnet mask (a.k.a. the network mask or netmask). - option domain-name-servers - Point to your network's DNS servers with this option. You can specify multiple servers by separating their values with commas. Most clients accept up to three DNS server addresses, but you can deliver fewer than this number if you like. Example 15-1 specifies DNS servers by IP address, but you can specify hostnames for the DHCP server to resolve when it starts up. (The DHCP server delivers IP addresses to clients in both cases.) - option domain-name - You can tell clients what domain name to use with this option. Not all clients use this information, but for those that do, it can be a handy feature. - option netbios-node-type - This option tells Windows clients how they should attempt to resolve names—whether to use a NBNS system, broadcast resolution, or both. A value of 8 tells the system to use an NBNS system if possible but to fall back on broadcast name resolution. Chapter 5 describes NBNS configuration in more detail. - option netbios-name-servers - This option is the NetBIOS equivalent of option domain-name-servers and works in a similar way. Linux clients ignore this information, though; it's useful only for Windows clients. - option ntp-servers - You can point clients at an NTP server with this option; however, many clients ignore this information. Section 15.3, describes NTP in more detail. - option x-display-manager - This option can point certain X terminal thin clients at an XDMCP server, as described in Chapter 12. Some thin clients ignore this information, however. - option tftp-server-name - A TFTP server delivers files to computers, such as some thin clients, that boot off of the network. This option points such clients to the TFTP server. - option routers - Although Example 15-1 shows this option within a declaration block, it can appear outside such a block. It points the clients at the network's router (a.k.a. the gateway). DHCP supports many additional parameters, but most of them are quite obscure. Consult the dhcpd.conf manpage or a book on DHCP for more information. The core of the DHCP configuration, and the part that sets the dynamic addresses it can deliver, is the subnet declaration in Example 15-1. This declaration begins with a specification of the numeric subnet it serves—192.168.1.0 netmask 255.255.255.0. The curly braces then set off several lines that define features unique to this declaration. In Example 15-1, the declaration contains just two parameter lines, but you can add more. These lines override parameters set outside the declaration body or set new options. The key to defining a dynamic DHCP definition is the range parameter: range 192.168.1.50 192.168.1.254; This line tells dhcpd what IP addresses it may deliver. In this case, the range includes 205 addresses, from 192.168.1.50 through 192.168.1.254. The server won't deliver addresses outside of this range, even within the 192.168.1.0/255 subnet. Thus, you can assign IP addresses for some systems without using DHCP. For instance, the DHCP server itself typically has a static IP address. You might also want to give a router or other important server a static IP address outside the DHCP server's control. Once you make changes to the DHCP server's configuration, you must restart the server. Typically, you do this using the server's SysV startup script, as in /etc/init.d/dhcpd restart. If the server isn't already running, you can start it the same way. Consult distribution-specific documentation if you need help with SysV startup scripts. Fixed address assignment The leap from dynamic IP address assignment to fixed address assignment is a matter of adding new declarations, one for each computer to which you want to assign a fixed address. These host declarations appear within the declaration for the dynamic subnet: subnet 192.168.1.0 netmask 255.255.255.0 { option routers 192.168.1.1; range 192.168.1.50 192.168.1.254; host gingko { hardware ethernet 00:0C:76:96:A3:73; fixed-address 192.168.1.20; } } Each host declaration begins with a hostname (gingko in this case). This hostname may be passed to the client if you set the use-host-decl-names true parameter, but most clients ignore the name. The declaration then contains two lines. The first sets the client's media type (ethernet in this case, although token-ring is appropriate for Token Ring networks) and media access control (MAC) address, a.k.a. the hardware address. The DHCP server then knows to assign the specified fixed-address as the IP address whenever the computer with the specified MAC address requests an address. Warning The IP address you specify with fixed-address must be outside the range specified with range but within the range determined by the subnet IP address and netmask declaration. Of course, on a large network, managing all the computers' MAC and IP addresses can be tedious. For this reason, assigning fixed IP addresses in this way is best reserved for small networks or for a limited number of computers (say, important servers) on large networks. This type of configuration is also often used when configuring thin clients, which may need to be told on a client-by-client basis what files to use as a boot OS. This topic is described in Chapter 12. One critical detail about this configuration is locating the target computer's MAC address. Several approaches to doing so exist: - Examining board markings - Some network card manufacturers mark the MAC address on their boards, usually by affixing a sticker. This can be a good way to get a MAC address if you're installing a card, but it can be inconvenient if the computer's already assembled and has the network card in it. Also, not all manufacturers label their cards this way. - Client configuration tools - Most clients enable you to view the MAC address in one way or another. On Linux and most other Unix-like clients, you can find the address using ifconfig, as in ifconfig eth0. The MAC address is called the HWaddr in the output. Typing IPCONFIG /ALL at a DOS prompt on Windows NT/200x/XP systems also displays this information, on a line labelled Physical Address. Windows 9x/Me systems provide a GUI tool, WINIPCFG, which delivers this information. - Using arp - You can give the client an IP address, either by configuring it statically or by using DHCP without a static IP address defined for the system. You can then use the Linux arp command to find the MAC address. For instance, arp 192.168.1.78 finds the MAC address (and some other information) for 192.168.1.78. You may need to direct some other traffic at the computer first, though; using ping should do the job. - Examining DHCP logs - If you have the client obtain an IP address from the DHCP server's pool of dynamic addresses, you can then examine the /var/lib/dhcp/dhcpd.leases file to locate the MAC address. This appears in a block named after the IP address given to the client. Similarly, the /var/log/messages or other system logfile on the DHCP server usually records the MAC address of clients and the assigned IP address. These techniques are both simplest to use on a network with little DHCP activity, such as a small network. Locating the correct entry on a larger network can be trickier. In all these cases, the exact form of the MAC address can vary. For inclusion in the dhcpd.conf file's host declaration, the address appears as a series of hexadecimal (base 16) numbers separated by colons (:). Some utilities may show the address in another form, such as separated by dashes. If necessary, make the change. For hexadecimal values between A and F, the DHCP server doesn't care about case. For instance, 5a is exactly equivalent to 5A. Telling Clients to Use DHCP Like any server, the ISC DHCP server is useful only if it has clients. These clients can be Windows, Linux, Mac OS, or just about any other system. The DHCP client sets its own basic TCP/IP features by consulting the DHCP server, so the DHCP client program must run before most other network-related programs on the client. Tip A DHCP client can be a server for other protocols. For instance, you might use DHCP to assign an IP address to an SMB/CIFS file or printer server. Some servers work best with fixed IP addresses simply because this makes it easier to enter a name-to-IP-address mapping in your DNS server. For them, you can assign a fixed IP address to the server via DHCP, as just described. To tell a computer to use a DHCP server, you must typically run the computer's basic network configuration tools. For instance, you can do this job on a Windows XP system that's already configured with a static IP address: - Open the Windows Control Panel. - Double-click the Network Connections icon in the Control Panel. This action opens a Network Connections window. - In the Network Connections window, right-click the Local Area Connection icon and select Properties from the resulting context menu. This action opens a Local Area Connection Properties dialog box. - In the Local Area Connection Properties dialog box, select the Internet Protocol (TCP/IP) item and click Properties. This action yields a dialog box called Internet Protocol (TCP/IP) Properties, as shown in Figure 15-1. - In the Internet Protocol (TCP/IP) Properties dialog box, click "Obtain an IP address automatically". If any are set, the values in the "Use the following IP address" fields should disappear. - If your DHCP server delivers DNS server addresses, click "Obtain DNS server address automatically". Any addresses you've set manually should disappear. (You can continue to set DNS server addresses manually, though, which can be handy if you want to use a nonstandard DNS server for some reason.) - Click OK. This should activate your changes. You then need to close the remaining open dialog boxes and network option windows. In many cases, you'll configure the DHCP client when you first set up its networking features. For instance, you might double-click the Network Setup Wizard in Windows XP. This setup procedure will guide you through various network settings, but in all cases, you should be presented with a choice to use DHCP or to set the IP address manually, as in Figure 15-1. (Windows often doesn't use the term DHCP, though, instead referring to this option as "obtain IP address automatically," as in Figure 15-1, or something similar.) Precise details vary from one operating system to another, as well. Most versions of Windows, Mac OS, and other GUI-oriented OSs provide a procedure similar to that just described for Windows XP, but many details differ. Consult the OS's documentation, or browse the system configuration options for ones relating to network configuration. Linux distributions with GUI system administration tools can usually be configured to use DHCP in much this way, as well. You can also do so using text-mode tools: install a DHCP client (usually in a package called dhcpcd, dhcp-client, or pump), and use chkconfig or other tools to enable this package in your default runlevel. Consult distribution-specific documentation if you need help with this task. Delivering Names with DNS A second key network management tool is DNS. DNS servers fill two roles: enabling your local clients to convert names to IP addresses for local and remote computers, and enabling remote systems to find local computers that you choose (such as web or mail servers). One important question is whether you should even run a local DNS server; for many purposes, relying on outside servers makes a lot of sense. Sometimes, though, running a DNS server locally is very helpful. If you decide you want to run your own DNS server, you must be able to configure it. The basic DNS server configuration varies with the server software you select. BIND is the most popular Linux DNS server, and so it's described in this chapter. Once the basic configuration is set, you must create files that describe the computers on your network—their hostnames, IP addresses, and related characteristics. Finally, you must be able to tell clients to use the DNS servers you've configured. Principles of DNS DNS is, essentially, a global database of computer names. The huge size of the DNS database presents many challenges, including maintenance of the database and providing storage space for it. Both challenges are overcome by the fact that DNS is a distributed database; no one computer holds all the data in the DNS database. Instead, the DNS namespace is arranged hierarchically. At the top of the hierarchy are the top-level domains (TLDs), which appear at the end of a DNS hostname. Common examples include .com, .edu, and .net. These three TLDs are all examples of generic TLDs (gTLDs), which are (theoretically) not tied to specific nations. Another type of TLD is the country code TLD (ccTLD), which uses a two-digit country code as the TLD, such as .us for the United States or .ru for Russia. Below the TLDs are the domain names that are so common, such as oreilly.com for O'Reilly Media or upenn.edu for the University of Pennsylvania. These domains can be further subdivided, such as cis.upenn.edu for the Computer and Information Science department at the University of Pennsylvania. At some point, individual computers can be specified, as in for the O'Reilly web server. The beauty of DNS's distributed nature is that it ties into this hierarchy. At each level of the hierarchy, a single DNS server can reasonably hold data on all the domains or subdomains at that level. At the very top of this hierarchy, a set of computers known as the root servers maintain information on the TLDs. Each root server can field queries concerning TLDs; most importantly, the root servers can tell a client where to find DNS servers for the .com, .ru, and other TLDs. The client can then contact a TLD's DNS server for information on a specific domain, such as oreilly.com; the result is the address of the oreilly.com DNS servers. With this information in hand, the client can ask about a specific computer, such as. The distributed DNS system therefore enables lookups in a huge address space relatively quickly. Although multiple queries may be needed, each one finishes rather rapidly. DNS also includes certain time-saving features. For instance, rather than have users' workstations perform the full recursive lookup , in which a name is queried starting with the root servers, a network can host a DNS server that does this job and caches the results. Thus, if two users on a network look up in quick succession, the local DNS server needn't perform a full recursive lookup for the second query; it simply retrieves the result of the original lookup from its cache and delivers that result. This characteristic is also a key to understanding the two main roles that a DNS server can play on your network: - The DNS server can perform full recursive lookups for the benefit of your local computers, and also deliver information on local computers to other local computers. Running a DNS server this way doesn't require modifying your domain's registration with the outside world. - The DNS server can hold information on your local network and deliver that information when queried by remote systems. This capability is extremely important for delivering the IP address of your externally accessible servers, such as your mail server. Although this chapter can help get you started running your own DNS server, you must consult your domain registrar to link your server to the global DNS system. This chapter focuses on the first type of DNS configuration—that which is most useful to local computers. The principles described here also form the foundation for making changes that are accessible to the outside world, though. Tip You can assign one DNS server to be used by local computers and another for use by outside systems. In fact, you don't need to run both servers yourself. For instance, you might run your own local DNS server to help your computers perform DNS lookups, but rely on a domain registrar or a domain hosting provider to run DNS servers that hold information on your domain for the outside world. Running a DNS server for the benefit of your local computers is most useful if your ISP doesn't provide one or if you want to deliver information that's unique to your private network. For instance, you might have a subnet behind a firewall that holds file servers, print servers, and pull mail servers to be used by other computers behind the firewall. Entering information on these systems in a globally accessible DNS server is unnecessary and can even give potential attackers information about your network, so running a DNS server behind the firewall can be a good way to provide local name resolution. This server can also handle full recursive lookups for the benefit of other local computers. Tip An alternative to DNS for local name resolution is to configure an NBNS system. Windows clients often use an NBNS system automatically if the DHCP server is configured to deliver the NBNS address, as described earlier in Section 15.1.4.1. You can also configure Linux systems to use NBNS, as described in Chapter 6. NBNS has certain advantages, such as simpler adaptation to dynamic IP addresses, but it's also got limitations, such as a lack of support for DNS domain information. Basic Name Server Configuration Running a name server involves two basic configuration tasks: setting up the name server itself (that is, the options it uses to control where it stores additional configuration files, how it should respond, and so on) and setting up the domains it handles. This section describes the first of these tasks, using the BIND software as an example. (If you use another server, such as djbdns, you need to read its documentation.) The second task is described in the next section. The Berkeley Internet Name Domain (BIND) is distributed by the ISC (), which also distributes the most common Linux DHCP server. As with ISC's DHCP server, BIND is available with all major distributions, except for some very desktop-oriented ones; thus, you shouldn't need to download it from the ISC web site unless you have a specific reason to avoid your distribution's BIND package. Typically, the package name is bind. Although the official name for this server package is BIND, the executable filename is named , and BIND configuration files are named after this—namely, the main configuration file is /etc/named.conf . For a simple configuration, this file contains two broad classes of entries: - Global options appear in a section called options. These include features such as a directory in which domain definitions exist, on what network interfaces the server should listen, and so on. - Each domain or subdomain (that is, a zone) is briefly described in a zone section. This section sets only the broad outlines for a zone; the description of the zone's computers appears in zone configuration files, as described in the next section. Example 15-2 shows a simple but usable /etc/named.conf file. This file defines the basic settings for a BIND server handling the example.com domain. It includes an options section and four zone sections, which are described in more detail shortly. A DNS server for a network with multiple subnets or domains is likely to have additional zone sections. Example 15-2. Sample /etc/named.conf file options { directory "/var/named"; listen-on{ 192.168.1.1; 172.24.21.1; }; forwarders { 10.29.102.7; 10.65.201.7; }; forward first; }; zone "." { type hint; file "named.ca"; }; zone "example.com" { type master; file "named.example.com"; }; zone "1.168.192.in-addr.arpa"{ type master; file "named.192.168.1"; }; zone "0.0.127.in-addr.arpa"{ type master; file "named.local"; }; The general format of the /etc/named.conf file is similar to that of the ISC DHCP server. Most lines set individual options and end in semicolons (;). Other lines, though, begin or end blocks of options. The line that begins such a block ends in an open curly brace ({), and the line ending such a block ends in a close curly brace and a semicolon (};). The options section in Example 15-2 sets several important global features of the server: - directory - This may be the most important line in the options section; it sets the name of the directory in which BIND looks for zone definition files—that is, the files that define the mappings of hostnames to IP addresses and related domain features. - listen-on - This optional subsection specifies one or more IP addresses on which BIND listens for queries. This feature can be handy if you run the server on a computer with multiple network interfaces but want to make the server available on only some of them. - forwarders - This subsection is optional. If you use it, you can specify the IP addresses of one or more DNS servers that you want to handle DNS queries other than those for which your own server is the ultimate authority. Typically, you use this feature if your ISP offers DNS servers of its own. You can point BIND to your ISP's servers using this directive and, rather than perform a full recursive lookup itself, your server queries your ISP's servers and lets them perform the full recursive lookup. This can result in faster responses if your ISP's servers are working correctly, because they probably have better Internet connections than your own server. This option has no effect on lookups within your own domains (such as example.com in this example). - forward - The forward option tells BIND when to use the DNS servers specified with the forwarders directive. The forward option takes either of two values: only or first. The forward only directive tells BIND to use the servers listed in the forwarders section and its own zone files exclusively; BIND doesn't perform its own recursive lookup. The forward first directive, by contrast, tells BIND to attempt to use the servers specified by forwarders but to perform a full recursive lookup if those servers are unavailable. This option can improve reliability, but it can also slow the return of a failure code. Many other directives can be placed within the options section, but the ones described here should be enough for many small configurations. Consult the documentation that came with BIND, or a book on the server, such as O'Reilly's DNS and BIND, for more information on these options. If you want BIND to deliver information on your local network, the zone definitions are just as important as the options section. Each zone definition begins with the zone keyword followed by the name of the zone. Chances are your named.conf file will have three broad classes of zone definitions: - The root zone - The zone "." entry in Example 15-2 defines the root zone, which ultimately points BIND to the root DNS servers. This definition uses a type hint line, which is unique to the root zone definition. - Forward lookup zones - The only forward lookup zone in Example 15-2 is for the example.com domain. This type of entry specifies the domain or subdomain name as the zone name, and enables clients to pass a hostname to get an IP address. On the domain's primary DNS server, this zone will have a type master line in the zone definition. (Slave DNS servers can copy zone files from another DNS server and use a type slave definition; however, slave DNS server configuration is beyond the scope of this book.) - Reverse lookup zones - Frequently, DNS servers include zone definitions for reverse lookups, in which a client enters an IP address and receives back a hostname. Reverse lookups work much like forward lookups, but they require an unusual notation for the zone type. Specifically, reverse lookups use hostnames of the form backwards-IP-address.in-addr.arpa, where backwards-IP-address is an IP address fragment in reverse. For instance, Example 15-2 has two reverse lookup zones, named 1.168.192.in-addr.arpa and 0.0.127.in-addr.arpa. These correspond to the 192.168.1.0/24 and 127.0.0.0/24 network blocks, respectively—note that the order of the four bytes of the IP addresses are reversed. In both cases, the first byte of the reversed address (the final byte of the original) is omitted, which denotes the fact that these zones apply to networks with 255.255.255.0 netmasks. The reverse ordering of these names is confusing at first, but the reason is that the most- and least-significant portions of IP addresses and hostnames are reversed. A reverse lookup converts an IP address to a hostname in the special in-addr.arpa domain. However, to define the individual hosts in this domain, the machine identifier portion (that is, the final byte of the address in a /24 netblock) must be the first part of the name in the in-addr.arpa domain, so the order of the IP address elements must be reversed. Example 15-2 defines two reverse lookup zones, one for the loopback address (127.0.0.0/24) and the other for the local network address (192.168.1.0/24). Tip It's possible to omit a reverse lookup zone. In fact, if your DNS server will be serving names for IP addresses on the Internet as a whole and you don't control the entire netblock, you should omit the reverse lookup zone. You're responsible for handling forward lookups on your domain, but whoever controls the netblock (usually an ISP for small networks) is responsible for the reverse lookup. If you're configuring a DNS server for a small private network, though, you might want to include both forward and reverse lookups. Once you've configured the basics in /etc/named.conf, you might be tempted to restart the named server. You can do so in the usual way, such as by using a SysV startup script, however, you should probably wait until you've created appropriate domain configuration files, as described next. Setting Up a Domain Configuring the basics of the server's options is just the start of the process. In day-to-day operation, you're more likely to need to modify your zone definitions, which are stored in files in the directory specified with the directory keyword in the options section of the /etc/named.conf file. Each zone has its own configuration file, which defines features of the zone as a whole and creates mappings of hostnames to IP addresses for each member of the zone. Each type of zone definition in named.conf has its own variant style of zone definition file. The most fundamental of these is the root zone definition. Chances are your BIND configuration includes a default configuration that will work. Typically, the filename is named.ca or db.cache. If this file isn't present, or if it's very old, you should try to obtain a more up-to-date version. You can find the latest copy from. Copy this file to the directory specified in your named.conf file, and name it as specified by the file option in that file's root zone definition (zone "."). Additional zone files are the forward and reverse zone files. Configuring forward zone files The second type of zone definition is for forward lookups—those that use an ordinary domain name in the zone line of named.conf. Use whatever filename you specify in named.conf for the file. Typically, this name is related to your domain's name, such as named.example.com for the example.com domain. Example 15-3 shows a sample forward lookup zone configuration file. Example 15-3. A sample forward zone definition file $ORIGIN . $TTL 604800 ; 1 week example.com IN SOA maize.example.com. linnaeus.example.com. ( 2004102609 ; serial 28800 ; refresh (8 hours) 14400 ; retry (4 hours) 3600000 ; expire (5 weeks 6 days 16 hours) 86400 ; minimum TTL (1 day) ) $ORIGIN example.com. maize IN A 192.168.1.1 gingko IN A 192.168.1.2 mandragora IN A 192.168.1.3 mandrake IN CNAME mandragora mail IN A 10.23.186.78 www IN A 172.24.217.102 @ IN NS maize.example.com. @ IN MX 10 mail.example.com. The zone file begins with two lines that set some global parameters. The $ORIGIN. line should be present in your zone files unchanged. The $TTL 604800 line sets a default time-to-live(TTL) value, which tells other servers how long, in seconds, they may cache entries obtained from your server. You may increase or decrease this value as you see fit. The lines beginning with example.com and ending with a single close parenthesis ")" define the start of authority(SOA) record for this zone. This entry sets several important overall features for the zone: - Zone name - The zone name (example.com in this example) begins the SOA line. You should change it to match your own domain or subdomain name. - Entry class - The IN code defines the class of the entry. IN stands for Internet, and it's the most common SOA entry class and the only one described in this chapter. - Record type - The SOA code identifies this entry as creating an SOA record. - Master name server - The maize.example.com. entry in the SOA record identifies the zone's primary name server. Note that this hostname ends in a dot (.). Technically, all DNS hostnames end in a dot. Most user programs enable you to omit this dot, but you must include it when specifying a full hostname in the DNS configuration files. - Administrative email account - The linnaeus.example.com. entry, although it doesn't look like one, represents an email address for the person responsible for administering the domain. Replace the first dot with an at sign (@; to create linnaeus@example.com.) to generate an email address. As with other addresses, this one must end in a dot. - Timing information - The remaining information, beginning with the open parenthesis on the main SOA line and ending with the close parenthesis line, represents timing information for the data retrieved from this zone. This information is used mainly by other DNS servers. Values are a serial number (often set to the date followed by a code for the change number on the day), the interval for slaves to use between checks for updated information, the interval at which slaves should attempt transfers if the first one failed, the time after which a slave should expire and discard an entire zone if it's not been updated, and a minimum TTL value for remote DNS servers to cache information. The values shown in Example 15-3 are reasonable starting points. Note that most of these values are important only if you run multiple DNS servers, with one configured as a master and the rest as slaves. Following the SOA record is a line that explicitly sets the $ORIGIN to your domain, including its trailing dot—example.com. in this case. Subsequent lines are similar in form to the SOA line, but they're simpler; most take the following form: hostname IN code address The hostname is the hostname in question, without a domain component. Some entries enable you to specify an at sign (@) as the hostname. This symbol stands in for the domain name and is used by certain code types, as described shortly. The IN component is invariant in these entries, at least as far as described in this chapter. The code is a code that stands for the entry type and is described in more detail shortly. Finally, the address is the address to associate with the hostname. In many cases, this is an IP address; but for some code types, it can be a hostname—either a hostname without a domain, which is interpreted as a hostname in the current domain or a hostname with domain component and trailing dot. The MX code is unique in that it includes a number before the address, as described shortly. In defining a domain, you're likely to include several different types of code: - A - An A record defines an individual host in the domain. Use this to associate an IP address with a hostname. - CNAME - A CNAME record sets up an alias—a linkage of one name with another. CNAME records are often used when a single computer goes by multiple names, such as a single system that functions as both a web server and an FTP server, and that you want to be accessible by the names www and ftp for this reason. Alternatively, you can create multiple A records, but doing so requires you to change all the A records if you ever change the server's IP address; using CNAMEs for most records makes subsequent changes easier and less prone to error. - NS - A name serverrecord identifies a DNS server for the domain. Normally, one NS record points to the computer you're configuring. Others may point to other DNS servers, such as slaves of a master server. The hostname on this line is either the domain name alone or an @ sign, and the address is the name of an A record—with or without the domain component. - MX - A mail exchanger record points to a domain's mail server. This record requires a priority number for each server listed; sending mail servers attempt to contact your mail servers in sequence, starting with the one with the lowest number and moving up from there. As with NS records, the hostname is either the domain name alone or an @ sign, and the address is the name of an A record. - PTR - Example 15-3 shows no pointer (PTR) records because they're unique to reverse lookup zone files. They use a pseudo-hostname based on an IP address as a hostname, and they list a regular hostname as the address. PTRs are described in more detail shortly. Configuring reverse zone files In some cases, you need to configure only forward lookups. For instance, your ISP might own your network block and so handle the reverse lookups, or you might simply not care about reverse lookups. (Some programs, though, perform reverse lookups and compare them to the forward lookups. If the two don't match, the programs terminate the connection or otherwise cause headaches. Thus, working reverse lookups can be more than just a convenience.) If you're in control of your network block, including if you're running in a private reserved address space, you can configure a reverse lookup zone. To do so, you must first specify a reverse lookup zone in the /etc/named.conf file, as described earlier, in Section 15.2.2. You can then create a reverse lookup file in your zone file directory. This file is likely to be named after the zone, e.g., named.192.168.1. Example 15-4 shows an example of such a file. Example 15-4. A sample reverse zone definition file $TTL 1W 1.168.192.in-addr.arpa. IN SOA maize.example.com. linnaeus.example.com. ( 2004102609 ; serial 28800 ; refresh 14400 ; retry 3600000 ; expire 86400 ; default_ttl ) 1 IN PTR maize.example.com. 2.1.168.192.in-addr.arpa. IN PTR gingko.example.com. 3.1.168.192.in-addr.arpa. IN PTR mandragora.example.com. 1.168.192.in-addr.arpa. IN NS maize.example.com. The reverse lookup file is very similar to the forward lookup file. Like the forward lookup file, it includes a $TTL directive. (Example 15-4 shows an alternative way of specifying the time, though, by including a one-letter abbreviation for the time unit—1W meaning one week.) This file also contains an SOA record, which takes the same form as the equivalent record in the forward zone definition file; the main difference is in the name of the domain. (You can use different specifics, such as refresh times or network administrator email address if you like, though.) The bulk of the post-SOA entries in a reverse lookup file are PTR records, which tie an IP address (in the form of its reversed in-addr.arpa pseudo-hostname) to conventional hostnames. As with forward lookup files, you can abbreviate hostnames by omitting the domain portion of the name. In the case of reverse lookup files, though, the domain portion of the name is the reversed network portion of the address and in-addr.arpa. Thus, the reverse lookup for the 192.168.1.1 address in Example 15-4 is 1, referring to the final byte of the IP address. Example 15-4 doesn't use this convention for the remaining addresses. The looked-up names (maize.example.com., gingko.example.com., and so on in Example 15-4) may not be abbreviated by omitting their domain portions. You must also include the trailing dot after each of these names. In addition to SOA and PTR records, reverse lookup zone files typically include one or more NS records, which point to the DNS servers that handle the network block. These might or might not be the same servers that handle forward lookups for the computers in that network block. Other record types, such as A, CNAME, and MX, are uncommon in reverse lookup files. Running the server Once you've set up your domain, you can start the server. Typically, this is done via a SysV startup script; typing /etc/init.d/named start or something similar usually does the job. To run the server permanently, you can use chkconfig or a similar tool to add the server to your default runlevel, or do the job manually by creating appropriate symbolic links yourself. Consult distribution-specific documentation if you need help with this job. Once the server has started, you may want to check the last few lines of your log files to see if the server has reported any problems. Typing tail /var/log/messages can do this. Warning If you restart the server, you may get an error message in your logs about the journal forward failed, and you might not be able to resolve names in a domain. This often happens if you change your BIND configuration while the server is running; it doesn't like that. The solution is to shut down named, delete the file whose name starts with the name of the zone configuration file but ends in .jnl in the directory that holds your zone configuration files, and restart named. A better practice is to make changes to your zone files only when named isn't running. You can test your server's operation using the host command on the server or any other computer that has this tool. Type host name server to look up name using the specified server. If the computer pauses for several seconds and responds connection timed out, chances are the server has crashed on startup or you've specified the wrong server. (You may need to specify server as an IP address if the computer isn't configured to use that system for name resolution by default.) Other error messages typically denote problems with your DNS configuration; check your logfiles for clues. Be sure to test both forward and reverse DNS lookups. Pointing Clients at the Name Server Client configuration is, of course, critically important to DNS operation. If you want local workstations and servers to use your DNS server for name resolution, you must tell them to do so. If you use DHCP to assign IP addresses to these computers, the simplest way to configure them to use your DNS server is to adjust your DHCP configuration using the option domain-name-servers line in your DHCP configuration file, as described earlier, in the section Section 15.1.4.1. Once configured in this way, a DHCP server can deliver DNS server information to Windows, Linux, Mac OS, and other clients that use DHCP. If you want to configure some or all of your computers using static IP addresses without using DHCP, you must configure these computers to use your DNS servers manually. Precisely how you do so varies from one OS to another, but most provide GUI tools that enable you to enter the DNS server addresses manually. Earlier, the Section 15.1.5 described how to configure Windows XP to use DHCP. Part of this process provided an opportunity to tell Windows to use the DNS servers provided by the DHCP server or to use servers you specify. In particular, Figure 15-1 shows the relevant dialog box. Click "Use the following DNS server addresses," and enter up to two DNS server addresses to have Windows use them instead of those provided via DHCP or if you don't use DHCP at all. Similar tools exist in other versions of Windows and in other OSs. Although you can enter DNS server addresses using GUI tools in most Linux distributions, Linux supports another method: the /etc/resolv.conf file specifies DNS servers and the domains that Linux should attempt to search. This file is likely to be quite short: domain example.com search example.com,pangaea.edu nameserver 192.168.1.1 nameserver 10.29.102.7 Each line has a specific purpose: - domain - This line tells the computer the domain to which it belongs. The main practical upshot is that names are searched for in this domain before they're searched in other domains or without the domain name. - search - This line enables you to tell the system to search domains instead of the one specified by domain. You can list up to six domains, separated by commas or spaces. - nameserver - You list DNS servers, one per line, using nameserver keywords. Linux supports up to three DNS servers; it tries each one in sequence until a lookup returns a definitive success code (a certain success or failure, as opposed to a failure of the server). Whether the DNS client runs Linux, Windows, or some other OS, a DNS lookup normally uses a domain search list, even if the user specified a hostname with a domain. For instance, if you do a lookup on mandragora.example.com from within the example.com domain, the computer first tries a lookup on mandragora.example.com.example.com. If additional domains are in the search paths, similar lookups are performed on them, as in mandragora.example.com.pangaea.edu. When these lookups fail, the name resolver tries the lookup without appending any item from the search path. The assumption is that the user has entered a relative hostname without a domain component. You can block this initial, and probably erroneous, lookup by appending a dot, e.g., typing mandragora.example.com. rather than mandragora.example.com when entering the hostname. This trick works with most programs and protocols, but it might confuse some. In most cases, it's unnecessary; the extra lookup that fails is unlikely to take very long at all, so it does no real harm. Keeping Clocks Synchronized with NTP One of the frustrations of using a computer network is that the individual computer clocks can report different times. This fact can be a minor annoyance when, say, you seem to have jumped back in time by two minutes when switching computers. It can become more serious when programs that rely on time stamps see inconsistent times on files. A make utility, for instance, might fail to compile a file if it believes that file changed before the last compilation, when in fact it changed after the last compilation but the time stamps are off. Even more serious temporal problems result with tools such as Kerberos, which embed timestamps in some of their packets as a security measure. Depending on your Kerberos settings, logins can fail completely if two computers' clocks are inconsistent. These problems can all be overcome using a protocol designed to keep computers' clocks synchronized. The most popular protocol to do this job is known as the Network Time Protocol, which is headquartered at. Before proceeding with the details of NTP configuration, you should understand its basic operating principles; this will help you decide how to implement NTP. As with most protocols, you must then configure both servers and clients. The Linux NTP server, though, does double duty as both a server and a client. On the Windows side, you can use either a full NTP implementation or a built-in Windows command. Principles of NTP NTP can do more than simply keep your clocks synchronized on your local network: it's designed to help you keep all your computers' clocks set to an accurate time source. It does so by creating a hierarchy of NTP servers, most of which also function as clients to NTP servers that are closer to the ultimate time source—usually an atomic clock or a device that reads its time from one, such as a radio that receives signals from an atomic clock. This arrangement is illustrated in Figure 15-2. The atomic clock or other time source is referred to as a stratum 0 time source. The servers that communicate with this device are known as stratum 1 servers; those that communicate with the stratum 1 servers are stratum 2 servers, and so on. This arrangement provides a powerful exponential effect on the number of computers a single time source can serve. For instance, if each server has just 100 clients, a single stratum 1 server can have 10,000 stratum 3 and 1,000,000 stratum 4 clients. As the stratum level increases, the accuracy of the clocks decreases, but not by much; times are typically accurate to well under a second up to several stratums. (The exact values depend on factors such as the variability of transit times and how evenly divided the transit times are on each leg of the journey.) At each step of the way, NTP works by measuring the time it takes for packets to traverse the network. For instance, if you send a packet to a computer, and it replies, you can measure the round-trip transit time. (You can use ping to do this in a crude way.) If the return packet includes a time stamp, you can use the time stamp and round-trip transit time to set your own clock to that of the remote server; you use the time stamp in the packet and half the transit time. NTP uses this principle at its core, although it's more sophisticated. For instance, a full NTP implementation runs as a daemon and checks its upstream time source on a periodic basis. It can use the data gleaned from these checks to adjust the rate at which its own clock "ticks," thus maintaining a more accurate time even between time checks. NTP can also refer to multiple upstream time sources, thus providing redundancy and enabling it to select the best time source. In practice, you'll set up one computer as a master NTP server for your network. (You might set up more than one if your network is very large or is geographically diverse.) Your master NTP server refers to an upstream server to set its own clock; the rest of your computers set their clocks based on their own master NTP server. This configuration minimizes network traffic; you can set potentially thousands of computers' clocks using the external bandwidth required to set just one system's clock. What computer should you use as your master NTP server? In practice, requirements are fairly minor. Compared to most other network protocols, NTP generates little network traffic and requires practically no disk space, aside from that needed for the OS itself. Therefore, it's common to piggyback NTP duties onto another server. On the other hand, you don't want to add master NTP duties to a server that's already overloaded, because delays in handling the NTP packets will be quite detrimental to the NTP server functions. In any event, the server should have ready network access to the Internet and to all the computers on your local network. Of course, like all servers, NTP is a potential security risk, although it's a minor one compared to servers that provide login or file access. NTP Server Configuration In Linux, an NTP server acts as both a client and a server. In fact, to maintain the most accurate time in Linux, you may want to install a full NTP server, even if it has no clients of its own; your NTP server will act only as a client. All major Linux distributions ship with NTP servers, typically in packages called ntp, xntp, or a variant with a major version number appended, such as ntp4. The major NTP configuration file is /etc/ntp.conf. Most distributions ship ntp.conf files that should require few changes; you may only need to set an appropriate server. A few other options may need attention as well, though: - server - This line sets the hostname or IP address of an NTP server, as in server tick.pangaea.edu to tell NTP to refer to the NTP server on tick.pangaea.edu. You can also add various options to support authentication and other features, but, in most cases, these aren't needed. Picking a server is described in more detail shortly. One special case that deserves attention is setting server 127.127.1.0. This line tells NTP to use the local system clock. It may be included as a fallback position in case all other servers become unavailable. - fudge - Ordinarily, NTP automatically detects the stratum of the servers to which it communicates; it can then set its own stratum automatically. The fudge line enables you to force NTP to treat a server as belonging to another stratum. It's most often used in conjunction with the 127.127.1.0 address to force NTP to give the local NTP server a very high stratum number so that it's not used in preference to more accurate sources. For instance, fudge 127.127.1.0 stratum 10 tells NTP to treat the local clock as a stratum 10 server. - driftfile - You can specify a file in which NTP stores information on the hardware clock's drift. This information can help when you first start the server after it's been down for a while or in case your network access goes out. Using the drift file, NTP should be able to maintain your clock's accuracy much better than is possible using the computer's unmodified clock. You shouldn't need to adjust this entry unless you rearrange your directory structure in some unusual way. - broadcast - If your network hosts many systems that also run the full version of NTP, you can minimize local NTP-related network traffic by telling your main NTP server to periodically broadcast its time information, which then reaches all the clients, obviating the need for them to contact the server individually. To use this feature, specify the broadcast keyword followed by the computer's own IP address; it then broadcasts to the local network. - broadcastclient - The flip side of the broadcast feature is the configuration of the NTP broadcast clients. On these systems, you set broadcastclient yes to have NTP listen for broadcasts from other NTP servers, or broadcastclient no to have the server ignore such broadcasts. One of the trickiest aspects of NTP configuration is in selecting an upstream NTP server. NTP server lists are maintained at; this list has links to both stratum 1 and stratum 2 servers, and it describes rules of etiquette for using the servers. You may be able to find other sources, as well. For instance, your ISP might operate an NTP server that you can use, or if you're setting up NTP for a single department in a much larger organization, your organization might run an NTP server. In most cases, you should contact the server's operator before connecting your own server, although some server operators provide blanket permission for certain people to use their NTP servers. (Lists of NTP servers often contain information on what types of permission should be obtained before using any given server.) You should try to pick a server that's close to you in network topology. For rough estimates of this measure, use ping to determine the round-trip transit time to potential servers, and use traceroute to measure the number of intervening systems. The lower the transit time and the fewer the intervening systems the better. The higher you go in the NTP stratum hierarchy, the more accurate the times; however, NTP servers with low stratum numbers are few in number and shouldn't be used except by clients that themselves serve many clients. As a general rule of thumb, you shouldn't use a stratum 1 server unless your own server is itself delivering time to at least 100 clients. For smaller networks, use a stratum 2 or lower server; the accuracy of your time won't suffer much, and the variability within your network won't suffer at all, but you'll be helping to distribute the load on the NTP network as a whole. You can specify multiple upstream NTP servers, but you can get by with just one. Using multiple servers provides redundancy and enables the NTP software to pick the best server from the lot automatically. On the other hand, using few servers reduces network load. Generally speaking, small networks can get by just fine with just one server, although you might want to try several at first to determine which works best. Large networks, or networks on which precision timekeeping is particularly important, may do well to use multiple upstream servers—typically, at least three to make it easier to pick the bad time keeper, if there is one. Once you've entered one or more server lines in ntp.conf and made any other changes you like, you should start NTP. On most distributions, this can be done using a SysV startup script, e.g., by typing /etc/init.d/ntpd start. (The exact name of the SysV startup script varies; some omit the d from the end of the script name or add x to the start.) To run NTP regularly, use tools such as chkconfig to add the NTP startup script to your default runlevel. Consult distribution-specific documentation for help on this topic. Once the NTP server is running, you can use the ntpq tool to monitor its operation. Type ntpq to run the program, and it replies with a ntpq> prompt. Type peers to obtain a list of upstream NTP servers and assorted statistics on them. In particular, note the value of the st column, which shows the upstream server's stratum. Initially, NTP polls the upstream servers frequently to determine which one is the most accurate. After a few minutes, it settles on one as its primary source and marks it with an asterisk (*) to the left of the server's hostname. Other servers that generate reasonable results receive a plus (+) mark in this position. Be wary of a server that's marked with an x to the left of its name; this is a false ticker, which is providing times that are inaccurate compared to the other servers. To configure Linux NTP clients (which may run other servers, such as Samba), configure them just as you do your primary NTP server, but instead of pointing them at one or more external NTP servers, point them to your primary NTP server alone. Because these servers are all on the same network, the time for NTP packets to make their round trip will be tiny, and the NTP clients you configure will have times that are virtually identical to the time on your primary NTP server. Configuring Windows Clients In principle, Windows computers are no different from Linux computers when it comes to NTP. In practice, though, it may be easier to use a standard Windows command, NET, to set their clocks than to install a full NTP package. You can take the full approach if you prefer, though. This is most likely to be helpful on important servers or if you want the Windows system to function as an NTP server to other clients. Using NET SET The Windows NET command lets you set the Windows computer's clock. In Windows NT/200x/XP, you can use this command to set the clock using NTP with the /SETSNTP:server option, where server is the NTP server's name. For instance, to set the Windows system's clock to the time maintained by the harrison.example.com server, use this command: C:\> NET TIME /SETSNTP:harrison.example.com This command actually uses a simplified variant of the full NTP protocol, known as SNTP. This procedure should be good enough for most purposes. If the computer restarts on a regular basis, you can include a command like this in a batch file that runs when the computer starts. Placing it in the Windows StartUp folder can be a good choice, particularly on desktop computers; this ensures that the script is run on a regular basis. Another option is to place this call in a domain's network logon script. Unfortunately, Windows 9x/Me doesn't accept the /SETSNTP option, so you can't set a Windows 9x/Me computer's clock using an NTP server in this way. You can, though, use a similar command to set the clock using part of the SMB/CIFS protocol suite: C:\> NET TIME \\HARRISON /SET /YES This command sets the computer's time to that maintained on HARRISON. If your main NTP server also runs Samba, this can be a good way to deliver the time to Windows 9x/Me clients. If your primary NTP server doesn't run Samba, but you do run Samba on another computer, you can use this procedure to set the clock from the Samba server, which can use NTP to synchronize its clock to your main NTP server's clock. As with the /SETSNTP variant, you can include this command in a batch file you run from a StartUp folder or network logon script. Windows NT/200x/XP responds to this command as well, so if you want to simplify your configuration task, you can use this SMB/CIFS variant on all your Windows computers. Windows NTP clients Sometimes, only the "real thing" will do. Perhaps you want a Windows computer to function as an NTP server, or you want it to maintain highly accurate time without having to run NET TIME on a periodic basis. In such cases, running a full NTP package on Windows is an option. Even if you don't need a full NTP client/server package, you might want to track down an NTP client for Windows 9x/Me—say, if you don't use SMB/CIFS at all on your network but do want to set Windows 9x/Me systems' clocks. The official NTP software package is available only for Unix and Unix-like systems. However, the NTP protocol has been implemented on many other OSs, either by porting the official package or by writing a new implementation. Microsoft's NET TIME /SETSNTP command is one implementation. Here are some others: - Automachron - This is an SNTP client only, but it runs on all versions of Windows, making it a good choice for Windows 9x/Me clients. This program is free in the sense of no-cost, but it's not open source. Check its home page at for more details. - NetTime - This program, headquartered at, is an open source SNTP client and server for all versions of Windows. This program can run as a service on Windows NT/200x/XP, meaning that it runs at all times, much like the NTP daemon in Linux. Development has officially been abandoned because of Microsoft's inclusion of SNTP support in recent versions of Windows, but NetTime can still be useful if you're running old versions of Windows. - NTP for Windows - The Unix NTP code has been ported to Windows NT/200x/XP and is available, in both source and binary forms, from. If nothing but a full NTP implementation for Windows will do, this package is well worth investigating. However, it doesn't run on Windows 9x/Me. Summary Linux can fill many unglamorous server roles on a network—roles that go largely unnoticed by users but that are vital to a network's normal functioning. A Linux DHCP server can help you automatically configure basic networking features of other computers; a Linux DNS server can convert between hostnames and IP addresses; and a Linux NTP server can help you keep your computers' clocks synchronized. Employing Linux in these roles can simplify your overall network administrative workload or improve your network's functionality.
http://commons.oreilly.com/wiki/index.php?title=Linux_in_a_Windows_World/Additional_Server_Programs/Managing_a_Network_with_Linux&diff=9561&oldid=8783
CC-MAIN-2017-13
refinedweb
12,791
62.27
Button component in Actionscript 3 – part 2 This is a continuation of the previous post on the button component in Actionscript 3.0. In this post I will go into more detail about the button component. For each of the parts below you will need to have the button component in the library by selecting Windows > Components and dragging the component into the library. 1. Dynamically create button component instance The first example will dynamically create a button instance on the stage. You need to have the component in the library panel. //Imports the Button Class. import fl.controls.Button; //This creates a new instance of a button and adds it to the display //list using the addChild() method. var my_Button:Button = new Button(); addChild(my_Button); You should now have a button in the top left corner like below. 2.Setting button position and size The second example will move the button anywhere on the stage using the move() method. This method sets the x & y coordinates of the component. The setSize() method changes the size of the component by adjusting the width and height properties. //Imports the Button Class. import fl.controls.Button; //This creates a new instance of a button. var my_Button:Button = new Button(); //Sets the position and size of component. my_Button.move(20, 20); my_Button.setSize(100, 50); //Adds the component to the display list using the addChild() method. addChild(my_Button); You should get the following result. The button has move to (20,20) on the stage and has a width of 100px and a height of 50px. 3.Change button label The third example will change the text in the button component using the label property. import fl.controls.Button; var my_Button:Button = new Button(); my_Button.move(20, 20); my_Button.setSize(100, 50); my_Button.label = "ilike2flash"; addChild(my_Button); Your button should now have the label “ilike2flash”. 4.Add actions to Buttons The fourth example will add actions to the button by using an eventlistener method with a click event. import fl.controls.Button;Part 3 – Coming soon. var my_Button:Button = new Button(); my_Button.move(20, 20); my_Button.setSize(100, 50); my_Button.label = "ilike2flash"; //Adds the click event to the button. my_Button.addEventListener(MouseEvent.CLICK, myClick); addChild(my_Button); //Function outputs the message hit when the button is clicked. function myClick(event:MouseEvent):void { trace("Hit!"); } 2 comments: I understand how to dynamically add or use the component to add buttons, but it seems that no one explains how to make it so you can add a URL or load a SWF when your button is actually clicked. In AS2 I could easily use the On(Release) statement and simply say, gotoandplay, gotoURL, or loadMovieClip, but with as3 it's so different and I don't understand how to tell my button to do any of these things either using the component or by dynamically creating the button. How did you tell your button to go to the Photobucket URL? @popflier This is very easy. Firstly, take a look at example 4 in the above tutorial. Then look at the Open URL in AS3
http://www.ilike2flash.com/2009/10/button-component-in-actionscript-3-part.html
CC-MAIN-2017-04
refinedweb
517
58.58
Web Service Secrets Introduction Welcome to Web Service Secrets! I'm Karl Moore and this is the twelfth and final installment of the .NET secrets series, the bundle of articles based on my latest book, VB.NET and ASP.NET Secrets. - Five Things You Need to Do Before Publicizing Your Web Service - Improving Performance with Easy Caching - Adding Google Search to Your Programs - View the Real World in Your Application, with TerraServer Of course, these are only teasers—you'll find full versions, plus hundreds more such tricks in the book. But you'll need to cough up a few dollars first. Go on, don't be mean. Ready to begin exploring those nifty little Web service secrets? Top stuff... The Secrets! Five Things You Need to Do Before Publicizing Your Web Service So, you've written the greatest Web service since SlicedBread.asmx, and now you want to tell the whole world about your creation? Well, before you do, ensure you follow this list of five quick changes that will give your service that professional touch: - Rename Your Class. Nobody likes dealing with a Web service called Service1, so, before you redistribute, make sure that you rename your class from something like Public Class Service1 to something like Public Class Customer. Or something. - Christen Your ASMX File. You've renamed your Web service so it sounds all professional, but your clients are still accessing your Service via the file. Eugh. To combat this, simple rename your ASMX file by right-clicking on it in the Solution Explorer and selecting Rename. - Add a Service Description. What does your Web service do? Provide access to your customer database or allow you to send SMS messages? Well, you could just let your clients guess. However, a more user-friendly technique would be to add a description to the <WebService> attribute. So, before distributing, change your class as follows: <WebService(Description:="This class does amazing things _ with data.")> _ Public Class AmazingData ' ... etc ... End ClassThis description is used in the automatically generated Web interface, plus is automatically absorbed by all clients using your service and utilized in the Visual Studio .NET programming environment. - Add Method Descriptions. Just as your service can include a description, so can your individual methods and functions. Again, this is used by the Web interface and Visual Studio .NET. And, again, it's simple to implement: Just add a description to each <WebMethod> attribute, like so: <WebMethod(Description:="Returns the current server date _ and time.")> _ Public Function GetServerDate() As Date Return Now End Function - Change the Namespace. You've already seen the .NET Framework organizing functionality into "namespaces." They're just unique identifiers for a certain set of functionality. That's all a namespace is here, too: a unique string that identifies this Web service. By default, VS.NET uses, and you will need to change this to a unique value. The namespace you provide doesn't necessarily have to point to anything on the Web, but if it does, I'd recommended that you at least own the domain you use (ahem). So, change the namespace to something unique before unveiling your service by altering the Namespace property of the <WebService> attribute, as so: <WebService(Description:="Yadda", _ Namespace:="")> _ Public Class AmazingData ' ... etc ... End Class Improving Performance with Easy sixty seconds after the last query. You can check out this cute tip in action by returning the time from a function. See what happens? Adding Google Search to Your Programs It started off as "that nerdy site with the funny name" and ended up as the world's number one search engine. Yes, it's Google at—an intelligent, easy-to-use searchable archive of over two billion Web pages. And thanks to the world of Web services, you can plug your application into this mass of knowledge—with just a few lines of code. How? First off, you'll need to check out for information on the process. The main thing you'll want to do here it create a Google account. You'll be asked for your e-mail address and other details—in return, you'll be provided with a license key. You need to use this when accessing the service.Got your license key? Then fire up Visual Studio .NET and create a new project, such as a Windows application. Select Project > Add Web Reference and type in the URL of the Google .WSDL (Web Service Definition Language) file— as listed on the Google site—then press Return. Click 'Add Reference' when the button becomes available. And now? Simply start using the service! To get you started, let's review a little sample code. Here's my own attempt at performing a simple search, returning a maximum of ten items for the term 'Karl Moore' (I know, narcissistic): ' Create a new Google search object Dim objSearch As New _ com.google.api.GoogleSearchService() ' Invoke the search method Dim objResults As _ com.google.api.GoogleSearchResult = _ objSearch.doGoogleSearch( _ "license-key-goes-here1Ga0szyTgT0K3r2Oq5pAMSvX1SYGvNYl", _ "Karl Moore", 0, 10, False, "", False, _ "", "", "") ' Loop through result elements Dim shtCount As Short For shtCount = 0 To objResults.endIndex - 1 MessageBox.Show(objResults.resultElements(shtCount).title & _ " - " & objResults.resultElements(shtCount).URL) Next Top Tip: The Google service will include <b> bold tags around text that you search for. This doesn't matter if you're developing for Web applications, where highlighting searched-for terms is actually quite user friendly. For Windows applications, however, that don't use HTML tags, you'll want to strip these out using a custom algorithm or regular expression (check out my "Converting HTML to Text, Easily" tip in the "More .NET Secrets" chapter of my book, VB.NET and ASP.NET Secrets for a ready-to-run algorithm). So, that's a regular search. But there's more. Regular users of Google will know that when you accidentally mistype a search term, the engine will suggest a possible correct spelling. You can access that exact functionality through your Web service too, as so: ' Create a new Google search object Dim objSearch As New _ com.google.api.GoogleSearchService() ' Retrieve the suggest spelling, if any Dim strSuggestion As String strSuggestion = objSearch.doSpellingSuggestion( _ "license-key-goes-here1Ga0szyTgT0K3r2Oq5pAMSvX1SYGvNYl", _ "Britnee Speyers") MessageBox.Show(strSuggestion) Thought that was it? You also can retrieve cached versions of a page (alongside the Google "this is a cached page, click here for the latest version, etc." HTML). Here's a little sample code: ' Create a new Google search object Dim objSearch As New _ com.google.api.GoogleSearchService() ' Retrieve cached version of a page Dim bytPage() As Byte = _ objSearch.doGetCachedPage( _ "license-key-goes-here1Ga0szyTgT0K3r2Oq5pAMSvX1SYGvNYl", _ "") ' Convert base 64 byte array to string Dim strHTML As String = _ System.Text.ASCIIEncoding.ASCII.GetString(bytPage) MessageBox.Show(strHTML) Here, I've simply demonstrated the three core features of the Web service; however, by downloading the Developer's Toolkit above, you can really delve into any of these areas. By filling out a few of the extra . doGoogleSearch parameters, for example, you can restrict results to a particular language, search within a particular topic, or alter the number of returned results. Be sure to check it out. Also, it's worthwhile noting that at the time of writing, the Google Web service was still in beta. It is, however, unlikely that Google will change the interface definitions (a prediction based on the way it has continued to keep certain redundant properties available, even though still in beta—a sure sign of a user-conscious organization, if not one lacking in a little foresight). In addition, be aware that (again at the time of writing) you are limited to 1,000 searches per day, per license key and that no commercial pay-per-search facility is yet available. Plugging directly into the power that is Google, through Web services Page 1 of 2
http://www.developer.com/net/asp/article.php/2222811/Web-Service-Secrets.htm
CC-MAIN-2015-11
refinedweb
1,326
65.52
Xacobeo::UI::DomView - DOM tree view use Xacobeo::DomView; use Xacobeo::UI::SourceView; my $view = Xacobeo::UI::SourceView->new(); $window->add($view); # Load a document my $document = Xacobeo::Document->new_from_file($file, $type); $view->set_document($document); $view->load_node($document->documentNode); The application's main window. This widget is a Gtk2::TreeView. The following properties are defined: The UI Manager used by this widget. The action group that provides the values in the context menu. The context menu of the widget. The document being displayed. The namespaces registered in the document. The following methods are available: Creates a new instance. This is simply the parent's constructor. Sets the tree view nodes hierarchy based on the given node. This is the method that will actually add items to the widget. Parameters: The node to be loaded into the tree widget;.
http://search.cpan.org/~potyl/Xacobeo-0.15/lib/Xacobeo/UI/DomView.pm
CC-MAIN-2015-32
refinedweb
138
53.07
Sometimes its desirable to have access to a web control that is not available in the control panel shipped with Visual Studio. Luckily, Visual Studio gives you some capability to create your own web user controls if you need them. One of our C# Corner readers gave me the idea of converting my Add/Remove Control from a Windows Form control to a User Web Control, so we will use this control as an example for this tutorial. The first step in demonstrating how to create a Web User Control is to create a new Web Application. Creating Web Apps is performed simply by going to the New-->Project menu item, and choosing a new ASP.NET Web Application. Once we've created the application that will be running our Web User Control, we can actually create our Web User control and drag it directly into our Web Application. Figure 1 - Add/Remove Web User Control in Internet Explorer Begin by choosing right clicking on the Solution Explorer and Choosing Add-->Add Web User Control as shown in Figure 2: Figure 2 - Creating a Web User Control inside our Web App This menu Item will bring up the Add New Item dialog with a default user control. Simply change the name of the control to the desired name of the control (in our case the AddRemoveControl). Note that all Web User controls contain the file extension ascx. Figure 3 - Choosing the Web User Control Template Once we've clicked the Open button, this places the Web User Control in our solution explorer where we can work with it: Figure 4 - The Web User Control File appearing in the Solution Explorer Double clicking on the ascx file in the solution explorer gives us a design view in which we can put generic html and web form controls into our Web User Control simply by dragging them from the Control Panel. Below is the group of controls we placed from the control panel onto our Add/Remove Web User Control. You can't see it here, but the controls are placed in an html table consisting of a single row and three columns. Figure 5 - Controls added to the Web User Control Design View Now we need to place the web user control inside our web application. Placing the user control is again a trivial task made easy by the Design View. Simply drag the AddRemoveControl.ascx file from the solution explorer onto the WebForm we want to populate. Note The Web User Control appears with the ID of the control in a gray box on the design form. Figure 6 - User Control Appearing in the Web Form Page Unfortunately the task is not completely automated. In order to use the User Control inside the Form we also need to add a declaration statement that matches the exact name of the user control class and the ID of the control. I'm not sure why Microsoft didn't automatically generate this line of code for us, but I suspect in the future they will. Below is the line of code placed in the WebForm1.aspx.cs code- behind of our web page: Listing 1 - Declaration for the Add/Remove Web User Control in the Web Form Page public class WebForm1 : System.Web.UI.Page{ Now we need to fill in the web user control itself with some useful functionality. Most of the functionality could actually be taken out of my previous article on the Window Form User Control. For the most part, all I needed to do was drag the contents of the Windows User Control methods into the AddRemoveControl.ascx.cs file. The windows controls behave almost identical to the web form controls down to the method name. Unfortunately, the Window Form property and method set for ListBoxes is much richer, so this example is only for a single selection Add/Remove control. What I couldn't quite understand was although it is possible to set up the Web Form ListBox for multiple selection, there didn't seem to be many properties that support multiple section. Also, the ListBox didn't seem to respond to the SelectionChange event when clicking the mouse on the ListBox, so I was forced to forgo some of the control logic. Despite these minor kinks, I was able to reproduce most of the behavior of the Add/Remove Control. Below is a sample event handler that demonstrates the code executed when the Add Button is pressed. Listing 2 - Add Button Event Handler in the Web User Control private It seems like Microsoft did a good job mirroring the architecture of projects between Windows and the Web with .NET. In this way, if you learn to program the Windows architecture, programming the same application for the Web is not a big leap. Also the symmetry between the class libraries for the web controls and the window controls makes porting your apps from Windows to the Web a lot easier than it used to be. The addition of both the Windows User Control and the Web User Control gives you a powerful way to create custom controls that you can reuse throughout your particular organization. View All
http://www.c-sharpcorner.com/article/creating-a-web-user-control-in-net/
CC-MAIN-2017-22
refinedweb
869
56.18
Object detection using OpenCV Hello everyone, I'm trying to do pattern recognition from some images and it's not working. I have my drone with a bottom camera, and the camera is connected to a ROS node. Using cv_bridge I converted the image from a ROS format to an OpenCV format, but what I have to do now is to detect if a determined pattern (learned previously) is in the image. In the ROS node it appears a different image each 0.02 second (I can change the frequency). The pattern will stay on the floor, so what can be done is to detect the variance of the image (for example, the floor or the sea will have low variance, and the pattern that I set on the floor will have high variance (for example, a pattern like a chess table)). This is the code that I'm using (...): #include <ros/ros.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> static const std::string OPENCV_WINDOW = "Image window"; class ImageConverter { ros::NodeHandle nh_; image_transport::ImageTransport it_; image_transport::Subscriber image_sub_; image_transport::Publisher image_pub_; public: ImageConverter() : it_(nh_) { // Subscrive to input video feed and publish output video feed image_sub_ = it_.subscribe("/camera/image_raw", 1, &ImageConverter::imageCb, this); image_pub_ = it_.advertise("/image_converter/output_video", 1); cv::namedWindow(OPENCV_WINDOW); } ~ImageConverter() { cv::destroyWindow(OPENCV_WINDOW); } void imageCb(const sensor_msgs::ImageConstPtr& msg) { cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } // Draw an example circle on the video stream if (cv_ptr->image.rows > 60 && cv_ptr->image.cols > 60) cv::circle(cv_ptr->image, cv::Point(50, 50), 10, CV_RGB(255,0,0)); // Update GUI Window cv::imshow(OPENCV_WINDOW, cv_ptr->image); cv::waitKey(3); // Output modified video stream image_pub_.publish(cv_ptr->toImageMsg()); } }; int main(int argc, char** argv) { ros::init(argc, argv, "image_converter"); ImageConverter ic; ros::spin(); return 0; } but that code just prints the image and puts a red circle on the upper left corner, so what has to be modified is this part: // Draw an example circle on the video stream if (cv_ptr->image.rows > 60 && cv_ptr->image.cols > 60) cv::circle(cv_ptr->image, cv::Point(50, 50), 10, CV_RGB(255,0,0)); I would like if you can help me. This is just the beginning of the project, then I have to take decisions in order to what is seen, and so on. If you don't have a code that does what I need, please provide me some links or books or whatever that can help me (I've been 2 days trying to make this work and I couldn't). EDIT: So I need your help in the OpenCV part (if you know about ROS it would be much better, but I can try to do the translation between OpenCV and ROS): imagine that a different image come to your program each 0.02 seconds and you ... (more) unfortunately, noone can solve ROS problems from here ;( we can help you if you maybe more focus on the opencv part. then, "object detection" is far too broad, to be useful. can you narrow it down ? maybe also showing an example image would be helpful. Thanks for your answer. I edited the main post, so I hope it's more clear now :)
https://answers.opencv.org/question/196075/object-detection-using-opencv/
CC-MAIN-2019-35
refinedweb
563
55.84
Update, March 25, 2019: The latest Volta and Turing GPUs now incoporate Tensor Cores, which accelerate certain types of FP16 matrix math. This enables faster and easier mixed-precision computation within popular AI frameworks. Making use of Tensor Cores requires using CUDA 9 or later. NVIDIA has also added automatic mixed precision capabilities to TensorFlow, PyTorch, and MXNet. Interested in learning more or trying it out for yourself? Get tensor core optimized examples for popular AI frameworks here. architecture and CUDA 8, NVIDIA is expanding the set of tools available for mixed-precision computing with new 16-bit floating point and 8/16-bit integer computing capabilities. “As the relative costs and ease of computing at different precisions evolve, due to changing architectures and software, as well as the disruptive influence of accelerators such as GPUs, we will see an increasing development and use of mixed precision algorithms.” — Nick Higham, Richardson Professor of Applied Mathematics, University of Manchester Many technical and HPC applications require high precision computation with 32-bit (single float, or FP32) or 64-bit (double float, or FP64) floating point, and there are even GPU-accelerated applications that rely on even higher precision (128- or 256-bit floating point!). But there are many applications for which much lower precision arithmetic suffices. than FP32 or FP64 transfers. Moreover, for many networks deep learning inference can be performed using 8-bit integer computations without significant impact on accuracy. In addition to deep learning, applications that use data from cameras or other real-world sensors often don’t require high-precision floating point computation, because the sensors generate low-precision or low dynamic range data. The data processed from radio telescopes is a good example. As you’ll see later in this post, the cross correlation algorithm used for processing data from radio telescopes can be greatly accelerated by using 8-bit integer computation.). The new NVIDIA Tesla P100, powered by the GP100 GPU, can perform FP16 arithmetic at twice the throughput of FP32. The GP102 (Tesla P40 and NVIDIA Titan X), GP104 (Tesla P4), and GP106 GPUs all support instructions that can perform integer dot products on 2- and4-element 8-bit vectors, with accumulation into a 32-bit integer. These instructions are valuable for implementing high-efficiency deep learning inference, as well as other applications such as radio astronomy. In this post I will provide some details about half-precision floating point, and provide details about the performance achievable on Pascal GPUs using FP16 and INT8 vector computation. I will also discuss the mixed-precision computation capabilities provided by various CUDA platform libraries and APIs. A Bit (or 16) about Floating Point Precision As every computer scientist should know, floating point numbers provide a representation that allows real numbers to be approximated on a computer with a tradeoff between range and precision. Floating point numbers approximate the real value to a set number of significant digits, known as the mantissa or significand, and then scaled by an exponent in a fixed base (base 2 for IEEE standard floating point numbers used on most computers today). Common floating point formats include 32-bit, known as “single precision” (`float` in C-derived programming languages), and 64-bit, known as “double precision” (`double`). As defined by the IEEE 754 standard, a 32-bit floating point value comprises a sign bit, 8 exponent bits, and 23 mantissa bits. A 64-bit double comprises a sign bit, 11 exponent bits, and 52 mantissa bits. In this post, we’re interested in the (newer) IEEE 754 standard 16-bit floating half type, which comprises a sign bit, 5 exponent bits, and 10 mantissa bits, as Figure 1 shows.. So why use a small floating-point format like FP16? In a word, performance. The NVIDIA Tesla P100 (based on the GP100 GPU) supports a 2-way vector half-precision fused multiply-add (FMA) instruction (opcode HFMA2), which it can issue at the same rate as 32-bit FMA instructions. This means that half-precision arithmetic has twice the throughput of single-precision arithmetic on P100, and four times the throughput of double precision. Specifically, the NVLink-enabled P100 (SXM2 module) is capable of 21.2 Teraflop/s of half-precision. With such a big performance benefit, it’s worth looking at how you can use it. One thing to keep in mind when using reduced precision is that because the normalized range of FP16 is smaller, the probability of generating subnormal numbers (also known as denormals) increases. Therefore it’s important that NVIDIA GPUs implement FMA operations on subnormal numbers with full performance. Some processors do not, and performance can suffer. (Note: you may still see benefits from enabling “flush to zero”. See the post “CUDA Pro Tip: Flush Denormals with Confidence”.) High Performance with Low-Precision Integers Floating point numbers combine high dynamic range with high precision, but there are also cases where dynamic range is not necessary, so that integers may do the job. There are even applications where the data being processed has low precision so very low-precision storage (such as C short or char/byte types) can be used. For such applications, the latest Pascal GPUs (GP102, GP104, and GP106) introduce new 8-bit integer 4-element vector dot product (DP4A) and 16-bit 2-element vector dot product (DP2A) instructions. DP4A performs the vector dot product between two 4-element vectors A and B (each comprising 4 single-byte values stored in a 32-bit word), storing the result in a 32-bit integer, and adding it to a third argument C, also a 32-bit integer. See Figure 2 for a diagram. DP2A is a similar instruction in which A is a 2-element vector of 16-bit values and B is a 4-element vector of 8-bit values, and different flavors of DP2A select either the high or low pair of bytes for the 2-way dot product. These flexible instructions are useful for linear algebraic computations such as matrix multiplies and convolutions. They are particularly powerful for implementing 8-bit integer convolutions for deep learning inference, common in the deployment of deep neural networks used for image classification and object detection. Figure 3 shows the improved power efficiency achieved on a Tesla P4 GPU using INT8 convolution on AlexNet. DP4A computes the equivalent of a total of eight integer operations, and DP2A computes four. This gives the Tesla P40 (based on GP102) a peak integer throughput of 47 TOP/s (Tera operations per second). An example application of DP4A is the cross-correlation algorithm commonly used in radio telescope data processing pipelines. As with optical telescopes, larger radio telescopes can resolve fainter and more distant objects in the cosmos; but building larger and larger monolithic single-antenna radios radio telescopes is not practical. Instead, radio astronomers build arrays of many antennae spread over a large area. To use these telescopes, the signals from all the antennae must be cross-correlated—a highly parallel computation with cost that scales quadratically with the number of antennas. Since radio telescope elements typically capture very low precision data, floating-point computation is not needed for cross correlation of the signals. GPUs have already been used in production radio astronomy cross correlation, but they have typically used FP32 computation. The introduction of DP4A promises much higher power efficiency for this computation. Figure 4 shows the results of modifying a cross-correlation code to use DP4A, resulting in a 4.5x efficiency improvement on a Tesla P40 GPU with default clocks (compared to FP32 computation on P40), and a 6.4x improvement with GPU clocks capped to reduce temperature (and therefore reduce leakage current). Overall, the new code is nearly 12x more efficient than FP32 cross-correlation on the previous-generation Tesla M40 GPU (credit: Kate Clark). Mixed Precision Performance on Pascal GPUs The half precision (FP16) Format is not new to GPUs. In fact, FP16 has been supported as a storage format for many years on NVIDIA GPUs, mostly used for reduced precision floating point texture storage and filtering and other special-purpose operations. The Pascal GPU architecture implements general-purpose, IEEE 754 FP16 arithmetic. High performance FP16 is supported at full speed on Tesla P100 (GP100), and at lower throughput (similar to double precision) on other Pascal GPUs (GP102, GP104, and GP106), as the following table shows. The 8-bit and 16-bit DP4A and DP2A dot product instructions are supported on GP102-GP106, but not on GP100. Table 1 shows the arithmetic throughput of the different numerical instructions on Pascal-based Tesla GPUs. Mixed-Precision Programming with NVIDIA Libraries The easiest way to benefit from mixed precision in your application is to take advantage of the support for FP16 and INT8 computation in NVIDIA GPU libraries. Key libraries from the NVIDIA SDK now support a variety of precisions for both computation and storage. Table 2 shows the current support for FP16 and INT8 in key CUDA libraries as well as in PTX assembly and CUDA C/C++ intrinsics. cuDNN cuDNN is a library of primitive routines used in training and deploying deep neural networks. cuDNN 5.0 includes FP16 support for forward convolution, and 5.1 added support for FP16 backward convolution. All other routines in the library are memory bound, so FP16 computation is not beneficial to performance. Therefore these routines use FP32 computation but support FP16 data input and output. cuDNN 6 will add support for INT8 inference convolutions. TensorRT TensorRT is a high-performance deep learning inference engine for production deployment of deep learning applications that automatically optimizes trained neural networks for run-time performance. TensorRT v1 has support for FP16 for inference convolutions, and v2 will support INT8 for inference convolutions. cuBLAS cuBLAS is a GPU library for dense linear algebra— an implementation of BLAS, the Basic Linear Algebra Subroutines. cuBLAS has support for mixed precision in several matrix-matrix multiplication routines. cublasHgemm is a FP16 dense matrix-matrix multiply routine that uses FP16 for compute as well as for input and output. cublasSgemmEx() computes in FP32, but the input data can be FP32, FP16, or INT8, and the output can be FP32 or FP16. cublasGemm() is a new routine in CUDA 8 that allows specification of the computation precision, including INT8 computation (which uses DP4A). Support for more BLAS level 3 routines with FP16 computation and/or storage will be added based on demand, so please contact us if you need them. Level 1 and level 2 BLAS routines are memory bound, so reduced precision computation is not beneficial. cuFFT cuFFT is a popular Fast Fourier Transform library implemented in CUDA. Starting in CUDA 7.5, cuFFT supports FP16 compute and storage for single-GPU FFTs. FP16 FFTs are up to 2x faster than FP32. FP16 computation requires a GPU with Compute Capability 5.3 or later (Maxwell architecture). Sizes are restricted to powers of 2 currently, and strides on the real part of R2C or C2R transforms are not supported. cuSPARSE cuSPARSE is a library of GPU-accelerated linear algebra routines for sparse matrices. cuSPARSE supports FP16 storage for several routines (`cusparseXtcsrmv()`, `cusparseCsrsv_analysisEx()`, `cusparseCsrsv_solveEx()`, `cusparseScsr2cscEx()`, and `cusparseCsrilu0Ex()`). FP16 computation for cuSPARSE is being investigated. Please contact us via the comment form if you have specific needs. Using Mixed Precision in your own CUDA Code For developers of custom CUDA C++ kernels and users of the Thrust parallel algorithms library, CUDA provides the type definitions and APIs you need to get the most out of FP16 and INT8 computation, storage, and I/O. FP16 types and intrinsics For FP16, CUDA defines the `half` and `half2` types in the header `cuda_fp16.h` included in the CUDA include path. This header also defines a complete set of intrinsic functions for operating on `half` data. As an example, the following shows the declarations of the scalar FP16 addition function, `hadd()` and the 2-way vector FP16 addition function, `hadd2()`. __device__ __half __hadd ( const __half a, const __half b ); __device__ __half2 __hadd2 ( const __half2 a, const __half2 b ); `cuda_fp16.h` defines a full suite of half-precision intrinsics for arithmetic, comparison, conversion and data movement, and other mathematical functions. All are described in the CUDA Math API documentation. Use `half2` vector types and intrinsics where possible achieve the highest throughput. The GPU hardware arithmetic instructions operate on 2 FP16 values at a time, packed together in 32-bit registers. The peak throughput numbers in Table 1 assume `half2` vector computation. If you use scalar `half` instructions, you can achieve 50% of the peak throughput. Likewise, achieving maximum bandwidth when loading from and storing to FP16 arrays requires vector access of `half2` data. Ideally, you can vectorize loads further to achieve even higher bandwidth by loading and storing `float2` or `float4` types and casting to/from `half2`. See past Parallel Forall Pro Tip blog post for related examples. The following example code demonstrates the use of CUDA’s __hfma() (half-precision fused multiply-add) and other intrinsics to compute a half-precision AXPY (A * X + Y). The complete code for the example is available on Github, and it shows how to initialize the half-precision arrays on the host. Importantly, when you start using half types you are likely to need to convert between half and float values in your host-side code. This blog post from Fabian Giesen includes some fast CPU type conversion routines (see the associated Gist for full source). I used some of Giesen’s code for this example. __global__ void haxpy(int n, half a, const half *x, half *y) { int start = threadIdx.x + blockDim.x * blockIdx.x; int stride = blockDim.x * gridDim.x; #if __CUDA_ARCH__ >= 530 int n2 = n/2; half2 *x2 = (half2*)x, *y2 = (half2*)y; for (int i = start; i < n2; i+= stride) y2[i] = __hfma2(__halves2half2(a, a), x2[i], y2[i]); // first thread handles singleton for odd arrays if (start == 0 && (n%2)) y[n-1] = __hfma(a, x[n-1], y[n-1]); #else for (int i = start; i < n; i+= stride) { y[i] = __float2half(__half2float(a) * __half2float(x[i]) + __half2float(y[i])); } #endif } Integer Dot Product Intrinsics CUDA defines intrinsics for 8-bit and 16-bit dot products (the DP4A and DP2A instructions described previously) in the header `sm_61_intrinsics.h` (sm_61 is the SM architecture corresponding to GP102, GP104, and GP106. Also known as Compute Capability 6.1). For convenience, there are both `int` and `char4` versions of the DP4A intrinsics, in both signed and unsigned flavors: __device__ int __dp4a(int srcA, int srcB, int c); __device__ int __dp4a(char4 srcA, char4 srcB, int c); __device__ unsigned int __dp4a(unsigned int srcA, unsigned int srcB, unsigned int c); __device__ unsigned int __dp4a(uchar4 srcA, uchar4 srcB, unsigned int c); Both versions assume that the four vector elements of A and B are packed into the four corresponding bytes of a 32-bit word. The `char4` / `uchar4` versions use CUDA’s struct type with explicit fields, while the packing is implicit in the `int` versions. As mentioned previously, DP2A has a “high” and a “low” version for selecting either the high or low two bytes of input B, respectively. // Generic [_lo] __device__ int __dp2a_lo(int srcA, int srcB, int c); __device__ unsigned int __dp2a_lo(unsigned int srcA, unsigned int srcB, unsigned int c); // Vector-style [_lo] __device__ int __dp2a_lo(short2 srcA, char4 srcB, int c); __device__ unsigned int __dp2a_lo(ushort2 srcA, uchar4 srcB, unsigned int c); // Generic [_hi] __device__ int __dp2a_hi(int srcA, int srcB, int c); __device__ unsigned int __dp2a_hi(unsigned int srcA, unsigned int srcB, unsigned int c); // Vector-style [_hi] __device__ int __dp2a_hi(short2 srcA, char4 srcB, int c); __device__ unsigned int __dp2a_hi(ushort2 srcA, uchar4 srcB, unsigned int c); Keep in mind that DP2A and DP4A are available on Tesla, GeForce, and Quadro accelerators based on GP102, GP104, and GP106 GPUs, but not on the Tesla P100 (based on the GP100 GPU). Download CUDA 8 Today To get the most out of mixed-precision computing on GPUs, download the free NVIDIA CUDA Toolkit version 8. To learn about all the powerful features of CUDA 8, check out the post CUDA 8 Features Revealed. To learn more about all the performance improvements in CUDA 8 and the latest GPU-accelerated libraries, join us for the free overview session about CUDA 8 Toolkit Performance to be presented on Thursday, November 3.
https://devblogs.nvidia.com/mixed-precision-programming-cuda-8/
CC-MAIN-2020-24
refinedweb
2,736
50.87
Building a Real-time Short News App using HuggingFace Transformers and Streamlit This article was published as a part of the Data Science Blogathon. Introduction News apps are one of the most downloaded apps and also they have huge traffic. Everyone is interested in knowing about the things happening in the world. But they may not have the time to go through those lengthy news articles and they may like to know the crux of the article without missing details. The latest developments in the field of artificial intelligence have made such a thing reality. Today people can read a summary of an entire news article in just two or three lines and understand all the details about the article. Text Summarization is one such task in Natural Language Processing that can enable us to build such short news summaries. There are many famous apps like Inshorts that leverage Artificial Intelligence to deliver short news articles in their app. In this article, we shall see how to build such an app using Streamlit and HuggingFace transformers and we will also deploy that app on stream cloud. To fetch news into our app we will use Free News API by Newscatcher. Overview - Free News API - Newspaper3k - HuggingFace Transformers - Streamlit - Application setup - Building our Application - Testing - Deploying - Conclusion Free News API Free News API is provided by Newscatcher. It helps us fetch live news based on several input parameters. Unlike many news APIs that are available on the internet, it is free to use. It aggregates news from over 60,000 news websites with up to 15,00,000 news articles daily. The basic version of this API has limited ability. We can not fetch news based on country or given category. But we can make unlimited API calls to fetch news. In this project, we will use the basic version as it is free. Newspaper3k for extracting News Articles Newspaper3k is a python library for extracting and curating news articles from the internet. It’s a very useful library to deal with news article links and also extract all the metadata of a news article. In this project, we will use this library to get the news article. HuggingFace Transformers for Summarizing News Articles We will use the transformers library of HuggingFace. This library provides a lot of use cases like sentiment analysis, text summarization, text generation, question & answer based on context, speech recognition, etc. We will utilize the text summarization ability of this transformer library to summarize news articles. Streamlit for deploying the News App Streamlit is an open-source python library for building Data science and machine learning apps fastly. We can use this to prototype our data science apps quickly. Streamlit is also very easy to learn. It is good to have this skill to test our app before we take it to production. We can also build an analytics dashboard using this library. Streamlit also offers cloud services where we can deploy our apps. In this project, we will deploy our app on the Streamlit cloud. Application Setup Our application works as per the process shown in the below figure In other words, - Get news from the internet using Free News API - Extract the news link and send it to the newspaper3k library to download the news article - Pass the resulting article through the transformers pipeline to get the summarized version of the article. - Finally, display the News title and summarized article to the user in a streamlit UI Let’s start building our app!! Building our News Application for Discord First, let’s install all necessary libraries pip install streamlit pip install transformers pip install json pip install requets pip install newspaper3k Now we import all the installed libraries as follows import streamlit as st from transformers import pipeline import json import requests from newspaper import Article Before we code our app we need to get an API to fetch news links based on our search from the internet. As discussed earlier we will be using Free news API to get that link. So for this, we get an API from this link. Follow the steps given in the link to get the API. If you have doubts please comment below so that I can clear your doubts. Now that we have installed and imported all necessary libraries and also got our API key, we code our Streamlit app in the following way. The final code looks like below – import streamlit as st import json import requests from newspaper import Article from transformers import pipeline st.set_page_config(page_title='Short News App', layout='wide', initial_sidebar_state = 'expanded') st.title('Welcome to Short News App n Tired of reading long articles? This app summarizes news articles for you and gives you short crispy to the point news based on your search n (This is a demo app and hence is deployed on a platform with limited computational resources. Hence the number of articles this app can fetch is limited to 5)') summarizer = pipeline("summarization") article_titles = [] article_texts = [] article_summaries = [] def run(): with st.sidebar.form(key='form1'): search = st.text_input('Search your favorite topic:') submitted = st.form_submit_button("Submit") if submitted: try: url = " querystring = {"q":search, "lang":"en", "page":1, "page_size":5} headers = {'x-rapidapi-host':"free-news.p.rapidapi.com", 'x-rapidapi-key':"your_api_key"} response = requests.request("GET", url, headers=headers, params = querystring) response_dict = json.loads(response.text) links = [response_dict['articles'][i]['link'] for i in range(len(response_dict['articles']))] for link in links: news_article = Article(link, language = 'en') news_article.download() news_article.parse() article_titles.append(news_article.title) article_texts.append(news_article.text) for text in article_texts: article_summaries.append(summarizer(text)[0]['summary_text']) except: print("Try with new search") for i in range(len(article_texts)): st.header(article_titles[i]) st.subheader('Summary of Article') st.markdown(article_summaries[i]) with st.expander('Full Article'): st.markdown(article_texts[i]) if __name__=='__main__': run() Explanation of the above code - First, we import all necessary libraries. - Then we set the page configuration of our app using st.set_page_config(). We give all parameters as shown in the above code. - Next, we give a title of our app using st. title() as shown in the code. You can give your title and explanation as shown in the above code. - Now we define three empty lists to store our article titles, article texts, and their corresponding summaries for final display. Next, we create a sidebar in our app for searching the desired topic. We create this search form using st.sidebar().form() of Streamlit as shown in the above code and also we create a submit button using st.form_submit_button(). - So now if the user enters a search term and clicks submit button we have to fetch news articles and display their summaries. We do that as follows – - First, we get our API URL. - We give our query parameters like search term, language, number of pages, and number of articles per page. - Create headers for API as shown code. - Using requests library we fetch data from the internet using our query parameters and headers. - We convert the request object from the above step into a dictionary using JSON. - Next, we extract the links from the dictionary metadata we obtained from the internet using requests. - For each link we have, we use the newpaper3k library to get the article title and article text and append them into the corresponding empty lists we defined earlier. - Now that we have article titles, article texts we get our summaries for each article using transformers summarization pipeline as shown in the above code. - Now we have article titles, article texts, and their corresponding summaries. So we display the article using st.header() and we display the summary of the article using st.markdown(). Before that we create a heading ‘Summary of Article’ and then we display the news summary under this. - Finally, if the user wants to read the full article, we also give an option to look at the full article using st.expander(). This expander widget of streamlit hides the content in it and displays the content only when the user clicks to expand. Testing We built our app. Save the code in a .py file and open the terminal. Type streamlit run your_app_name.py in the terminal and press enter. You will see a new tab in your browser with your app. Deploying We built and tested our app. It’s time to deploy it. We will deploy this on Streamlit cloud. Streamlit offers to host three apps for free on its cloud. Go to this link of Streamlit sharing and create an account if you don’t have one already. After you create an account and sign in you will see a web page with the option ‘New App’. Click on it. It will ask you to connect to a Github repository. So create a Github repository of your app and upload the .py file we just created. We also need a requirements.txt. So create a file with the name ‘requirements.txt’ and type the following in that file, streamlit transformers tensorflow requests newspaper3k save the file and commit changes to your repository. Now come to the Streamlit sharing website and connect your newly created Github repository and click deploy. Streamlit does the rest of the work for us and deploys our app. Finally, our app will look like this – You can search the news for your favorite celebrity and get a summarized version of each article. Try this app I created here Short News App · Streamlit Conclusion We successfully built our short news app leveraging AI capabilities. AI has made our life simple. More features can be added to this app. Try it. Read my other articles here – - Live Twitter Sentiment Analyzer with Streamlit, Tweepy and Huggingface (analyticsvidhya.com) - NeatText Library | Pre-processing textual data with NeatText library (analyticsvidhya.com) Image sources: Image-1: Image-2: Leave a Reply Your email address will not be published. Required fields are marked *
https://www.analyticsvidhya.com/blog/2021/11/building-a-real-time-short-news-app-using-huggingface-transformers-and-streamlit/
CC-MAIN-2022-21
refinedweb
1,661
56.96
This is more to be filed under “I don’t want to have to search the wabz for this again so I’m using my blog to post something so I don’t have to”, but if someone else in this world gets something from this, then well someone else in the world gets something from this. As I’m the only person I care about, helping myself is about as far as my concern goes. This is really simple: import datetime from datetime def someMethod(): currentSecond= datetime.now().second currentMinute = datetime.now().minute currentHour = datetime.now().hour currentDay = datetime.now().day currentMonth = datetime.now().month currentYear = datetime.now().year And actually there is one more if you print out datetime.now(): 2010-09-24 10:06:06.599000 That .599000 is called microsecond: datetime.now().microsecond Anyhow, thanks for playing. 4 thoughts on “Python: Getting the Current Year, Day, Month, Hour, Minute, Second… Even Microsecond? EH?” Do you mean “from datetime import datetime”? It has to be. its ” from datetime import datetime “
https://byatool.com/uncategorized/python-getting-the-current-year-day-month-hour-minute-second-even-microsecond-eh/
CC-MAIN-2021-31
refinedweb
173
70.5
You need to explicitly set an XML Schema type, but there's no way to tell ext/soap how to set that value through a normal PHP data structure. Create a SOAPVar and pass the type and namespace in the constructor: $ns = ''; $job = new SOAPVar($data, SOAP_ENC_OBJECT, 'CustomReportJob', $ns); $response = $client->scheduleReportJob(array('job' => $job)); This creates XML that looks like: <ns1:job xsi: ... </ns1:job> Where the ns1 namespace prefix is. The SOAP extension exposes a number of classes to help you create the data that you pass into SOAP clients. These are rarely necessary when you're using a WSDL file. However, sometimes it's unavoidable. One such case is when you must set an XML Schema type attribute. SOAP uses XML Schema as its behind-the-scenes way of encoding data using XML. One feature of XML Schema is the ability to define the type of structure. Normally, this is one of the built-in XML Schema types, such as a string, integer, or object. However, you can extend XML Schema to create custom types. When a service requires a custom type, you must set it using the SOAPVar class. This class takes six parameters. The first four are most important here. They are the data to be sent, the general class of XML Schema type, the name of the value assigned to the xsi:type attribute, and the namespace that value lives in. For example, here's a piece of code that creates a CustomReportJob for the Google AdWords reporting web services: $ns = ''; $job = new SOAPVar($data, SOAP_ENC_OBJECT, 'CustomReportJob', $ns); $response = $client->scheduleReportJob(array('job' => $job)); You can ignore the specific details as to what information is actually being passed into the service (it's stored in $data), or that it's an object (so you pass in SOAP_ENC_OBJECT as the second parameter). They're important, but not relevant to the XML Schema type. For that, you must look at the third and fourth parameters to the SOAPVar constructor: 'CustomReportJob' and $ns. In this example, you're creating a job of type CustomReportJob that lives under the XML namespace, which is the value of $ns. Now when ext/soap serializes the data into XML, it adds the necessary attribute: Depending on the number of XML namespaces your code is using, you may or may not get the same prefix of ns1. The specific prefix string doesn't matter, what does matter is that your prefix is mapped to in the SOAP-Envelope element, as it is here: <SOAP-ENV:Envelope xmlns: Recipe 14.5 for using complex SOAP types.
https://flylib.com/books/en/3.131.1.249/1/
CC-MAIN-2020-05
refinedweb
433
69.72
It looks like a bug to me. Can you show an exact list of nodes and edges that is causing mkGraph to fail? Or is that what you have displayed, and I can't parse it properly? Thanks, Neil. Ivan Lazar Miljenovic wrote: > When developing my QuickCheck-2 test-suite for graphviz, I wrote the > following Arbitrary instance for FGL graphs (which needs > FlexibleInstances): > > ,---- > | instance (Graph g, Arbitrary n, Arbitrary e, Show n, Show e) => Arbitrary (g n e) where > | arbitrary = do ns <- liftM nub arbitrary > | let nGen = elements ns > | lns <- mapM makeLNode ns > | trace ("Nodes: " ++ show lns) (return ()) > | les <- listOf $ makeLEdge nGen > | trace ("Edges: " ++ show les) (return ()) > | return $ mkGraph lns les > | where > | makeLNode n = liftM ((,) n) arbitrary > | makeLEdge nGen = liftM3 (,,) nGen nGen arbitrary > | > | shrink gr = map (flip delNode gr) (nodes gr) > `---- > > However, when I try to run this, I occasionally get irrefutable pattern > match failures as follows: > > ,---- > | *Data.GraphViz.Testing.Instances.FGL Data.Graph.Inductive.Tree> sample (arbitrary :: Gen (Gr Int Char)) > | > | > | 0:0->[] > | > | 0:-2->[] > | 1:0->[('\a',0)] > | 2:0->[] > | > | -4:-3->[('U',-3),('#',1)] > | -3:3->[] > | 1:-1->[('}',-3)] > | > | -8:8->[] > | -3:2->[] > | -1:-5->[('\US',-3),('&',0)] > | 0:5->[('F',-1),('p',4)] > | 4:-1->[] > | > | -2:8->[('\177',-2),('(',-2),('d',-2),('4',-2),('D',-2),('\US',-2),('d',-2),('u',-2)] > | > | -16:11->[] > | -2:-2->[] > | 0:11->[('@',1)] > | 1:13->[('u',11)] > | 9:-11->[('\231',11)] > | 11:12->[('\226',1)] > | 16:15->[] > | > | -10:2->[] > | -4:8->[] > | 1:30->[] > | 26:26->[('<',1),('K',-4)] > | 31:-21->[] > | > | -35:51->[('@',-29)] > | -29:21->[('\132',-11)] > | -11:-31->[('j',61)] > | -4:40->[('a',-29)] > | 0:6->[('z',-35),('9',28),('\170',-11),('\SUB',28)] > | 23:8->[('P',-29),('(',61),('\\',28)] > | 28:60->[] > | 61:44->[('q',61)] > | *** Exception: Data/Graph/Inductive/Graph.hs:250:26-59: Irrefutable pattern failed for pattern (Data.Maybe.Just (pr, _, la, su), g') > `---- > > The actual error comes from the definition of insEdge: > > ,---- > | -- | Insert a 'LEdge' into the 'Graph'. > | insEdge :: DynGraph gr => LEdge b -> gr a b -> gr a b > | insEdge (v,w,l) g = (pr,v,la,(l,w):su) & g' > | where (Just (pr,_,la,su),g') = match v g > `---- > > with the Graph instance for Tree-based graphs using this for its mkGraph > method: > > ,---- > | mkGraph vs es = (insEdges' . insNodes vs) empty > | where > | insEdges' g = foldl' (flip insEdge) g es > `---- > > So, is this really a bug in FGL, or am I using mkGraph wrong? > > On another note, why doesn't the PatriciaTree graph type have a Show > instance? :( > >
http://www.haskell.org/pipermail/haskell-cafe/2009-November/069631.html
CC-MAIN-2014-15
refinedweb
415
58.86
All of us at Twilio are over the moon by the possibilities now unlocked by the availability of MMS on US phone numbers. We know from experience that the real ingenuity will come from you – the air around Twilio is electric with anticipation of the amazing things you’ll build. We’ve got a lot of hacks we’re excited to show you in the weeks that follow along with the best work we find from all of you. Have a sick MMS hack? Send it my way – rob@twilio.com. Want to get started? Check out this guide by Kevin Whinnery. We can’t wait to see what you build. To kick off our autumn of MMS hacking, I wanted to share the first thing I did with Twilio MMS. A couple years ago, my buddy Aidan Feldman released one of the most critical photo services the Internet has yet seen: Mustachify.me. A truly democratizing technology, Aidan’s killer website makes the august, sophisticated countenance of a long, curly mustache available to everyone. His magical code can turn this: Into this: From the second I got my hands on Twilio MMS, I knew I had to extend Aidan’s service to every phone in the United States and Canada. Try it now by sending a selfie here: US – (646) 846-8238 Canada – (438) 793-8863 Now let’s build our own together. What You’ll Need If you want to cut to the chase and have your own working mustache machine, go ahead and deploy the Mustached Message Service to Heroku immediately: If you’d like to build the service yourself, we can get those glorious mustaches messaging with a few ingredients: - Your Twilio account – signup for free here. - A Twilio phone number enabled for MMS (available in Canada and the United States only for now) - Python - Flask, a web microframework for Python. - A web host accessible on the Internet or a localhost tunneling service like the excellent ngrok. Getting Started Awww snap gang – time to bust some hot Pythonic stash action. First, we’ll kick out a little boilerplate to get our Flask app ready to accept some Twilio requests. If you are using pip, you can satisfy these dependencies with a requirements.txt file. Flask==0.10.1 twilio==3.6.7 Or directly by running this command: pip install twilio flask Now let’s cut a little boilerplate to respond with a simple text message. # Import Flask microframework from flask import Flask # Import Twilio Python module from twilio import twiml app = Flask(__name__) # Define the endpoint we'll use for the project. @app.route('/sms', methods=['POST']) def sms(): # Use the Twilio Python module to craft our response to inbound MMS. response = twiml.Response() # For now, send a text message back. response.message("Boiler plate, snacky!") # Casting the object as a string will format our response into TwiML # that Twilio can read and parse. return str(response) if __name__ == "__main__": # Since this is a development project, we will keep debug on to make our # lives easier. We would want to configure our app more conservatively # in production. app.debug = True app.run() Configuring Your Twilio Number Now we’ll take the basic endpoint we created and point a Twilio phone number to it. First, we need to go to our Twilio account and purchase a MMS-enabled number. (Note: MMS enabled phone numbers are only available for numbers in the United States and Canada) Next we’ll set up that number with the publicly accessible address of the application we created above. Like we specified in our app’s only route, we’ll point to /sms for our domain. Awesome – now after we click save, we should be able to send a message to the number and get a response from our boilerplate app. Echoing Back MMS Messages Next, let’s adjust our app to echo back to the user the messages he/she sends to our Twilio MMS-enabled number. We can leverage the request object to send the photo our app receives back to the user as a visual echo statement. from flask import Flask # Import the request object from Flask. from flask import request from twilio import twiml app = Flask(__name__) # Define the endpoint we'll use for the project. @app.route('/sms', methods=['POST']) def sms(): response = twiml.Response() # Check if we have media in the message. if request.form['NumMedia'] != '0': # If we do, echo back the media to the user. with response.message() as message: message.body = "I received this image." message.media(request.form['MediaUrl0']) else: # If we do not, indicate such to user. response.message("Could not find an image in your message.") return str(response) if __name__ == "__main__": # Since this is a development project, we will keep debug on to make our # lives easier. We would want to configure our app more conservatively # in production. app.debug = True app.run() Rad – now that we can receive an image and then send it back to the user. Stashing The Faces Now we can use Aidan’s mustachify.me service to apply upon every face it can fine with a killer curly cookie duster. Fortunately, mustachify’s interface is a simple URL param with the MediaUrl we receive from Twilio. from flask import Flask from flask import request from twilio import twiml app = Flask(__name__) # Define the URL for the service mustaching our photos. MUSTACHIFY_URL = "" @app.route('/sms', methods=['POST']) def sms(): response = twiml.Response() if request.form['NumMedia'] != '0': with response.message() as message: message.body = "STASHED." # Give mustachify.me our MediaUrl message.media("{0}{1}".format(MUSTACHIFY_URL, request.form['MediaUrl0'])) else: response.message("Could not find an image in your message.") return str(response) if __name__ == "__main__": # Since this is a development project, we will keep debug on to make our # lives easier. We would want to configure our app more conservatively # in production. app.debug = True app.run() Now if we give it a try, every photo gets some distinguished upperlipholstery. Check out what the Twilio Devangel crew did with this already: Next Steps If you’d like to see a more fully fleshed version of this application, be sure to check out the Github Repo here. You can also find the code for Aidan’s mean mustaching machine here. While mustaches make everything more fun, this is just the entertaining tip of the iceberg of what is possible with receiving and sending Twilio MMS. Here are just a few of the MMS-powered image manipulation use cases we’ve kicked around: - Funhouse mirror photobooths - Using optical character recognition to translate signs into different languages - Chromakey / alpha channel replacement transporting photo subjects to different places - Apply Instagram style vintage filters We know from experience that no matter how imaginative we get with the services we create, those ideas serve as a mere horizon of the world of wonder you – the Twilio developer – have built time and time again. We can’t wait to see it – reach out to me at @dn0t on Twitter or via email at rob@twilio.com with your MMS hacks!
https://www.twilio.com/blog/2014/09/how-to-build-a-mustached-message-service-with-twilio-mms-and-python.html
CC-MAIN-2020-50
refinedweb
1,189
63.8
How to use the XML Signature secure validation mode By Smullan-Oracle on Mar 13, 2014. org.jcp.xml.dsig.secureValidationhas been defined to allow applications to enable the mode. The property can be set by an application by calling the setProperty method of the javax.xml.crypto.dsig.dom.DOMValidateContext class with the name of the property above and a Boolean value. For example: DOMValidateContext context = new DOMValidateContext(key, element); context.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.TRUE); The property should be set before you validate an XML Signature. When set to true , this property instructs the implementation to process XML signatures more securely. This will set limits on various XML signature constructs to avoid conditions such as denial-of-service attacks. Specifically, it enforces the following restrictions: - Forbids use of the XSLT Transform - Restricts the number of SignedInfo or Manifest References to 30 or less - Restricts the number of Reference Transforms to 5 or less - Forbids the use of MD5 related signature or mac algorithms - Ensures that Reference Ids are unique to help prevent signature wrapping attacks - Forbids Reference URIs of type http or file - Does not allow a RetrievalMethod to reference another RetrievalMethod The feature is based on a similar validation mode that was included in version 1.5.0 of Apache Santuario XML Security. The JDK implementation is based on Apache Santuario. This mode is also in the soon to be released JDK 8. Hello, sorry to bother but I have couple of questions and I'd be very grateful if you could help me. I have a project on college to create XAdES Baseline and verify it, so I am using javax.xml.crypto.dsig for it. I've added couple of elements to xml dsig to create xades signature but I have some problems. First, I want to add namespace prefix to my xades elements, eg <xades:SignedProperties> etc. But when I do that, verification fails on this reference so could you tell me what i need to do in process of generating the signature to make correct reference digest value. I've found that someone already had similar problem,, you gave your response too on this topic but the question in the last post remained unanswered and that question bothers me too. Without prefix everything works well... Another thing I want to ask you, I need in my detached signature to create reference to detached file with URI that would have a relative path, ie URI would only have name of the file. How can I do that? And how can I validate that reference? Thanks in advance, Ivan Celija Posted by guest on May 20, 2014 at 04:27 PM EDT #
https://blogs.oracle.com/mullan/entry/how_to_use_the_xml
CC-MAIN-2015-35
refinedweb
450
53.71
Feature #6074 Allow alias arguments to have a comma Description This is one my biggest pet peeves with Ruby. I am always typing: alias :foo, :bar And getting a damn syntax error. Btw, is there a reason why alias is a keyword and not a method? History #1 Updated by Marc-Andre Lafortune over 3 years ago - Priority changed from Normal to 3 If that this is your biggest pet peeve, you must really love Ruby! Just use alias_method instead. The alias keyword is more general and allows other aliases like global variables; also you don't need to give symbols to alias, you can write alias foo bar. #2 Updated by Thomas Sawyer over 3 years ago Yes, I have almost exclusively used #alias_method in the past, but it's always seems rather silly to have to use the longer term. And I bet it would be an easy adjustment to support a comma. Btw, I really dislike using the non-symbol form of alias as it sticks out under syntax highlighters like a sore thumb. #3 Updated by Yusuke Endoh over 3 years ago Hello, 2012/2/24 Thomas Sawyer transfire@gmail.com: Btw, is there a reason why aliasis a keyword and not a method? Just historical reason, I guess. A keyword-style alias was first introduced, and then alias_method was later introduced as a reflection API for the feature. I understand the feeling. No keyword was needed for such a feature. If matz designed it now, he would implement it as a method, I believe. Btw, I really dislike using the non-symbol form of alias as it sticks out under syntax highlighters like a sore thumb. In this regard, you should blame your syntax highlighter? -- Yusuke Endoh mame@tsg.ne.jp #4 Updated by Koichi Sasada over 3 years ago - Category set to core - Target version set to 2.0.0 I think there are no reason why comma should be rejected. #5 Updated by Nobuyoshi Nakada over 3 years ago Hi, (12/02/25 13:51), Koichi Sasada wrote: I think there are no reason why comma should be rejected. It's simple. diff --git a/parse.y b/parse.y index e47dac4..f55e754 100644 --- a/parse.y +++ b/parse.y @@ -979,40 +979,40 @@ stmt_or_begin : stmt %*/ } -stmt : keyword_alias fitem {lex_state = EXPR_FNAME;} fitem +stmt : keyword_alias fitem opt_comma {lex_state = EXPR_FNAME;} fitem { /*%%%*/ - $$ = NEW_ALIAS($2, $4); + $$ = NEW_ALIAS($2, $5); /*% - $$ = dispatch2(alias, $2, $4); + $$ = dispatch2(alias, $2, $5); %*/ } - | keyword_alias tGVAR tGVAR + | keyword_alias tGVAR opt_comma tGVAR { /*%%%*/ - $$ = NEW_VALIAS($2, $3); + $$ = NEW_VALIAS($2, $4); /*% - $$ = dispatch2(var_alias, $2, $3); + $$ = dispatch2(var_alias, $2, $4); %*/ } - | keyword_alias tGVAR tBACK_REF + | keyword_alias tGVAR opt_comma tBACK_REF { /*%%%*/ char buf[2]; buf[0] = '$'; - buf[1] = (char)$3->nd_nth; + buf[1] = (char)$4->nd_nth; $$ = NEW_VALIAS($2, rb_intern2(buf, 2)); /*% - $$ = dispatch2(var_alias, $2, $3); + $$ = dispatch2(var_alias, $2, $4); %*/ } - | keyword_alias tGVAR tNTH_REF + | keyword_alias tGVAR opt_comma tNTH_REF { /*%%%*/ yyerror("can't make alias for the number variables"); $$ = NEW_BEGIN(0); /*% - $$ = dispatch2(var_alias, $2, $3); + $$ = dispatch2(var_alias, $2, $4); $$ = dispatch1(alias_error, $$); %*/ } @@ -5432,6 +5432,10 @@ opt_nl : /* none */ | '\n' ; +opt_comma : /* none */ + | ',' + ; + rparen : opt_nl ')' ; Nobu Nakada #6 Updated by Marc-Andre Lafortune over 3 years ago I might have sounded more negative than I intended, so let me say that I also agree that we should allow a comma. #7 Updated by Robert A. Heiler over 3 years ago I myself prefer "alias" because: - It does not require a ',' - It is shorter to type - It reads easier. def bar puts 'Hi from bar.' end alias foo bar alias_method :foo, :bar The first way is more readable for my poor old eyes. #8 Updated by Yusuke Endoh over 3 years ago - Status changed from Open to Assigned - Assignee set to Nobuyoshi Nakada Sorry, I didn't know alias syntax accepts symbols as arguments! Then I agree with this proposal. Ruby always gives me a fresh surprise for me. -- Yusuke Endoh mame@tsg.ne.jp #9 Updated by Yusuke Endoh about 3 years ago - Target version changed from 2.0.0 to next minor #10 Updated by Thomas Sawyer almost 3 years ago Is there any reason this can't make it into 2.0? #11 Updated by Alexey Muranov almost 3 years ago Just another idea in this direction: allow def :foo, :bar do puts bar end in addition to def foo(bar) puts bar end (the " do" in the first case can be optional). #12 Updated by Eric Hodel almost 3 years ago On Dec 7, 2012, at 9:10, "alexeymuranov (Alexey Muranov)" redmine@ruby-lang.org wrote: Issue #6074 has been updated by alexeymuranov (Alexey Muranov). Just another idea in this direction: If you have a separate idea open a separate feature request. Do not hijack existing issues. Hijacking issues makes them difficult for the committers to understand. Since this feature is delayed until next minor, continued off-topic discussion may lead to an issue being closed because its purpose is too difficult to determine. #13 Updated by Nobuyoshi Nakada over 1 year ago Salvaged. #14 Updated by Nobuyoshi Nakada over 1 year ago #15 Updated by Nobuyoshi Nakada over 1 year ago - Assignee changed from Nobuyoshi Nakada to Yukihiro Matsumoto Request for syntax change. #16 Updated by Akinori MUSHA over 1 year ago I believe the lack of comma is an important sign that alias is not really a method call in which directive arguments are not evaluated like with normal method calls. If you are allowed to, and should you put a comma in an alias statement, it would look like a method call and confuse you in that you might think it could be passed any expressions. Here is an example: class Foo name = :to_str method = :to_s alias name, method # Likely a mistake, but won't err because `method` happens to exist. end I think we should instead deprecate the alias :sym1 :sym2 form so that it is clear that alias takes bare identifiers, not expressions. #17 Updated by Shugo Maeda over 1 year ago Akinori MUSHA wrote: I believe the lack of comma is an important sign that alias is not really a method call in which directive arguments are not evaluated like with normal method calls. Agreed, and this issue should be judged by Matz, shouldn't it? #18 Updated by Yukihiro Matsumoto over 1 year ago - Status changed from Assigned to Rejected As Akinori stated, alias is special to be special. In your case, forget alias and always use alias_method. Matz. #19 Updated by Thomas Sawyer over 1 year ago Special cases always make me cringe. Why is alias a special case anyway? It seems very odd since alias_method is a method and does the same thing. Also available in: Atom PDF
https://bugs.ruby-lang.org/issues/6074
CC-MAIN-2015-48
refinedweb
1,110
69.92
(For more resources related to this topic, see here.) Getting started PyroCMS, like many other content management systems including WordPress, Typo3, or Drupal, comes with a pre-developed installation process. For PyroCMS, this installation process is easy to use and comes with a number of helpful hints just in case you hit a snag while installing the system. If, for example, your system files don't have the correct permissions profile (writeable versus write-protected), the PyroCMS installer will help you, along with all the other installation details, such as checking for required software and taking care of file permissions. Before you can install PyroCMS (the version used for examples in this article is 2.2) on a server, there are a number of server requirements that need to be met. If you aren't sure if these requirements have been met, the PyroCMS installer will check to make sure they are available before installation is complete. Following are the software requirements for a server before PyroCMS can be installed: - HTTP Web Server - MySQL 5.x or higher - PHP 5.2.x or higher - GD2 - cURL Among these requirements, web developers interested in PyroCMS will be glad to know that it is built on CodeIgniter, a popular MVC patterned PHP framework. I recommend that the developers looking to use PyroCMS should also have working knowledge of CodeIgniter and the MVC programming pattern. Learn more about CodeIgniter and see their excellent system documentation online at. CodeIgniter If you haven't explored the Model-View-Controller (MVC) programming pattern, you'll want to brush up before you start developing for PyroCMS. The primary reason that CodeIgniter is a good framework for a CMS is that it is a well-documented framework that, when leveraged in the way PyroCMS has done, gives developers power over how long a project will take to build and the quality with which it is built. Add-on modules for PyroCMS, for example, follow the MVC method, a programming pattern that saves developers time and keeps their code dry and portable. Dry and portable programming are two different concepts. Dry is an acronym for "don't repeat yourself" code. Portable code is like "plug-and-play" code—write it once so that it can be shared with other projects and used quickly. HTTP web server Out of the PyroCMS software requirements, it is obvious, you can guess, that a good HTTP web server platform will be needed. Luckily, PyroCMS can run on a variety of web server platforms, including the following: - Abyss Web Server - Apache 2.x - Nginx - Uniform Server - Zend Community Server If you are new to web hosting and haven't worked with web hosting software before, or this is your first time installing PyroCMS, I suggest that you use Apache as a HTTP web server. It will be the system for which you will find the most documentation and support online. If you'd prefer to avoid Apache, there is also good support for running PyroCMS on Nginx, another fairly-well documented web server platform. MySQL Version 5 is the latest major release of MySQL, and it has been in use for quite some time. It is the primary database choice for PyroCMS and is thoroughly supported. You don't need expert level experience with MySQL to run PyroCMS, but you'll need to be familiar with writing SQL queries and building relational databases if you plan to create add-ons for the system. You can learn more about MySQL at. PHP Version 5.2 of PHP is no longer the officially supported release of PHP, which is, at the time of this article, Version 5.4. Version 5.2, which has been criticized as being a low server requirement for any CMS, is allowed with PyroCMS because it is the minimum version requirement for CodeIgniter, the framework upon which PyroCMS is built. While future versions of PyroCMS may upgrade this minimum requirement to PHP 5.3 or higher, you can safely use PyroCMS with PHP 5.2. Also, many server operating systems, like SUSE and Ubuntu, install PHP 5.2 by default. You can, of course, upgrade PHP to the latest version without causing harm to your instance of PyroCMS. To help future-proof your installation of PyroCMS, it may be wise to install PHP 5.3 or above, to maximize your readiness for when PyroCMS more strictly adopts features found in PHP 5.3 and 5.4, such as namespaceing. GD2 GD2, a library used in the manipulation and creation of images, is used by PyroCMS to dynamically generate images (where needed) and to crop and resize images used in many PyroCMS modules and add-ons. The image-based support offered by this library is invaluable. cURL As described on the cURL project website, cURL is "a command line tool for transferring data with URL syntax" using a large number of methods, including HTTP(S) GET, POST, PUT, and so on. You can learn more about the project and how to use cURL on their website. If you've never used cURL with PHP, I recommend taking time to learn how to use it, especially if you are thinking about building a web-based API using PyroCMS. Most popular web hosting companies meet the basic server requirements for PyroCMS. Downloading PyroCMS Getting your hands on a copy of PyroCMS is very simple. You can download the system files from one of two locations, the PryoCMS project website and GitHub. To download PyroCMS from the project website, visit and click on the green button labeled Get PyroCMS! This will take you to a download page that gives you the choice between downloading the Community version of PyroCMS and buying the Professional version. If you are new to PyroCMS, you can start with the Community version, currently at Version 2.2.3. The following screenshot shows the download screen: To download PyroCMS from GitHub, visit and click on the button labeled Download ZIP to get the latest Community version of PyroCMS, as shown in the following screenshot: If you know how to use Git, you can also clone a fresh version of PyroCMS using the following command. A word of warning, cloning PyroCMS from GitHub will usually give you the latest, stable release of the system, but it could include changes not described in this article. Make sure you checkout a stable release from PyroCMS's repository. git clone As a side-note, if you've never used Git, I recommend taking some time to get started using it. PyroCMS is an open source project hosted in a Git repository on Github, which means that the system is open to being improved by any developer looking to contribute to the well-being of the project. It is also very common for PyroCMS developers to host their own add-on projects on Github and other online Git repository services. Summary In this article, we have covered the pre-requisites for using PyroCMS, and also how to download PyroCMS. Resources for Article : Further resources on this subject: - Kentico CMS 5 Website Development: Managing Site Structure [Article] - Kentico CMS 5 Website Development: Workflow Management [Article] - Web CMS [Article]
https://www.packtpub.com/books/content/downloading-pyrocms-and-its-pre-requisites
CC-MAIN-2016-30
refinedweb
1,200
59.74
Debug vs Release build Many of us have been bitten by an app behaving differently under debug and release builds. What are common tips/tricks that the JOS audience can suggest to avoid the release build problems? Let me start: MS VC++ initializes local variables to 0 in the debug build, but not in release. Other problems/gotchas, anyone? Thanks! Floridian Wednesday, December 03, 2003 Regular "Release" builds on clean machines. If you have a build schedule, make a release build and test it on a nice clean machine (VMWare and Virtual PC can help). Gp Wednesday, December 03, 2003 . Wednesday, December 03, 2003 For debugging, I highly recommend Microsoft's free "Windows Application Verifier". It can detect all sorts of runtime errors like heap corruption (PageHeap), lock misuse, bad handles. It's like Purify or BoundsChecker, but it uses debug features in Windows memory management. runtime Wednesday, December 03, 2003 ASSERTS are not active in release builds....so in case the side effect is important use VERIFY instead e.g ASSERT ( f() ) which checks to make sure that the function f() returns a non-zero value. In release mode f() will not be called at all. To avoid this use VERIFY ( f() ) Code Monkey Wednesday, December 03, 2003 Working with a lot of different codes and computers, I see this all the time. I do however not work in Windows. All compilers have problems like that. Optimizations levels can bring in problems, a bit like Debug/Release. The code can be perfectly correct and still be too much for the compiler. There are no shortcuts. QA is important. Automated unit testing, or something will help. It depends on the program how you can set it up, but the easier it is to test the code the more frequent it will be done. Add timing and you will also be able to have a history of how computeintensive part change. What may help is to have a clean code, not too big source files, no extraordinary strange loop structures or strange references. Depends a bit on the language you are working with. Sometimes a restructuring of the code is the only thing that works. Even a simple print statement can get the compiler on track, then you know where to restructure. Often you find a simpler solution at the end anyway, so it is worth the extra work restructuring. Fredrik Svensson Wednesday, December 03, 2003 Another ASSERT variation that's a "classic" debug vs release issue: if(blah) ASSERT(something); nextThing(); In release, the ASSERT gets stripped out, obviously, and nextThing() only gets called if blah is true... A PS2 Programmer Wednesday, December 03, 2003 To A PS2 Programmer, That is incorrect. danpop Wednesday, December 03, 2003 The famous one in MFC-land is that incorrect signatures in message map entries work fine in Debug, but crash in Release. This is devilishly hard to find the first time it happens to you. Here's an example of a correct declaration: //{{AFX_MSG(CMaintBatchDetailTree) afx_msg LRESULT OnMumbleFoobar(WPARAM wParam, LPARAM lParam); //}}AFX_MSG If you incorrcetly declare (and elsewhere define) it like this: //{{AFX_MSG(CMaintBatchDetailTree) afx_msg LRESULT OnMumbleFoobar( ); //}}AFX_MSG It will very probably work just fine in Debug mode, but crash in Release mode. I've been bitten by this mostly when I cut and paste message map entries. Grumpy Old-Timer Wednesday, December 03, 2003 Also a Vsiaul C++ short article regarding this is available @ danpop - It's not nice to say "That is incorrect" without any further explanation. I happen to agree with you in this case, but if you're posting to help someone rather than just feel good that you're smarter than them, then you should give an explanation. I think your reasoning is: "ASSERT(something);" will evaluate to ";" in release, and so it will work right. Perhaps PS2 was thinking of where ASSERT(x) is defined to "<something>;", and you write "ASSERT(something)" in your code? Exception guy Wednesday, December 03, 2003 Make SURE you are compiling with the highest warning level (which is 4 at the moment). This will point out some things that might cause different behavior between the two. With ASSERTS, test values, not "complex" statements with side effects. Example: ASSERT((fp = fopen("foobar", "r"))); // BAD fp = fopen("foobar", "r"); ASSERT(fp); // Good njkayaker Wednesday, December 03, 2003 "Perhaps PS2 was thinking of where ASSERT(x) is defined to '<something>;', and you write "ASSERT(something)" in your code?" That's why you should never write this: if (foo) bar; ... but should always do this instead: if (foo) { bar; } How often do we get to say "always" and "never", anyway? Um.. never? :) sgf Wednesday, December 03, 2003 Exception guy: yes, you’re right. I should’ve explained myself. Speaking of ASSERTs: many people do not know how to use them. An ASSERT should express a fact (logic, business, etc), rather than an error, as it is so commonly done. For instance, in the previous example, opening a file COULD fail so it is nothing to ASSERT, it is an error that should be dealt with. Here is something that I recently used where I think an ASSERT is properly used: Input: std::vector<T> v; v is supposed to be sorted…. (is_sorted<T> is a function that verifies whether an array is sorted) ……. ASSERT(is_sorted(v)); // verify that v is sorted do_something(v); ASSERT(is_sorted(v)); // verify that v is still sorted ……….. Right, that's why you should *never* use the VERIFY macro. Use ASSERT for assertions in debug builds, and real honest-to-goodness error-checking in release builds. For most people, VERIFY is a subtle way to avoid doing error-checking. A higher-level method we used to use is to have a pre-release build just before the release, with enough time to handle small-to-medium problems before the release build (varied from program to program, usually 1-2 days, but one big program used 4). I liked the concept; if there weren't any problems generated from the pre-release, we used the time to catch up or get a head start on whatever's next. Gave people some slow time to catch their breath. van pelt Wednesday, December 03, 2003 Thanks to all for the info! Now I'm armed to find my problems! Floridian Wednesday, December 03, 2003 Yes, one would not use ASSERT on an fopen. It was just a quick illustration of the side effect problem. I tend to think of ASSERTS as guides to the programmer or very-early testers. They are a way to document that "this is not supposed to happen" or "you are using this incorrectly" as code instead of as a mere comment. Thus, they say "fix this now" when they report an error. They really don't make a program more reliable in production because they go away in the release version. If testing is done on the release version, they are no help. If you use ASSERTS, you may also need release error reporting. My solution is to not have a different debug and release build code base. It's the same code that runs all the time. Test what you ship and ship what you test. What you would compile out make settable by level or efficient enough it can always run. son of parnas Wednesday, December 03, 2003 Son, you are missing something. The problem, at least for my team, is that we do test and release the release version, but often a bug is reported, we go to debug the code, and it works fine. I think that's the issue being raised in this thread. GML Wednesday, December 03, 2003 GML, you are missing something. Son of Parnas is saying that you should not waste your time debugging the debug builds. As you pointed out, it has not helped you find these (particular) bugs. He is recommending that you only debug your release builds. I guess I can throw in my missive about overuse of asserts in general. Overuse? Yes. RUN-TIME CHECKING, with extensive, tunable run-time logging, can help find the most devilish problems and provide an audit trail for your support team. My simplified example is: ... do { if ((rc = TableOpen(...)) != 0) { Log("Couldn't open table"); break; } bTableOpen = TRUE; if ((rc = TableLock(...)) != 0) { Log("Couldn't lock table"); break; } bTableLocked = TRUE; if ((rc = RecordLock(...)) != 0) { Log("Couldn't lock record"); break; } bRecordLocked = TRUE; if ((rc = RecordUpdate(...) != 0) { Log("Couldn't update record"); break; } } while (0); if (bRecordLocked) { if ((rc1 = RecordUnlock()) != 0 && !rc) { Log("Couldn't unlock record"); rc = rc1; } } if (bTableLocked) { if ((rc1 = TableUnlock()) != 0 && !rc) { Log("Couldn't unlock table"); rc = rc1; } } if (bTableOpened) { if ((rc1 = TableClose(...)) != 0 && !rc) { Log("Couldn't close table"); rc = rc1; } } return (rc); IOW, everything is checked _at run-time_. Period. Everything can be tracked, depending upon the trace level of logging. My key finding over 20+ years: few applications are so performance-intensive that you can't afford checking whether a pointer is NULL or not or verifying a return-code came back the right way. IMO, a big reason most software is unreliable is that "go-naked" tools like ASSERTs are overused (so called, because is in RELEASE mode, you're going nekkid :-). doug badblue com Wednesday, December 03, 2003 One problem with release builds is that they aren't very debuggable. If your program crashes, the stack trace is usually useless. Even if you disable frame pointer omission you can't tell what the variables are without recourse to the (obfuscated) disassembly. What a pain! Some people say you shouldn't use debuggers. I disagree, but if you don't like them then it's true that you may as well not bother with debugging builds. (It's been my experience that you can program without introducing any bugs that appear only in release builds. It just takes a bit of practice. This will of course skew my opinion.) Insert half smiley here. Wednesday, December 03, 2003 Our core product has: ASSERT(ptr != NULL); ptr->Foo(); in over 3,000 places... Skagg Wednesday, December 03, 2003 >> Let me start: MS VC++ initializes local variables to 0 in the debug build, but not in release. Other problems/gotchas, anyone? << Uh, no it doesn't. In debug builds, it initializes local variables to 0xCC to make unitialized values obvious. It also initializes dynamically allocated and freed memory to similar values to likewise make them obvious. I have a vague memory of what you said being true in the past but it certainly isn't the case for version 6 with the latest SP and version 7. SomeBody Wednesday, December 03, 2003 "doug badblue", you are my kind of programmer. Ours is the one true path, because you and I can fix any bug in an *instant*. Here's an interesting article on the subject: Unrewarded Genius Wednesday, December 03, 2003 I've used this approach in the past. It is especially good when you can recover from errors like unexpected NULL pointers #define MYASSERT(x) if(!(x)) { throw MyAssertException(__FILE__,__LINE__);} (writing the above from memory - please don't get sidetracked by syntax errors...) Then I catch MyAssertException at a high level in the code and act appropriately. A real example: The code I was writing was a plugin to another program that exported that program's documents in a custom format. I wrapped the main export process in a try...catch block. If there was an assertion failure in the export I didn't have to bring the program down. I could pop up a dialog suggesting the user save their file (to a different name!!) and restart the program. This discussion really reminds me why I much prefer Java these days. AndrewR Wednesday, December 03, 2003 well, one app our developers worked on (previous employer by several generations) was somewhat non-deterministic -- how it worked depended just a bit too much on timing of certain events in the app, which meant that program flow ended up depending upon execution speed. the net result of it was, we in my team (not the developers) discovered somewhat to our surprise one day, was that our company's 'released' code was in fact the 'debug' code. when we asked about it, the head-honcho developer basically told us that the app didn't work right unless it was compiled as a debug build. the timing was wrong otherwise, and it just wouldn't work. they hadn't figured out why, so they'd just gone ahead and released the debug build. ouch. it's a good place to be gone from. horseWithNoName Wednesday, December 03, 2003 .. just to add another one. with VC++ uninitialized automatic variables are often set to 0 in debug mode. void foo() { int a; printf("%d",a); // gets you 0 in debug mode. Ouch! // good source of release mode crashes. } Michael Moser Thursday, December 04, 2003 You should get 0xCCCCCCCC in your auto variables in a debug build. Make sure you are specifying /GZ on the command line. It's very handy -- this sticks out a mile in the debugger, and if you use floats you'll quickly get to recognise its float equivalent. The VC++.NET compiler has even better options. Insert half smiley here. Thursday, December 04, 2003 Grumpy Old timer said : >Right, that's why you should *never* use the VERIFY macro. >Use ASSERT for assertions in debug builds, and real >honest-to-goodness error-checking in release builds. I don't think you know how the VERIFY macro operates...VERIFY is not a way to show a message in release mode...in release mode VERIFY just evaluates its arguments and does nothing no matter what the result is. >For most people, VERIFY is a subtle way to avoid doing >error-checking. Wonder where I can meet these "most" people :-) Around here ASSERTS are used to check conditions which you know are true or which rarely ever fail but which you still want to cross check just in case Mr Murphy intervenes. So you would check for a fopen call with a a normal error messsage but it is perfectly normal to check for the corresponding close with an ASSERT since it rarely if ever fails if you are closing a valid file opened earlier. Show me a programmer who checks each and every function call for each and every error and I will show you a programmer who is writing a "hello world" program :-) Code Monkey Thursday, December 04, 2003 "Show me a programmer who checks each and every function call for each and every error and I will show you a programmer who is writing a "hello world" program" Show me one who doesn't, and I'll show you an amateur hack. I check virtually every return code (not the silly ones, of course, like the return value for printf, but everything else). This makes the debugging of problems trivial, because I always know exactly what went wrong, on which line of code. (Can you say that?) My logging class automatically logs all available error numbers and messages for every kind of error and exception. So, what takes most people hours or days to find and fix, I can do in minutes. I never spend time wondering how this function could have possibly failed: when a (fatal) error occurs, my classes and macros capture the values of local variables, the call stack, and (when I want it to), a dump of the values in specific whole "branches" in the Registry. And there's a lot more. This kind of thing, BTW, is why the top 5% of programmers are 20 times as productive as the other 95% - I spend zero time *hunting* for bugs. Bragging? Yup - it took me a long time, and a lot of hard work, to get here. Chipper-Dipper Thursday, December 04, 2003 hi I want to write a program with VC++ about read and write from PS2 or USB what can I do? bita Monday, May 10, 2004 Recent Topics Fog Creek Home
http://discuss.fogcreek.com/joelonsoftware3/default.asp?cmd=show&ixPost=91907&ixReplies=33
CC-MAIN-2017-17
refinedweb
2,692
72.16
Play Rock, Paper, Scissors Using the ESP8266 Play Rock, Paper, Scissors Using the ESP8266 Rock, paper, scissors... shoot! Click here to learn more about creating your own rock, paper, scissors game using the ESP8266. Join the DZone community and get the full member experience.Join For Free In this tutorial, we will build an online rock, paper, scissors game using ESP8266, the Wia Dashboard, and Github. What You Will Need - 2x ESP8266 - 2x Micro USB to USB cables Before you begin, you must have a Wia account. You can create one here. If you have not set up your ESP8266 with the Arduino yet, you will need to do that first. This tutorial will show you how. Getting Started First, connect a USB cable to one of the ESP8266 and plug it into your computer or laptop. Open the Arduino IDE. You can download the latest version here. In Arduino IDE, create a new sketch and save it as playerOne.ino. Create a second sketch and name it playerTwo.ino. Next, navigate to the Wia Dashboard, create a new space and add device. Name it something like "playerOne." Once you have added your device, navigate to the Devices tab on the left-hand side of the page. Select your device, then navigate to the configuration tab. You will see your device ID as well as your device_secret_key. You will need the device secret key later. The Code Copy and paste the following code into your Arduino sketch named playerOne.ino: #include <Arduino.h> #include <ESP8266WiFi.h> #include <ESP8266WiFiMulti.h> #include <ESP8266HTTPClient.h> #define USE_SERIAL Serial ESP8266WiFiMulti WiFiMulti; const char* ssid = "name-of-your-Wifi"; const char* password = "your-Wifi-Password"; // get this from the wia dashboard. it should start with `d_sk` const char* device_secret_key = "your-device-secret-key"; boolean buttonState = HIGH; boolean buttonDown = false; void setup() { // put your setup code here, to run once: pinMode(0, INPUT); Serial.begin(115200); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } WiFi.mode(WIFI_STA); WiFiMulti.addAP(ssid, password); } void loop() { // put your main code here, to run repeatedly: buttonState = digitalRead(0); // check if the pushbutton is pressed. // if it is, the buttonState is LOW: if (buttonState == LOW) { if (buttonDown == false) { Serial.println("Button Pushed"); buttonDown = true; postToWia(); delay(750); } } else { buttonDown = false; } } void postToWia() { // wait for WiFi connection if((WiFiMulti.run() == WL_CONNECTED)) { HTTPClient http; USE_SERIAL.print("[HTTP] begin...\n"); // configure wia rest api http.begin(""); USE_SERIAL.print("[HTTP] POST...\n"); // set authorization token http.addHeader("Authorization", "Bearer " + String(device_secret_key)); // set content-type to json http.addHeader("Content-Type", "application/json"); // start connection and send HTTP headers. replace name and data values with your own. int httpCode = http.POST("{\"name\":\"buttonPress\"}"); // httpCode will be negative on error if(httpCode > 0) { // HTTP header has been send and Server response header has been handled USE_SERIAL.printf("[HTTP] POST... code: %d\n", httpCode); // file found at server if(httpCode == HTTP_CODE_OK) { String payload = http.getString(); USE_SERIAL.println(payload); } } else { USE_SERIAL.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str()); } http.end(); } } Change the following values: name-of-your-WiFito the name of your Wi-Fi. This must be the same Wi-Fi network that your computer is using. your-WiFi-passwordto your Wi-Fi network password you-device-secret-keyto your device secret key, which can be found on the Wia Dashboard under Devices > Configuration Upload the code to your device by clicking upload in the Arduino IDE. Then, set your device aside. Remember that this device is playerOne and contains the playerOne code. Connect the second device to your computer, and add it to your space in the Wia Dashboard. This device will have an entirely different device-secret-key. Collect the key from the configuration tab. Copy and paste the code from before into the Arduino file playerTwo.ino, but change the device-secret-key to match the second device. Upload the code from the file playerTwo.ino onto your second device. Wia Flows Now, in your Wia dashboard, click Flows in the left-hand sidebar. Create a new flow and name it whatever you would like. Drag over an Event from the trigger tab and name it buttonPress . Select both devices: In the logic tab, drag over a run-function node. Drag the yellow dot from the Event node to the run-function node. In the box, copy and paste this code: var items = [ '��', '��', '✂' ]; var item = items[Math.floor(Math.random()*items.length)]; output.body.data = item; Your screen should look like this: Next, click Update. Then, in the action tab, drag over an event and name it emoji. To connect the nodes, drag the orange dots. Your screen should look like this: Next, navigate to Devices > playerOne. This should take you to the overview page for your device. In the right hand corner, click add a widget. Write emoji for the title and emoji for the event. Then, navigate back to Devices on the sidebar and select your device for playerTwo. Create a new widget and write emoji for the title and emoji for the event. Plug both devices into your computer. Press the flash button on both devices. Your widgets will show whether the device chose rock, paper, or scissors. However, navigating between the two devices is not an efficient way to play the game. So, we must make a webpage that will show us the result of each player's choice simultaneously. To do this, we will use Github. You can create an account here. Web Page Begin by logging into GitHub. Create a new repository and name it your-github-username.github.io. Check the box to initialize with a README. Once you have created your repository, open it. Click create new file. Copy and paste the code below into a file called index.html. The file must be named index.html. <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Wia Game</title> </head> <body> <h1>Wia Rock Paper Scissors</h1> </body> </html> This is the HTML boilerplate. To see our game update in real time, we need to embed our widgets from Wia. Back in the Wia Dashboard, navigate to one of the two player devices. In the overview, you can see your widget. Click the box with an arrow in the upper right hand corner of the widget. Choose the setting anyone can view this widget. Copy the code of embed the widget. The code starts with <iframe> and ends with </iframe>. Back in GitHub, edit the index.html file. Paste the widget code below the header <h1>Wia Rock Paper Scissors</h1>. Repeat this with the widget for the other device. Now, your HTML file should look like this: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Wia Game</title> </head> <body> <h1>Wia Rock Paper Scissors</h1> <iframe> YOUR WIDGET </iframe> <iframe> YOUR SECOND WIDGET </iframe> </body> </html> To view your new web page, navigate to And, there is your game! Enjoy! Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/play-rock-paper-scissors-using-the-esp8266
CC-MAIN-2018-51
refinedweb
1,185
68.77
Build a paid content site with replit.web and. By the end of this tutorial, you'll be able to: Getting started To get started, create a Python repl. Our application will have the following functionality: - Users can log in with their Replit accounts. - Users can purchase PDFs. - Users can view free PDFs and PDFs that they've previously purchased. - Administrators can upload new PDFs. We've covered both replit.web and Stripe in previous tutorials, so some aspects of the following may be familiar if you've built a brick shop or a technical challenge website. We'll start our app off with the following import statements in main.py: import os, shutil import stripe from flask import Flask, render_template, render_template_string, flash, redirect, url_for, request, jsonify from flask.helpers import send_from_directory from werkzeug.utils import secure_filename from replit import db, web from functools import wraps Here we're importing most of what we'll need for our application: - Python's osand shutilpackages, which provide useful functions for working with files and directories. - Stripe's Python library. - Flask, our web framework and the heart of the application. - A Flask helper function send_from_directory, which will allow us to send PDFs to users. - A function secure_filenamefrom the Werkzeug WSGI (which Flask is built on) that we'll use when admins upload PDFs and other files. - Replit's web framework and Replit DB integration, which we'll use for user authentication and persistent data storage. - The wrapstool from Python's functools, which we'll use to make authorization decorators for restricting access to sensitive application functionality. Now that the imports are out of the way, let's start on our application scaffold. Add the following code to main.py: app = Flask(__name__, static_folder='static', static_url_path='') This code initializes our Flask application. We've added a static_folder and static_url_path so that we can serve static files directly from our repl's file pane without writing routing code for each file. This will be useful for things like images and stylesheets. Add the following code to initialize your application's secret key: # Secret key app.config["SECRET_KEY"] = os.environ["SECRET_KEY"] Our secret key will be a long, random string. You can generate one in your repl's Python console with the following two lines of code: import random, string ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(20)) Rather than putting this value directly into our code, we'll retrieve it from an environment variable. This will keep it out of source control and is good practice for sensitive data. In your repl's Secrets tab, add a new key named SECRET_KEY and enter the random string you just generated as its value. Once that's done, return to main.py and add the code below to initialize our Replit database: # Database setup def db_init(): if "content" not in db.keys(): db["content"] = {} if "orders" not in db.keys(): db["orders"] = {} # Create directories if not os.path.exists("static"): os.mkdir("static") if not os.path.exists("content"): os.mkdir("content") db_init() Replit's Database can be thought of and used as one big Python dictionary that we can access with db. Any values we store in db will persist between repl restarts. We've written a function to initialize the database as we may want to do it again if we need to refresh our data during testing. Whenever we initialize our database, we will also create the content and static directories, which will contain user-uploaded files. Next we need to create our UserStore (a secondary database keyed by username), and list of admins: users = web.UserStore() ADMINS = ["YOUR-REPLIT-USERNAME-HERE"] Make sure to replace the contents of the ADMINS list with your Replit username. Finally, let's make our root page. Add the following code, and then run your repl. # Main app Replit username on the greeting message. Content upload and other admin functionality Before we do anything else with our site, we need to have some PDFs to sell. While we could manually upload our PDFs to our repl and write code to add each one to the database, it will make our site more user-friendly if we include an upload form for this purpose. This upload form should only be accessible by admins, so we can enforce some level of quality control. We'll also create a route that allows admins to refresh the application database. Access control Add the following functions to main.py, just below the line where you've assigned ADMINS: # Helper functions def is_admin(username): return username in ADMINS # Auth decorators def admin_only(f): @wraps(f) def decorated_function(*args, **kwargs): if not is_admin(web.auth.name): flash("Permission denied.", "warning") return redirect(url_for("index")) return f(*args, **kwargs) return decorated_function The code in the second function may look a bit strange if you haven't written your own decorators before. Here's how it works: admin_only is the name of our decorator. You can think of decorators as functions that take other functions as arguments. (The two code snippets below are. Now we can create the following admin routes below the definition of the index function: # Admin functionality @app.route('/admin/content-create', methods=["GET", "POST"]) @web.authenticated @admin_only def content_create(): pass @app.route('/admin/db-flush') @web.authenticated @admin_only def flush_db(): pass Note that both of these functions are protected with the @web.authenticated and @admin_only decorators, restricting their use to logged-in admins. The first function will let our admins create content, and the second will allow us to flush the database. While the second function will be useful during development, it's not something we'd want to use in a finished application, as our database will contain records of user payments. Content creation form Before we can fill in the code for content creation, we need to create the web form our admins will use. As the form creation code will include a lot of information and functionality and require several special imports, we're going to put it in its own file so we can keep a navigable codebase. In your repl's files pane, create forms.py. Enter the following import statements at the top of forms.py: from flask_wtf import FlaskForm from flask_wtf.file import FileField, FileRequired, FileAllowed from wtforms import StringField, TextAreaField, SubmitField, FloatField, ValidationError from wtforms.validators import InputRequired, NumberRange, Length from replit import db Here we're importing from WTForms, an extensive library for building web forms, and Flask WTF, a library which bridges WTForms and Flask. We're also importing our Replit database, which we'll need for uniqueness validations. The structure of our forms is dictated by the structure of our database. In our db_init function, we defined two dictionaries, "content" and "orders". The former will contain entries for each of the PDFs we have for sale. These entries will contain the PDF's filename as well as general metadata. Thus, our "content" data structure will look something like this: { "content": { "ID": { "name": "NAME", "description": "DESCRIPTION", "file": "PDF_FILENAME", "preview_image": "IMAGE_FILENAME", "price": 5, } } } The ID value will be the content's create our form. With Flask WTF, we model a form as a class inheriting from FlaskForm. This class takes in the value of Flask's request.form and applies validations to the fields therein. Add the following class definition to the bottom of forms.py: class ContentCreateForm(FlaskForm): name = StringField( "Title", validators=[ InputRequired(), Length(3) ] ) description = TextAreaField( "Description", validators=[InputRequired()] ) file = FileField( "PDF file", validators=[ FileRequired(), FileAllowed(['pdf'], "PDFs only.") ] ) image = FileField( "Preview image", validators=[ FileRequired(), FileAllowed(['jpg', 'jpeg', 'png', 'svg'], "Images only.") ] ) price = FloatField( "Price in USD (0 = free)", validators=[ InputRequired(), NumberRange(0) ] ) submit = SubmitField("Create content") def validate_name(form, field): if name_to_id(field.data) in db["content"].keys(): raise ValidationError("Content name already taken.") When admins create content, they'll specify a name, a description, and a price, as well as upload both the PDF and a preview image. We've used WTForm's validators to restrict the file types that can be uploaded for each. Should we decide to branch out from selling PDFs in the future, we can add additional file extensions to the file field's FileAllowed validator. We could also make individual fields optional by removing their InputRequired() or FileRequired() validators. The final part of our form is a custom validator to reject new PDFs with IDs that match existing PDFs. Because we're validating on ID rather than name, admins won't be able to create PDFs with the same name but different capitalization (e.g. "Sherlock Holmes" and "SHERLOCK HOLMES"). We've finished creating our form class. Now we can return to main.py and import the class with the following import statement, which you can add just below the other imports at the top of the file. from forms import name_to_id, ContentCreateForm Note that we've also imported name_to_id, which we'll use when populating the database. Admin routes We can now use our form to implement our content creation route. Populate the content_create function with this code: # Admin functionality @app.route('/admin/content-create', methods=["GET", "POST"]) @web.authenticated @admin_only def content_create(): form = ContentCreateForm() if request.method == "POST" and form.validate(): content_name = form.name.data content_id = name_to_id(content_name) content_price = form.price.data content_file = form.file.data content_filename = secure_filename(content_file.filename) content_file.save(os.path.join('content', content_filename)) image_file = form.image.data image_filename = secure_filename(image_file.filename) image_file.save(os.path.join('static', image_filename)) content_paywalled = content_price > 0 # Construct content dictionary db["content"][content_id] = { "name": content_name, "description": form.description.data, "filename": content_filename, "preview_image": image_filename, "paywalled": content_paywalled, "price": content_price, } flash("Content created!") return redirect(url_for('content', content_id=content_id)) return render_template("admin/content-create.html", form = form, **context()) First, we create an instance of ContentCreateForm. This will automatically use the values in request.form, including the uploaded files. We then check whether the current request is an HTTP POST, and we call content's ID using the helper function from forms.py, store our content's price value, and then save our PDF and image files to the content and static directories. Saving images to static will allow Flask to serve them without us writing additional code. We'll need custom code for PDFs, however, as we need to ensure they're only accessible to paying customers. We use the variable content_paywalled to determine whether this PDF should be available for free or behind a paywall. Finally, we save our content's details to the database and redirect the creator to the content page, which we'll build in the next section. At the bottom of the function, we render our content-create page and tell it which form to use. This will happen regardless of whether the initiating request was a GET or a POST. We'll create the template and define the context function when we build the application front-end. Next, we need to create our database flushing functionality. Populate the flush_db function with the following code: @app.route('/admin/db-flush') @web.authenticated @admin_only def flush_db(): # clear db del db["content"] del db["orders"] # clear users for _, user in users.items(): user["content_library"] = [] # delete content and images shutil.rmtree("content") shutil.rmtree("static") # reinit db_init() return redirect(url_for("index")) After deleting all database content and uploaded files, we call db_init() to start afresh. Keep in mind that this function should not be used if you're storing real user data unless you've made a backup. Content viewing and paywalls Now that our site admins can upload PDFs, we need a way for users to view them. We'll start by creating another helper function, just below the definition of is_admin: def owns_content(username, content_id): if "content_library" in users[username].keys() and users[username]["content_library"] is not None: return content_id in users[username]["content_library"] We have to do several checks on our user's content_library, as it can be in a few different states – the key might not exist, or it might be set to None, or it might be a list. We'll use this function to determine which content has been purchased by a given user and thus avoid writing all these checks again. Now we need to create our application's content-viewing routes. We'll start by rewriting the / route so that it renders a template rather than a greeting string. This page will contain a list of PDFs. Change the code in index to the following: # Main app @app.route("/") @web.authenticated def index(): return render_template("index.html", **context()) Then we'll write a route that displays individual PDF metadata, by adding this function just below the definition of index: @app.route("/content/<content_id>") @web.authenticated def content(content_id): return render_template("content.html", content_id=content_id, **context()) The content_id value will be the same ID that we're using in our database. This page will contain the content's name, preview image, description, and either a download link, or a purchase link, depending on whether the PDF is paywalled, and whether the current user has purchased it. Lastly, we need a route that handles downloading actual PDFs. Add the following code just below the content function definition: @app.route("/content-file/<content_id>") @web.authenticated def content_file(content_id): content = db["content"][content_id] if not content["paywalled"] or owns_content(web.auth.name, content_id): return send_from_directory("content", path=content["filename"]) else: return "Access denied." If the current user owns this PDF, or it's not paywalled, we use Flask's send_from_directory to allow them to download it. Otherwise, we return an error message. Creating the application frontend We have most of our application back-end, so now let's create the front-end. We'll do this using HTML and Jinja, Flask's front-end templating language. First, let's create the following HTML files in a new directory called templates: templates/ |__ admin/ | |__ content-create.html |__ _macros.html |__ content.html |__ index.html |__ layout.html Once you've created these files, let's populate them, starting with templates/layout.html: <!DOCTYPE html> <html> <head> <title>Books and Manuscripts</title> </head> <body> {% with messages = get_flashed_messages() %} {% if messages %} <ul class=flashes> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> {% endif %} {% endwith %} {% if name != None %} <p>Logged in as {{ username }}</p> {% endif %} {% block body %}{% endblock %} </body> </html> We'll use this file as the base of all our pages, so we don't need to repeat the same HTML. It contains features we want on every page, such as flashed messages, and an indication of who's currently logged in. provide our form fields with error-handling, provided by WTForms. We'll use this macro in templates/admin/content-create.html, which we'll populate with the following code: {% extends "layout.html" %} {% block body %} {% from "_macros.html" import render_field %} <h1>Upload content item</h1> <form action="/admin/content-create" method="post" enctype="multipart/form-data"> {{ render_field(form.name) }} {{ render_field(form.description) }} {{ render_field(form.file) }} {{ render_field(form.image) }} {{ render_field(form.price) }} {{ form.csrf_token }} {{ form.submit }} </form> {% endblock %} Here, {% extends "layout.html" %} tells our templating engine to use layout.html as a base template, and {% block body %} ... {% endblock %} defines the code to place inside layout.html's body block. Our render_function macro will be used to show our different form fields – some of these will be text input fields, while others will be file upload fields. Our form also has a hidden field specified by {{ form.csrf_token }}. This is a security feature WTForms provides to prevent cross-site request forgery vulnerabilities. Let's define our home page now, with a list of content items. Add the following code to templates/index.html: {% extends "layout.html" %} {% block body %} <h1>Marketplace</h1> <ul> {% for id, content in content.items() %} <li> <a href="/content/{{ id }}">{{ content.name }}</a> {% if content.paywalled %} {% if id in my_library %} (PURCHASED) {% else %} ({{ "${:,.2f}".format(content.price) }}) {% endif %} {% endif %} </li> {% endfor %} {% if admin %} <li><a href="/admin/content-create">NEW CONTENT...</a></li> {% endif %} </ul> {% if admin %} <h1>Admin functions</h1> <ul> <li><a href="/admin/db-flush">Flush database</a></li> </ul> {% endif %} {% endblock %} We display each piece of content in a list. If an item is paywalled, we show its price if the current user hasn't already purchased it, or "(PURCHASED)" if they have. In addition, we use {% if admin %} blocks to include links to admin functionality, such as content creation and database flushing, that will only display when an admin is logged in. The last page we need to create is templates/content.html, which will display information about individual PDFs: {% extends "layout.html" %} {% block body %} <h1>{{ content[content_id].name }}</h1> <img src='/{{ content[content_id].preview_image }}' style='max-width: 150px'> <p>{{ content[content_id].description }}</p> {% if content_id in my_library or not content[content_id].paywalled %} <a href="/content-file/{{ content_id }}">Download PDF</a> {% else %} <form action="/checkout/{{ content_id }}" method="POST"> <button type="submit" id="checkout-button">Buy {{ content[content_id].name }} for {{ "${:,.2f}".format(content[content_id].price) }}</button> </form> {% endif %} {% endblock %} As with the home page, we display different parts of the page depending on whether the content is paywalled, and whether the current user owns it. If the user must purchase the PDF, we include a single-button form that posts to We've referred to a lot of different variables in our front-end templates. Flask's Jinja templating framework allows us to pass the variables we need into render_template, as we did when building the application backend. Our content creation page needed a form, and our content viewing pages needed an ID. In addition, we unpack the return value of a function named context to all of our rendered pages. Define this function now with our other helper functions in main.py, just below owns_content: def context(): if "content_library" in users.current.keys() and users.current["content_library"] is not None: my_library = users.current["content_library"] else: my_library = [] return { "username": web.auth.name, "my_library": my_library, "admin": is_admin(web.auth.name), "content": db["content"] } This will give every page most of the application's state, including the full content dictionary and the current user's library. If we find we need another piece of state later, we can add it to the context helper function, and it will be available to all our pages. Run your repl now and add some content. For best results, open the site in a new tab, rather than using it in your repl's browser. If you add free PDFs, you'll be able to download them, but you won't be able to purchase paywalled PDFs yet. Integrating with Stripe Our application is fully functional for free PDFs. To have users pay for premium PDFs, we'll integrate Stripe Checkout. This will save us the trouble and risk of developing our own payment gateway or storing users' card details. To use Stripe Checkout, you will need an activated Stripe account. Create one now at if you haven't already. Once you've created a Stripe account, add the following code near the top of main.py, just below the import statements: # Stripe setup stripe.api_key = os.environ["STRIPE_KEY"] DOMAIN = "YOUR-REPL-URL-HERE" You can find your Stripe API keys on this page of the developer dashboard. Make sure that you're in test mode and copy the secret key to your clipboard. Then return to your repl and create an environment variable called STRIPE_KEY with the value you just copied from Stripe. You will also need to replace the value of DOMAIN with your repl's root URL. You can get this URL from the in-repl browser. Stripe Checkout Stripe provides detailed technical documentation and code snippets in a variety of languages, so setting up basic integration is largely a matter of copying and adapting these code snippets to our needs. We'll start by creating the /checkout/<content_id> route. This will create a new Stripe checkout session and redirect the user to a Stripe payment page. Add the following code below your content_file function definition: # Stripe integration @app.route("/checkout/<content_id>", methods=["POST"]) @web.authenticated def checkout(content_id): # Proceed to checkout try: line_items=[ { "price_data": { "currency": "usd", "product_data": { "name": db["content"][content_id]["name"], "images": [DOMAIN + "/" + db["content"][content_id]["preview_image"]] }, 'unit_amount': int(db["content"][content_id]["price"]*100), }, "quantity": 1 }, ], payment_method_types=[ 'card', ], mode='payment', success_url=DOMAIN + '/success?session_id={CHECKOUT_SESSION_ID}', cancel_url=DOMAIN + '/cancel' ) except Exception as e: return str(e) # Record order order_id = checkout_session.id db["orders"][order_id] = { "content_id": content_id, "buyer": web.auth.name } return redirect(checkout_session.url, code=303) This code is adapted from Stripe's sample integration Python code. It initiates a checkout from the pricing and product details we provide and redirects the user to Stripe's checkout website to pay. If payment is successful, it sends the user to a success_url on our site; otherwise, it sends to the user to a cancel_url. We'll define both of these shortly. We've made two key changes to the sample code. First, we've included the details for our content item in line_items: line_items=[ { "price_data": { "currency": "usd", "product_data": { "name": db["content"][content_id]["name"], "images": [DOMAIN + "/" + db["content"][content_id]["preview_image"]] }, 'unit_amount': int(db["content"][content_id]["price"]*100), }, "quantity": 1 }, ], Rather than defining individual products on Stripe's side, we're programmatically constructing our products at checkout time. This saves us from having to add our PDF metadata in two places. We provide our product's name, and the full URL of its preview image, so both can be shown on the Stripe Checkout page. As Stripe expects prices in cents, we multiply the price from our database by 100 before converting it to an integer. The second change we've made to the sample code is to record the order details in our database. We need to do this so that we can fulfill the order once it's paid for. # Record order order_id = checkout_session.id db["orders"][order_id] = { "content_id": content_id, "buyer": web.auth.name } We reuse Stripe's Checkout Session object's id as our order_id so that we can link the two later. If you run your repl now, you should be able to reach the Stripe checkout page for any paywalled content you've added. Don't try to pay for anything yet though, as we still need to build order fulfillment. Stripe fulfillment As we're selling digital goods, we can integrate fulfillment directly into our application by adding purchased content to the buyer's library as soon as payment has been made. We'll do this with a function called fulfill_order, which you can add just below the def fulfill_order(session): # Get order details content_id = db["orders"][session.id]["content_id"] buyer = db["orders"][session.id]["buyer"] # Add content to library if session.payment_status == "paid" and not owns_content(buyer, content_id): if users[buyer]["content_library"] is not None: users[buyer]["content_library"].append(content_id) else: users[buyer]["content_library"] = [content_id] This function takes a Stripe Checkout Session object, retrieves the corresponding order from our database, and then adds the order's content to the buyer's library if a payment has been made, and the buyer does not already own the content. We'll invoke this function from our /success route, which we'll define just below it. @app.route('/success', methods=['GET']) @web.authenticated def success(): # Get payment info from Stripe session = stripe.checkout.Session.retrieve(request.args.get('session_id')) # Abort if user is not buyer if web.auth.name != db["orders"][session.id]["buyer"]: return "Access denied." fulfill_order(session) return render_template_string(f'<html><body><h1>Thanks for your order, {web.auth.name}!</h1><p>Your purchase has been added to your <a href="/">library</a>.</p></body></html>') Here we retrieve the session details from the session_id GET parameter Stripe passed to our app, ensure that the current user is also the order buyer, and call fulfill_order. We then render a simple success page. You can replace this with a full Jinja template if you want to make it a bit fancier. We also need to define the /cancel route, used if the payment fails. This one is quite simple: @app.route('/cancel', methods=['GET']) @web.authenticated def cancel(): return render_template_string("<html><body><h1>Order canceled.</h1></body></html>") If you run your repl now, you should be able to purchase content. You can find test credit card numbers on the Stripe integration testing documentation page. You can use any future date as the expiry date and any CVV. Webhooks A potential problem with the way we're fulfilling orders is that a user might close the Stripe Checkout tab or lose internet connectivity after their payment has been confirmed, but before they're redirected to our /success route. If this happens, we'll have their money, but they won't have their PDF. For this reason, Stripe provides an additional method for fulfilling orders, based on webhooks. A webhook is an HTTP route intended to be used by machines rather than people. Much like we've created routes for our admins to upload PDFs, and our users to buy PDFs, we'll now create a route for Stripe's bots to notify our application of completed payments. First, you'll need to create a webhook on your Stripe Dashboard. Visit the Webhooks page and click Add endpoint. You should then see a page like this: On this page, do the following: For the Endpoint URL value, enter your repl's URL, followed by /fulfill-hook. Select the Click Add endpoint. Stripe should then redirect you to your new webhook's details page. From here you can see webhook details, logs and the signing secret. The signing secret is used to ensure that our webhook only accepts requests from Stripe – otherwise, anyone could call it with spoofed data and complete orders without paying. Reveal your webhook's signing secret and copy it to your clipboard, then return to your repl. We'll use another environment variable here. Add the following code below your cancel function definition: endpoint_secret = os.environ['ENDPOINT_SECRET'] Then create an environment variable called ENDPOINT_SECRET with the value you just copied from Stripe. For our app's webhook code, we can once again tweak Stripe's sample code. We'll use this order fulfillment code as a base. Add this code below your endpoint_secret assignment: @app.route('/fulfill-hook', methods=['POST']) def fulfill_webhook(): event = None payload = request.data sig_header = request.headers['STRIPE_SIGNATURE'] try: event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) except ValueError as e: # Invalid payload raise e except stripe.error.SignatureVerificationError as e: # Invalid signature raise e # Handle the event if event['type'] == 'checkout.session.completed': session = event['data']['object'] # Fulfill the purchase... fulfill_order(session) else: print('Unhandled event type {}'.format(event['type'])) return jsonify(success=True) After ensuring that the request we've received comes from Stripe, we retrieve the Checkout Session object from Stripe's fulfill_order. If you run your repl now, you should be able to purchase a PDF, close the checkout page after your payment is accepted but before being redirected, and still end up with the PDF in your library. You can also view webhook invocation logs on the Stripe Dashboard. Where next? We've built a functional if fairly basic storefront for digital goods. If you'd like to continue with this project, consider the following extensions: - Improving the site's appearance with custom CSS. - Branching out from PDFs to other files, such as audio podcasts, videos, or desktop software. - Providing a subscription option that gives users access to all PDFs for a limited time. - Converting the site into a peer-to-peer marketplace where users can all upload and purchase files from each other. You can find the code for this tutorial here:
https://docs.replit.com/tutorials/paid-content-site
CC-MAIN-2022-27
refinedweb
4,621
57.67
Comment on Tutorial - FileReader and FileWriter example program in Java By Tamil Selvan Comment Added by : João Comment Added at : 2012-04-11 19:22:14 Comment on Tutorial : FileReader and FileWriter example program in Java By Tamil Selvan The actual code to write F2 is: f2.write(buffer,buffer.length-buffer.length/4,buffer.length/4); f2.close(); Because here you "say" Write the buffer. Starting from buffer.length-buffer.length/4 = 96-(96/4) = 96-24 = 72. Than it will start after the 72tah char of buffer. And finally write buffer.length/4 = (24 hav project work in this topic so pls View Tutorial By: sullan at 2011-05-08 12:08:56 2. Hi,first of all thats for this code developer, its View Tutorial By: Kathir at 2008-02-08 06:16:51 3. I have tried that but still getting the same error View Tutorial By: pra at 2008-04-14 21:55:44 4. Hi Friends, Saw all of your comments. The a View Tutorial By: Avinash at 2011-11-28 04:43:09 5. Simpler example: import java.io.*; View Tutorial By: Joseph Harner at 2011-12-04 23:20:48 6. i have to learn java View Tutorial By: md arif alam at 2013-04-15 18:30:27 7. this site is really very useful. it provide View Tutorial By: ankush bansal at 2009-11-12 08:34:13 8. Thx, this helped a lot. How can I I View Tutorial By: Marko at 2008-10-09 01:32:37 9. Very usefull info.. Thank alot View Tutorial By: Srikanth at 2012-09-04 15:44:30 10. hello after working with this code i got the follw View Tutorial By: Tapaswini Sabat at 2011-11-05 12:43:49
http://java-samples.com/showcomment.php?commentid=37727
CC-MAIN-2018-22
refinedweb
299
77.13
Is it possible to update a file without modifying its ctime? Sorry if my topic seems unclear but I'm coming from the world of IBM's main frame. If I correctly understand, under Unix, ctime attribute of a file is not the creation date/time but the date/time of last change of an attribute, and if we modify a file, we modify its mtime, thus an attribute, thus its ctime also. And IOS comes from the same kernel as Unix... Thus my question is: is it possible to update/modify a file (in place) without modifying its ctime? I'm not sure about when exactly the ctimeis updated. There is an os.utimefunction that can be used to change the atimeand mtime(but not the ctime), so you could use that to preserve the access/modification times. Thanks for spending your time. I know utime but I want to know if it's possible to keep the real creation time. The question is for what you need this. If you want to preserve ctimevalue even when you modify file content / metadata, then there's no way. But if you want to know real time when the file was created, fstat64& birthtime(not ctime) is your friend. Or NSFileCreationDateattribute on iOS 64-bit ( NSFileManager.attributesOfItemAtPath:error:). @zrzka I only want to know the creation date/time, thus this birthtime should be what I need, but I don't understand how to use it. Thanks for your help Copy & paste this script to your Pythonista and run it. from objc_util import ObjCClass import editor NSFileManager = ObjCClass('NSFileManager') NSFileCreationDate = 'NSFileCreationDate' attrs = NSFileManager.defaultManager().attributesOfItemAtPath_error_(ns(editor.get_path()), None) creation_date = attrs[NSFileCreationDate] print('File name: {}'.format(editor.get_path())) print('File creation date: {}'.format(creation_date)) print('File creation timestamp: {}'.format(creation_date.timeIntervalSince1970())) Console output File name: /private/var/mobile/Containers/Shared/AppGroup/6644AB67-CC6B-4108-B96C-5DCDAC15FB7C/Pythonista3/Documents/birthtime.py File creation date: 2017-08-11 14:55:52 +0000 File creation timestamp: 1502463352.8284547 @zrzka "ns not defined" error, but if I replace ns(...) by a file name, it's ok. Thanks a lot for your help. Ok, I also imported ns 😅 That's how Pythonista works. Always forgot to reset env before testing and some of these things are already imported. Glad you fixed it by yourself :) Analyze (pyflakes)in the wrench menu can help you to see these issues.
https://forum.omz-software.com/topic/4278/is-it-possible-to-update-a-file-without-modifying-its-ctime
CC-MAIN-2018-30
refinedweb
400
58.89
CSPICE_SINCPT computes the surface intercept of the ray on a target body at a specified epoch, optionally corrected for light time and stellar aberration, given an observer and a direction vector defining a ray, This routine supersedes cspice_srfxpt, which does not have an input argument for the target body-fixed frame name. For important details concerning this module's function, please refer to the CSPICE routine sincpt_c. Given: method is a short string providing parameters defining the computation method to be used. In the syntax descriptions below, items delimited by brackets are optional. `method' may be assigned the following values: 'ELLIPSOID' The intercept computation uses a triaxial ellipsoid to model the surface of the target body. The ellipsoid's radii must be available in the kernel pool. 'DSK/UNPRIORITIZED[/SURFACES = <surface list>]' The intercept double precision scalar epoch of participation of the observer, expressed as ephemeris seconds past J2000 TDB: intercept intercept point `spoint' and the observer-to- intercept vector `srfvec' will be expressed relative to this reference frame. abcorr the scalar string. Case and embedded blanks are not significant in 'abcorr'. obsrvr the scalar string. dref the name of the reference frame relative to which the ray's direction vector is expressed. This may be any frame supported by the SPICE system, including built-in frames (documented in the Frames Required Reading) and frames defined by a loaded frame kernel (FK). The string `dref' is case-insensitive, and leading and trailing blanks in `dref' are not significant. the double precision 3-vector defining the'. the call: cspice_sincpt, method, target, et, fixref, abcorr, $ obsrvr, dref, dvec, spoint, trgepc, $ srfvec, found returns: spoint double precision 3-vector defining target body-fixed frame designated by FIXFRM.. trgepc the scalar double precision "intercept epoch." This is the epoch at which the ray defined by 'obsrvr' and 'dvec' intercepts the target surface at 'spoint'. 'trgepc' is defined as follows: letting 'lt' be the one-way light time between the observer and the intercept vector from the observer's position at 'et' to 'spoint'. 'srfvec' is expressed in the target body-fixed reference frame designated by 'fixref', evaluated at 'trgepc'. The components of 'srfvec' are given in units of km. One can use the CSPICE function vnorm_c found a scalar logical indicating whether or not the ray intersects the target. If an intersection exists 'found' will return as true If the ray misses the target, 'found' will return as false. Any numerical results shown for this example may differ between platforms as the results depend on the SPICE kernels used as input and the machine specific arithmetic implementation.. ;; ;; Local variables ;; abcorr = 'CN+S' camera = 'MGS_MOC_NA' fixref = 'IAU_MARS' method = 'Ellipsoid' obsrvr = 'MGS' target = 'Mars' utc = '2003 OCT 13 06:00:00 UTC' NCORNR = 4 ;; ;; Load kernel files. ;; cspice_furnsh, 'standard.tm' cspice_furnsh, [ '/kernels/MGS/ik/moc20.ti', $ '/kernels/MGS/sclk/MGS_SCLKSCET.00061.tsc', $ '/kernels/MGS/spk/mgs_ext12_ipng_mgs95j.bsp',$ '/kernels/MGS/ck/mgs_sc_ext12.bc' ] ;; ;; Convert the UTC request time to ET (seconds past ;; J2000, TDB). ;; cspice_str2et, utc, et ;; ;; Get the MGS MOC Narrow angle camera (MGS_MOC_NA) ;; ID code. Then look up the field of view (FOV) ;; parameters. ;; cspice_bodn2c, camera, camid, found if ( ~found ) then begin print, 'SPICE(NOTRANSLATION) ' + $ 'Could not find ID code for instrument ', camera return endif ;; ;; cspice_getfov will return the name of the camera-fixed frame ;; in the string 'dref', the camera boresight vector in ;; the array 'bsight', and the FOV corner vectors in the ;; array 'bounds'. ;; cspice_getfov, camid, NCORNR, shape, dref, bsight, bounds print, 'Surface Intercept Locations for Camera' print, 'FOV Boundary and Boresight Vectors' print, ' ' print, ' Instrument: ', camera print, ' Epoch: ', utc print, ' Aberration correction: ', abcorr print, ' ' for i=0, NCORNR do begin if ( i lt NCORNR ) then begin print, 'Corner vector ', i dvec = bounds(*,i) endif if ( i eq NCORNR ) then begin print, 'Boresight vector' dvec = bsight endif print, ' ' ;; ;; Compute the surface intercept point using ;; the specified aberration corrections. ;; cspice_sincpt, method, target, et, fixref, abcorr, $ obsrvr, dref, dvec, spoint, trgepc,$ srfvec, found if ( found ) then begin ;; ;; Compute range from observer to apparent intercept. ;; dist = norm( srfvec ); ;; ;; Convert rectangular coordinates to planetocentric ;; latitude and longitude. Convert radians to degrees. ;; cspice_reclat, spoint, radius, lon, lat lon = lon * cspice_dpr() lat = lat * cspice_dpr() print, FORMAT ='("Vector in ", A, " frame")', dref print, FORMAT ='(" ",E18.10, E18.10, E18.10)', dvec print, ' ' print, 'Intercept:' print, ' ' print, FORMAT = $ '(" Radius (km) = ",E18.10)', radius print, FORMAT = $ '(" Planetocentric Latitude (deg) = ",E18.10)', lat print, FORMAT = $ '(" Planetocentric Longitude (deg) = ",E18.10)', lon print, FORMAT = $ '(" Range (km) = ",E18.10)', dist print, ' ' endif else begin print, 'Intercept not found.' return endelse endfor ;; ;; It's always good form to unload kernels after use, ;; particularly in IDL due to data persistence. ;; cspice_kclear IDL outputs: Surface Intercept Locations for Camera FOV Boundary and Boresight Vectors Instrument: MGS_MOC_NA Epoch: 2003 OCT 13 06:00:00 UTC Aberration correction: CN+S Corner vector 0 Vector in MGS_MOC_NA frame 1.8571383810E-06 -3.8015622659E-03 9.9999277403E-01 Intercept: Radius (km) = 3.3849411359E+03 Planetocentric Latitude (deg) = -4.8477481924E+01 Planetocentric Longitude (deg) = -1.2347407905E+02 Range (km) = 3.8898310366E+02 Corner vector 1 Vector in MGS_MOC_NA frame 1.8571383810E-06 3.8015622659E-03 9.9999277403E-01 Intercept: Radius (km) = 3.3849396987E+03 Planetocentric Latitude (deg) = -4.8481636340E+01 Planetocentric Longitude (deg) = -1.2339882297E+02 Range (km) = 3.8897512129E+02 Corner vector 2 Vector in MGS_MOC_NA frame -1.8571383810E-06 3.8015622659E-03 9.9999277403E-01 Intercept: Radius (km) = 3.3849396899E+03 Planetocentric Latitude (deg) = -4.8481661910E+01 Planetocentric Longitude (deg) = -1.2339882618E+02 Range (km) = 3.8897466238E+02 Corner vector 3 Vector in MGS_MOC_NA frame -1.8571383810E-06 -3.8015622659E-03 9.9999277403E-01 Intercept: Radius (km) = 3.3849411271E+03 Planetocentric Latitude (deg) = -4.8477507498E+01 Planetocentric Longitude (deg) = -1.2347408220E+02 Range (km) = 3.8898264472E+02 Boresight vector Vector in MGS_MOC_NA frame 0.0000000000E+00 0.0000000000E+00 1.0000000000E+00 Intercept: Radius (km) = 3.3849404102E+03 Planetocentric Latitude (deg) = -4.8479579822E+01 Planetocentric Longitude (deg) = -1.2343645396E+02 Range (km) = 3.8897573572E+02 Given a ray defined by a direction vector and the location of an observer, cspice_sincpt computes the surface intercept point of the ray on a specified target body. sincpt_c also determines the vector from the observer to the surface intercept point. If the ray intersects the target in multiple locations, the intercept closest to the observer is selected.' Round-off errors and mitigating algorithms ------------------------------------------ When topographic data are used to represent the surface of a target body, round-off errors can produce some results that may seem surprising. Note that, since the surface in question might have mountains, valleys, and cliffs, the points of intersection found for nearly identical sets of inputs may be quite far apart from each other: for example, a ray that hits a mountain side in a nearly tangent fashion may, on a different host computer, be found to miss the mountain and hit a valley floor much farther from the observer, or even miss the target altogether. Round-off errors can affect segment selection: for example, a ray that is expected to intersect the target body's surface near the boundary between two segments might hit either segment, or neither of them; the result may be platform-dependent. A similar situation exists when a surface is modeled by a set of triangular plates, and the ray is expected to intersect the surface near a plate boundary. To avoid having the routine fail to find an intersection when one clearly should exist, this routine uses two "greedy" algorithms: 1) If the ray passes sufficiently close to any of the boundary surfaces of a segment (for example, surfaces of maximum and minimum longitude or latitude), that segment is tested for an intersection of the ray with the surface represented by the segment's data. This choice prevents all of the segments from being missed when at least one should be hit, but it could, on rare occasions, cause an intersection to be found in a segment other than the one that would be found if higher precision arithmetic were used. 2) For type 2 segments, which represent surfaces as sets of triangular plates, each plate is expanded very slightly before a ray-plate intersection test is performed. The default plate expansion factor is 1 + 1.e-10 In other words, the sides of the plate are lengthened by 1/10 of a micron per km. The expansion keeps the centroid of the plate fixed. Plate expansion prevents all plates from being missed in cases where clearly at least one should be hit. As with the greedy segment selection algorithm, plate expansion can occasionally cause an intercept to be found on a different plate than would be found if higher precision arithmetic were used. It also can occasionally cause an intersection to be found when the ray misses the target by a very small distance. FRAMES.REQ NAIF_IDS.REQ PCK.REQ SPK.REQ TIME.REQ -Icy Version 2.0.0, 04-APR-2017, EDW (JPL), NJB (JPL) Updated to support use of DSKs. -Icy Version 1.0.1, 25-OCT-2011, SCK (JPL) References to the new 'cspice_pxfrm2' routine were added to the 'I/O returns' section. A problem description was added to the 'Examples' section, and the references to 'srfxpt_c' and the second example were removed. -Icy Version 1.0.0, 11-FEB-2008, EDW (JPL) find surface intercept point find intersection of ray and target body surface find intercept of ray on target body surface Wed Apr 5 17:58:03 2017
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/IDL/icy/cspice_sincpt.html
CC-MAIN-2019-35
refinedweb
1,580
55.03
Go to: Synopsis. Return value. Related. Flags. Python examples. polyAppendVertex([append=[[, float, float, float, ]]], [constructionHistory=boolean], [hole=boolean], [name=string], [point=[float, float, float]], [texture=int], [vertex=int]) Note: Strings representing object names and arguments must be separated by commas. This is not depicted in the synopsis. polyAppendVertex is undoable, queryable, and editable.Appends a new face to the selected polygonal object. The direction of the normal is given by the vertex order: the face normal points towards the user when the vertices rotate counter clockwise. Note that holes must be described in the opposite direction. In query mode, return type is based on queried flag. import maya.cmds as cmds cmds.polyPlane( sx=3, sy=3 ) # add a new face cmds.polyAppendVertex( a=[6, 10, (.167, .3, -.167), (.167, .3, .167)] ) # add a new holed face cmds.polyAppendVertex( a=[9, 5, (-.167, .3, .167), (-.167, .3, -.167), (), (-.167, .2, .1), (-.167, .1, 0), (-.167, .2, -.1)] ) # connect the two new faces cmds.polyAppendVertex( a=[18, 17, 16, 19] ) # add a new unconnected quad cmds.polyAppendVertex( a=[(-.5, .5, -.5), (.5, .5, -.5), (.5, .5, .5), (-.5, .5, .5)] )
http://download.autodesk.com/global/docs/maya2014/en_us/CommandsPython/polyAppendVertex.html
CC-MAIN-2019-13
refinedweb
189
68.47
Convert Text to Speech using Python Want to share your content on python-bloggers? click here. In this article we will discuss how to convert text to speech using Python. Table of contents - Introduction - Basic text to speech conversion - Changing voice - Changing speech rate - Changing volume - Saving speech as mp3 file - Conclusion Introduction The text-to-speech (TTS) conversion along with speech synthesis became increasingly popular with the growth of programming communities. There are currently several Python libraries that allow for this functionality and are continuously maintained and have new features added to them. To continue following this tutorial we will need the following Python library: pyttsx3. If you don’t have it installed, please open “Command Prompt” (on Windows) and install it using the following code: pip install pyttsx3 Basic text to speech conversion using Python The basic functionality of this library is very simple to use. All we are required to do is import the library and initialize the speech engine, have the text in the string format, and execute the text to speech process: import pyttsx3 engine = pyttsx3.init() engine.say('This is a test phrase.') engine.runAndWait() What you will hear at default settings is a female voice that pronounced the phrase quite fast. For the cases when you either want to change the voice or the speech rate or the volume, the library provides a lot of flexibility. The engine instance of the class we initialized has the .getProperty() method which will help us adjust the current default settings to the ones we want. Now you can start to explore more features and learn more about how to convert text to speech using Python. Changing voice The The engine instance of the class we initialized in the previous section has pyttsx3 library has two types of voices included in the default configuration: male voice and female voice. These can be retrieved by simply running: voices = engine.getProperty('voices') print(voices) What you should get in return is a list that has the local memory locations of each voice. Now we want to try each of them, and we simply run the text to speech basic usage code through a loop: for voice in voices: engine.setProperty('voice', voice.id) engine.say('This is a test phrase.') engine.runAndWait() An observation we can get is that the male voice is stored in the list at index 0 and female voice is stored in the list at index 1. To set the voice as a permanent setting, the engine instance of the class we initialized has the .setProperty() method. It will allow us to specify which of the two voices the code should use. Let’s say I want to permanently change the voice to male’s (remember it’s at index 0): engine.setProperty('voice', voices[0].id) Now every phrase you will try to run through using the initialized engine will always have the male voice. Changing speech rate After we changed the voice, we may want to adjust the speech rate of how fast each phrase is being said. Using the known .getProperty() method we will first find out what the current speech rate is: rate = engine.getProperty('rate') print(rate) For the default settings the rate showed to be 200 (which should be in words per minute). When I listened to the engine initially I thought it was too fast, so I would like to decrease the words per minute rate to let’s say 125. Similarly to setting the voice, we will use setProperty() method to work with the speech rate and test it: engine.setProperty('rate', 125) engine.say('This is a test phrase.') engine.runAndWait() You should hear a significantly slower speech that it more comfortable to listen. In another case, if you feel that the speech rate is too low you can always adjust it and generally just keep trying different values until you find the one that you are satisfied with. Changing volume Similarly to the speech rate adjustment, we can alter the volume of the voice we set. Using the known .getProperty() method we will first find out what the current volume is: volume = engine.getProperty('volume') print(volume) For the default settings the rate showed to be 1.0 (which is the maximum we can have and the range is between 0 and 1). You can basically choose any value between 0 and 1 to see how the volume changes. Similarly to setting the speech rate, we will use setProperty() method to work with the volume and test it: engine.setProperty('volume', 0.5) engine.say('This is a test phrase.') engine.runAndWait() Here we set the volume to be half of what it was before and notice the difference when we listen to the test phrase. Such a setting allows for great flexibility with adjustments depending on the narrative based on the use of your text to speech conversion. Saving speech as mp3 file using Python Another wonderful functionality provided in this library is the ability to simply store our text to speech conversions as mp3 files which can be listened later in any audio player.. You can of course alter the destination by specifying it in the output file path. Conclusion In this article we discussed how to convert text to speech using Python. By working through this code, you should be able to convert full texts to speech with the required adjustments. I also encourage you to check out my other posts on Python Programming. You can learn more about the pyttsx3 library here. Feel free to leave comments below if you have any questions or have suggestions for some edits. The post Convert Text to Speech using Python appeared first on PyShark. Want to share your content on python-bloggers? click here.
https://python-bloggers.com/2020/10/convert-text-to-speech-using-python/
CC-MAIN-2021-10
refinedweb
970
61.87
asinh, asinhf, asinhl - inverse hyperbolic sine functions #include <math.h> double asinh(double x); float asinhf(float x); long double asin inverse hyperbolic s sine of their argument. [MX] If x is NaN, a NaN shall be returned.If x is NaN, a NaN shall be returned. If x is ±0, or ±Inf, x(), sinh(), the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.18, Treatment of Error Conditions for Mathematical Functions, <math.h> First released in Issue 4, Version 2. Moved from X/OPEN UNIX extension to BASE. The asinh() function is no longer marked as an extension. The asinhf() and asin.
http://pubs.opengroup.org/onlinepubs/009604499/functions/asinhl.html
crawl-003
refinedweb
106
71
echash_track_versioning NameName echash_track_versioning — Enable versioning on a hash table SynopsisSynopsis #include "echash.h" | void **echash_track_versioning** ( | h ); | | ec_hash_table * <var class="pdparam">h</var>; DescriptionDescription Enable versioning on a hash table. When versioning is enabled, each change to the content of the hash will cause the version field of the hash table to change. For a description of this data structure see “ec_hash_table”. The version field is a nearly unique counter that will allow you cheaply determine if a hash table has changed its contents since you last looked at it and recorded its version number. Since the version counter is a global variable, it is guaranteed that no two hash tables can have the same version number, provided that they are both relatively short lived—it is possible to roll the counter but this should take a very long time to occur. - h The ec_hash_table. This function returns void. It is legal to call this function in any thread.
https://www.sparkpost.com/momentum/3/3-api/apis-echash-track-versioning/
CC-MAIN-2021-49
refinedweb
158
62.68
We are pleased to release version 0.7.0 of the Snowplow Java Tracker. Many thanks to David Stendardi from Viadeo, former Snowplow intern Jonathan Almeida and Hamid from Trello for their contributions to this release! In the rest of this post we will cover: - Architectural updates - API updates - Testing updates - Upgrading the Java Tracker - Documentation - Getting help 1. Architectural updates Some Snowplow Java and Android Tracker users have reported serious performance issues running these trackers respectively in server and mobile environments. We are working to fix these issues as quickly as we can; in the meantime, to facilitate these improvements, we have decided to formally separate these trackers and evolve them separately. As of this release, the Java Tracker repository no longer contains a Java Tracker Core library: this functionality has been merged back into the Java Tracker proper. Many thanks to David Stendardi for contributing this merge (#116). The last release of the Android Tracker (0.2.0) is not affected by this change; the next Android Tracker release will remove its dependency on the Java Tracker Core library as well. No longer having to support Android within the Java Tracker repository has allowed us to clean up the code somewhat: specifically, we have reintroduced formal dependencies on Apache Commons Codec and Google Guava where previously we had copy-and-pasted code to keep Android file sizes down. 2. API updates The main update to the API is the merging of the core sub-package back into the main tracker. This means that if you have existing code referencing for example: import com.snowplowanalytics.snowplow.tracker.core.DevicePlatform<span class="o">; This import would become: import com.snowplowanalytics.snowplow.tracker.DevicePlatform<span class="o">; Besides this change, we have also started to clean-up the SchemaPayload and TrackerPayload classes, together with their shared Payload interface (#72, #126). However these updates should not affect the public API materially. 3. Testing updates We have updated our Travis CI configuration to test the tracker on OpenJDK 6 and OracleJDK 8 as well as both JDK 7 versions. Former Snowplow intern Jonathan Almeida has also added some Emitter and Tracker tests which verify the sent payloads using WireMock (#40) – many thanks Jonathan! 4. Upgrading the Java Tracker The new version of the Snowplow Java Tracker is 0.7.0. The Java Setup Guide on our wiki has been updated to the latest version. 5. Documentation You can find the updated Android and Java Tracker usage manual on our wiki. There are no material API changes. You can find the full release notes on GitHub as Snowplow Java Tracker v0.7.0 release. 6. Getting help The Java Tracker is still an immature project and we will be working hard with the community to improve it over the coming weeks and months; in the meantime, do please share any user feedback, feature requests or possible bugs. Feel free to get in touch or raise an issue Java Tracker issues on GitHub!
https://snowplowanalytics.com/blog/2015/01/24/snowplow-java-tracker-0-7-0-released/
CC-MAIN-2022-27
refinedweb
498
52.29
PKCS7_verify - verify a PKCS#7 signedData structure #include <openssl/pkcs7.h> int); PKCS7_verify() verifies a PKCS#7 signedData structure. p7 is the PKCS7 structure to verify. certs is a set of certificates in which to search for the signers certificates from p7, it does not check their validity or whether any signatures are valid. The certs and flags parameters have the same meanings as in PKCS7_verify(). Normallyers certificates, first looking in the certs parameter (if it is not NULL) and then looking in any certificates contained in the p7 structure itself. If any signers certificates cannot be located the operation fails. Each sign signatures checked. If all signaturesers certificates are not chain verified. If PKCS7_NOCHAIN is set then the certificates contained in the message are not used as untrusted CAs. This means that the whole verify chain (apart from the signers certificate) must be contained in the trusted store. If PKCS7_NOSIGS is set then the signatures on the data are not checked. One). PKCS7_verify() returns 1 for a successful verification and zero or a negative value if an error occurs. PKCS7_get0_signers() returns all signers or NULL if an error occurred. The error can be obtained from ERR_get_error(3)(). ERR_get_error(3), PKCS7_sign(3) PKCS7_verify() was added to OpenSSL 0.9.5
http://manpages.sgvulcan.com/PKCS7_verify.3ssl.php
CC-MAIN-2017-09
refinedweb
210
58.69
The Java Specialists' Newsletter Issue 0552002-08-26 Category: Language Java version: GitHub Subscribe Free RSS Feed Welcome to the 55th edition of The Java(tm) Specialists' Newsletter sent to 4461 Java Specialists in 85 countries. We had a good growth in the last two weeks, thanks to your concerted effort in forwarding this newsletter to your friends. There are three people in particular that I want to thank, although many more would be worthy of a mention: Thanks for reading this newsletter on our website. We also have a mailing list. That is where the real action takes place (webinars, free reports, etc.). Maybe subscribe today? A few weeks ago I was talking to someone about the origins of Java, and it occurred to me that I had big gaps in that part of world history. History had never been my forte, at school this was my weakest subject at 35% (at my worst level). Perhaps I should add that I was very weak with South African history, which at the time of me going to high school supposedly started with the white settlers arriving on the shores, and consisted almost entirely of remembering dates. I found such parrotting frivolous, and so my marks were not too hot.). For more history on the origins of Java, please have a look at The Green Project and Java(TM) Technology: An Early History. I printed the manual and kept it next to my bed in case of insomnia (so I thought). When I started reading it, I discovered answers to ancient questions: Why can we have only one public class per .java file? Why are protected members also accessible from the same package? Why do short fields use as much memory as int fields (at least pre-JDK 1.4)? short int In this newsletter I want to highlight the differences between Java 0.2 (i.e. Oak 0.2) and what we have now. For your reference, I will include the section numbers in the Oak 0.2 specification.. Oak had the ability to write a one-line JavaDoc comment. public class OneLineJavaDoc { //* The number of lines allowed in a document. public int numberOfLines; } This is fortunately not supported in Java as it is quite confusing. Oak had some additional keywords that are not currently used in Java: ushort string Cstring unsynchronized clone const goto protect unprotect enum The specification says: "The four integer types of widths of 8, 16, 32 and 64 bits, and are signed unless prefixed by the unsigned modifier. unsigned In the sidebar it says: "unsigned isn't implemented yet; it might never be." How right you were. In my newsletter on Determining Memory Usage in Java, I noted that when you have a data member of byte or short, that they still use up at least 4 bytes of memory. This was changed in JDK 1.4, but the historical reason is found in the Oak spec: "A variable's type does not directly affect its storage allocation. Type only determines the variable's properties and legal range of values. If a value is assigned to a variable that is outside the legal range of the variable, the value is reduced modulo the range." I wish I had known that when I wrote my first Java program. I spent a lot of time deciding which data types I wanted to use in order to save memory, but I was actually wasting my time. Please note that this has changed as of JDK 1.4, so now it does help to use bytes and shorts to reduce the memory footprint. byte In Oak, you were able to declare arrays as follows: int a[10]; a[5] = 1; However, we were also able to declare an array in the current Java fashion, with new. I think having two ways of doing the same thing causes confusion, so I am very pleased that this way of making new arrays has been removed. new It appears that final was initially only meant to be used for classes and methods, and that const was used for making fields constant. final This is the most surprising part of Oak 0.2. There were only three access levels as opposed to our current four. There was private which did not require a keyword, and which equated to our current "package private" or "friendly" or "package access" type of access level. All classes in a particular package could use all variables and methods declared in the classes in that package, regardless of public, protected and private declarations. I am very glad that they introduced a more private version of private, one that was only accessible within the class. The lack of private as we know it today explains why when a member is protected, it is also accessible from within the same package. When Oak was written, protected was obviously accessible within the package because their private (our "package access") was the most restrictive access level. I seem to remember that in JDK 1.0 we had a fifth access level called "private protected", which meant that only subclasses could access the member. This piece of surprising history also explains why fields are not private by default - they actually were "private" originally when private meant different things. I don't need to emphasize how pleased I am that we now have the more restrictive "private" modifier. Without that, our industry would be in even more trouble. Abstract methods were defined as in C++: public interface Storing { void freezeDry(Stream s) = 0; } Unfortunately the assertions in Oak 0.2 were not implemented in time, so they were thrown out to satisfy the release deadline. In case you think that assertions are back in JDK 1.4, have a look at the power that "those" assertions gave you: class Calender { static int lastDay[12]= {31,29,31,30,31,30,31,31,30,31,30,31}; int month assert(month>=1 && month<=12); int date assert(date>=1 && date<=lastDay[month]); } While objects are not required to obey the legality constraints within methods, the constraints are enforced at the entry and exit of every public and protected method. I wish that James Gosling had worked a few extra weekends (if that were possible) to finish the implementation of assert as it appeared in the original Oak spec. Preconditions and Postconditions were also loosely defined, but were also kicked out due to time pressure. Pity. assert In Oak, you were able to post-increment a String. You could literally say s1++;, which was equivalent to s1 = s1 + 1;. The post-increment statement is often (if not always) implemented as +=1 so it seems that this also was true for Strings. Fortunately this is not allowed in Java anymore. s1++; s1 = s1 + 1; +=1 Of course, being based on C, Oak included the infamous goto statement. Fortunately this is not in Java. Where does the name RuntimeException come from? Aren't all exceptions thrown at runtime? These are exceptions which are thrown by the runtime system. RuntimeException In Oak 0.2, all exceptions were unchecked, meaning that there was no throws clause. My guess is that checked exceptions were only added once the whole exception hierarchy had already been set in wet concrete. I would have had a separate branch for checked exceptions, something like: throws public class Throwable { } /** Serious errors in the virtual machine */ public class Error extends Throwable { } public class CheckedException extends Throwable { } public class IOException extends CheckedException { } public class UncheckedException extends Throwable { } public class NullPointerException extends UncheckedException { } This way you would avoid catching unchecked exceptions when you catch CheckedException. However, as it appears, the exception class hierarchy was developed before the idea of checked vs. unchecked exceptions, so we are stuck with an exception mechanism that will cause headaches for generations to come. CheckedException If your program gets an asynchronous exception, you are dead. A few weeks ago I was looking at a program that was throwing OutOfMemoryError. This can happen at any time really, which is why it is called an asynchronous exception. Another place where this can happen is with Thread.stop(). As you can imagine, this is inherently dangerous, that is why it is deprecated. In Oak, life was even more dangerous. You could cause an asynchronous exception in another thread using Thread's postException() method. Now that was dangerous! Imagine if other threads could cause asynchronous exceptions at any place in your code! Thread.stop() postException() In order to safeguard your code, you could "protect" it. If you wanted to indicate that you had some critical code which could not handle asynchronous exceptions, you did the following: protect { /* critical section goes here */ } And code that was quite happy with asynchronous exceptions did the following: unprotect { /* code that can afford asynchronous exceptions */ } There was a note in the sidebar saying that the default would probably be changed to not allow asynchronous exceptions except in explicitely unprotected sections of code. I'm very glad that this feature was binned. I cannot imagine how complex our Java programs would have become with it in place. That's it. The rest of the manual was filled with a Glossary and an Index, to push the manual to 38 pages. Even though this manual was written way back in 1994, it provided for fascinating reading, even late at night ;-) Until next time ... Heinz Language Articles Related Java Course
http://www.javaspecialists.eu/archive/Issue055.html
CC-MAIN-2013-48
refinedweb
1,573
61.77
Hi everyone, I'm new to Biopython and python in general so im going through the tutorials trying to get the hang of it for future job prospects in bioinformatics and for fun because why not. I am having a few issues though, for example tutorials aren't great at telling you where to be playing with your program. I was using IDLE for a while until it turned out that i needed to use python.exe to actually install biopython. A problem at the minute is the program not finding the example stuff for this tutorial: from Bio import SeqIO for seq_record in SeqIO.parse("ls_orchid.fasta", "fasta"): printseq_record.id) print(repr(seq_record.seq)) print(len(seq_record)) This just leaves the error: Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> for seq_record in SeqIO.parse("ls_orchid.fasta", "fasta"): File "C:\Users\dlb_p\Desktop\Python\lib\site-packages\Bio\SeqIO\__init__.py", line 592, in parse with as_handle(handle, mode) as fp: File "C:\Users\dlb_p\Desktop\Python\lib\contextlib.py", line 81, in __enter__ return next(self.gen) File "C:\Users\dlb_p\Desktop\Python\lib\site-packages\Bio\File.py", line 87, in as_handle with open(handleish, mode, **kwargs) as fp: FileNotFoundError: [Errno 2] No such file or directory: 'ls_orchid.fasta' I have no idea where to start with this. By the way this may be the first of many posts for help so any pointers would be greatly appreciated. King regards, D Pointon Have you tried hardcoding the full name of the path (including the present working directory) instead of just the filename "ls_orchid.fasta"? Sorry for the late reply, doing alot of 11 hour shift ATM. How would I go about hardcoding the location? Yup, that's exactly how you'd do it. Awesome, I'll give it a go when I get back home. Thanks for the help. I know error messages are scary at first, but especially with Python these usually describe very well what's going wrong. Reading error messages carefully is also an essential skill. Sorry for the late reply. I did try reading it through but it made no sense to me, to me it looks like it found a file but the wrong one and then something on a line if that file caused it to stop working.
https://www.biostars.org/p/287652/
CC-MAIN-2017-51
refinedweb
391
65.73
Hello everybody. When importing xml.parsers.expat from within sublime plugin I get an error: File "./PluginRT.py", line 1, in <module> import xml.parsers.expat File ".\xml\parsers\expat.py", line 4, in <module> ImportError: No module named pyexpat The bundled ST python seems to have this module, zipped inside python26.zip Is there a way I could fix this and use xml.parsers.expat? Maybe the error is platform-specific (I'm on Linux)? I think this might be platform specific I will have to check my linux box at home, but I just tried tried to import xml.parsers.expat on a windows box here at work, and it was included without error. Yeah, I was able to check it myself too — expat is loadable in windows version, but not in linux version (checked with fresh profile just in case). Btw., select python module is missing altogether, unfortunately, though it seems to be the part of standard Python bundle. The linux package does not distribute the pyd files; I believe that is why. Windows package includes pyexpat.pyd, select.pyd, and others, while linux has none. expat cannot be loaded without pyexpat.pyd And how to fix it for Linux? Any ideas? Interesting package github.com/a-sk/sublime-css-colors also generates this error. in my ubuntu with default python 2.7 for some packages I did next trick: import sys sys.path.append("/usr/lib/python2.6/lib-dynload/") /usr/lib/python2.6/lib-dynload - in that folder is pyexpat on the local machine.
https://forum.sublimetext.com/t/import-xml-parsers-expat/2883/3
CC-MAIN-2017-22
refinedweb
259
60.21
Commenter Sys64738 points out that Bjarne Stroustrup's Web site says that "Literally everything at Microsoft is built using various flavors of Visual C++ - mostly 6.0 and 7.0 but we do have a few holdouts still using 5.0 :-(" and wonders if it's true. Well, let's see. Visual C++ 6 came out in 1998 and doesn't support the /GS flag, nor does it support various replacement functions like strcpy_s. This makes it hard for anything compiled with Visual C++ 6 to conform to Microsoft's Security Development Lifecycle which requires all code to be compiled with /GS and bans functions like strcpy. As a result, I would suspect that the statement is no longer true. It may have been mostly true when the statement was originally written in the late 1990's, but things have changed a lot since then. (The statement wasn't even 100% true when it was written, because Windows 95 used a special version of the compiler not found in nature for selected portions of the operating system.) I find it interesting that the fact that the claim appeared on Bjarne Stroustrup's Web site caused the reader to turn off all brain functions responsible for critical evaluation of information. It is unlikely that Mr. Stroustrup has first-hand knowledge of the information on that page; it's almost certainly just a compilation of information reported to him by unnamed sources. (Actually, he even says as much in the opening paragraphs.) And do you honestly think that Visual Studio 2010 is compiled with Visual C++ 6? This reminds me of a comment that I found at the website of a prominent open-source advocate, which claimed that Microsoft doesn't use source control for any of its Windows development. Seriously, where do people get this stuff? VC6+Visual Assist X+WndTabs FTW (everyone said vc10 was the next vc6, it's not) I think the idea that MS still uses VC6 internally was because the Windows Driver Development Kit required VC6 due to changes in the name-mangling of later VC++ compilers. This statement comes from when I was looking at writing a driver just a few years ago, and I don't know if it's true any more given the software policies as reported by Raymond. I have a hunch none of Microsoft's C# apps were compiled using Visual C++ 6 either. I work in one of the largest European investment banks. We use Visual C++ 6.0 for one of our most important software. I just read somewhere that VS2010 was compiled with Visual Basic 6. Microsoft now calls this "legacy dogfooding." I suspect this meme came about during the period when Microsoft was pushing hard to get everyone on VS.NET and everyone was going "screw that, VS6 is good enough for Microsoft, it's good enough for us". I think this misconception might come from the fact that Windows code uses MSVCRT.DLL, which some people think is "the MSVC6 runtime". Which actually brings up a pet peeve of mine: Why is it so hard for non-Microsoft developers to build software written in plain C against MSVCRT.DLL using Microsoft's tools? (For MinGW it is the default C runtime.) For much portable software written in plain C, MSVCRT.DLL is quite sufficient, and building against it has the benefit that you don't need to bundle any C runtime with your installer. (For C++, I fully agree that you want to use something relatively-latest-and-greatest. But then personally I much prefer C# to C++ anyway.) It's not just that the version numbers are wrong; many of those products are not written in C++. I know that WinNT/2k/XP are mostly in C, and I'm pretty sure that SQL Server is also mostly in C. Of course C++ is still heavily used, but it's wrong to say that Windows is written in C++ when the kernel itself and all major DLLs are actually in C. Gabe: That depends on how you define what Windows is. IIRC, Windows was compiled with the WDK tools, which exist a bit outside the Visual C++ realm. Pretty sure that the WDK has the Visual C++ compiler (sometimes the same version, sometimes a different build revision) and other tools but different headers and libraries. LOL. VS2010 is far too slow to have been primarily written in a real language. @Marquess, Compiler/link toolchain is the same, though the revisions are not synchronized with VC releases., and this precludes using most of the secure CRT functions, unless you put some hacks into the code. Also, a debug build wouldn't work because Msvcrtd.dll is not publicly available. Definitely, this might be useful for small in-house developed tools, but not for more complex projects. Although it might be misleading sometimes, the linker version field in the PE header structure would match the Microsoft compiler version used to build a specific Microsoft file. For example, most of Windows XP, as of Service Pack 3, was built with compilers based on either Visual C++ 7.0 (matching Visual Studio .NET 2002) or Visual C++ 7.1 (matching Visual Studio .NET 2003). @blah: Define "real" language. Offtopic: I'm coming to Redmond for a plugfest. If you see a man whistling a tune from, say, Mahler's 6th, that's probably me. "For example, most of Windows XP, as of Service Pack 3, was built with compilers based on either Visual C++ 7.0 (matching Visual Studio .NET 2002) or Visual C++ 7.1 (matching Visual Studio .NET 2003)." Probably depending on whether the file was from original XP or updated as part of SP2. " Indeed, that is how MS internally does it, I think. "But if you want the program be functional on versions prior to Windows Vista, you need to link another object file, and this precludes using most of the secure CRT functions, unless you put some hacks into the code. " That is probably not a problem because MS likely internally use the Strsafe.h functions instead. Windows uses the WDK. It just uses Msvcrt.dll, there's no need for any hacks. I use the WDK for everything, including user space code. I find Visual Studio big and slow and useless, and I particularly dislike vcbuild/msbuild. I absolutely love WDK's build.exe + nmake. @Tor Lillqvist, I *think* it's because you're not supposed to… See msdn.microsoft.com/…/abx4dbyh%28VS.80%29.aspx Specifically (about halfway down the page): What is the difference between msvcrt.dll and msvcr80.dll? The msvcrt.dll is now a "known DLL," meaning that it is a system component owned and built by Windows. It is intended for future use only by system-level components. It is known that Windows at one time used GNU make as its make program, GNU make was invoked recursively. It is also known that some parts of Services for UNIX were at one time compiled with GCC. strcpy_s is never a problem, there is a thing "Platform SDK"(i using version feb 03 or 04), #include <strsafe.h> #pragma comment(lib, "strsafe.lib") i think that StringCbCopy() is better than strcpy_s. It's amazing how many people, and sites, and still using VC++ 6.0 (I've joked in the past that Microsoft has two major C development suites, Visual Studio <insert-current-year-here> and VC++ 6.0). I support a globally-used piece of OSS and every couple of years I ask users whether I can disable 6.0 support, and every year I get the same chorus of replies saying "Hell, no!". I think the reason for VC++ 6.0's ongoing popularity is that it runs circles around any of its successors in terms of speed and responsiveness (every time I've moved to a new version of VS I've felt like I was wading through molasses until I got used to the slowdown), and if you're doing straight C development there's nothing really compelling in newer VS releases that outweigh the bloat that comes with them. I have to admit, I still develop primarily in VC++ 6.0, optionally in VS 2005 if I need newer features. 2008 and 2010 were just too painfully heavyweight to use. From informal surveys of people still on VC++ 6.0 this seems to be the general case, it's good enough for most purposes of the people using it and old enough that it hasn't succumbed to the VS bloat/molasses effect yet. I'll observe here that nothing in the Microsoft section implies that the source is anything but a single email (probably from an MS employee), but from 6-7 years ago. I'd guess it was probably a lot more true 6-7 years ago. We still have many use of VC6 here for old project maintainance. While those project does have moved to VC2005/08, those companies (cough… banks) has bought components from much older version that's before we port-ed the source to newer compilers. They have paid renewal service contract so we can't drop those support, and under the terms we cannot change the required compiling/execution environment without their consent. (Considering my company even still have to support a few products for DOS, this is hardly surprising…) Before I discovered WDK, I searched the binary Windows files for clues what version of the toolchain they used. And it was fun – kind of little detective game. Now I just go to %ddk%binx86_amd64 and check the version of c2.dll :-D That said, the two other major MS products – Office and SQL Server have own pace and I do not know what compiler they use. Causal observation of SQL Server 2008 makes me think it's built with VS 2005 / VC9. (Offtopic rant, feel free to ignore) While VS IDES since '98 are very bad for C/C++ developer, the compilers (and the other parts of the toolchain) are getting better and better. I'd use vs 2008 over vs 98 any time, simply because the compiler is MUCH less buggy (in terms of bad code generation), it understands C++ (the vc6 compiler was atrocious); it generates good code – I've seen instances where vc6 generates one screenful of code where vs2008 generates two asm instructions! And things like stack protection really helps finding bugs early in the development stage – it did this for me yesterday. For VS2010 – well, the new X++ 0x features are like heaven's gift, but the IDE is so slow that it's completely unusable. While the speed of Visual C++ is an issue, personally I've found the tab behaviour (Goes in MRU order rather than the order of the tabs in the toolbar) and the lack of C99 support are bigger nuisances. This is Visual Studio 2008, mind, not sure if 2010 fixes any of that. The way the compiler evangelises strcpy_s and kin is also a bit of an irritance, but you can shut it up easily enough.). "Literally everything at Microsoft is built using various flavors of Visual C++ – mostly 6.0 and 7.0 but we do have a few holdouts still using 5.0 :-(" This link is slow. The site is still up, so just get rid of the web.archive.bibalex.org/…/20071011225313 part. In fact, looks like they already updated the page. public.research.att.com/…/applications.html now says that: "Microsoft: Literally everything at Microsoft is built using recent flavors of Visual C++ (using older versions would automatically cause an application to fail the security review)." So what is Visual Studio 2010 compiled with? If CFF Explorer is to be believed, the IDE was built with VS2005. The toolchain … not so much. [ASK] Using Dependency Walker tool, a dependency from MSVCR100.DLL can be found. So it seems that they may have used VC10 to build VS2010 :-) BTW: Part of the IDE changed from using native technologies like GDI (in VS200x, x <= 8) to WPF; so VS2010 must be a mix of C++ and C#. PS: I find it interesting that the fact that the topic is discussed on Raymond Chen's blog caused Bjarne Stroustrup to finally update his web site :-) PPS: I find it more interesting that several people still use VC6 (which – despite not having a C++0x-compliant C++ compiler – has a great IDE focused on C++, especially if combined with Visual Assist X and WndTabs), after several iterations of VS. BTW: public.research.att.com/…/applications.html I was unaware of "Windows System 7" :) In Windows itself, Microsoft doesn't have to worry when using recent "secure" functions from MSVCRT, because you know that the user has a certain version of Windows! Now if only Microsoft would release the compiler they use internally for putting infrequently-executed code into different parts of the executable… "(The statement wasn't even 100% true when it was written, because Windows 95 used a special version of the compiler not found in nature for selected portions of the operating system.) " What was the banner this compiler displayed when it started up? Microsoft had rapid succession with Visual Studio releases, which introduces new language features, new frameworks, new .NET platforms which was tightly coupled to each version of Visual Studio. One of the biggest Japanese company I'm working with still using Visual C++ 6.0 for developing. They're slowly switching for the new versions of Visual Studios. And we've a number of problems facing for creating build using msbuild, upgrading *huge source* and make it compatible with the newest versions of Visual studio. The product releases and business is important than upgrading to a new version of compiler and it's a mammoth effort. Most of their code are proven for long time even without the secure version of libraries. It's easy for small companies to switch according to Microsoft's frequent releases but for a big company, it's truly hard and the amount spend for license is too huge and it's for a short period of time and then Microsoft come up with entirely new product. security APIs as a litmus test was not my first thought. 64-bit support is. Visual C++ 6's compiler doesn't support 64-bit. I would still use VC6 if I didn't have to do 64-bit… the level of C++ it support is just find for almost everything we need in our 14 milion line of code app. There's just a couple of template things missing. And.. edit-and-continue, debugging, browser, and find-in-file UI was fast and reliable. So much more productive.. The interesting question is, what build system MS uses? nmake? build from WDK? msbuild? VS ide build system? team build? internal one company wide? internal one for teams? batch files? Or gnu make using the posix subsystem :-)
https://blogs.msdn.microsoft.com/oldnewthing/20100607-00/?p=13793
CC-MAIN-2018-47
refinedweb
2,509
63.8
Hi everyone, I'm new and hope someone can help with my problem. First of all English is not my first languaje so I hope you all can be a little patient with my writing :icon_cheesygrin: Here's the thing. I'm new to C++, and I'm using Borland 3.1 (this is the teacher's choice so I prefer to work with this compiler, because I will have to use it for the tests), and I simply haven't been able to work with Strings. I have tried these 3 "includes" (I don't really know how they are called :?: ), #include <string> The compiler gives me an error when I use this one #include <string.h> No problem when compiling #include <CString> No problem when compiling But when I put string q; or CString q; The compiler gives me this 2 errors: "Undefined symbol 'string' (or 'CString' depending of which one I'm using)" and "Statement misssing ;" Any idea? :(
https://www.daniweb.com/programming/software-development/threads/140770/can-t-use-strings
CC-MAIN-2016-50
refinedweb
161
74.93
This has been bugging me for some time now and I can’t seem to make sense of it. My phpinfo reports that PDO is installed and I can connect to my database on my index.php file. But when I try to open a PDO connection on a namespaced class, php is trying to use my autoload function to find PDO.php which won’t work. My class is as follows: abstract class { protected $DB; public function __construct() { try { $this->DB = new PDO("mysql:host=$host;port=$port;dbname=$dbname", $user, $pass); } catch(PDOException $e) { echo $e->getMessage(); } } } And the error is Warning: require_once((...)/Model/PDO.php): failed to open stream: No such file or directory in /(...)/Autoloader.php Fatal error: require_once(): Failed opening required 'vendor/Model/PDO.php' (include_path='.:/Applications/MAMP/bin/php/php5.4.4/lib/php') in /(...)/Autoloader.php As far I as know the autoloader should be called because PHP PDO extension is installed (yes I’m completely sure). My autoload is as follows: spl_autoload_register('apiv2Autoload'); /** * Autoloader * * @param string $classname name of class to load * * @return boolean */ function apiv2Autoload($classname) { if (false !== strpos($classname, '.')) { // this was a filename, don't bother exit; } if (preg_match('/[a-zA-Z]+Controller$/', $classname)) { include __DIR__ . '/../controllers/' . $classname . '.php'; return true; } elseif (preg_match('/[a-zA-Z]+Mapper$/', $classname)) { include __DIR__ . '/../models/' . $classname . '.php'; return true; } elseif (preg_match('/[a-zA-Z]+Model$/', $classname)) { include __DIR__ . '/../models/' . $classname . '.php'; return true; } elseif (preg_match('/[a-zA-Z]+View$/', $classname)) { include __DIR__ . '/../views/' . $classname . '.php'; return true; } } Any help please? Its not really an autoload issue. You are attempting to call a class on the root namespace. By the looks of it your are in some ‘Model’ namespace and calling PDO, you must remember that namespaces are relative by default. What you want is to either call the the absolute path: \PDO or at the top of your file say you’re going to use PDO like this: use PDO; Tags: class, function, pdo, phpphp
https://exceptionshub.com/php-trying-to-use-autoload-function-to-find-pdo-class.html
CC-MAIN-2021-31
refinedweb
331
55.84
Barr works for Schering-Plough Research, a pharmaceutical company. He can be reached at 60 Orange Street, Bloomfield, NJ 07003. The emerging class of small, relatively inexpensive multiple-processor workstation computers provides a degree of raw computing power that seriously challenges the computing power offered by minisupercomputers. The availability of the appropriate software tools -- language extensions, parallelizing compilers, and parallel environment debuggers and profilers -- makes it possible to exploit this multiprocessor architecture in a straightforward manner. This article explores the SGI parallelization scheme that Silicon Graphics has implemented in its Power Series two-processor and four-processor work-stations and their accompanying software development tools. I use a test program to take you through this exploration process. First, I'll introduce the syntax, highlighting coding problems and solutions. Next, I'll describe the actual implementation of the parallelization scheme. Finally, I'll show the bottom line for high-performance computing, and confirm that performance gains are possible with the SGI scheme if one is mindful of its limitations. SGI Parallelization Scheme My exploration strategy centers around the DO loop. If the iterations of the loop are independent from each other, then the loop can be divided among n available processors, and can run roughly n times faster. These separate executing processes are known as "threads." This parallelization scheme is not intended for use with complex, independently executing routines (although a separate set of Unix tools exists to accomplish that). The goal here is to accelerate the speed of more common forms of code. For instance, consider the two DO loops in Figure 1. The scalar DO loop is transformed into a parallel loop by the inclusion of a parallelization directive immediately before the DO statement. Figure 1: A scalar and a parallel DO loop <b>Scalar:</b> do i = 1, n a(i) = b(i) * c(i) enddo <b>Parallel:</b> c$doacross local(i), share(a, b, c, n) do i = 1, n a(i) = b(i) * c(i) enddo The program is parallelized after compilation with the -mp option. The parallelization directive affects only the DO loop that immediately follows that directive. The directive resembles a Fortran comment, and is ignored by the compiler when the -mp option is not used. More importantly, the directive is ignored by other platforms that do not have multiple processors. The syntax allows for LOCAL, SHARE, and LASTLOCAL declarations to restrict the scope of variables and improve program performance (see sidebar 1, page 74). LOCAL variables are localized to each thread. SHARE variables are in common between executing threads. LASTLOCAL variables are treated like LOCAL except that the value of the variable in the thread, which finishes last, is made available to code past the parallelized loop. A variety of Fortran statements, including subroutines, functions, and intrinsics, are allowed inside of parallelized loops. The only restriction is that the statements must have no side effects -- the statements must depend upon input in the passed arguments, they cannot modify common data, and they cannot use static data. All of the intrinsic functions that are supplied in the library meet this requirement and can be used safely. The one construct that is forbidden is branching outside the DO loop. Typically, this construct is a logical test that causes premature termination of the loop. It doesn't make sense to use a conditional exit, which may behave differently for each thread in a parallel environment. Additionally, a number of functions that are unique to the parallel environment are available to help the executing program work more efficiently within the multiprocessor environment. The straightforward syntax of these functions, (which retains the algorithm in its original form), along with transparency to other platforms, facilitate implementation. (This is especially useful for programmers who do not wish to master the details of systems-level programming.) The syntax is conservative in the sense that the loop code itself needs no restructuring; the addition of the directive (and the optional addition of the scope declarations) are the only requirements. The retention of the basic algorithm maintains clarity and aids in the transformation of scalar code. The parallel implementation restructures the code during compilation into separate slaved processes for the parallelized loop (see sidebar 2, page 76). The parallelized program is under software control during execution, and can create as many processes as are appropriate for the machine on which the code is executing. (The number of processes can range from 1, for a single processor system, to 4.) The sensing and adjustment is automatic so that separate versions of a program need not be created for a multiplatform environment. This feature offers a great deal of flexibility to programmers who use networked NFS systems, in which a single executable can go to any target machine. In practice, this works well, although parallelized programs that run on single processor systems execute more slowly due to the system overhead. Data Dependency The primary limitation of a parallelized program is "data dependency," in which one of several currently executing threads alters data that can be read by any other executing thread, producing nonsensical results. When this method of parallelization is used, many common coding situations become unusable unless they are recognized, and then solutions are applied. Consider, for example, the DO loop in Example 1. The process of successful parallelization requires each iteration of the loop to be data-independent of any other iteration of the loop. In this way, the loop can be broken into n separate parallel processes, or can even be left scalar, without affecting the results. As long as the code in the loop for all values of the index is run, regardless of the order or grouping of the code, the outcome is the same. Example 1: A typical DO loop do i = 1, n a(i) = x * b(i) enddo Data dependency occurs when a variable is modified (or could be modified) by one executing thread, while at the same time, other executing threads may be reading or modifying the same variable. The value of the variable becomes unpredictable, causing the code in the loop to produce results that vary from the scalar and also vary from run to run. In the DO loop in Example 2, the array variable arr references a value that is not current with the index. The variable is manipulated and then assigned to arr(i). Other threads can write to arr(i-1), and arr(i) can be referenced by other threads. The iterations are not truly independent. When the DO loop is parallelized, the parallel version cannot guarantee the same result that is guaranteed by use of the scalar version of the loop. This type of data dependence is known as "recurrence." Example 2: A DO loop in which the array variable references a value that is not current with the index do i = 2, n arr(i) = b(i) - arr(i-1) enddo Data dependency inhibits parallelization and does not yield the performance inherent in the machine. The solution to the problem of data dependency is recognition of its existence, followed by modification of the algorithm. A simple modification of the algorithm isn't always possible to do, and not all algorithms can be parallelized. In short, the ability to break data dependency is algorithm-specific. Most algorithms must be approached as special cases. Many different types of dependency can prevent parallelization. A number of common situations have data dependencies that can be generalized. In addition, other situations have data dependencies that are not obvious. Once again, the key is recognition of the existence of data dependency, especially when existing scalar code is adapted to the parallel environment. When parallelization is not possible, the solution usually involves major restructuring of the algorithm. Recurrence The data dependency case discussed in the previous section is an example of recurrence. Modified values recur during the execution cycle of the threads that are associated with a parallelized loop, causing unpredictable results. There is no general way to parallelize loops in which recurrence occurs. One possible solution is to rewrite the algorithm. If the recurrence occurs in the inner loop of nested loops, a solution is to parallelize the outer loop. To see how this works, consider the parallelization shown in Figure 2. If x is used only inside of the loop and the value of x is assigned before x is used, then the loop can be declared a local variable, and can be parallelized. If the value of x is not assigned first, then x becomes data dependent upon the value of x from other iterations. The loop cannot be parallelized by declaring x to be LOCAL. Figure 2: The effect of data dependency with LOCAL variables <b>Local Variables:</b> do i = 1, n x = a(i)**3 b(i) = x * b(i) enddo The variable x is dependent. Without an explicit declaration as LOCAL, this loop cannot be parallelized. c$doaccross local(i, x) do i = 1, n x = a(i)**3 b(i) = x*b(i) enddo Figure 3 presents another example of data dependence, where the value of indx is passed between iterations, causing data dependency to occur. Although indx is used inside of the loop, the value of indx is read before indx is assigned, so indx cannot be a local variable. Dependency can also be created by the manner in which indx is determined, but the determination of indx in this particular case is independent. Figure 3: Example of loop-carried values (complicated indexing) <b>Scalar:</b> index = 0 do i = 1, n indx = indx +i a(i) = b(indx) enddo <b>Parallel:</b> c$doacross local(i, indx) do i = 1, n indx = (i* (i + 1))/2 a(i) = b(indx) enddo If the variable can be determined uniquely for each iteration, so that a value for the variable is not passed from iteration to iteration, then the loop can be parallelized. The value of indx in Figure 3 is determined only from the loop index i. In order to arrive at this solution, the original algorithm was rewritten and is no longer straightforward. This solution, then, is highly algorithm-dependent. The next example of indirect indexing is shown in Figure 4. The problem is seen in the last line of the loop. The value of iix is dependent upon the values stored in the ixoffset and indexx arrays, and cannot be guaranteed to be independent from iteration to iteration. This problem is different from the loop carried value problem because the value of iix is looked up, rather than calculated. Unless the contents of indexx and ixoffset are known to not introduce dependency, iix must be considered dependent. Figure 4: Example of indirect indexing <b>Scalar:</b> do i = 1, n ix = indexx(i) iix = ixoffset(ix) total(iix) = total(iix) + delta enddo <b>Parallel:</b> c$doacross local(ix, i) do i = 1, n ix = indexx(i) iix(i) = ixoffset(ix) enddo do i = 1, n total(iix(i)) = total(iix(i)) + delta enddo Indirect indexing is also a great source of run-time bugs that are nearly impossible to find. The solution is to remove the data-dependent element and place it into a nonparallelized loop. The array index for the second loop is now the only task of the first loop, and is stored in array elements indexed by i, which is common to both loops. Half of the original loop is now parallelized, but performance may be an issue if n is small. Rewriting the loop, or even leaving the original loop as a nonparallelized loop, should be considered if performance suffers in the two-loop case. Note that data dependency is still present in the second loop. "Sum reduction" (Figure 5) is a common procedure that is highly data-dependent. The implementation of sum reduction is similar to the implementation of the loop-carried variable case. In the case of sum reduction, however, the value of total is presumably used outside of the loop (while indx was only used inside of the loop). Figure 5: Example of sum reduction <b>Scalar:</b> total = 0.0 do i = 1, n total = total + a(i) enddo <b>Parallel:</b> c$doacross local(i, k) do k = 1, 4 ! assume no more than 4 processors sub_total(k) = 0.0 do i = k, n, 4 sub_total(k) = sub_total(k) +a (i) enddo enddo total = 0.0 do i = 1, 4 total = total + sub_total(i) enddo The solution to the data dependency of sum reduction is similar to the solution used for the indirect indexing case: Subtotals are determined, permitting the loop to be parallelized, and the loop is followed by a grand summation loop. The original loop is converted into the inner loop of a nested pair of loops. Parallelization then takes place on the outer loop, which then divides the inner loop into the maximum number of parallel processes. Unlike the example of indirect indexing, which contains two loops of roughly equal size, the bulk of the original loop in this case is parallelized and followed by a small grand summation loop. In order to prevent cache and performance problems, the threads interleave the array and are not handled as a set of contiguous blocks. The solution to sum reduction can also be made more efficient and more general. An example of this approach is shown in TEST.F (Listing One, page 122). Performance Issues A number of issues can affect the performance of parallel schemes. Foremost among these issues are overhead, caching, and load balancing. The CPU overhead is approximately 100 cycles for loop parallelization. The loop must iterate more than about 50 times in order to recover that overhead. Otherwise, small parallelized loops will run slower than the speed of scalar loops. Two solutions can be employed: Enclosing the maximum amount of work in the parallelized loop, and using multiple versions of a loop. The parallelization process can accommodate a wide range of normal Fortran functionality, including IF ... THEN ... ELSE ... ENDIF blocks, other loops, function calls, subroutine calls, and even G0T0s. If data dependency does not introduce restrictions, the inclusion of as much functionality in the loop as possible cuts down on overhead and keeps the highest number of threads in action to improve performance. This solution also means that outer loops should be examined preferentially to inner loops so that the greatest amount of code is parallelized. The other solution to the problem of CPU overhead is to write both parallel and scalar versions of a loop, and place them in an IF ... (index gt. threshold) ... THEN ... (do parallel) ... ELSE ... (do scalar) ... ENDIF block. This is a good approach for maximizing program performance when the value of the index varies across the threshold value of roughly 50 iterations. These multi-processor machines have exceptionally large data caches. If programs are not written with the cache in mind, performance can suffer significantly. In practical terms, when a multidimensional array is referenced inside nested loops, the leftmost index of the array must be varied fastest by the innermost loop so that memory is addressed as contiguously as possible. (Fortran stores arrays in column order, so the arrays must be referenced in what always seems to me to be a backwards order. I will say more about cache effects later.) The parallelization process handles load balancing by dividing the target DO loop into equal pieces, based upon the number of available threads (usually the same number as the number of available processors). If the loop contains IF blocks, or variable-sized inner loops (as is the case in the next example), then the execution time for each thread can be random. As a consequence, if the work of the parallelized loop is not performed equally, time is wasted as completed threads wait for the slower threads to finish. The execution of the code that follows the loop will not occur until all of the threads are completed. The load is not balanced, and the penalty is increased execution time due to the idle processors. The code in Example 3 is a particularly vicious example of load imbalance. Assume that the outer loop is parallelized. The duration of the execution of the inner loop varies according to the value of the index of the outer loop. Although the outer loop's index is divided into ranges of equal size, the threads associated with the ranges that have larger values of the index will take longer to complete. Example 3: An example of load imbalance do i = 1, n do j = 1, i a(j, i) = a(j, i) * xmult enddo enddo As Example 4 shows, a solution is to use index i to break the outer loop into interleaving blocks, such that each thread has a range of values of i. No thread has only the large values of i and the resulting longer execution time. The result is that all threads execute in about the same amount of time. The load is balanced. The only concern is that the process of interleaving can disrupt contiguous memory blocks, which can potentially degrade cache performance. Example 4: Load balancing num_threads = mp_numthreads () c$doacross local (i, j, k) do k = 1, num_threads do i = k, n, num_threads do j = 1, i a (j, i) = a(j, i) * xmult enddo enddo enddo The Bottom Line The real test of the efficiency of the SGI parallelization scheme is with the clock. The goal of the scheme is faster execution, which allows larger and more complex problems to be addressed. A short test program was developed that reflects the types of tasks I would like to speed up in my own work. It fills and manipulates large, multidimensional arrays using nested DO loops, and generates a grand total via sum reduction. The nested loops allow me to examine alternative parallelization strategies. The grand total number serves as a behavior reference for different cases. Three cases were tested: A purely scalar case (SCA), an inner loops parallelized case (IN), and an outer loop parallelized case (OUT). To test each of the cases, the appropriate * comments were removed in order to unmask the desired compiler directives. Each program was compiled at optimization level 2. This level is primarily loop optimization, and currently is the maximum level of optimization that is permitted for the -mp option. I have found that programs compiled at optimization level 1 typically perform about 40 percent slower than programs that are compiled at level 2, making it essential to compile at the higher optimization level. Both a two-headed 4D/120s system and a four-headed 4D/240s system were evaluated. The various configurations are listed in Table 1. Instead of listing aggregate power, I prefer to list the power per processor. This gives an honest view of these machines and reflects nominal scalar performance. The processing power is relative to the old standard of scientific computing -- the VAX 11/780 -- as being 1 mips by definition. These 13 and 20 mips numbers are real! Table 1: Platforms model 4D/120s 4D/240s processors 2 4 processors MIPS R2000 MIPS R3000 clock speed (MHz) 16 25 processing power (mips) 2x13 4x20 FPU 2xR2010 4xR3010 Mflops (double precision) 2x1.5 4x3.0 data cache (kbytes/processor) 64 64 ram (Mbytes, nonstandard) 32 64 I have broken down the timing results into the categories of User, System, and Total (wall clock). The times were determined by using the Unix time utility, and were determined on machines free of competing tasks. The speedup is relative to scalar, and reflects the number of processors that contribute to the job. The times between the two-processor and four-processor systems are not comparable because the CPU and clock rates are very different for each system. All versions of TEST.F are well-behaved. Each version returns a value of 0.518e+8 for the grand total, which indicates correct operation under both scalar and parallel modes. The value of ITEST that is typically returned is random, and ranges between 0 and 5 (except in the IN case, when it returns an enormous integer value that reflects the increased cycling time being measured, as it should). The random nature of the value of ITEST, which is declared as type LASTLOCAL, suggests that caution must be used in the interpretation and use of LASTLOCAL values. The speedup, as shown in Tables 2 and 3, is impressive. In both processor tests, the difference between the IN and OUT tests likely reflects load balancing, but is small, regardless. This suggests that parallelization of the most time-dependent code, rather than of the largest quantity of most code, is the real issue. Outer loops that enclose much-varied code can be far more difficult to parallelize than inner loops, due to the occurrence of data dependency. The difference between IN and OUT suggests that no significant performance penalty may exist if time-dependent inner loops are preferentially parallelized. The results also suggest that no generalization is safe, and that a variety of coding possibilities should be examined. Table 2: Two-processor results (sec.) case user sys total speedup --------------------------------- SCA 40.4 2.1 42.5 1.00 IN 21.0 0.8 21.8 1.95 OUT 21.8 1.0 22.8 1.86 Table 3: Four-processor results (sec.) case user sys total speedup --------------------------------- SCA 25.6 1.0 26.6 1.00 IN 7.1 0.2 7.3 3.64 OUT 6.4 0.5 6.9 3.86 Cache Tests While experimenting with TEST.F, I uncovered a performance issue that is apparently uncommon to programming on PC-class machines: Data cache management. Although the issue of data cache management is common to both scalar and parallel programming environments, the observed effects of mismanagement of the cache, and their cure, are important enough to highlight separately because they affect performance. The cure is the proper use of array indexing. Intentional cache mismanagement leads to significant performance degradation. Management in this context consists of the maximization of the use of existing data in the cache, and the minimization of data movement into the cache from regular memory. The amount of the reuse of existing cache data is commonly referred to as the "hit rate". Better performance is obtained from optimizing the hit rate. In practical terms, the hit rate can be increased by addressing memory contiguously. Memory references of this sort typically consist of array variables in which contiguous blocks of values can be moved into the cache with less overhead than is required in order to move single values into the cache multiple times. Keep in mind that in Fortran, multidimensional arrays are stored in column order; the leftmost index represents contiguous memory addresses. Therefore, nested DO loops must vary the leftmost index of a two-dimensional array fastest, so the references are to contiguous memory locations. Cache mismanagement was tested by reversing the array index variables, and by reversing the array size declarations. The array sizes guarantee that the arrays cannot be wholly contained in the cache and that the movement of data into the cache is handled via the movement of individual array elements. The reason why cache management is a concern is shown in Table 4. Note that the speedup for parallelization is less, due to increased system overhead, while the slowdown relative to the speed observed for proper array indexing is substantial. This translates to an additional day added to the time required to perform a three-day simulation, which is a significant penalty. The effects of cache mismanagement may be inconsequential for tasks that have small memory requirements. In the case of large memory requirements, the penalty for improper use of the cache can be considerable. Table 4: Two-processor reversed-array indexing (sec.) case user sys total speedup slowdown ----------------------------------------- SCA 45.7 6.9 52.6 1.00 1.24 OUT 22.8 7.0 29.7 1.77 1.31 Conclusion Will the application of these tools to real programs translate to significant performance gains, as shown by TEST.F? This will very likely depend upon the individual program. In the case of one program that is important to my own work, I have created significant speed enhancements by the parallelization of key routines found by profiling. An additional increase in speed is also possible by paying attention to load balancing and cache management. Number crunching has never been cheap. Not everyone has access to a supercomputer, and not every problem can justify the cost. Al Cameron, who writes the "Engineering/Science" column for MIPS magazine, advocates the use of workstations dedicated to running one problem around the clock for long periods of time as a low-cost alternative to supercomputing. I share his opinion, but this solution is clearly acceptable only if you can afford to wait. Machines such as the Power Series from Silicon Graphics provide the raw power needed for numerically intensive computing, plus the software tools needed to extract that power. With properly parallelized programs, the wait is considerably shorter. Acknowledgments I would like to thank Nancy Marx and Josh Blumert, both of Silicon Graphics, for their helpful discussions. I would especially like to thank the authors of the "SGI Parallelization Documentation" for an exceptionally clear and useful manual. All documentation should be written this way. Many of the examples (somewhat simplified) were taken directly from the documentation, with permission from Silicon Graphics. Parellelization Directives Each directive begins in column 1 and behaves as a comment unless multiprocessing is enabled during compilation (-mp option). Code containing directives is generally portable except to platforms, which use a similar scheme such as the CRAY. Variables referenced in the scope arguments are by name only; declaration is done in the usual manner at the top of the program. Default scope declaration is SHARE for all undeclared variables and for variables appearing in COMMON blocks, except the DO loop index, which is LASTLOCAL. Variables can only appear in one scope argument. C$DOACROSS [LOCAL(list...), SHARE(list...), LASTLOCAL(list...)] This is the principal directive used to select a loop for parallelization. It immediately proceeds the selected loop and any of three optional scope arguments. C$DOACROSS directives do not nest and subsequent nested directives are ignored. LOCAL(list ... ) are all variables local to each separately executing thread. All LOCAL variables must be explicitly declared, and all data types, including arrays, can be of type LOCAL. SHARE(list ... ) are all variables in common to all executing threads and the remainder of the program. SHARE variables are typically arrays, while nonarray variables can be used if read only, to avoid data dependency. LASTLOCAL(list ... ) are local variables in which the last executing thread returns its value for use past the parallelized block. The value returned is not always the assumed value and great caution must be used especially if load balancing between threads is not even. C$& -- This is treated as a continuation line for lenghty parallelization directives. C$ -- This is used to selectively include lines or blocks of code during parallelization. Typically, this is used to mask lines that are parallel specific or call routines from the parallel library. -- B.B. Parallel Implementation Upon encountering a C$DOACROSS statement, the compiler creates a new subroutine that represents the loop and its contained functionality, and then replaces the loop with a call to the library routine MP_MULTI. The new subroutine is named by prepending an underscore to the name of the routine that originally called the loop and then appending an underscore and a number to that name. The number that is appended starts at 1, and is incremented for each C$DOACROSS contained in the original routine. The new subroutine handles variables declared as LOCAL as local variables. Variables declared as SHARE are resolved by reference back to the original routine. Any required additional variables are local. The new routine is called with four arguments: The starting value of the index, the maximum number of executions of the loop, the increment value of the index, and a unique process ID number. The remainder of the routine consists of the parallelized DO loop. The DO loop is restructured (see Listing Two, page 123) in order to permit multiple copies of the new routine running in parallel to work with independent sections of the DO loop. The code of the new subroutine is written once and the portion of the DO loop that is manipulated is controlled by the calling routine, MP_MULTI. This permits a great deal more run-time flexibility than is available when hard-coded routines are used. At run time, the parallelization is effected by a master routine, which handles all of the scalar code. At the point in the code when the DO loop would have been executed, the master routine passes the name of the new process to MP_MULTI, along with the starting value of the DO loop index, the number of cycles, and the index increment, MP_MULTI divides the loop according to the number of available processors, and then invokes the new process that number of times, with each new process as a slave routine. Additional routines manage interprocess signalling and synchronization. The slave subprocesses do not have to run in synchronization with each other. When the last slave process is completed, control returns to the master routine at the point past the loop. This parallelization scheme is very flexible. Parallelized code can run on a single processor system without change, while dynamically adapting to the number of available heads. At the other extreme, the number of threads can be limited dynamically by setting the environment variable NUM_THREADS to a number less than the maximum number of available heads. -- B.B. _OPTIMIZING IN A PARALLEL ENVIRONMENT_ by Barr E. Bauer [LISTING ONE] <a name="023c_001e"> program test 1 * 2 * purpose is to test SGI parallelization scheme for loop selection, 3 * numerically-intensive calculations, and total reduction. See text 4 * for details. 5 * 6 parameter (MAXFIRST=250, MAXSECOND=250, MAXTHIRD=10) 7 real*8 a(MAXTHIRD,MAXSECOND,MAXFIRST) 8 real*8 b(MAXTHIRD,MAXSECOND,MAXFIRST) 9 real*8 sub_total(MAXFIRST), partial_total(4) 10 real*8 d(MAXTHIRD), c, tmp ! local variables 11 real*8 dist(MAXSECOND,MAXFIRST), grand_total 12 real*8 grand_total ! test for proper operation 13 logical parallel ! selects 2-version loops 14 integer*4 iflag ! used to show LASTLOCAL value 15 16 data parallel /.false./ 17 data sub_total, iflag /MAXFIRST*0.0, 0/ 18 * 19 * outer loop: contains both interior loops 20 * 21 22 * C$doacross local(k,j,i,tmp,d,c), share(a,b,sub_total,dist), 23 * C$& lastlocal(iflag) 24 25 do i = 1, MAXFIRST 26 * 27 * first inner loop: fills arrays a and b 28 * 29 30 * C$doacross local(j,k,c), share(i,a,b) 31 32 do j = 1, MAXSECOND 33 do k = 1, MAXTHIRD 34 a(k,j,i) = dsqrt(dfloat(i*j*k)) 35 c = 1.0 - a(k,j,i) 36 if (c .le. 0.0 .and. i .lt. j*k) then 37 c = -c 38 else 39 c = c**2 40 endif 41 b(k,j,i) = 32*(dcos(c)**5)*dsin(c)- 42 1 32*(dcos(c)**3)*dsin(c)+ 43 2 6*dcos(c)*dsin(c) 44 enddo 45 enddo 46 * 47 * seond inner loop: determines distance and starts summation 48 * 49 50 * c$doacross local(j,k,d,tmp), share(i,a,b,dist,sub_total), 51 * c$& lastlocal(iflag) 52 53 do j=1, MAXSECOND 54 tmp = 0.0 55 do k = 1, MAXTHIRD 56 d(k) = a(k,j,i) - b(k,j,i) 57 enddo 58 do k = 1, MAXTHIRD 59 tmp = tmp + d(k)**2 60 enddo 61 dist(j,i) = dsqrt(tmp) 62 if (dist(j,i) .le. 0.1) iflag = iflag + 1 63 sub_total(j) = sub_total(j) + dist(j,i) 64 enddo 65 enddo 66 * 67 * the next section is an example of sum reduction optimized to the 68 * parallel environment and the use of a more efficient 2 loop summation 69 * 70 * if -mp option is active, parallel is set to .true. which then 71 * selects the parallel version 72 * 73 74 C$ parallel = .true. 75 grand_total = 0.0 76 if (parallel) then ! parallel version 77 C$ num_threads = mp_numthreads() 78 ichunk = (MAXFIRST + (num_threads - 1))/num_threads 79 80 C$doacross local(k,j), 81 C$& share(num_threads,partial_total,sub_total,ichunk) 82 83 do k = 1, num_threads ! this loop is parallelized 84 partial_total(k) = 0.0 85 do j = k*ichunk - ichunk + 1, min(k*ichunk,MAXFIRST) 86 partial_total(k) = partial_total(k) + sub_total(j) 87 enddo 88 enddo 89 do j = 1, num_threads ! smaller loop handled as scalar 90 grand_total = grand_total + partial_total(j) 91 enddo 92 else ! the scalar version 93 do j = 1, MAXFIRST 94 grand_total = grand_total + sub_total(j) 95 enddo 96 endif 97 98 if (parallel) then 99 C$ write (*,10) grand_total, num_threads 100 C$ write (*,20) iflag 101 else 102 write (*,30) grand_total 103 write (*,40) iflag 104 endif 105 stop 106 C$10 format(1x,'grand total = ',g10.3,'threads = ',i4) 107 C$20 format(1x,'parallel iflag = ',i10) 108 30 format(1x,'grand total = ',g10.3) 109 40 format(1x,'scalar iflag = ',i10) 110 end 111 <a name="023c_001f"><a name="023c_001f"> <a name="023c_0020">[LISTING TWO] <a name="023c_0020"> (source code) subroutine example(a, b, c, n) integer*4 n real*4 a(n), b(n), c(n) (additional code) c$doacross local(i, x) do i=1, n x = a(n) * b(n) c(n) = x**2 enddo (additional code) return end (the loop is transformed to) subroutine _example_1( 1 _local_start, ! index starting value 2 _local_ntrip, ! number of loop executions 3 _incr, ! index increment 4 _my_threadno) ! unique process ID number integer*4 _local_start, _local_ntrip, _incr, _my_threadno integer*4 i ! declared local real*4 x ! declared local integer*4 _tmp ! created local i = _local_start do _tmp = 1, _local_ntrip x = a(i) * b(i) c(i) = x**2 i = i + _incr enddo return end Example 1: A typical DO loop do i = 1, n a(i) = x * b(i) enddo Example 2: A DO loop in which the array variable references a value that is not current with the index do i = 2, n arr(i) = b(i) - arr(i-1) enddo Example 3: An example of load imbalance do i = 1, n do j = 1, i a(j, i) = a(j, i) * xmult enddo enddo Example 4: Load balancing num_threads = mp_numthreads() c$doacross local(i, j, k) do k = 1, num_threads do i = k, n, num_threads do j = 1, i a(j, i) = a(j, i) * xmult enddo enddo enddo
http://www.drdobbs.com/database/data-independence-is-the-key-to-performa/184408237
CC-MAIN-2016-30
refinedweb
5,793
52.19
From: Robert Ramey (ramey_at_[hidden]) Date: 2006-11-09 11:42:22 That's not exactly correct. From the link sited: "permits association of an arbitrary key with a type. Often this key would be the class name - but it doesn't have to be. This key is referred to as a GUID - Globally Unique IDentifier. Presumably it should be unique in the universe. Typically this GUID would be in header files and be used to match type accross applications." So the extended_type_info is a USER rather than a SUPPLIER of ag GUID. One of the main functions of BOOST_CLASS_EXPORT_GUID is to associate at type with type with a portable GUID. The specific GUID is left up to the user. The macro BOOST_CLASS_EXPORT(class name) just uses the class name as the GUID. So the existence of an open, portable GUID would complement extended_type_info rather than conflict with it. This system let me isolate serialization from having to address a number of issues related to comming up with a GUID. Among those are: a) it would seem attractive to make a GUID derived from typeinfo as provided by RTTI. In practice this doesn't seem attractive since there is no standardized typeinfo format. b) namespaces: the same type might appear in different namespaces in different programs. In fact, one of the uses of namespaces is to "wrap" libraries so that it can be guarenteed not to accidently conflict. c) Having the GUID look like a class name is attractive - but then it runs into character set issues. d) Having the GUID be derived from the class declaration might seem attractive, but what bout when the class changes - we don't want to obsolete all the programs which depend upon it - or do we? and others. So what starts out seeming like a simple idea, starts to get pretty complicated as one tries to realize it in a specific way. So - the extended_type_info - and by implication the serialization library takes a pass - it presumes you've got your own GUID or are happy with using the class name. And this shows up as a problem from time to time as user want to use classnames including a namespace as the GUID which conflicts with HTML. Robert Ramey Janek Kozicki wrote: > Andy said: (by the date of Thu, 9 Nov 2006 15:57:31 +0000 (UTC)) > >>> Thanks Sebastian, >>> >>> The file I downloaded was GUIDv3.zip, as I couldn't find anyother >>> (did I go to the wrong place: boost-consulting.com/vault ?). > > > GUID which stands for Global Uniqie IDentifier is already in boost. > Why include a second one? If you want to work on this, then better > improve the existing one. > > For the beginning, it can be separated from lirbary > boost::serialization (it is an extended_type_info): > > > > In fact it is already a separate module (because it makes testing much > simpler), so the separation will just make things more formal, and > involve just changing namespaces. Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2006/11/112983.php
CC-MAIN-2019-35
refinedweb
514
63.9
What is DFS (Distributed File System)?. Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.. A DFS is executed as a part of the operating system. In DFS, a namespace is created and this process is transparent for the clients. DFS has two components: - Location Transparency – Location Transparency achieves through the namespace component. - Redundancy – Redundancy is done through a file replication component. In the case of failure and heavy load, these components together improve data availability by allowing the sharing of data in different locations to be logically grouped under one folder, which is known as the “DFS root”. It is not necessary to use both the two components of DFS together, it is possible to use the namespace component without using the file replication component and it is perfectly possible to use the file replication component without using the namespace component between servers. Features of DFS : - Transparency : - Structure transparency – There is no need for the client to know about the number or locations of file servers and the storage devices. Multiple file servers should be provided for performance, adaptability, and dependability. - Access transparency – Both local and remote files should be accessible in the same manner. The file system should be automatically located on the accessed file and send it to the client’s side. - Naming transparency – There should not be any hint in the name of the file to the location of the file. Once a name is given to the file, it should not be changed during transferring from one node to another. - Replication transparency – If a file is copied on multiple nodes, both the copies of the file and their locations should be hidden from one node to another. - User mobility : It will automatically bring the user’s home directory to the node where the user logs in. - Performance : Performance is based on the average amount of time needed to convince the client requests. This time covers the CPU time + time taken to access secondary storage + network access time. It is advisable that the performance of the Distributed File System be similar to that of a centralized file system. - Simplicity and ease of use : The user interface of a file system should be simple and the number of commands in the file should be small. - High availability : A Distributed File System should be able to continue in case of any partial failures like a link failure, a node failure, or a storage drive crash. A high authentic and adaptable distributed file system should have different and independent file servers for controlling different and independent storage devices. - Scalability : Since growing the network by adding new machines or joining two networks together is routine, the distributed system will inevitably grow over time. As a result, a good distributed file system should be built to scale quickly as the number of nodes and users in the system grows. Service should not be substantially disrupted as the number of nodes and users grows. - High reliability : The likelihood of data loss should be minimized as much as feasible in a suitable distributed file system. That is, because of the system’s unreliability, users should not feel forced to make backup copies of their files. Rather, a file system should create backup copies of key files that can be used if the originals are lost. Many file systems employ stable storage as a high-reliability strategy. - Data integrity : Multiple users frequently share a file system. The integrity of data saved in a shared file must be guaranteed by the file system. That is, concurrent access requests from many users who are competing for access to the same file must be correctly synchronized using a concurrency control method. Atomic transactions are a high-level concurrency management mechanism for data integrity that is frequently offered to users by a file system. - Security : eterogeneity in distributed systems is unavoidable as a result of huge scale. Users of heterogeneous distributed systems have the option of using multiple computer platforms for different purposes. - Heterogeneity : A distributed file system should be secure so that its users may trust that their data will be kept private. To safeguard the information contained in the file system from unwanted & unauthorized access, security mechanisms must be implemented. History : The server component of the Distributed File System was initially introduced as an add-on feature. It was added to Windows NT 4.0 Server and was known as “DFS 4.1”. Then later on it was included as a standard component for all editions of Windows 2000 Server. Client-side support has been included in Windows NT 4.0 and also in later on version of Windows. Linux kernels 2.6.14 and versions after it come with an SMB client VFS known as “cifs” which supports DFS. Mac OS X 10.7 (lion) and onwards supports Mac OS X DFS. Applications : - NFS – NFS stands for Network File System. It is a client-server architecture that allows a computer user to view, store, and update files remotely. The protocol of NFS is one of the several distributed file system standards for Network-Attached Storage (NAS). - CIFS – CIFS stands for Common Internet File System. CIFS is an accent of SMB. That is, CIFS is an application of SIMB protocol, designed by Microsoft. - SMB – SMB stands for Server Message Block. It is a protocol for sharing a file and was invented by IMB. The SMB protocol was created to allow computers to perform read and write operations on files to a remote host over a Local Area Network (LAN). The directories present in the remote host can be accessed via SMB and are called as “shares”. - Hadoop – Hadoop is a group of open-source software services. It gives a software framework for distributed storage and operating of big data using the MapReduce programming model. The core of Hadoop contains a storage part, known as Hadoop Distributed File System (HDFS), and an operating part which is a MapReduce programming model. - NetWare – NetWare is an abandon computer network operating system developed by Novell, Inc. It primarily used combined multitasking to run different services on a personal computer, using the IPX network protocol. Working of DFS : There are two ways in which DFS can be implemented: - Standalone DFS namespace – It allows only for those DFS roots that exist on the local computer and are not using Active Directory. A Standalone DFS can only be acquired on those computers on which it is created. It does not provide any fault liberation and cannot be linked to any other DFS. Standalone DFS roots are rarely come across because of their limited advantage. - Domain-based DFS namespace – It stores the configuration of DFS in Active Directory, creating the DFS namespace root accessible at \\<domainname>\<dfsroot> or \\<FQDN>\<dfsroot> Advantages : - DFS allows multiple user to access or store the data. - It allows the data to be share remotely. - It improved the availability of file, access time and network efficiency. - Improved the capacity to change the size of the data and also improves the ability to exchange the data. - Distributed File System provides transparency of data even if server or disk fails. Disadvantages : - In Distributed File System nodes and connections needs to be secured therefore we can say that security is at stake. - There is a possibility of lose of messages and data in the network while movement from one node to another. - Database connection in case of Distributed File System is complicated. - Also handling of the database is not easy in Distributed File System as compared to a single user system. - There are chances that overloading will take place if all nodes tries to send data at once.
https://www.geeksforgeeks.org/what-is-dfsdistributed-file-system/?ref=rp
CC-MAIN-2021-49
refinedweb
1,299
54.63
One of the best methods to read or write data is Data binding against objects. The below tutorial demonstrates how to build ASP.NET 2.0 that binds data against Objects using Visual Studio 2005 . 1. Create App_Code Folder in your Project root. 2. Right-click on the App_Code and select Add->Add New Item to add a new DataSet called "Sample.xsd" to the project. 3. Double click on DataSet Sample.xsd. You will get a tool box for your Data set. You may see another Table Adapter as shown below. 5. Create appropriate connection string or select already created one. 6. Click Next and tick "Use Sql Statements" and write a Query to select the rows. You can use the Query Builder for automatic queries and check the results there it self. 7. Rename DataTable1 to Sample (for an example). Which renames the adapter also. 8. After successful creation of the sql query which creates a Method by default say GetData(). Right-click on the App_Code and select Add->Add New Item to add a new Class file called "AssignValues.cs" to the project. Double Click on the class and create a method in it public class AssignValues { public void Fill(GridView gdv) { gdv.ID = string.Empty; SampleTableAdapters.MemberTableAdapter mtadptr = null; mtadptr = new SampleTableAdapters.MemberTableAdapter(); Sample.MemberDataTable dt=null; dt=mtadptr.GetData(); gdv.DataSourceID=string.Empty; gdv.DataSource=dt; gdv.DataBind(); } } Explanation for the above code: Grid view is an object parameter you passing it from in which event you need to fill the data.Then creating an object of Sample data set dt and filling the data into it and bind it. After that you can make an instance of the class and call the method in any other c# code page of the Project files. Pass the parameter Grid View say GridView1 after grabbing a Grid view from the Tool Box. Accessing Data using Object Data Source in ASP.Net 2.0 and C# Object DataSource in ASP.NET 2.0 This is the most useless article ever written - it should be deleted
http://www.c-sharpcorner.com/UploadFile/praveennam/objectdata08222006063557AM/objectdata.aspx
crawl-003
refinedweb
347
67.96
Solving the Knight's Tour Puzzle In 60 Lines of Python Soulskill posted more than 5 years ago | from the snakes-and-horsies dept. !" awesome (5, Funny) sofar (317980) | more than 5 years ago | (#25935075) too bad that your code will break with the next python version. Re:awesome (-1, Offtopic) Anonymous Coward | more than 5 years ago | (#25935165) Re:awesome (0) Anonymous Coward | more than 5 years ago | (#25935189) Good job it'll take 2 seconds to update. Re:awesome (-1, Offtopic) Anonymous Coward | more than 5 years ago | (#25935263) porn: Re:awesome (-1, Offtopic) Anonymous Coward | more than 5 years ago | (#25935897) Re:awesome (1) QUILz (1043102) | more than 5 years ago | (#25935297) Re:awesome (3, Interesting) orkybash (1013349) | more than 5 years ago | (#25935365) Re:awesome (1, Informative) Anonymous Coward | more than 5 years ago | (#25935485) And the use of xrange() Re:awesome (0, Redundant) Anonymous Coward | more than 5 years ago | (#25935831) Re:awesome (0) Anonymous Coward | more than 5 years ago | (#25936113) I'm aware of the difference between the two. But last I checked "xrange" will not exist at all in Python 3, having been renamed "range" (not merely mapped to it). Re:awesome (0) Anonymous Coward | more than 5 years ago | (#25936199) tada! evolve or die (0, Flamebait) mkcmkc (197982) | more than 5 years ago | (#25935587) Yawn. A good language needs to occasionally shed unneeded features, or it will ossify into an unusable mess. (This is why Perl is dying.) Re:evolve or die (2, Informative) Anonymous Coward | more than 5 years ago | (#25935621) Yawn. Another claim that Perl is "in its last throes". Re:evolve or die (4, Insightful) RightSaidFred99 (874576) | more than 5 years ago | (#25937011) Re:awesome (4, Funny) Falstius (963333) | more than 5 years ago | (#25936099) Re:awesome (0, Flamebait) jellomizer (103300) | more than 5 years ago | (#25936717) Does it? Python is a prototype language, the fact that people use it for real applications is besides the point. It should be kept simple and basic to aid for faster prototyping of code. A basic print command is needed not a printf replacement. printf (3, Interesting) hdon (1104251) | more than 5 years ago | (#25936759) Point of fact: Python has the sexiest sprintf() support available. Observe.. >>> print "I ate %d %s in %.3f seconds" % (99,'hotdogs',62.0895) I ate 99 hotdogs in 62.090 seconds Re:awesome (1) IamTheRealMike (537420) | more than 5 years ago | (#25937149) wtf? That has to be the most retarded backwards compatibility break I've ever seen. Phisht! (0, Offtopic) ArsenneLupin (766289) | more than 5 years ago | (#25935081) Slow news day? (-1, Offtopic) Anonymous Coward | more than 5 years ago | (#25935083) ??? Easy (5, Funny) Anonymous Coward | more than 5 years ago | (#25935089) C-x C-m KnightsPuzzle Re:Easy (5, Informative) RAMMS+EIN (578166) | more than 5 years ago | (#25935983) While your humor is appreciated, I feel compelled to point out that it should be M-x knights-puzzle Lisp doesn't use CamelCase. OK (1) dotslashdot (694478) | more than 5 years ago | (#25935107) Re:OK (1) plasticsquirrel (637166) | more than 5 years ago | (#25935157) "rm -rf knights" rm: cannot remove `knights': No such file or directory Ummm..... Re:OK (3, Funny) $RANDOMLUSER (804576) | more than 5 years ago | (#25935223) All done. (3, Interesting) DeadDecoy (877617) | more than 5 years ago | (#25935131) #! Re:All done. (5, Funny) Anonymous Coward | more than 5 years ago | (#25935287) Except you commented out all of the code. Re:All done. (4, Funny) Kingrames (858416) | more than 5 years ago | (#25936497) Re:All done. (3, Funny) svank (1301529) | more than 5 years ago | (#25937113) Re:All done. (5, Funny) somenickname (1270442) | more than 5 years ago | (#25935337) There. I did it in one line of code. That doesn't look like perl to me... Re:All done. (-1, Offtopic) Anonymous Coward | more than 5 years ago | (#25935453) maybe because it's python... Re:All done. (4, Funny) gparent (1242548) | more than 5 years ago | (#25935943) What would Michael Knight do? (4, Funny) Anonymous Coward | more than 5 years ago | (#25935145) He'd hop into KITT and go anywhere he damn well pleases. Nice. And a Mathematica implementation... (2, Interesting) gardyloo (512791) | more than 5 years ago | (#25935161) ... here: [tri.org.au] Least.. Readable.. Code.. Ever... (1) mkcmkc (197982) | more than 5 years ago | (#25935729)]; := KnightMoves[lis] = Complement[ \t \tendMoves = If[end != {}, If[IntegerQ[end[[1]]],{end},end], {}]; \t \t area = (rows*columns) - Length[endMoves]; \t KnightMoves[lis_List] Cases[ Map[ lis +#&, \ {{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}}], {x_/;0<x<sR, \ y_/;0<y<sC}], endMoves]; Re:Least.. Readable.. Code.. Ever... (2, Interesting) gardyloo (512791) | more than 5 years ago | (#259358. Try lisp (4, Insightful) FlyingBishop (1293238) | more than 5 years ago | (#25935171) Though I have better things to do than actually try, looking over the code FTFA, I have to say that I think a transliteration of this code into Scheme or Lisp would actually look cleaner than Python. And I do know that that would deal with the problem the writer ran into, namely that Python has an absurdly low recursion limit. I do like Python's syntax (for anything under 100 lines of code) but calling it a model of functional programming is just silly. Re:Try lisp (1) morgan_greywolf (835522) | more than 5 years ago | (#25935269) Bah. Python is just Lisp with wacky syntax. [norvig.com] Re:Try lisp (0) Anonymous Coward | more than 5 years ago | (#25936461) The C version wouldn't be all that terrible either -- just use function pointers where he uses lambda functions. Re:Try lisp (2, Interesting) maxume (22995) | more than 5 years ago | (#25936523) #). better algo (5, Informative) Coneasfast (690509) | more than 5 years ago | (#25935203) Apparently, this isn't NP-complete. There is an algorithm that can solve this in O(n) time, see here: [wolfram.com] This will save a LOT of time for larger boards. Try to implement this. Re:better algo (1, Insightful) Anonymous Coward | more than 5 years ago | (#25935333) "This algorithm is rather complicated because it has to deal with many special cases, but has been implemented in Mathematica by A. Roth." This would pretty much defeat the fun of coding it in python. Re:better algo (1) gardyloo (512791) | more than 5 years ago | (#25935739) True. But have you looked at the algorithm? It's remarkably simple, was written in 1992, and is totally generalized to any size chessboard (there is an example in Arnd Roth's implementation for a 180x180 board). Re:better algo (1) Willbur (196916) | more than 5 years ago | (#25935735) The Wolfram page notes two approaches. One is a heuristic approach that works well until the board gets large (76x76 is the size quoted). This is the algorithm implemented by Python code. The second approach is only referenced on the Wolfram page, not described in any detail. The text on that algorithm from the Wolfram page is: Sounds hard to implement in 60 lines of python - especially when most of the 60 lines is UI. Re:better algo (4, Interesting) eulernet (1132389) | more than 5 years ago | (#25936723)] Re:better algo (3, Interesting) misterpib (924404) | more than 5 years ago | (#25937127) . 28 lines in Prolog :-) (5, Interesting) Anonymous Coward | more than 5 years ago | (#25935257):28 lines in Prolog :-) (0) Anonymous Coward | more than 5 years ago | (#25935443) Time for a J [wikipedia.org] solution! Re:28 lines in Prolog :-) (5, Insightful) phantomfive (622387) | more than 5 years ago | (#25936027) I would truly be amazed to see anyone writing the same logic in C++ in anything less than 3 times the lines of code I wrote in Python. And even if this is somehow possible (using external libraries like BOOST, I'd wager), the code will take longer to write, and it will be far more difficult to comprehend or refactor... And I'd wager that this guy has never worked on huge projects. Any chunk of code that is less than a hundred lines is not going to be difficult to refactor; in fact, such a short piece of code probably gets longer and more confusing by adding object oriented structure (notice his code isn't encapsulated into a class or anything). The real advantages of structured programming isn't seen until you have a large project that has constantly changing requirements. That is where flexibility REALLY makes a difference. I would also argue that any modern language gives you everything you need to write good, flexible code, and the quality of the code produced is more closely related to the skill of the programmer, than it is to the programming language itself. In fact, for myself, it would not be an exaggeration to say I can write more flexible code in assembly now than I could five years ago in any language. Of course, it would be well structured assembly, not the wild mess of code I've written in previous years. YMMV. Re:28 lines in Prolog :-) (5, Interesting) IamTheRealMike (537420) | more than 5 years ago | (#25937095):28 lines in Prolog :-) (3, Insightful) omuls are tasty (1321759) | more than 5 years ago | (#25937119) That Java code is only 10 lines longer, but it doesn't include the code for some other classes it uses to solve the problem. But anyhow, you're missing his point. The basic backtracking algorithm for the problem is simple in any language, and could indeed be made much shorter in Java (w/o the entire search framework). He's talking about improving the search with a heuristic (in his case, what is known as a "minimum remaining values" search heuristic among the AI folks). But he's still probably wrong, as you:28 lines in Prolog :-) (4, Interesting) RedWizzard (192002) | more than 5 years ago | (#25936777)). J solution (0) Anonymous Coward | more than 5 years ago | (#25935271) I know nothing of the problem but have a look at's_Tour for a J version and some comments. Also, Re:J solution (2, Interesting) jackharrer (972403) | more than 5 years ago | (#25935597) It's even less readable that PERL. Shit, I didn't think it's possible. And I used to "program" in PERL... Re:J solution (1) Draykwing (900431) | more than 5 years ago | (#25936821) Python has "perfect syntax"? (1, Funny) Anonymous Coward | more than 5 years ago | (#25935301) Please... Why do we need slashvertisements for programming languages on Slashdot? Re:Python has "perfect syntax"? (1, Troll) mkcmkc (197982) | more than 5 years ago | (#25935791) It's not "perfect", but compared to the 40+ other languages I've used, it seems to be at or near the top, in terms of human readability. (Lisp has obvious advantages for machine readability, but it's quite rare that this is useful.) Re:Python has "perfect syntax"? (2, Interesting) Intron (870560) | more than 5 years ago | (#25936041) [wordpress.com] I think even if you didn't know any lisp you would find this solution to be pretty readable. Perl (5, Interesting) Anonymous Coward | more than 5 years ago | (#25935403) #!/usr/bin/perl use Chess; $knight = Chess::Piece::Knight->new(); $board = Chess::Board->new(100, 100, setup => { $knight => "a1"; }); $knight->tour()->show(); Re:Perl (5, Informative) berend botje (1401731) | more than 5 years ago | (#25935517) Chess::Piece::Knight [cpan.org]. Perl is awesome! Re:Perl (1) jellomizer (103300) | more than 5 years ago | (#25936745):Perl (0) Anonymous Coward | more than 5 years ago | (#25935901) > use Chess; > > $knight = Chess::Piece::Knight->new(); > $board = Chess::Board->new(100, 100, setup => { > $knight => "a1"; > }); > > $knight->tour()->show(); > EOF Can't locate Chess.pm in @INC (@INC contains: BEGIN failed--compilation aborted at - line 1. You lose. The Python version didn't need any external modules. Re:Perl (1) FooAtWFU (699187) | more than 5 years ago | (#25935999) dump the recursion (4, Interesting) Jecel Assumpcao Jr (5602) | more than 5 years ago | (#25935413):dump the recursion (0) Anonymous Coward | more than 5 years ago | (#25935635) Re:dump the recursion (0) Anonymous Coward | more than 5 years ago | (#25935655) "the very first attempt at each step will lead to a good solution (add a print to the backtracking part and see if this isn't the case)" You used engineering induction to prove this did you? Look at the wolfram.com link given above and you'll see that backtracking is needed for n>76. A trivial backtracking algorithm and... (5, Insightful) berend botje (1401731) | more than 5 years ago | (#25935473) Re:A trivial backtracking algorithm and... (5, Funny) jellomizer (103300) | more than 5 years ago | (#25935853) Of course like all other programmers he thinks he is better then everyone else. Doing it without CS teaching? (1) jonaskoelker (922170) | more than 5 years ago | (#25935869). Re:Doing it without CS teaching? (4, Insightful) jellomizer (103300) | more than 5 years ago | (#25936691) Yes, but a lot of this stuff really isn't worth posting online. Espectially Slashdot I have created many algorithms myself without the need to post it for slashdot acceptance. Some interesting compression algorithms, Memory management algorithms... Whatever that I feel like exploring today. But it is for my own personal knowledge not for public viewing of my code as my method will be to prove some particular point to myself nor will it be efficient or complete, and any attempt to have it posted like the guy who posted this thread will just get critized for anything that is not the best as it could possibly be. Re:A trivial backtracking algorithm and... (1) rrohbeck (944847) | more than 5 years ago | (#25936887) I did this in high school you insensitive clod! Oh and it was in FORTRAN :P Python uses lambda calculus? (1) Spilver (258781) | more than 5 years ago | (#25935523) Re:Python uses lambda calculus? (4, Informative) Free the Cowards (1280296) | more than 5 years ago | (#25935573):Python uses lambda calculus? (1, Informative) harry666t (1062422) | more than 5 years ago | (#25936021) wtf? of course you could! lambda x,y: (spam(x), meth(y)) [-1] yeah, less readable etc but works. And yes, Python is even capable of executing interesting, obscure one-liners: Re:Python uses lambda calculus? (1) Free the Cowards (1280296) | more than 5 years ago | (#25936161) Nice technique, thanks, I'll have to remember that. Still, it would be nice if lambdas had the same basic syntax as regular functions so you could do multiple lines in the same way. Re:Python uses lambda calculus? (0) Anonymous Coward | more than 5 years ago | (#25935893) You might be interested in Higher-Order Perl Idea of the Book : Higher-Order Perl is about functional programming techniques in Perl. It's about how to write functions that can modify and manufacture other functions. Re:Python uses lambda calculus? (2, Interesting) RAMMS+EIN (578166) | more than 5 years ago | (#25936051). Re:Python uses lambda calculus? (1) maxume (22995) | more than 5 years ago | (#25936097) Python is probably best described as multi-paradigm. Functions do happen to be first class objects (along with everything else), so a lot of stuff can be written in a functional style. The lambda keyword is little more than a way to declare a function without giving it a name. A downside compared to lisp is that it isn't really possible to declare something as static, so optimization and compilation are more problematic (it is possible to construct a stubborn object, but names/references to that object can simply be rebound to a more flexible object, so it is hard to rely on the object being stubborn). Heuristic (1) DohnJoe (900898) | more than 5 years ago | (#25935531) OMG (3, Funny) l3v1 (787564) | more than 5 years ago | (#25935569) Re:OMG (0) Anonymous Coward | more than 5 years ago | (#25935841) Times have really changed since the 90's. My 3 year old daughter finds the solution every so often in a box of Cracker Jacks, licks it, and tattoo's it to the back of her hand. yuo Fail It (-1, Redundant) Anonymous Coward | more than 5 years ago | (#25935613) Imagine... (0) DiLLeMaN (324946) | more than 5 years ago | (#25935819) ...a beowulf cluster solving this puzzle. Actually, to go beyond mere meme-tossing: solving a knight's tour for a really large board with a beowulf... how would you do that? ...and then there's APL (4, Interesting) shking (125052) | more than 5 years ago | (#25935845) no backtracking (1) Dulimano (686806) | more than 5 years ago | (#25935871) There is something about the OP's algorithm that I'm not sure he realized: It never backtracks. The 'choose the loneliest' method works even when applied in a greedy fashion. I did the following patch to artificially make the backtrack codepath run: Changed the key=lambda c: reduce( part to key=lambda c: random.random()*3+reduce( This means that the 'choose the loneliest' rule is broken sometimes. Backtracking is able to correct these mistakes sometimes, mostly if they did not happen too early in the search. Re:no backtracking (1) nneonneo (911150) | more than 5 years ago | (#25936361) It does. Run it with a value of 163 or higher. Pentominoes Quine in Perl (4, Interesting) Speare (84249) | more than 5 years ago | (#25935931) I had to solve it in C (5, Interesting) gillbates (106458) | more than 5 years ago | (#25935949):I had to solve it in C (1, Interesting) Anonymous Coward | more than 5 years ago | (#25936587) See also this sudoku solver [youtube.com] Python??? Try it getting that speed in Java. (1) mongoose(!no) (719125) | more than 5 years ago | (#25936065) Anyhow, what's the point? I didn't think this was a hard problem at all when we did it. sum instead of reduce (1) pinkpuppy (46681) | more than 5 years ago | (#25936129) Can't you replace the call to reduce(lambda x,y: x+y, ...) with sum(...)? Re:sum instead of reduce (1) pinkpuppy (46681) | more than 5 years ago | (#25936333) Actually, the sum and map is better replaced with len and filter key=lambda c: len(filter(lambda j: InRangeAndEmpty(c[0]+j[0], c[1]+j[1]), jumps)) Re:sum instead of reduce (1) maxume (22995) | more than 5 years ago | (#25936601) Or a generator expression and sum. lambda c: sum(InRangeAndEmpty(c[0]+j[0], c[1]+j[1]) for j in jumps) It might be even better to have a function called CountValidJumps or count_valid_jumps and pass that to the sort. Re:sum instead of reduce (1) nneonneo (911150) | more than 5 years ago | (#25936419) Better yet, replace the whole thing with a generator expression wrapped in sum, thus removing map and the temporary array: key=lambda c:sum((int(InRangeAndEmpty(c[0]+j[0], c[1]+j[1])) for j in jumps)) int(bool) turns True into 1 and False into 0, and is more readable than "and 1 or 0" (better yet, use the Python 2.5 conditional "1 if InRangeAndEmpty(...) else 0"). I rewrote the code using a stack, to see how far it could get. It does 162x162 in linear time (w.r.t. the number of squares) and then, at 163x163, it abruptly stops being fast, as it begins to perform heavy backtracking -- it fails to fill in a region near the top-right corner. Hence, the heuristic (as written) is not powerful enough for all grids. He mixed tabs and spaces (2, Interesting) Anonymous Coward | more than 5 years ago | (#25936249) Not cool. A few lines of Mathematica (1) NSRaffy (585440) | more than 5 years ago | (#25936499) $Jumps = {{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}}; solve[n_] jump[x_, y_, z_, n_] board[x, y] = z; If[z == n^2, Throw[1]]; jump[x + #1, y + #2, z + 1, n] & @@@ $Jumps; board[x, y] =.; ); Block[{$RecursionLimit = Infinity}, solve[5] stuff that matters (1) thc4k (951561) | more than 5 years ago | (#25936751) seriously, is this "article" some bad joke? modJ up (-1, Troll) Anonymous Coward | more than 5 years ago | (#25936847) I hope a firehose exploit was involved. (5, Insightful) Vexorian (959249) | more than 5 years ago | (#25937065) 1 #include <set> 2 #include <iostream> 3 #include <cassert> 4 using namespace std; 5 6 int dx[8]={1,1,-1,-1,2,2,-2,-2}, dy[8]={2,-2,2,-2,1,-1,1,-1}; 7 int D[50][50]; 8 int N,C; 9 10 #define valid(x,y) ((x>=0) && (x<N) && (y>=0) && (y<N) && (D[x][y]==-1 ) ) 11 12 bool show() 13 { 14 for (int i=N;i--;) 15 { 16 for (int j=N;j--;) 17 cout<<"\t"<<D[i][j]; 18 cout<<"\n"; 19 } 20 return true; 21 } 22 23 bool rec(int x, int y) 24 { 25 D[x][y]=C++; 26 if(C==N*N) 27 return show(); 28 29 set< pair<int, pair<int,int> > > poss; 30 for (int r=8;r--;) 31 if(valid(x+dx[r], y+dy[r])) 32 { 33 int neighb=0; 34 for (int t=8;t--;) 35 neighb+= valid(x+dx[r]+dx[t],y+dy[r]+dy[t] ); 36 poss.insert( make_pair(neighb, make_pair(x+dx[r],y+dy[r] ) )); 37 } 38 39 for (typeof(poss.begin()) q=poss.begin(); q!=poss.end(); q++) 40 if (rec(q->second.first, q->second.second)) 41 return true; 42 43 D[x][y]=-1; 44 C--; 45 46 return false; 47 } 48 49 void solve(int n) 50 { 51 N=n, C=0; 52 memset(D,-1,sizeof(D)); 53 assert(rec(0,0)) 54 } 55 56 int main() 57 { 58 int n; 59 while((cin>>n) && (n>0)) 60 solve(n); 61 return 0; 62 } The bastards! Those darn brackets force me to have 2 extra lines Re:I hope a firehose exploit was involved. (1) OrangeTide (124937) | more than 5 years ago | (#25937091) Just change your coding style to have the { on the same line as if and for, which is a popular style, and you've done it.
http://beta.slashdot.org/story/110853
CC-MAIN-2014-15
refinedweb
3,674
68.5
Occasionally an off hand remark, perhaps even one said with a snide and “challenge” tone to it, will cause me to wonder. And dig, maybe just a tiny bit… One of those happened a week or three ago. I was telling a computer engineer friend about the Raspberry Pi and some of the things you could do with it. Probably a bit effusive, but as I’m generally criticized for being too “bland” or “reserved” (thanks Mum…) it’s rare that I’m “effusive” about anything. But in the case of the R.Pi I was happy with it, so may have been… Don’t remember exactly what I was “effusive” about. I’d gotten Samba and file shares going, a Torrent Server (that’s humming still), and a caching DNS server. I think we’d been talking about his use of Arduino for teaching robotics and I was suggesting the R.Pi might be fun for kids to program too… He was talking about learning Java, as a lot of Arduino projects are heading that way (and kids seem to learn Java easily) or some such. I made some comment about languages on the R.Pi, and that I’d gotten FORTRAN running easily. He then challenged with something like “What, no COBOL?” (in that mocking kind of tone…) Now both of us learned FORTRAN as our first computer language at the same school and from the same instructor. (Old college roomie… ) He’s an Engineer by degree, training, and career; and has used FORTRAN. So it was a bit of a ‘dig’ to have him slamming me with COBOL… ( I had one COBOL class that I hated… and did some minor maintenance on COBOL programs when out of school… but it’s really a horrid wordy cumbersome language with arcane rules about reading file and writing records or maybe the other way around… in any case, the structures you read are different from those you write, for the “same thing”. ) Well, time passes. And the “slight” fades. But sometimes not the “I wonder…” So I found this: your COBOL programs on various platforms, including Unix/Linux, Mac OS X, and Microsoft Windows. The compiler is licensed under GNU General Public License. The run-time library is licensed under GNU Lesser General Public License. Since it’s a translator to C, and C runs on the R.Pi; it’s pretty much guaranteed this will work on the Raspberry Pi. Though I don’t know if I can be that cruel to the Raspberry as to force it to do COBOL… It is already under general Debian: For Debian, it’s apt-get install open-cobol So it ought to be there… Dare I? The VM with Emulator with… Unrelated… it seems that early on with hardware scarce and memory more limited, some folks wanted to do a load of development (and likely compiling a lot of Debian… perhaps even Open COBOL) and made a Virtual Machine to do so. This is complicated by the fact that the R.Pi is an ARM chipset and most folks have an Intel computer. So they used an ARM emulator inside the virtual machine… Now on a high end quad core or more box with a couple of dozen GB of memory, you can still get a heck of a lot of performance boost by using a Virtual Machine (OpenBox) with an emulator inside of it… though for the rest of us it does look just a tiny bit cruel.… But then, to install Debian Linux on that emulated chip in that virtual CISC under a Linux OS, inside a core of an Intel CPU, wrapped in MicroSoft Windows and, then, in a fit of fancy, to compile, port, install and run COBOL via a translator to C. Well… I’m sure someone will do it, but I don’t have to watch. ;-) How to do the VM / qemu stuff: You Know I Pull Wings Off Flies? From the “burning ants with lenses and pulling wings off flies department”… you know I’ve got to “go there”, don’t you?: pi@dnsTorrent ~ $ sudo apt-get install open-cobol Reading package lists... Done Building dependency tree Reading state information... Done The following extra Suggested packages: db5.1-doc libgmp10-doc libmpfr-dev libtool-doc ncurses-doc autoconf automaken gcj The following NEW open-cobol 0 upgraded, 13 newly installed, 0 to remove and 250 not upgraded. Need to get 2,977 kB of archives. After this operation, 8,298 kB of additional disk space will be used. Do you want to continue [Y/n]? y Get:1 wheezy/main libgmpxx4ldbl armhf 2:5.0.5+dfsg-2 [20.6 kB] Get:2 wheezy/main autotools-dev all 20120608.1 [73.0 kB] Get:3 wheezy/main libgmp-dev armhf 2:5.0.5+dfsg-2 [552 kB] Get:4 wheezy/main libgmp3-dev armhf 2:5.0.5+dfsg-2 [13.7 kB] Get:5 wheezy/main libltdl-dev armhf 2.4.2-1.1 [203 kB] Get:6 wheezy/main libtinfo-dev armhf 5.9-10 [89.6 kB] Get:7 wheezy/main libncurses5-dev armhf 5.9-10 [202 kB] Get:8 wheezy/main libtool armhf 2.4.2-1.1 [618 kB] Get:9 wheezy/main libcob1 armhf 1.1-1 [87.6 kB] Get:10 wheezy/main libcob1-dev armhf 1.1-1 [111 kB] Get:11 wheezy/main libdb5.1-dev armhf 5.1.29-5 [775 kB] Get:12 wheezy/main libdb-dev armhf 5.1.6 [2,256 B] Get:13 wheezy/main open-cobol armhf 1.1-1 [228 kB] Fetched 2,977 kB in 33s (88.3 kB/s) Selecting previously unselected package libgmpxx4ldbl:armhf. (Reading database ... 61520 files and directories currently installed.) Unpacking libgmpxx4ldbl:armhf (from .../libgmpxx4ldbl_2%3a5.0.5+dfsg-2_armhf.deb) ... Selecting previously unselected package autotools-dev. Unpacking autotools-dev (from .../autotools-dev_20120608.1_all.deb) ... Selecting previously unselected package libgmp-dev:armhf. Unpacking libgmp-dev:armhf (from .../libgmp-dev_2%3a5.0.5+dfsg-2_armhf.deb) ... Selecting previously unselected package libgmp3-dev. Unpacking libgmp3-dev (from .../libgmp3-dev_2%3a5.0.5+dfsg-2_armhf.deb) ... Selecting previously unselected package libltdl-dev:armhf. Unpacking libltdl-dev:armhf (from .../libltdl-dev_2.4.2-1.1_armhf.deb) ... Selecting previously unselected package libtinfo-dev:armhf. Unpacking libtinfo-dev:armhf (from .../libtinfo-dev_5.9-10_armhf.deb) ... Selecting previously unselected package libncurses5-dev. Unpacking libncurses5-dev (from .../libncurses5-dev_5.9-10_armhf.deb) ... Selecting previously unselected package libtool. Unpacking libtool (from .../libtool_2.4.2-1.1_armhf.deb) ... Selecting previously unselected package libcob1. Unpacking libcob1 (from .../libcob1_1.1-1_armhf.deb) ... Selecting previously unselected package libcob1-dev. Unpacking libcob1-dev (from .../libcob1-dev_1.1-1_armhf.deb) ... Selecting previously unselected package libdb5.1-dev. Unpacking libdb5.1-dev (from .../libdb5.1-dev_5.1.29-5_armhf.deb) ... Selecting previously unselected package libdb-dev:armhf. Unpacking libdb-dev:armhf (from .../libdb-dev_5.1.6_armhf.deb) ... Selecting previously unselected package open-cobol. Unpacking open-cobol (from .../open-cobol_1.1-1_armhf.deb) ... Processing triggers for man-db ... Processing triggers for install-info ... Setting up libgmpxx4ldbl:armhf (2:5.0.5+dfsg-2) ... Setting up autotools-dev (20120608.1) ... Setting up libgmp-dev:armhf (2:5.0.5+dfsg-2) ... Setting up libgmp3-dev (2:5.0.5+dfsg-2) ... Setting up libltdl-dev:armhf (2.4.2-1.1) ... Setting up libtinfo-dev:armhf (5.9-10) ... Setting up libncurses5-dev (5.9-10) ... Setting up libtool (2.4.2-1.1) ... Setting up libcob1 (1.1-1) ... Setting up libcob1-dev (1.1-1) ... Setting up libdb5.1-dev (5.1.29-5) ... Setting up libdb-dev:armhf (5.1.6) ... Setting up open-cobol (1.1-1) ... pi@dnsTorrent ~ $ So now I’ve gone and done it… I’ve installed COBOL on my Raspberry Pi. It’s no longer just a DNS server / Torrent Server / Samba – M.S. File Server / FORTRAN Climate Codes port station… it’s now also a COBOL workstation. Sigh. Guess what I’ll be telling the “Old College Roomie” tomorrow? ;-) I guess next thing I need to do is learn how to remove packages. ;-) cobol still gives me the creeps. That 60 char limit, the exact placement of text on a line or else. Almost made me drop programming all together. I new a Cobol programer, he seemed weird, was it a coincidence? LOL I cut my programming teeth on COBOL on ICL2900 mainframes and have good memories. I found that, mixed with a bit of the system programming language to do the bits that would have been cruel and unusual in COBOL. It proved to be surprisingly versatile. At one one time I wrote a finite state machine to parse a large query/display ‘natural’ language and the interpreter that executed the display language on returned query items. The interpreter ran to about 20-30k LOC, and the parser/lexer (didn’t write the lexer) another 10k or so. It proved to be remarkably easy, apart from the maintenance of the state table. As for position dependent layout, plainly the world has learned nothing, because we have Python. A long discussion on various ways and degrees of package removal: So looks like a variety of choices. Maybe later I’ll have time to decide which one to use… @Petrossa: I’d forgotten the 60 char fixed format “issue”… (it’s been a while… and IIRC that limit was removed in the commercial version where I was doing minor maintenance). @BobN: IMHO, both COBOL and RPG (RPG II ?) programmers are a ‘different sort’. At one extreme are the C / FORTRAN folks. Very math oriented and lots of short terse symbols used (and compact code too). At the other extreme are the COBOL / database guys with a load of words to do anything of interest. More like reading a novel written by someone with a weird dialect problem… Then RPG is like ticking boxes on a check sheet with some modifiers…almost not a language at all, really. Non-procedural and limited. (Don’t get me started on PL/I – where you can write FORTRAN, or COBOL, or any of a couple of other languages all inside the approved syntax…; or APL which has been called “write only programming”… and takes a special keyboard with obscure symbols on it…; and LISP for folks in love with parenthesis, and whatever happened to the straitjacket of Pascal and Ada?…) My favorite was Algol 68. Sort of a half way house between Pascal and C. Not as terse and cryptic as C, but not a straitjacket like Pascal. I wonder if there’s any Algol for Debian… Hmmm… @Steve Cook: You have my admiration. I was never able to really master COBOL. “Sort of functional” was about all I could do. I don’t really “speak Python” (though I’ve ported some things written in it). Is it strongly positional? (Last time I did anything with it was about 2009 and that was just ‘compile and install’ some C libraries for it in GIStemp and run the code as provided…) I kind of remember something about position dependent chars at the front of lines… Guess I need a ‘refresher’…. Oh Dear… pi@dnsTorrent ~ $ sudo apt-get install algol68g Reading package lists… Done Building dependency tree Reading state information… Done The following NEW packages will be installed: algol68g 0 upgraded, 1 newly installed, 0 to remove and 250 not upgraded. Need to get 422 kB of archives. After this operation, 1,030 kB of additional disk space will be used. Get:1 wheezy/main algol68g armhf 2. 4.1-1 [422 kB] Fetched 422 kB in 2s (150 kB/s) Selecting previously unselected package algol68g. (Reading database … 61758 files and directories currently installed.) Unpacking algol68g (from …/algol68g_2.4.1-1_armhf.deb) … Processing triggers for man-db … Setting up algol68g (2.4.1-1) … Well… now I’ve got Algol68 on the R.Pi too…. In a way, it’s kind of amazing what all is already built and ready to go. Stuff that was just sitting in Debian already and “just works” after a compile or with a dedicated interest group that did some ‘touch up’ for ARM at some point. (And likely some bits that ‘need patching’ and will get attended after some damn fool, like me, actually tries using Algol or COBOL on a R.Pi and turns up some odd corner with ‘issues’… and that same ‘interest group’ finds out what we’ve done with their favored software on some platform they don’t have ;-) While I’m on the subject, some resources for Algol: Open source Algol: Algol home page: Has a pretty good list of links on it too. Well. Now I’m in a pickle…. While I really liked Algol, do I really want to be writing code in a language from 1968? 45 years back? Well, maybe ;-) Made my living writing/maintaining COBOL programs for 18 years. Pedestrian, adequate, stable, easy to learn. Remember its origin – military – Grace Hopper. It was an advancement for its time and place. Regard it like classical Latin or Greek. @Gary: Never could get motivated to learn Greek either ;-) (Latin I can puzzle out some bits and I’m ‘working on it’…) So I guess this means you can get a comfortable COBOL workstation for $35 that likely has more processing power than those mainframes from 18 years back… In fairness, I’d had a fairly intense FORTRAN immersion, and then an Algol class (in the Engineering department) so was pretty much indoctrinated that THEY were the right way to do things. Then signed up for a single (small units / little time or instruction…) class in COBOL that was mostly “here’s the book, there’s the lab… come ask me if you have questions”… I suspect that with a better ‘presentation’ I’d have done better. It was in some ways frustrating as I had to “unlearn” a lot of the FORTRAN way I’d just learned… Now, a dozen languages later, I’d likely be less biased toward it; especially in a decent class setting. It did seem “easier” when I had to do some maintenance than when I’d been taking the class… even though it was a dozen years later with no use in between. @ E.M. Smith 25 May 2013 at 5:47 pm IIRC Python requires indent of ‘if’ clauses rather than using braces. Seemed like a gimmick that is always going to blow up in your face sooner. Like deciding to only use C braces when forced to :-) When I started programming in C, I had a hard time coming to grips with just how easy it was to shoot oneself in the foot. I’d been spoiled by COBOL. I was used to only having to deal with debugging logic errors and C introduced me to a whole new class of bug I could create just by a typographical error. Ahhh, those were the days. I went on a Cobol training course and hated it. I concluded that Cobol was commissioned by a committee too dumb ever to be able to do any programming themselves. I liked Algol, but PL1 was my favourite. Steve Crook says: 25 May 2013 at 4:41 pm “I cut my programming teeth on COBOL on ICL2900 mainframes…” I worked on the 2903, 2910, 2920 and 2930 machines at West Gorton and Kidsgrove. I worked with Ed Mack, David Dace and Charlie Portman. In those days if you used anything other than COBOL you could get fired. At ICL it was hard to know who you worked for thanks to “Matrix Management” that caused confusion at all levels! My final job at ICL was as project manager for the ME29 which sold quite well. Later while I was working at STC, Kenneth Corfield decided to acquire ICL. Later STC got gobbled up by Nortel and then Fujitsu. I wonder if anything is left other than the pension fund that coughs up a few dollars each year. Gary, You have to love the inimitable Grace Hopper. I use this video to help people remember that electrical signals travel roughly one foot in a nano-second: Or, you could run it on cp/m and get sharp on ddt and pipping. …” The art is of course writing the compilers, emulators, transpilers and VM’s in such a way that you lose as little power as possible when crossing each platform/language border. “He was talking about learning Java, as a lot of Arduino projects are heading that way (and kids seem to learn Java easily) or some such.” Java is on its way out IMHO. Javascript (a completely different language) is getting more interesting every day. Javascript is very easy to learn as well, has a semantic as powerful as Scheme or Python, and modern JIT compilers give it an edge over Python. I found this helpful: As the type system is based on Duck typing like Python, it is way easier to learn than the boxing/unboxing/container/generics mess of Java. I disliked Java from the start due to the lack of templates; which are necessary in statically typed OO languages. Only much much later did they bolt on their generics. As Javascript is not statically typed, it never had that problem but suffered instead from slowness. Which has been rectified since about 2008 by Google and Apple’s JIT compilers. Perhaps it’s Java Script he was talking about for the kids. Frankly, I didn’t realize there was that much difference between them so have not kept them “tidy” in different buckets. Classing it all as “Java*” … So I guess I need to start keeping two buckets ;-) Not long after the IBM System/360 appeared I worked at a small company that had an IBM 1401 installation and was upgrading to a 360. Management had the delusion, common at the time, that COBOL was the cure for all data processing problems. Most of the programmers thought COBOL was bad, evil, weak, inefficient, etc. I took a couple programs that had been written in 360 assembly language, and rewrote them in COBOL. It took me less time to debug them than the BAL programmers spent. That did not change any opinions. But my object programs, including all the linked in library routines were smaller than the BAL programs, much smaller. That does not say anything about the quality of the COBOL compiler. The BAL programmers just did not understand the architecture of the 360. We could not shrink their code by tweaking it; the only way was to replace almost all of it. That made COBOL less unacceptable. The 1401 treated a blank like a zero in many circumstances. New programs on the 360 using files produced on the 1401 sometimes failed because the 360 knew the difference when in native mode. I wrote an exception handler in COBOL to fix the data. That took away more of the resistance. COBOL is not a good choice for an exception handler, but it is a fine choice for removing doubt about its use. Related to code size, years later there was a debate about implementation languages at DEC. One survey of developers found that of those that had not used PASCAL or BLISS, twice as many developers thought PASCAL was superior. I worked in the group that developed BLISS compilers. We wondered how good the code was, compared to assembly language. We finally found a module that one developer had written in BLISS for a component of VMS. It was replaced by the assembly language equivalent, written by an ace, one of the original VMS team. The BLISS code was 2% larger. Several years later we were asked to put together a presentation about the same topic. By then, the difference was 1%. I have also observed many times that RPG is a superb language for the many commercial DP applications where it is widely used. This note is not to support a best language or complain about a bad one, but just to observe that many of our strongly held opinions should not be so strongly held. @Chuck Bradley: Well, about the only “strongly held” opinion I have on computer languages is that it’s better to use a language you know well, then the newest trendy language you don’t know well… I’ve sometimes “taken rocks” for programming things in some old / odd language or another rather than the “trendy language du jour”… but I’ve also managed enough projects to know that a really good and experienced programmer can make just about any language do just about anything… and knowing where the potholes and deadfalls are in a given language is more important than some arcane feature you have never used in the new language… The only exception being that I’ve seen many “Object Oriented” projects suffer massive code bloat / slowness problems. Can’t say if it is a structural thing to the languages, inexperience of the programmers, coincidence due to O.O. taking off just as everyone got lazy about memory (“hardware is cheap” ethic taking over) or what. I’ve also seen a lot of damn fast programs written in things like FORTRAN, ALGOL, C, etc…. Though frankly, the one thing that annoys me most is the tendency to a new language of preference every 5 years or so. I’ve managed to watch a half dozen come and go… Perl and Python, once trendy, now being shoved aside by the Java Javascript trend (that’s already a bit old itself…) I’ve mostly just “given up” on trying to stay “trendy” as it’s just not worth the workload. (I have done maintenance on Perl and Python without too much study, and since most of what I do is “port and fix”, getting proficient at “write from scratch” isn’t really needed.) In the end, I find myself mostly using FORTRAN these days (as what I’ve been doing for the last 4 years was written in it) along with various scripting languages. I’ve written C, and could do so again, but it’s been a while. (Still read it fairly well though…) And while folks tout things like R and Python and Java – I’ve just not felt motivated enough to bother. (Though don’t mind at all if someone on one of my teams wanted to use the new trendy things… I’ve generally figured “let folks use the tool they want”… and it’s worked well.) At the end of the day, I mostly like relatively straight forward languages. I just re-read the “book” on Algol at that algol home site. I was reminded of some of the “quirks” that had bothered me in the past… and why I’d not kept up using it. Nothing wrong with it, and it was my favorite language once… But now, looking back on it after C and others, it is just a bit more “lumpy” than I’d remembered… So maybe some of the “negatives” remembered about COBOL are from that same mold as the “positives” I was remembering about ALGOL. Both a bit “colored by time” ;-) Ah, well. Someday the Perfect Programming Language will be developed ;-) EM C is pretty straightforward, isn’t it? I like it a lot for the freedom it gives me, and the ease of IL Assembly. C++ has its advantages too, but admittedly a hello world application can easily be a megabyte if you’re not careful. Python, java,c#,.net etc. i can’t stand exactly for the reason why i like C. They are black box lego systems. You can do what they allow you to do and that’s it. But market forces…. nowadays you can hardly find a professional programmer that can use anything else but MS VS, which should be outlawed for creating the most unreadable code known to man. E.M.Smith says: 26 May 2013 at 10:09 pm “Perhaps it’s Java Script he was talking about for the kids. Frankly, I didn’t realize there was that much difference between them so have not kept them “tidy” in different buckets. Classing it all as “Java*” … So I guess I need to start keeping two buckets ;-)” Netscape invented Javascript and chose the name to take a ride on the Java hype. Entirely different language. Petrossa says: 27 May 2013 at 9:08 am “Python, java,c#,.net etc. i can’t stand exactly for the reason why i like C. They are black box lego systems. You can do what they allow you to do and that’s it.” Common industry practice these days is to write the engine in C/C++, and expose some functions and objects to an embedded Python or Javascript/ECMAscript/Ruby/Lua interpreter. This gives you the best of both worlds – ability to program on hardware level with C/C++ , and rapid prototyping / changing application logic with the scripting language. As large scale C++ systems involving lots of libraries can still take on the order of 10 minutes upwards for a complete recompile, even using a monster PC, scriptability has its advantages. To get a C++ / Python hybrid to work, check out SWIG; and google for “embedding and extending Python”. Tnx DirkH. Shows how much i am out of the loop already. Luckily i only program for fun, i retired at 45. I amuse myself with racking up my home automation system with the bells, whistles and the kitchensink. Just installed a finnicky warning system to count the number of icecreams my wife eats, which sets of a blue policetype revolving lamp at a certain number. @Petrossa: My only real complaint about C is that is presumes a style of I/O file layout (i.e. not fixed format) so using things that are fixed format (like FORTRAN files…. or just fixed column hand typed files) can be annoying. Yes, it does let you do it; but a built in “Fixed FORMAT” type statement would cut down the typing needed… (OTOH, doing variable format layout in FORTRAN is as much a PITA going from C to FORTRAN… the two just don’t have the same idea about how files ought to be laid out… Again, yes, you can do it; just how much “workaround” vs “built in easy” is the issue…) As someone who tries to get as much done with as little typing as possible, C is very nice… even if it does take a few lines to do fixed format file reads… So it avoids things like typing out the word “MULTIPLY” as in COBOL, and you don’t need to do BEGIN and END when {} would do. Yet, by the time I’ve opened a file, declared all the structures and variables, opened the file, fread data into a struct and then get set up to use it… Well, in FORTRAN you have enough implied variables and easy file open and it’s just FORMAT and READ variable list, then some math and WRITE (often with the same FORMAT). Fast. Simple. Obvious. (Almost as easy in Algol, but then again, our Algol at school had a FORTRAN influenced I/O package…) For reasons beyond my ken, many language designers have had a chip on their shoulder about Fixed Format files and seem to have designed their languages to make them painful to use. OK, not much of an issue for ‘built new’ use; but if interacting with anything already made, it just becomes a PITA. (One of the most valuable languages / systems I ever used was a DBMS with built in dump / load functions that were easy to configure. You could use it to glue together files of just about any layout. It used a “dump to fixed / load from fixed” as a kind of lingua franca for many interface discontinuities. Made life so easy…) Other than that, it doesn’t seem to get in my way, nor force me to type books, nor enforce some bizarre ideas about what is “proper” and ‘evil’… nor leave out key facilities due to some bias of the creators… nor… Oh Well… Why we have so many computer languages, I guess. Just a large tool box so the whole world need not look like a nail… ;-) I do find the “starting arrays at zero” a bit of a bother too. Algol lets you start and end arrays from any point, as you like it. Yes, the compiler has more work to do. So? The number of “off by one” errors I’ve seen from folks coping with “array item one is zero” or “array item 8 is number 7” just really wants a bit more flexibility there… but you get used to it… find ways to work around it. Eventually it gets built into your brain and you think it is “normal” and everything else is wrong and don’t notice that the ‘work around’ isn’t just how things ought to be done… There aren’t that many times you want an array to run from ” -20 to +20 “, but when you need it, it can be fairly convenient and make for obvious clear code. Oh Well… Golly… the things people do… and the things you can find… From that Algol “home page” via a link or two, I ended up at a site that preserves old software (even Algol 60!) and the run environment, such as the ICL 1900 A mainframe of years gone by… Yes, 6 bit characters and 24 bit word size… “Things were different then” ;-) So why mention this? Well…. Say you wanted your own ICL running “George”… Yes, in no time at all you can be running Algol 68 on an emulated ICL mainframe on your $35 Raspberry Pi…. Isn’t technology wonderful?…. Update Here’s some more… Making an IBM “Mainframe” on your R.Pi… running VM… So, just how much to I want to be reminded of my VM / IBM days or have a Vax Cluster in my pocket?… I remember Grace Hopper for her useful quote for dealing with BureauRats “It’s easier to ask forgiveness than it is to get permission.” (So very true) And of course her ‘BUGS’ so even those of us who are computer illiterate know who Grace Hopper is. @Gail: I always liked Grace Hopper. And Ada Lovelace… When teaching “intro to computers” I’d bring them both into the discussion and the women in the class would suddenly wake up ;-) I’d also use knitting books as an example of a programming language (complete with subroutines!) and point out that punched cards came from their earlier use in looms and weaving. About then the guys would be giving me that Oh No look but the women in class were realizing that computing was not a “Guy Thing”… The early history of computing was strongly influenced by some key woman, and Grace was one of them. @All: More ways to do odd things on your R.Pi… Want a Commodore Amiga? I’ve seen another emulator under Linux that is near perfect, so only a matter of time for the R.Pi to be that good. How about some other smaller nostalgia? How about all those old DOS programs in your attic or garage? Just amazing…. Not so much that it is being done, just that it is being done so fast. At this point, the history of computing from DOS and Amiga through BSD / Unix / Linux and even Vax Clusters and VM Mainframes, and more, all on a dinky little board… God I’d love to be assigned a “History Of Computing” class to teach… I’d have a half dozen of these set up with terminals showing what they could do, and a picture next to each one showing the Real Deal (and how big they were ;-) I’m starting to wonder if there’s anything folks won’t do with this card ;-) I’m running out of systems I’ve used to emulate. A Cray X-MP-48 and some Macintosh machines is sort of it… Oh, and a Lisa once. There were a couple of misc mini-boxes, but they were mostly running some flavor of Unix ( like Sun OS a BSD port, and a couple of others). Then there was that HP3000 with the HP operating system … But it’s just not that big a deal for them. (Though a “Toy” X-MP-48 would be fun.. “MP” is multiprocessor. 4 CPUs at 100 M-Flops each, and 8 Meg-words, or 64 MBytes of memory… ought to be able to do that with 4 x R.Pi boards with power left over… Maybe I could even make a little C shaped frame to hold it ;-) No idea where I’d get a copy of the OS… or applications… I hit “post” too soon: So add an Acorn Archimedes to the list.. I think I’m gonna need a bunch more SD cards ;-) UPDATE: And a virtual Mac: it then goes into a ‘fix’ done that ought to make it go… and the Apple IIgs: Then there is this Java based PC emulator; so one can likely run Windows on it… So that’s about a years worth of projects just getting one of each image up, configured, and running some cool old applications… Another UPDATE Looks like fpc Free Pascal Compiler too, along with something called Lazarus that is called “Object Oriented Pascal”… Not sure what an “Object Oriented Pascal” would be, but I presume someone who liked Pascal was feeling left out of the O.O. Fad and decided to glue it on… This page talks about building and using it including a build from sources, and has a neat Mandelbrot program including sources: though it looks like it pushes things close to the performance edge: Mandelbrot code: (All of 128 kB…) So far I’ve resisted putting Pascal, or anything O.O., on the Raspberry Pi… but I like Mandelbrots… though at 2 minutes to render one I think I can resist a bit longer… Though further down… It looks like there’s a lot of room for improvement and it’s not the R.Pi hardware that’s the issue: <blockquote. Well… as a cross compiler it might be more interesting too… Gee, cross compilers… a whole other area I’ve not investigated yet… ;-) “Not sure what an “Object Oriented Pascal” would be, but I presume someone who liked Pascal was feeling left out of the O.O. Fad and decided to glue it on…” Don’t remember Turbo Pascal? Anders Hejlsberg and two other Danes developed it and it got marketed by Philip Kahn in Cali under the company name Borland. Turbo Pascal developed OO capabilities; basically emulating the C++ work of Stroustrup but with pascal as the basic language. I bought a Turbo Pascal 6.0 I think in 1991 and it was a very good OO dev environment on a DOS computer. Later developed on into Delphi, adding the Visual Basic form-based GUI development; Hejlsberg later still went to Microsoft and developed the .NET family of languages, and lately has developed a superset of Javascript called TypeScript (adds optional static typing to JavaScript). Object Oriented Pascal is probably just Turbo Pascal without the company trademark… E.M.Smith says (3rd Update) 28 May 2013 at 2:51 am : Um, no. Seems to me that the “o.o. fad” was a mutation of modular coding, which has been practiced for decades by conscientious programmers. Even in FORTRAN, albeit supported more by personal discipline than by its characteristic separate compilation.As best I’ve been able to figure it, object orientation boils down to a combination of modularity (including visibility and inheritance rules) plus an abstraction for dynamic-storage allocation (to support recursion, reentrancy, or threading). Or have I boiled away anything significant?It was already available in more concrete form in PL/I (no later than F-level ver. 5, ca. 1970), by using pointervariables as surrogates for abstract “objects” that were dynamically allocateed using the controlledstorage class. But I digress, and you did insist that we “[d]on’t get [you] started on PL/I”.Any Pascal described as “o.o.” is likely a rethinking of various modular-Pascal extensions or related language designs, notably Niklaus Wirth’s own Modula (1977). Alas, Wirth just couldn’t let go of some of his math-theoretically ‘sufficient’–some might grumble “puritanically restrictive”–biases.So a more practically useful inspiration would’ve been UCSD Pascal, which was one of the original 2 O.S./development environments released for the IBM PC. It was ported by U.C. San Diego from their original research project native to LSI-11 systems (late 1970s), and commercialized as the “p-System”, as marketed by SofTech Microsystems. Alas, the p-System Pascal produced some variation on Wirth’s p-Code, and ran only on an interpreter with a nonDOS file system, and cost $100s extra; PC-DOS was $free and its compilers produced native 8086 code. Guess which one a professional Pascal enthusiast chose? And which one The Free Market chose?According to About Lazarus, the name properly applies only to “the class libraries for Free Pascal that emulate Delphi.” Ooops. Upon further reminiscing, the original PC-DOS (ver. 1) was not provided at no extra charge (see confirming source below), back when the PC’s only direct-access storage was a 5.25-in. floppy drive. So among programming-language products for it, only the BASIC interpreter came free. Compared to Pascal, it seemed nearly useless to me, but after all, the language had been named the “Beginners’ All-purpose Symbolic Instruction Code” (1965). I have no idea how much resemblance the language from Dartmouth still bears to recent versions of MS Visual BASIC. I recall the original Microsoft Pascal compiler being widely criticized. Perhaps its $300 cost created overly high expectations. Wikipedia confirms my vague recollection that the original Turbo Pascal cost $49.99. Early on, it was sometimes sold personally by Philippe Kahn himself, from a big box he’d carry around to computer clubs. And to wrap up my corrections, Wikipedia pointed out that CP/M-86 was a 3rd environment offered for the original IBM PC, altho’ at an unappealing $240, compared to $40 for PC-DOS. Sigh. I’ve had more than 30 years for these details to fade from memory. And it’s been a long time since I’ve seen my original IBM-logo sales receipt anywhere. @compuGator: Well, the O.O. folks I’ve talked with have vociferously asserted that it isn’t just modularity or fancy subroutines. (It looks like it to me…) So since it is their turf, I have to take them at their word on it. They seem to hang a lot on ‘inheritance’ that just looks like a wrapper subroutine call to me. But Lord knows I’m not qualified to judge. I’ve managed a product development to production rollout that was written in C++ and participated in the code reviews; but never did catch the fever for it. I’ve written some Pascal. Yeah, nice language. Pure. Straitjacket… FWIW, I’ve also been employed writing a cost accounting system in H.P. Business Basic. Which I described by calling it “BASIC written by a frustrated Pascal compiler guy” ;-) (It has “BEGIN / END” pairs, variables with long names, functions and subroutines, and your choice of interpreting or compilation, among other “minor enhancements” ;-) So you can turn BASIC into a real language if you graft enough Pascal into it… So original Pascal did not have inheritance (which seems the critical thing to O.O. folks in defining what makes it different – based only on the fact that THAT is the thing they all bring up and present first and with the most vigor). O.O. Pascal adds the “necessary traits”, but like I said, I can’t say what all they are. (To me it always just looks like regular old reusable modular subroutines wrapped up in fancy language and a painful syntax for how you apply them – oh, and nobody ever knows what all is in the library so ends up rewriting lots of the same Objects anyway…) It’s on my list of “Someday Things” to actually learn an O.O. language and use it. But every time I’ve tried it’s just seemed way more trouble than it was worth… I’m sure I’m missing something, just now sure it’s worth trying to catch it ;-) From the wiki: Which, after a long list of largely self referential words that try to define it as different, ends with a sentence that basically says “you can do the same thing with subroutines and functions” as part of modular programming… but then says, in effect, “but that’s not object oriented programming as it is something new”… I donno… it just looks like fancy function calls with an odd syntax wrapped up in self aggrandizing new jargon to me. Yeah, it works. But every project I’ve manage with it, or seen done in it, ends up with significant code bloat and efficiency issues compared to doing it with procedural orientation (though nobody cares as “hardware is cheap”…) The wiki goes on to try ever more to distinguish O.O. from Modular: Maybe my “block” is just that I’ve always seen data and process as strongly co-dependent. Just don’t see how you can isolate the data structure questions from the function / process questions. They are inherently bound to each other. Interesting sidebar: Looks like I worked for the folks who created Object Pascal when they were creating it! I was at Apple then, knew those folks, and my group reported to Larry Tesler. Which means they may well have been using my equipment in their development work (as we supported the Engineering computer needs / shop…) I remember it as MacApp, and I remember the transition from Pascal to C++; but had not made the connect to that history as “Object Pascal”… I suspect they called it Clascal (that I vaguely recognize) or something else. I also remember the “Think Pascal” connection. Oddly, my group was instrumental in the move to the PowerPC chip. (It’s a long story… but some of our work ended up in the PowerPC chip as the IBM chip was morphed into it. We introduced the RS6000? workstation to the guys in Engineering who then blended the designs). So this means I was, in some small way, part of both making Object Pascal, and then the move to C++ at Apple. Golly.. Yeah, it was the equivalent of “electronic janitor” mixed with “match maker”, but still… My group, my organization, we were all in staff meetings together… ATG, Advanced Technology Group. (Most of what my group did was run the Cray, but we also did all the infrastructure like networks and email and VAX Unix boxes and more. Lots of plastic simulation and a load of other stuff too. Pretty much all the data archives and backups too.) We were not part of corporate I.T. but a dedicated high response high tech group inside Engineering for the exclusive use of Engineers. Well… guess I ought to learn to use Object Pascal ;-) Why I find O.O. languages a bit of a pain. From that wiki page on Object Pascal. Here is “Hello World” in plain old Pascal, vs Object Pascal. Regular Pascal Pretty darned simple and clear, eh? Declare the program name, then do the deed. Not a lot of overhead or complexity. Object Pascal First off, there are FIVE different dialects of Object Pascal, with mutually exclusive syntax. So you must choose one. I’m going to take one from the middle that’s about average length, then also show the longest one so you can compare the two. Delphi and Free Pascal Oxygene Object Pascal Maybe it gets better in really really large programs, where the overhead of all this can be amortized over something that “gives back” enough to make up for it. Maybe not… But at first blush it looks like a lot of indirection getting in the way of a simple goal state. EM Embarcadero’s RADStudio XE has a delphi/pascal and a c++ compiler. I’m totally in love with it, despite it creating the hugest exe’s you’ll ever see. Very nice to mess about with. Highly recommended …..”I’d also use knitting books as an example of a programming language (complete with subroutines!) and point out that punched cards came from their earlier use in looms and weaving….” FWIW, the second company I worked for was a family owned business who started out in 1902 making ‘lace’ for carriages – think Fisher Body. ( Lace = narrow fabric some times like fake fur) The first hosiery and lace made on looms was in the mid 1700s – History of Machine-wrought Hosiery and Lace Manufactures The best loom in the company was an old antique made of walnut. It was used to make the fake fur wound onto a tube for Zerox copy machines. The unique quality of this machine was it wove both sides of the lace so the lace was straight and true without any camber. Most machines including those made today, knit one side and weave the other so the lace wants to bend in a circle or spiral. We had engineers over from Switzerland trying to figure out how to reproduce the workings of that old loom. They failed! This loom made a variety of laces thanks to the punch cards used to program it. If you own a car or house you have parts made by the company. All those fuzzy channels your car window rolls up into or the fuzzy weatherstripping on doors and windows. The company now seems to be out of the lace making business. I sure hope they kept that loom or donated it to a museum. (The Carriage Museum of Stony Brook was aware of the loom since I talked to the curator in the late 1980s) … I’m not antithetical to it (one of my guys wanted to use C++ to make a product. It worked well and he was productive in it) I just “don’t get it”… Maybe my “needs” are all too small to reach the benefit point so I don’t see it and they all look like a giant “Hello World” to me ;-) @Gail Combs: I’d wager the modern engineers could have duplicated it, but were not willing to work in walnut… Each wood has a particular character. One of them is surface friction. Some are self lubricating, others with just the amount of ‘drag’ wanted on a bit of thread. The degree of ‘flex’ (and that it is slightly different in different directions…) and more. I’d guess they were trying to use modern materials and it “just wouldn’t work” since some fine point of timing or thread position was not right with a non-wood friction surface and flex. Lots of folks have lost touch with the “feel” of the surfaces of structural materials. It really does matter, especially in things like handling fabrics and threads. That “feel” is what we sense when picking up fine points of the surface. From roughness to even Van der Waals forces. So take a gecko. They can climb glass due to Van der Waals forces from their pads. I’d wager that making fine lace and ‘fuzz’ gets into Van der Waals land too. How different is walnut from, say, aluminum or plastic on electrostatic and Van der Waals forces? Sure, with enough physics and math you can model it and ‘work it out’… Or just take a weaver with a lifetime of ‘feel’ for the materials and pair them with a craftsman with a lifetime of ‘feel’ for the woods and all… Perhaps in one person. A thousand and 1 little lessons learned over half a century. They make something that works, but has no analytical map for others to follow… So we could duplicate it, but not replace it… if we were willing to just duplicate it exactly with attention to every little detail of the materials… It’s “craftsmanship”, and it shows up in all sorts of places, and it matters. Much of our “modern” method of engineered things has lost touch with the craft aspects. We gain a lot of low cost and direct manufacture, like “stack” designs that are easy for robots to assemble. But we lose the subtle bits. One example. A western smith was in the tropics and marveling at their machete blades. He could make a fine blade, but his had a more sharp transition from the hardened edge to the annealed spine. He found a local smith to work with.. The “secret” was a particular gourd that grew in that area. Cut in half, it matched the outline of the machete blade. Red hot from the forge, blades were sunk into the gourd 1/2 with a chop, putting JUST the edge into the melon. The interaction of carbon and nitride from the melon, with cooling from the damp (but not bucket of boiling water fast cooling…) with residual spine heat keeping the center of the edge slightly annealed … It all produced a very hard surface layer (carbides and nitrides an rapid quench) with a strong but non-brittle core to the edge area, with a supple spine. Now, if you never saw the process of the melon ‘thunk’, how would you back engineer that? Does your typical western smith (or worse, Mechanical Engineer from a college) think in terms of “what melons and gourds do to metals”? Are melons even in the mind of a “modern” designer? Yeah, once explained it “makes sense”. And yeah, we can do the same things with other methods. But none as simple, cheap, and effective… (Urine can be used to nitride a surface too… think you find “urine treatment” in a college text book?… Maybe urea salt treatment, but it’s a lot easier to “find” urine than urea salts…) So there’s a long list of such bits of ‘craft’ that only exist in the minds of the craftsmen. Trying to backfigure them without ‘living the life’ is very hard. One other example: I was working in a hospital. The X-ray guy was ‘an old grey beard’ who had been doing it for a very long time, from before it was taught. I’d guess he started about 1930? (as this was the ’70s and he was about to retire). One of his proudest bits of “art”? A Doc had a patient with an ‘issue’ at the top of the spine. Wanted an X-ray, but knew the jaw was in the way (for some reason need a ‘front to rear’ view). Had no idea how to do it, but asked the X-ray guy to do what he could and give them “something” even with the shadows of teeth and all to cope with. He smiles. He has an idea… He knows his craft. Produces an X-ray image from the front, head in normal position, clearly showing the spine in normal alignment with the base of the skull… and no jaw in the image at all. Needless to say, the Doc was thrilled (though puzzled). How? The X-ray guy put the patient in a brace so they could not move their head, then did a very long exposure as they move their jaw slowly from wide open to closed to open to closed… The jaw and teeth just became ‘background’ shading bias and with the right exposure, that ‘white fuzz’ washes out. The jaw was never in any one place long enough to show as an image. Yes, now we would just chuck them in an MRI machine and that kind of ‘craft’ is lost. Does it really matter? Probably not so much, but some. Like how to properly put on a southern hoop skirt (all those gussets, stays, petticoats,…) and the best way to polish spats with plant products; they had a time, but most folks will never miss them. (Though real farm hams beat the commercial stuff… and are worth the effort to find someone who still has a smoke house for their own hams…) So I’d wager that a good local carpenter and weaver could reproduce that loom. Just not in “modern” materials… EM O.O is very handy. As an example take string handling. In C you have to use pointer addition, use risky memcpy’s etc. In C++ you have a class Strings which contain a multitude of wellbehaved functions to handle your strings. And adding your own is as easy as pie. Multithreading… (working code from on of my little apps) Forward declaration: class TDownloader : public TThread { protected: void __fastcall Execute(); public: __fastcall TDownloader(bool suspended); }; __fastcall TDownloader::TDownloader(bool suspended) : TThread(suspended) { } Declaration: TDownloader *Getfile[MAX_CHANNELS]; Getfile[CurrentChannel]=new TDownloader(true); if (Getfile[CurrentChannel]) { Abort->Visible=true; Getfile[CurrentChannel]->FreeOnTerminate = true; Getfile[CurrentChannel]->Priority=tpNormal; Getfile[CurrentChannel]->Start(); Stats->HideMessage(); } Now i can multithread my heart out. Try write that in pure C. E.M.Smith says: 31 May 2013 at 3:00 pm “… ” In my opinion the key advantage is the information encapsulation. I one downloaded a huge capable 3D editing package, the authors had decided to declare it Open Source; it had been a commercial success 10 years before that and was written in C. Had they written it in an OO language, they would have naturally created classes for points, vectors, matrices and so on, and declare the implementation details “private” so that code outside the classes methods would not be able to directly access the coordinates but would have to use the methods that the classes offer. like so: class Vector3D{ private: double x; double y; double z; public: AddVector(const Vector3D& other){ … Why is this an advantage? Well, in the package I downloaded it was difficult to impossible to find the place where a certain typical 3D operation is encoded; the operations were spread all over the place, specialized, duplicated etc. Structuring an application into domain specific classes leads naturally to the implementation of methods in the class that they manipulate. You can still violate this but you would have to have a good reason for that. So you would expect to find matrix multiplication implemented in the matrix class and, ideally, nowhere else. I gave up on attempts at refactoring the 3D package into a maintainable form, as I had no commercial interest… the reason they gave it into the Open Source domain was probably the same – they had given up on maintaining it; applications with a more modern design had long overtaken them. At many times in history and for various, mostly technical reasons, C programmers have emulated C++’s object orientation with the following technique: // pseudo class struct Vector2D{ double x; double y; }; // pseudo method void Vector2D_AddVector2D(Vector2D* this,Vector2D* other){ this->x += other->x; this->y += other->y; }; The trick is to explicitly give the “this” pointer argument as first argument in the “methods” of our “class”. In C++ and other OO languages this parameter is passed implicitly. C programs where this technique is used are easy to transform into C++ syntax, and are often well structured, as the C programmer already had the ordering principles of OO in mind. Petrossa says: 31 May 2013 at 10:26 am ” Embarcadero’s RADStudio XE has a delphi/pascal and a c++ compiler. ” These are descendants of Anders Hejlsberg’s Turbo Pascal and Turbo C++ from Borland. Borland sold them to Embarcadero. E.M.Smith says: 31 May 2013 at 7:00 am “Why I find O.O. languages a bit of a pain. From that wiki page on Object Pascal. Here is “Hello World” in plain old Pascal, vs Object Pascal. ” ChiefIO, those are artificial Hello World examples that are intentionally constructed to show off the OO syntax. In all OO languages I use it is still possible to write the simple imperative Hello World version known from C. That includes the object oriented Turbo Pascal. When all you need is stdout, just use a simple printf or writeln or print or whatever it’s called. DirkH, i know. Was a Borland user since Turbo Basic to see MS running after Borland all the time to catch up and never succeeding. Then it became Codegear and now RadStudio. EM Encapsulation is sometimes actually a pain in the butt. I had to write a program around an old C library which resulted in this mess: Petrossa, I looked at your code. What you did there looks like a simple wrapper; to wrap an object oriented calling interface around a non object oriented one. Such wrapping tasks are always repetitive and tedious – whether OO is in play or not -, often get automated with custom source code creators, and when you’re in a project where it is allowed, you can often compress the effort effectively using the X Macro technique. I like X macros because once you know the trick you end up with less code to read and to understand. Often I work in projects where they prohibit me from using the C preprocessor because they fear chaos. In those cases I often end up generating the wrapper code with custom Python scripts and give them what I generated. DirkH The point was because the call to the existing C library needed a static pointer. Since in O.O you can’t get a static pointer to a function outside of the class this whole mess was necessary. i.e. Encapsulation can be a pain in the butt. Petrossa says: 3 June 2013 at 9:26 am “DirkH The point was because the call to the existing C library needed a static pointer. Since in O.O you can’t get a static pointer to a function outside of the class this whole mess was necessary.” Why can’t you get a pointer to a function outside the class? int Function(int a); typedef int (*funcptr)(int); class MyClass{ funcptr m_funcptr; public: MyClass(funcptr fp){ m_funcptr = fp;}; int Execute(int a){return (*m_funcptr)(a);}; }; … MyClass obj = new MyClass(Function); int b = obj->Execute(arg); Maybe I misunderstand you. Or maybe you wanted to publish the static function pointer to somebody outside the class. But in that case you can just declare the function as static and make it accessible using “public:”. Or make it accessible via returning a function pointer. A class can expose its innards when it wants to. Tnx for thinking with me DirkH. But having tried all that in 2002 and failing i came up with this. It was some particularity with the library which by now i have longtime forgotten.
https://chiefio.wordpress.com/2013/05/25/cruel-raspberries/
CC-MAIN-2020-40
refinedweb
9,876
70.02
A little while back in the CB, someone (forgive me, I have forgotten who), mentioned it would be interesting to see the age distribution of those monks who have reported their ages for the PerlMonks Stats Pages. So I decided to take a stab at generating such stats. The script currently pulls up the upcoming birthdays page and scrapes the age information out, then outputs the requested file format (HTML or PNG). A future version might pull XML data from the server instead when it is available. Examples: HTML Output, Summary Graph, Detail Graph. Update: T'was dada that proposed the age stats in the CB. Thanks for the reminder ;) Changed PDF to PNG in the comments. Update: Ack! Looks like ar0n beat me to this almost a whole year ago: hup - home node updater. Thanks for pointing this out ybiC, and don't blame me - blame ar0n! . I started playing with the scripts when I noticed that in the early versions jcwren had experienced problems using my HTML::TableExtract module. The later versions of each script instead use the XML ticker and. The XML interface is far quicker, but apparently not all people wish to install the associated XML modules and libraries. This module incorporates both query methods, XML as well as HTML. The default is XML, but this behavior can be changed via the mode parameter. If you have XML parsing problems with non UTF-8 encodings in your titles, then simply set the mode to HTML. Behind a proxy server? Set your http_proxy environment variable to the URL of your proxy server. See the POD for more information. Thanks to jcwren and larryl for the original code. Basic usage: #!/usr/bin/perl use PerlMonks::StatsWhore; $sw = PerlMonks::StatsWhore->new( user => 'username', password => 'password', ); print $sw->summary_as_string; [download] Check out the code if you're interested in inheritance and polymorphism. Matt Updates thus far: A Perl extension to check PM experience points before a given PerlMonk reaches 'level vroom'. Handy for monks of the Saint(10)ly persuasion. Works fine as is, but substantial changes are in the works. You can peruse all the supporting files initially generated by h2xs here, plus there's a tarball of the whole shebang. (as this is my first serious-to-completion-of-working-code module writing effort, I'd particularly welcome any and all criticism, complaints, rotton fruit, or even constructive suggestions) A simple little program that will keep a log of any changes to the title, id, or rep of your nodes, including the addition or deletion of said nodes. 2002-03-31 Edit by the node bunny : Changed login and password. Please read the warnings about possible dangers. Do not simply execute any code/node you have reason to distrust, but that of course goes for manual downloads as well. This does work well for just downloading too though, if you just want to poke around in a script. :) Update: The provided patch by Amoe has been applied. My way worked for me on Win2k, cygwin and FreeBSD, so I lazied out on this one. :) Thanks Amoe! Update 2: Suggestion 2 by belg4mit should be working now: Using the -d option for deparsing instead of executing should now work. Note that in-memory-deparsing uses a new feauture (v5.6.1?) in B::Deparse that won't work with older perls. Use together with -M or -F instead. pm_username|pm_passwd|email_addy It's that simple (at least I hope it is). my example is below... please feel free to add your own. update: Tue Apr 2 10:37:58 2002 GMT ~ changed off trigger due to Petruchio update: Fri May 24 11:19:30 2002 GMT ~ " as added, so gots to take it out (and also added a \n remove, jeez, i'm gonna make this obsolete soon ~ and & ~ i hope the goods see pmdev wiki soon) update: Fri Jan 17 05:31:13 2003 GMT -- more changes, more fixes. A cool feature about your posts is the fact that you can put HTML comments in the title of your post. Armed with this feature, it is possible to put 'category markers' in your node titles and use a script to find them and make a nice list of your favorite nodes. The following code will do just that, the demo is on my home node. All you need to do is mark your favorite nodes by hand with something like <!--code--> or <!--obfu-->. Well that's how i did it before i saw jcwren's Bulk Node Title Editor. The side effect is that you have to link directly to a node's id instead of it's name when referring to it in other posts, chatbox, etc. But that's okay, you use id tags, don't you? Hey Rocko! Ask 'em if they use id tags! Feel free to send comments and suggestions to crazyinsomniac! :D'. Implements automatic updating of home node image, after so many hits on the home node. Uses a "bug" script (included) to detect hits, and this piece to automatically uploaded a new image after so many hits. Please read the section on SECURITY and the rest of the documentation before using. Requires some responsibility on the part of the user. Quickly check changes in your Perl Monks nodes' reputations. It will list all of your nodes, sorted by reputation in descending order, with any changes since the last time you ran Quickrep. hup is a home node updater. You can use it on the command line, or from a crontab, to automate updating your homenode. As always, suggestions welcome. Updates xml_pimp.pl - You heard of statswhore? You heard (x)luke_repwalker? Well dis da pimp! Like always, no comments are welcome(now that's what I call sarcasm ;-)) updates: July 20, 2001 - minor cosmetic changes; July 21, 2001 - updated some pod (a blah... got by me) July 27, 2001 - changed sort keys to sort {$a<=>$b> keys(print_HISTORY for -h1) September 26, 2001 - added &ticker=yes (details: New ticker login for PM XML clients) Sun Jan 13 21:11:13 2002 GMT - fixed serious bug nobody told me about, which I was unaware of due to my testing environment. I guess the good thing is i'm the only one using this ;)(or I lost the original posted version which worked) I. Also, Main features: Because pmchat is a text-mode client, it has the following shortcomings By default, the file is written to perlmonks.html. If that file already exists, a backup will be created at Operlmonks.html before the file is overwritten. I guess you need to have the WebFetch module installed to run this. Special thanks to : - OeufMayo for creating the XML::Parser tutorial that helped me create this. - mirod for helping me with the XML::Parser problem. Bugfixes: - xml_char () was altered to read in entire string as mirod suggested - the tests to return () were moved to xml_end () from xml_start () to keep from reading too many strings into one field Suggestions please ... The code is too large to post it here, so I'll point you to the web page instead. There are a number of clients that use these modules. Check out my home node for the full list. Enjoy! Note: Threaded mode can get dramatically slower as the number of nodes increases, so be prepared to wait when threading more than a few days worth (1000+). Be sure the #! and 3 config variables are correct first. Also: For some reason xNN is now very very slow checking anything more than 1 day of nodes. Nothing changed in the script which suggests that some change in the XML ticker (or something) is causing it. I'm kind of busy now so the fix will have to wait (unless you figure it out and send me a patch :-) Code updated: 5.23.2002 Because it's larger than 50k reputer has two nodes on Perlmonks. This is the source code node in code catacombs. Please make replies to the reply node. Also includes proxy support, restricted public access mode, integration with command line programs and compressed file export. Update: Fixed possible problem creating data files when first running script. This is an update of luke_repwalker.pl that uses mirods XML::Twig module. It's faster because it generates few hits to the server. People like tilly should appreciate this... And ultimately it's more reliable, since it doesn't try to parse the tables of article listings. I posted this as new code so that the old one would still be available. Some people have had trouble installing the various XML modules, or don't wish to. xstatswhore.pl is an update of statswhore.pl that uses mirods XML::Twig module, and includes larryls histogram code (if you like the histogram part, be sure to thank him. ++Re: statswhore.pl). This version has the advantage of being faster by generating fewer hits to the server, and fixing the problem of having exactly a multiple of 50 nodes. And the histogram part is really cool... d/l the code, and save the two pieces marked with ##filename=foo.html## as what the name is supposed to be. Be sure cookies and JavaScript are on. Then point your browser at perlmonks.html, and try it out. With this, this morning I was able to walk through every post for several days worth of PerlMonks in just a few hours. Most of that time was spent writing up responses. With this I can follow the whole site with less energy than it would take to hit a reasonable portion of it through using Newest Nodes. Update Clearly my cookie handling in JavaScript sucks. Oh well, I don't like either cookies or JavaScript, so I guess that was my internal bias showing. :-) Now fixed. Hear monks talk! Listen to your favorite monks battle it out in the chatterbox, as streaming audio! Make your co-workers think you're a basket case! This script delivers the chatterbox as MP3 encoded streaming audio. It uses the festival/MBROLA text-to-speech (TTS) system to create the audio on the fly. Since it's based on ZZamboni's Chatterbox Client you will need to download his module as well.. Update: I no longer post the graphs on my home node. The updated code given in the replies to this node is more modern. Thanks to everyone for the kind comments I received when I first wrote this. Yes No Other opinion (please explain) Results (102 votes), past polls
http://www.perlmonks.org/?node_id=26649
CC-MAIN-2015-40
refinedweb
1,763
73.58
10587/possible-jenkins-pipeline-function-fileexist-handle-wildcards The fileExist step does not accept wildcards. But, if you use the ‘Pipeline Utility Steps Plugin’, you can make use of the findFiles function which accepts wildcards. An example: def files = findFiles glob: '**/*.zip' boolean exists = files.length > 0 If you do not have the plug-in, you can use the shell "find". def exitCode = sh script: 'find -name "*.zip" | egrep .', returnStatus: true boolean exists = exitCode == 0 FileExists() does not support wildcards. FileFindFirst() does though, and you can check for a folder that way. Yes, you can create a Jenkins pipeline ...READ MORE Try Jenkins Plugin called as Slave SetupPlugin. This ...READ MORE There are some Jenkins plugins out there .. There is a parameterized remote trigger plugin ...READ MORE Try changing the port, Change JENKINS_AJP_PORT="xyz" to JENKINS_AJP_PORT="abc" If changing the ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/10587/possible-jenkins-pipeline-function-fileexist-handle-wildcards?show=45579
CC-MAIN-2019-43
refinedweb
149
61.43
multiple loop variables in C Language C programming allows to use one loop inside another loop. The following section shows a few examples to illustrate the concept. Syntax The syntax for a nested for loop statement in C is as follows − for ( init; condition; increment ) { for ( init; condition; increment ) { statement(s); } statement(s); } The syntax for a nested while loop statement in C programming language is as follows − while(condition) { while(condition) { statement(s); } statement(s); } The syntax for a nested do…while loop statement in C programming language is as follows − do { statement(s); do { statement(s); }while( condition ); }while( condition ); A final note on loop nesting is that you can put any type of loop inside any other type of loop. For example, a ‘for’ loop can be inside a ‘while’ loop or vice versa. Example The following program uses a nested for loop to find the prime numbers from 2 to 100 − Live Demo #include <stdio.h> int main () { /* local variable definition */ int i, j; for(i = 2; i<100; i++) { for(j = 2; j <= (i/j); j++) if(!(i%j)) break; // if factor found, not prime if(j > (i/j)) printf("%d is prime\n", c language tutorial learn c language study c language
https://www.efaculty.in/c-language/multiple-loop-variables-in-c-language/
CC-MAIN-2020-45
refinedweb
208
52.63
Hello everyone! Hope you’re having a good time using the new ReSharper 5.0. If you do, just ignore this post :) If you’re facing issues with ReSharper 5.0, read on. There are certain bugs, usability problems and otherwise weird behavior that users report following the release (surprise!). Some of them you can work around, others you can’t, but both kinds of issues will be addressed in the upcoming ReSharper 5.1. It’s scheduled for release in June but we’ll open the Early Access Program in May, and chances are that the most annoying issues will be fixed in these early builds. Here are some of the most annoying issues that have known workarounds: - RSRP-178681: aspx pages lose references to their code-behind files. A lot of people complained that when saving an aspx page with a code-behind file, the reference to the code behind file gets lost and lots of errors start to pop up. Workaround: Go back to the aspx page and save it again (without changing anything): the reference restores and both files display and work correctly. - RSRP-178492: Adding Cyrillic comments and creating new custom controls in WPF applications sometimes changes file encoding from UTF-8 to Win-1251. Workaround: The only way to change this behavior is to manually roll file encoding back to UTF-8 by choosing File | Advanced Save Options in Visual Studio. - Another problem reported in RSRP-178492 is that during refactorings, ReSharper changes the locale of XAML files based on your Windows locale. That only happens if you don’t select the “To enable Undo, open all files with changes for editing” check box in a refactoring dialog box. Workaround: Make sure to select the “To enable Undo, open all files with changes for editing” check box. - UPDATE! Thanks to Frans Bouma for reminding about the other annoying issue, NP-20: Splitting a Visual Studio text editor tab makes ReSharper marker bar and possibly other features go away in one or both parts of this particular tab. Workaround: Rejoin the editor tab, close it, then reopen. - UPDATE 2! Visual Studio 2010 crashes during file save and build operations. Workaround: ReSharper may cause this problem but there’s a known common cause of this behavior: a certain version of AnkhSvn. If you have both ReSharper and AnkhSvn installed, try following Microsoft guidelines on updating your AnkhSvn build. Builds 2.1.8420 and higher are reported to fix the intermittent Visual Studio crash problem. - UPDATE 3a! RSRP-147892: Calling GetTempFileName()in Windows 7 or in Windows Server 2008 R2 causes UnauthorizedAccessException Workaround: This is not a ReSharper problem. Microsoft has confirmed that this issue occurs because the GetTempFileName()function in Windows 7 and Windows Server 2008 R2 handles a duplicated file name incorrectly. Download this Microsoft hot fix to remove the issue. - UPDATE 3b! Even small cut-and-paste operations raise “insufficient memory” errors in Visual Studio 2010. Workaround: Again, this is not a ReSharper issue. Microsoft has released a patch for Visual Studio 2010 that removes this issue. For details on its symptoms and other implications, read this Visual Studio blog post. We also receive reports about performance issues when renaming and doing Find Usages in large projects that contain aspx files. We are doing performance analysis and aiming to solve these issues in time for the bug fix release. Just in case you’re interested, here’s the full list of issues currently scheduled for ReSharper 5.1. On a different note, people report on a regular basis about Visual Studio 2005 or 2008 installations that freeze or crash after opening web forms, or Solution Explorer that hangs up. There are known solutions to this kind of issues (not having anything to do with ReSharper), including: - Removing Microsoft Visual Studio Web Authoring Component, - Reinstalling Microsoft Office 2007, - Removing Communicator 2007 and LiveMeeting 2007. - (Update!) Uninstalling KB976569, installing KB974417 and reinstalling KB976569. Before you contact us with such issues suspecting ReSharper, please make sure to try the solutions provided above. By the way, if you’re using Visual Studio 2010, have you installed Windows Automation API? Rumors say it really boosts Visual Studio performance, particularly with ReSharper. The bug where you split the code window horizontally and which makes R# go away completely is not scheduled to be fixed at all? That’s one of the most annoying bugs in R# 5 at the moment: splitting a code window is a burden now, as you know you’ve to resplit the window after you’ve closed the split to get R# back (eg: to get intellisense back!) e.g. RSRP-178978 Other issues: - the current line highlight disappears randomly in 2008, the only way to get it back is to go into tools -> options of vs.net and click OK - The pencil icon stays on top of any window, even if you tabbed away from vs.net 2008 to another application. This is also very very annoying. @Frans, Oops, completely forgot the thing with window split. Will update the post now, thanks. As regards the other bugs you’ve mentioned, not sure if they’re on the top list to be resolved for 5.1. And you surely want to fix the bug where is incorrectly marked as an error when the view name does not match a controller action, right? In MVC view names and action names do not always match which is an important feature in postback scenarios. Or if you want to show a different view to a logged in user. Or a different view for google. Or a different view after a postback (as a thanks-message). Please please do not make me click “ignore this error” 10 times every time I open the solution. I’m a bit disappointed that you’re not going to do anything to make Structured Search and Replace more stable. The bugs you’re fixing are all ones I’ve never even seen. Still, if you’re crashing a lot of other users, you’ve got to set priorities. Hi SVP put back on your list please. Reproduce: Take from the office an laptop and go to the park, start the laptop with no vpn connection to the office. Open in VS2010 your webproject and start editing in one of the aspx pages (any code file will do probably). Your ide is frozen for 10 sec every n seconds. I think tobi is right. My company is suffering from the same problem. There seems to be no way of turning this particular (wrong!) behavior off without completely disabling MVC support. I can confirm the behavior Edward, tobi and rupdoc said. I think they are right what MVC is concerned. I found this “feature” quite annoying, too. It is frustrating when working code gets flagged as incorrect. Personally I am constantly working with several VS instances opened, with different VS solutions dependent on each others. When I compile a VS solution ‘root’, all the ‘dependent on the root’ VS solutions sees the corresponding compiled root dlls as missing. Consequently the code editors are full of red code elements which are not resolved by R#5. This is totally unusable and I had to downgrade to R#4.5 for VS 2008, and no R# for VS 2010. As a side note, my root folder where all my VS solutions files are is still polluted with dozens of .resharper and .resharper.user files. This bothers me for 4 years that I am using R#. I cannot imagine it is difficult that you put these files somewhere else. @tobi Yes that normal situation, when view name is different from action name. And in most cases R# doing well. What exactly is your situation? Errors in MVC view on anonymous Html.BeginForm()? You can provide explicitly name of action and controller for postback, i.e. Html.BeginForm(“Action”, “Controller”). @rupdoc You can disable one-by-one not-resolved MVC errors (in complex or not-supported cases) by special comments. Action is available by QuickFix. It will generetae surrounding comment like this # ReSharper disable Asp.NotResolved bla-bla-bla # ReSharper restore Asp.NotResolved @Patrick, the .resharper files will be checked into version control, so where else would you put them other than the solution directory? As for the .resharper.user files, those are no different from the .suo file. You add them to the list of extensions that your revision-control system should ignore. I mentioned the window split issue, because it wasn’t in the list of issues to fix for v5.1, so please make sure you have tagged the issue as one to fix for v5.1, as it’s annoying to no end… and please make the popup icons at the left of code lines NOT stay visible when the vs.net instance doesn’t have the focus (read: when another window is on top of it)… 4.5 didn’t have this issue. Joe, there are also some .sln.cache files I forgot to mention. So in my case I have 12 sln files and 36 R# files in my root folder. Why not having one dedicated sub-folder of the sln folder for all these R# files, or at the very least, have an option to let the user store all these files in a sub-folder if he prefers this way. Rename class with sync filename is extremely slow in the 5.0 release. It didnt seem to have those issues in earliere versions. Silverlight4 code is recognized as “Error in Solution” when referenced from a regular .NET assembly. Same goes for optional parameters. Cool – I’m happy to see you added RSRP-177814 (editing one pattern breaks another) for 5.1. That’s the big glaring stability issue. If you fix that, I’ll be able to have a lot more confidence in the feature. “Hope you’re having a good time using the new ReSharper 5.0.” Not at all Please see this forum thread, which is one the most popular threads in the ReSharper forum. Why do a blog post without even mentioning that? The fix for RSRP-178681 (aspx pages lose references to their code-behind files) works most but not all of the time for me. It seems to be worst on pages which reference user controls. In one instance I achieved the workaround by saving the user control and then going back to the page and saving that. This is on VS2008 on an asp.net web forms project. Visual Studio 2010 always crash when Resharper 5 is used. It happens very often usually when I make refactoring (rename fields) or when it is necessary to add usage of namespace. Also several times Visual Studio 2010 crashed when one property was underlined (with warning) and I drag mouse over this property. Rename is much slower with Synchronize file names on. It seems to spend a lot of time in Designer files.
http://blog.jetbrains.com/dotnet/2010/05/04/resharper-50-known-issues-workarounds-and-bugfix-schedule/
CC-MAIN-2015-35
refinedweb
1,834
64.81
13 Mar 2017, 10:34 A Desktop Raspberry Pi Selfie Camera A fun project that uses a Pi 3 plus Touch Screen display, Camera and SenseHAT. In this post we take a look at an easy to complete project that makes use of four official Raspberry Pi products, to create a desktop “selfie” camera. One of the really great things about this is that it does not require any soldering or custom electronics. Furthermore, with great software support for the hardware used, the software application is also super simple. Hardware The following components were used: - Raspberry Pi 3 Model B - Raspberry Pi Touch Screen - Raspberry Pi Camera - SenseHAT - Power supply - 32GB Micro SD card Plus a custom laser cut and folded acrylic case. Obviously, if you don’t have access to a laser cutter and acrylic folder, alternative enclosures could be utilised. O/S and dependencies Raspbian Jessie Lite was written out to a Micro SD card, following which the host name was changed to something more unique than simply raspberrypi, by editing the root filesystem etc/hostname and etc/hosts files. That way it would be easier to locate on the network. The openssh-server is now disabled by default and because I prefer to log in via SSH, this was enabled by simply creating an empty file called ssh on the boot partition. The Touch Screen was technically mounted upside down and so to rotate the display to the correct orientation, it was necessary to edit config.txt — also on the boot partition — and add the line: lcd_rotate=2 Next the Micro SD card was inserted into the Raspberry Pi and power applied. Following which, as is customary and highly advisable, the O/S was updated by logging in and entering: $ sudo apt get update $ sudo apt-get dist-upgrade Note that since we had changed the host name to selfiecam, it was possible to log in to the Pi from another Linux computer using: $ ssh pi@selfiecam.local Since we wanted to use the SenseHAT, Camera and framebuffer, some useful Python software was also installed via: $ sudo apt-get install sense-hat python-picamera python-pygame Finally, it was necessary to enable the Camera and reboot, which can be done via raspi-config: $ sudo raspi-config Software First we need to import some libraries, which includes those mentioned above. import os import time import pygame from picamera import PiCamera from sense_hat import SenseHat We need to initialise Pygame, which will be used to display images to the framebuffer (display). pygame.init() screen = pygame.display.set_mode([800,480]) Next we set up the camera and since it’s physical position is horizontally flipped, we flip it back via software. camera = PiCamera() camera.resolution = (800, 480) camera.hflip = True Following which the SenseHAT is configured. sense = SenseHat() sense.set_rotation(0) Next we define a function that will take a file as an argument and then use Pygame to paint the screen black, before displaying the image it contains. def displayImage(file): image = pygame.image.load(file) imagerect = image.get_rect() screen.fill([0, 0, 0]) screen.blit(image, imagerect) pygame.display.flip() Then we define a function which enables video preview, displays a 3-2-1-0 countdown on the SenseHAT LED matrix, before capturing a still, disabling preview, displaying the image and finally clearing the LED matrix. The image filename contains the date and time. def getSelfie(): # Start camera video preview camera.start_preview() # Commence countdown sense.show_letter("3", text_colour=[255, 0, 0]) time.sleep(1) sense.show_letter("2", text_colour=[255, 255, 0]) time.sleep(1) sense.show_letter("1", text_colour=[0, 255, 0]) time.sleep(1) sense.show_letter("0", text_colour=[0, 0, 255]) # Capture image and stop preview filename = time.strftime("/selfies/%Y-%m-%d-%H-%M-%S.jpg") camera.capture(filename) camera.stop_preview() # Display image and clear SenseHAT display displayImage(filename) sense.clear() Note that the numbers displayed on the LED matrix are different colours: 3 = red, 2 = yellow, 1 = green and 0 = blue. So far we have just imported libraries and defined functions. Next we use the displayImage() function to update the Touch Screen display with a welcome graphic upon start-up. displayImage("/usr/local/share/images/Welcome.png") Finally, we enter the main loop of the program. In this we wait for an event from the SenseHAT joystick. If this was depressed, we wait until it is released and call the getSelfie() function. If it was held to the left we initiate shutdown. We simply ignore any other actions. while True: # Wait for and process joystick events event = sense.stick.wait_for_event(emptybuffer=True) if event.direction == "middle" and event.action == "released": getSelfie() elif event.direction == "left" and event.action == "held": os.system("/sbin/shutdown -h now") else: pass Running The /etc/rc.local file is run at start-up and a line was added to this that disables screen blanking, followed by a second which launches the selfie camera application. sudo sh -c "TERM=linux setterm -blank 0 >/dev/tty0" /usr/local/bin/selfie.py & Upon rebooting we were then presented with the welcome graphic. On pressing the joystick a live video preview was displayed and the countdown commences. At zero a still image is captured, video preview stopped and the image displayed to the screen. And the final result could be copied off the SD card. Simple! :o) If you would like to have a go at making this project yourself the Python script and acrylic case design files can be found on GitHub. March 20, 2017 08:47 Pi Day Competition
https://www.rs-online.com/designspark/a-desktop-raspberry-pi-selfie-camera
CC-MAIN-2019-51
refinedweb
926
56.86
Eleventy is increasing in popularity because it allows us to create nice, simple websites, but also — because it’s so developer-friendly. We can build large-scale, complex projects with it, too. In this tutorial we’re going to demonstrate that expansive capability by putting a together a powerful and human-friendly environment variable solution. What are environment variables?What are environment variables? Environment variables are handy variables/configuration values that are defined within the environment that your code finds itself in. For example, say you have a WordPress site: you’re probably going to want to connect to one database on your live site and a different one for your staging and local sites. We can hard-code these values in wp-config.php but a good way of keeping the connection details a secret and making it easier to keep your code in source control, such as Git, is defining these away from your code. Here’s a standard-edition WordPress wp-config.php snippet with hardcoded values: <?php define( 'DB_NAME', 'my_cool_db' ); define( 'DB_USER', 'root' ); define( 'DB_PASSWORD', 'root' ); define( 'DB_HOST', 'localhost' ); Using the same example of a wp-config.php file, we can introduce a tool like phpdotenv and change it to something like this instead, and define the values away from the code: <?php $dotenv = Dotenv\Dotenv::createImmutable(__DIR__); $dotenv->load(); define( 'DB_NAME', $_ENV['DB_NAME'] ); define( 'DB_USER', $_ENV['DB_USER'] ); define( 'DB_PASSWORD', $_ENV['DB_PASSWORD'] ); define( 'DB_HOST', $_ENV['DB_HOST'] ); A way to define these environment variable values is by using a .env file, which is a text file that is commonly ignored by source control. We then scoop up those values — which might be unavailable to your code by default, using a tool such as dotenv or phpdotenv. Tools like dotenv are super useful because you could define these variables in an .env file, a Docker script or deploy script and it’ll just work — which is my favorite type of tool! The reason we tend to ignore these in source control (via .gitignore) is because they often contain secret keys or database connection information. Ideally, you want to keep that away from any remote repository, such as GitHub, to keep details as safe as possible. Getting startedGetting started For this tutorial, I’ve made some starter files to save us all a bit of time. It’s a base, bare-bones Eleventy site with all of the boring bits done for us. Step one of this tutorial is to download the starter files and unzip them wherever you want to work with them. Once the files are unzipped, open up the folder in your terminal and run npm install. Once you’ve done that, run npm start. When you open your browser at, it should look like this: Also, while we’re setting up: create a new, empty file called .env and add it to the root of your base files folder. Creating a friendly interfaceCreating a friendly interface Environment variables are often really shouty, because we use all caps, which can get irritating. What I prefer to do is create a JavaScript interface that consumes these values and exports them as something human-friendly and namespaced, so you know just by looking at the code that you’re using environment variables. Let’s take a value like HELLO=hi there, which might be defined in our .env file. To access this, we use process.env.HELLO, which after a few calls, gets a bit tiresome. What if that value is not defined, either? It’s handy to provide a fallback for these scenarios. Using a JavaScript setup, we can do this sort of thing: require('dotenv').config(); module.exports = { hello: process.env.HELLO || 'Hello not set, but hi, anyway 👋' }; What we are doing here is looking for that environment variable and setting a default value, if needed, using the OR operator ( ||) to return a value if it’s not defined. Then, in our templates, we can do {{ env.hello }}. Now that we know how this technique works, let’s make it happen. In our starter files folder, there is a directory called src/_data with an empty env.js file in it. Open it up and add the following code to it: require('dotenv').config(); module.exports = { otherSiteUrl: process.env.OTHER_SITE_URL || '', hello: process.env.HELLO || 'Hello not set, but hi, anyway 👋' }; Because our data file is called env.js, we can access it in our templates with the env prefix. If we wanted our environment variables to be prefixed with environment, we would change the name of our data file to environment.js . You can read more on the Eleventy documentation. We’ve got our hello value here and also an otherSiteUrl value which we use to allow people to see the different versions of our site, based on their environment variable configs. This setup uses Eleventy JavaScript Data Files which allow us to run JavaScript and return the output as static data. They even support asynchronous code! These JavaScript Data Files are probably my favorite Eleventy feature. Now that we have this JavaScript interface set up, let’s head over to our content and implement some variables. Open up src/index.md and at the bottom of the file, add the following: Here’s an example: The environment variable, HELLO is currently: “{{ env.hello }}”. This is called with {% raw %}{{ env.hello }}{% endraw %}. Pretty cool, right? We can use these variables right in our content with Eleventy! Now, when you define or change the value of HELLO in your .env file and restart the npm start task, you’ll see the content update. Your site should look like this now: You might be wondering what the heck {% raw %} is. It’s a Nunjucks tag that allows you to define areas that it should ignore. Without it, Nunjucks would try to evaluate the example {{ env.hello }} part. Modifying image base pathsModifying image base paths That first example we did was cool, but let’s really start exploring how this approach can be useful. Often, you will want your production images to be fronted-up with some sort of CDN, but you’ll probably also want your images running locally when you are developing your site. What this means is that to help with performance and varied image format support, we often use a CDN to serve up our images for us and these CDNs will often serve images directly from your site, such as from your /images folder. This is exactly what I do on Piccalilli with ImgIX, but these CDNs don’t have access to the local version of the site. So, being able to switch between CDN and local images is handy. The solution to this problem is almost trivial with environment variables — especially with Eleventy and dotenv, because if the environment variables are not defined at the point of usage, no errors are thrown. Open up src/_data/env.js and add the following properties to the object: imageBase: process.env.IMAGE_BASE || '/images/', imageProps: process.env.IMAGE_PROPS, We’re using a default value for imageBase of /images/ so that if IMAGE_BASE is not defined, our local images can be found. We don’t do the same for imageProps because they can be empty unless we need them. Open up _includes/base.njk and, after the <h1>{{ title }}</h1> bit, add the following: <img src="{{ env.imageBase }}mountains.jpg{{ env.imageProps }}" alt="Some lush mountains at sunset" /> By default, this will load /images/mountains.jpg. Cool! Now, open up the .env file and add the following to it: IMAGE_BASE= IMAGE_PROPS=?width=1275&height=805&format=auto&quality=70 If you stop Eleventy ( Ctrl+ C in terminal) and then run npm start again, then view source in your browser, the rendered image should look like this: <img src="" alt="Some lush mountains at sunset" /> This means we can leverage the CodePen asset optimizations only when we need them. Powering private and premium content with EleventyPowering private and premium content with Eleventy We can also use environment variables to conditionally render content, based on a mode, such as private mode. This is an important capability for me, personally, because I have an Eleventy Course, and CSS book, both powered by Eleventy that only show premium content to those who have paid for it. There’s all-sorts of tech magic happening behind the scenes with Service Workers and APIs, but core to it all is that content can be conditionally rendered based on env.mode in our JavaScript interface. Let’s add that to our example now. Open up src/_data/env.js and add the following to the object: mode: process.env.MODE || 'public' This setup means that by default, the mode is public. Now, open up src/index.md and add the following to the bottom of the file: {% if env.mode === 'private' %} ## This is secret content that only shows if we’re in private mode. This is called with {% raw %}`{{ env.mode }}`{% endraw %}. This is great for doing special private builds of the site for people that pay for content, for example. {% endif %} If you refresh your local version, you won’t be able to see that content that we just added. This is working perfectly for us — especially because we want to protect it. So now, let’s show it, using environment variables. Open up .env and add the following to it: MODE=private Now, restart Eleventy and reload the site. You should now see something like this: You can run this conditional rendering within the template too. For example, you could make all of the page content private and render a paywall instead. An example of that is if you go to my course without a license, you will be presented with a call to action to buy it: Fun modeFun mode This has hopefully been really useful content for you so far, so let’s expand on what we’ve learned and have some fun with it! I want to finish by making a “fun mode” which completely alters the design to something more… fun. Open up src/_includes/base.njk, and just before the closing </head> tag, add the following: {% if env.funMode %} <link rel="stylesheet" href="" /> <style> body { font-family: 'Comic Sans MS', cursive; background: #fc427b; color: #391129; } h1, .fun { font-family: 'Lobster'; } .fun { font-size: 2rem; max-width: 40rem; margin: 0 auto 3rem auto; background: #feb7cd; border: 2px dotted #fea47f; padding: 2rem; text-align: center; } </style> {% endif %} This snippet is looking to see if our funMode environment variable is true and if it is, it’s adding some “fun” CSS. Still in base.njk, just before the opening <article> tag, add the following code: {% if env.funMode %} <div class="fun"> <p>🎉 <strong>Fun mode enabled!</strong> 🎉</p> </div> {% endif %} This code is using the same logic and rendering a fun banner if funMode is true. Let’s create our environment variable interface for that now. Open up src/_data/env.js and add the following to the exported object: funMode: process.env.FUN_MODE If funMode is not defined, it will act as false, because undefined is a falsy value. Next, open up your .env file and add the following to it: FUN_MODE=true Now, restart the Eleventy task and reload your browser. It should look like this: Pretty loud, huh?! Even though this design looks pretty awful (read: rad), I hope it demonstrates how much you can change with this environment setup. Wrapping upWrapping up We’ve created three versions of the same site, running the same code to see all the differences: All of these sites are powered by identical code with the only difference between each site being some environment variables which, for this example, I have defined in my Netlify dashboard. I hope that this technique will open up all sorts of possibilities for you, using the best static site generator, Eleventy! I feel like the code block right before “By default, this will load /images/mountains.jpg.” is false. Isn’t it supposed to be <img src="{{ env.imageBase }}mountains.jpg{{ env.imageProps }}" alt="Some lush mountains at sunset" />? @YellowLed – yup. Thanks for the correx! I was about to try making a similar change myself, but then saw your comment. Thanks for this. I’ve updated it :)
https://css-tricks.com/give-your-eleventy-site-superpowers-with-environment-variables/
CC-MAIN-2021-04
refinedweb
2,052
64.81
In article <yJnA5.2123$bF.90406 at nntp1.onemain.com>, Jon Brisbin <mail at jbrisbin.net> wrote: >Quite a few have already perused and downloaded my new project Python >ServerPages ( ) and several have >asked "what's the difference between this and all those other packages??" >In a word: simplicity :-) One CGI script (which can be integrated with your >mod_pyapache, mod_snake, etc...) parses your embeded Python code...here's an >example of how easy it is to develop a PSP page: > ><body> >[$ if Form.has_key("variable"): $] > <h1>Hello [+Form.variable+]</h1> >[$ endif $] ><hr> >[- >def myFunc(self, param): > return "foo" + string.toupper(param) >-] ><hr> >[+myFunc("stuff")+]<br> >You are connecting from: [+Request.remote_addr+] ><hr> ><!-- Include another PSP page --> >[-Page.process("/full/path/to/file.pyml")-] > [snip] > >You can download Python ServerPages at > > Couple-o-things 1) Isn't there another Python Server Pages project out there, one that uses JPython? 2) Is this a pure interpreter, or are the pages turned into byte-compiled python .pyc files? 3) Any reason not to switch to the JSP <> based tag format? People, and more importantly web-page editors, are used to looking at <> based tags. Keep up the good work! -- cary
https://mail.python.org/pipermail/python-list/2000-September/029462.html
CC-MAIN-2014-15
refinedweb
197
60.92
From: Andy Little (andy_at_[hidden]) Date: 2006-08-24 06:24:18 "Matthias Troyer" <troyer_at_[hidden]> wrote in message news:0F6E6AED-1E91-4356-A72E-AFA684879045_at_itp.phys.ethz.ch... > > On Aug 23, 2006, at 8:40 PM, Andy Little wrote: > >> >> "Matthias Troyer" <troyer_at_[hidden]> wrote in message >> news:14AD1E01-8077-42A7-A25E-5B5AF8AB1EFA_at_itp.phys.ethz.ch... >> >>> I have a question here: what is the purpose of these named quantities >>> - is it to output J instead of kgm^2s^2 for energy and Nm instead >>> of kgm^2s^2 for torque? >> >> Basically yes. Way back someone requested that they be >> differentiated, so I >> differentiated them and hence (BTW) the notion of an anonymous >> quantity was born >> as a logical result of not being able to distinguish the two in >> some cases. >> >> After all torque is a vector quantity and energy is a scalar >> quantity, so they >> are quite different. >> One could output energy units as N.m , but the joule is the more >> well known SI >> energy unit, so it helps to put things in a familiar context. >> >> Also there are various non SI units which specifically mean >> torque, such as >> (reading from the SI manual) dyne centimeter, kilogram-force meter, >> etc. >> >> And for energy: erg per square centimeter second, watt per square >> inch etc.. > > OK, to be able to output specific unit symbols is a good thing. > >> >> >>> - is it to prevent adding energy and torque? >> >> am strictly against any disallowing of calculations. Just consider > the following pseudo code (I do not refer to any specific > implementation but hope the types are self-explanatory > > unit::force::N force; > unit::length::m distance; > > unit::energy::J energy; > unit::torque::Nm torque; > > energy = force*distance; // should this be allowed? > torque = force*distance; // should this be allowed? Quan allows this as it stands. > I think that in both cases the implicit conversion from the > (annonymous?) quantity force*distance to either energy or torque. I > think that to make the library usable one needs to allow these > conversions. The temporary result of force * distance is a so-called anonymous quantity. > If one want to prevent the operations then because one is a vector > scalar product (the energy) and the other a vector cross product (the > torque) then this should be done at the level of the value_type of > the quantity and not at the unit level. Yes the obvious way to make a quantity a vector quantity is simple. Put it as the value_type of a vector. Currently quan has 2D and 3D vectors in separate namespaces, but it was suggested that it would be more flexible to just have a quan::simple_vector<N_dimensions,quantity> and hopefully that will be implemented at some stage. regards Andy Little Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2006/08/109549.php
CC-MAIN-2021-43
refinedweb
473
64.1
In most cases, no matter what area of software development you are involved in, you will need a functionality of cloning your objects. The .NET Framework provides you three ways of achieving your object copying goal: ICloneable BinaryFormatter MemoryStream Sometimes, when you are working on a large project, a “stupid” deep copying would not be sufficient. Let’s say, in some cases, you need to include sub-objects, and in some of them, not. For example, let's consider these classes: public class Person { private List<Person> _friends = new List<Person>(); public string Firstname { get; set; } public string Lastname { get; set; } public List<Person> Friends { get { return _friends; } } public PersonManager Manager { get; set; } } public class PersonManager { private List<Person> _persons = new List<Person>(); public List<Person> Persons { get { return _persons; } } } In some cases, when copying a single Person, there is no need to copy the PersonManager too. In other cases, you would like to include the Person’s friends in the cloning, and again, in others, not. As you have already noticed, there are too many cases in this trivial example. In a real situation, they will be much more complicated. Person PersonManager I suggest a declarative way of defining the cloning logic. Consider the following modification to our Person class: public class Person { the Manager and Friends objects from cloning. However, when cloning with the “Friends” flavor ([Cloneable(CloneableState.Include, "Friends")]), copy the Person’s friends too. The usage of this machinery is quite easy. Example: Manager Friends [Cloneable(CloneableState.Include, "Friends")] ObjectCloner.Clone(person); ObjectCloner.Clone(person, "Friends"); So, the first statement in the previous sample copies only Firstname and Lastname. The second one performs deep copy and clones the person’s friends too. Here is the output of the demo application which is based on the sample described earlier. Here, you can see that both copies of “De Niro” have no manager defined, and when cloning with the “Friends” flavor, the machinery performs a deep copy by filling the person’s friends. The origin of this article can be found at C# Object Cloning Machinery. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
http://www.codeproject.com/Articles/34302/C-Object-Cloning-Machinery
CC-MAIN-2015-14
refinedweb
367
53.92
Code. Collaborate. Organize. No Limits. Try it Today. Phalanger is a PHP language compiler for Microsoft .NET platform. In the 1.0 version the primary goal was to be able to compile any existing PHP application, but in the 2.0 version of Phalanger, PHP became first-class .NET citizen. In this article I'd like to describe the most important and interesting features in the Phalanger project from .NET developers point of view. This means that I will focus a bit more on .NET, interoperability and possibilities to extend PHP applications using other .NET languages, than on the Phalanger support for running existing PHP applications. As I said earlier, the 1.0 version Phalanger was focused only on compiling existing PHP applications for .NET framework. The 2.0 version added the goal to allow interoperability between PHP and .NET world. This means that in 2.0 version it is possible to use most of the .NET objects right from the PHP code. To make this possible, Phalanger extends the PHP syntax in a few important ways (but it is still fully backwards compatible). The language extensions are called PHP/CLR. I will write about these later, but in a nutshell it allows you to use .NET features like generics and custom attributes from PHP and also to use C#-like compilation mode (in which application consists of classes instead of scripts). Phalanger became an open source project in 2.0 version and it was released under Microsoft Shared Source Permissive License (it allows commercial usage, modification, and redistribution, see the license for details). You can find more information about the project at Phalanger home page , which contains Phalanger wiki, articles and news or Phalanger home at CodePlex where you can find latest releases, source code, discussions and issue tracker. Phalanger is stable enough to be used in enterprise applications and Skilldrive company is using Phalanger. First I'd like to write about the possibility to run existing PHP applications on .NET Framework using Phalanger. The example of such web site is our web () which is based on an excellent wiki written in PHP called DokuWiki [^]. The list of applications that work well with Phalanger is still growing and currently contains for example PhpBB (Forum system), PhpMyAdmin (Admin for MySQL) and DokuWiki. If you want to configure existing application to use Phalanger, you need to follow the following simple steps: phpNet machine.config php .php C:\WINDOWS\Microsoft.Net\Framework\v2.0.50727\aspnet_isapi.dll web.config <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.web> <httpHandlers> <add verb="*" path="*.php" type="PHP.Core.PageFactory, PhpNetCore, Version=2.0.0.0, Culture=neutral, PublicKeyToken=0a8e8c4c76728c71" /> </httpHandlers> </system.web> </configuration> You can also configure this globally for the entire server by adding add element to the root ASP.NET web.config located in C:\WINDOWS\Microsoft.Net\Framework\v2.0.50727\CONFIG directory. add C:\WINDOWS\Microsoft.Net\Framework\v2.0.50727\CONFIG To make Phalanger as compatible with standard PHP implementation as possible, we provide way for using native PHP4 extensions. Most of the popular PHP extensions like pdf, image or calendar are available in Phalanger thanks to this mechanism. Internally, this part of Phalanger is written in (unsafe) C++/CLI and it is available only on Windows platform. The native extensions can be loaded in separate process, which is secure, because failure of native extension doesn't affect the rest of application, but it is also slower. The second option is to load native extension in the same process which isn't secure, but is faster. pdf image calendar Let's start with very simple example that prints names of months in gregorian calendar. It uses function cal_info that returns information about calendar. This function is part of the calendar extension: cal_info <ol> <?php $nf = cal_info(CAL_GREGORIAN); foreach($nf["months"] as $m) echo "<li>$m</li>"; ?> </ol> As you can see, nothing special appeared in the PHP source code. To tell Phalanger what native extensions you want to use, you must include it in the classLibrary section of the configuration file: classLibrary <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.web> <!--<span class="code-comment"> http handler as in perevious sample --></span> </system.web> <phpNet> <classLibrary> <add assembly="php_calendar.mng, Version=2.0.0.0, Culture=neutral, PublicKeyToken=4ef6ed87c53048a3" section="calendar" /> </classLibrary> </phpNet> </configuration> Also please note, that you need to install the managed wrapper to the GAC. Managed wrapper is library that contains interface used by Phalanger for calling the extension. Phalanger installer does this automatically, but if you want to do it manually, you can find managed wrappers in the Wrappers directory. The names of the wrapper for calendar extension is php_calendar.mng.dll. Wrappers php_calendar.mng.dll Thanks to the Phalanger project you can use PHP as a language for developing almost ANY .NET project. You can also add code that uses .NET to existing PHP application (which uses the PHP scripting model), but this will be discussed later (section 5.1). Why would you want to use PHP? There are a few very important reasons - first, there is a lot of existing PHP code, which works very well and doesn't have equivalent in the .NET world, also many people who know PHP might want to experiment with .NET, but don't want to learn another language or just prefer PHP. PHP itself is a dynamic language, which means that it can be very simple and it is easier to solve some tasks in it. You can also use it very well to combine together more components written in another languages, because dynamic languages serve this purpose very well. My favorite example which shows the power of PHP language is working with XML using SimpleXML extension: <?php // load the RSS feed $xml = simplexml_load_file (" nyt/HomePage.xml"); // print the contents of 'title' element echo $xml->rss->channel->title."\n"; // print latest posts echo "Latest posts:\n"; foreach($xml->rss->channel->xpath("item") as $item) { echo " - ".$item->title."\n"; } ?> I think that the code is very self-explanatory. The dynamic language "trick" here is using standard member notation (-> operator in PHP) for accessing to the child elements like $xml->rss->channel->title when reading the name of RSS feed. You don't have to define any structure of the XML document and the code is very straightforward. The introduction was a bit longer, but I wanted to show why PHP as a language is interesting and why it is valuable addition to the family of .NET languages. -> $xml->rss->channel->title As a first-class .NET language, you can also create PHP applications in Visual Studio. The Phalanger extensions are not part of the core Phalanger installer, so you'll need to download it separately. Due to the Visual Studio limitations, it is not possible to use Phalanger extensions with the VS Express versions. The following overview describes what projects you can develop using Phalanger in Visual Studio: aspx Thanks to the great .NET support debugging it is also possible to debug PHP applications (running on Phalanger) in the Visual Studio (as you can see on the screenshot). During the debugging you can also use watches and locals, but because of the dynamic nature of the PHP language, you may need to search for the variable value in the hashtable, where the value is often stored. The Visual Studio support is still in early phase of development and we're still working on improving the editing and debugging experience. In standard PHP the scripts are executed sequentially. This means that application execution starts with one main script, the global code in this file is run line by line and eventually other scripts can be included using include or require directives. If you want to use this logic with Phalanger you can use legacy compilation mode (it is the default mode). In the legacy mode, scripts contain global code and if you want to use classes or functions declared in another script, you have to include it first. This mode is fully compatible with standard PHP interpreter, so you'll be able to run the application using both Phalanger and PHP. include require On the other side, the pure mode is more similar to the logic known from C#. In this mode scripts are merged together during compilation (and no inclusions are allowed) and every script can contain only top-level declarations of classes and functions. The entry point is static function called Main in the selected main class. The pure mode is very interesting for .NET developers, because it allows you to use PHP language for example with ASP.NET 2.0 which depends on this object model. The standard PHP interpreter doesn't have equivalent to this mode. Main Let's look at the PHP language extensions called PHP/CLR that allows you to use .NET objects in Phalanger. Note that these extensions can be used in both legacy and pure mode, which means that you can use .NET objects from existing PHP application as you'll see later. Since all .NET libraries are ogranized in the structure of namespaces you have to be able to use namespaces in PHP when you want to use .NET libraries. Namespaces that are available in Phalanger are based on the PHP 6 proposal and it allows you to organize your PHP code into namespaces as well as use existing CLR namespaces. In PHP 6 proposal, the operator used for accessing namespace is :::, so instead of System.Web you have to use System:::Web. We used this syntax, because Phalanger needs to know whether you mean class or namespace (unlike in C#, where this can be checked during the compilation). The following sample shows how you can use simple Random class from the System namespace in PHP: ::: System.Web System:::Web Random System <?php $rnd = new System:::Random; echoNext(10); ?> You can also use the import namespace statement to make the code simpler and cleaner: <?php import namespace System; $rnd = new Random; echoNext(10); ?> Now you know how to use classes from existing namespaces (and you can even use CLR classes from CLR namespaces!). To run this example you'll need to add following to the application config file: <?xml version="1.0" encoding="utf-8"?> <configuration><phpNet> <compiler> <set name="LanguageFeatures"> <add value="PhpClr" /> </set> </compiler> <classLibrary> <add assembly="mscorlib" /> <add assembly="System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> </classLibrary> </phpNet></configuration> This tells Phalanger two things - first that you want to enable PHP/CLR language extensions (that include namespaces etc.) and second - that you're using CLR classes and you want to reference specified .NET assemblies. To build this application you can create new Legacy Console Application (from Phalanger project templates) - note that we used legacy application, which means that it is possible to use global code in the script file. Second option for building is to use the following command from Phalanger command line (this will also produce console application): phpc /lang:CLR program.php Next useful extension to the standard PHP syntax allows you to write identifiers that conflict with PHP keywords. This is similar to the @something syntax in C#. We had to make this possible, because some important classes from the .NET Framework (for example generic List) have names that collide with PHP keywords. For example if you have a function called function (which is an acceptable name for the C# compiler) you can call it using following syntax in Phalanger: @something List function <?php // Calls function called 'function' i'function'("Hello world!"); ?> In the paragraph I mentioned that you can use generic classes like List from the .NET Framework. The main reason for introducing generics in Phalanger is the ability to specify types when using .NET generic classes, but generic types may be useful for PHP developers as well - for example you can use generic collection and restrict the type that can be inserted to the collection (however this is checked at runtime as you would expect from a dynamic language). The Phalanger also allows you to write your own generic classes or functions and adds some possibilities that are unique to PHP. First simple example will show how you can use Dictionary class from .NET: Dictionary <?php import namespace System:::Collections:::Generic; // Add values to dictionary $d = new Dictionary<:string,string:>; $d->Add("cz", "Ahoj svete!"); $d->Add("en", "Hello world!"); $d->Add("fr", "Salut le Monde!"); $d->Add("de", "Hallo Welt!"); // OK - Implicit int to string conversion $d->Add(0, "Something less evil!"); // Invalid - can't add instance of Random as a key // $d->Add(new System:::Random, "Something more evil!"); // Read value $out = ""; if ($d->TryGetValue("cz",$out)) echo $out; ?> There is also one interesting thing to note - because we want to keep dynamic nature of the PHP language, we also allow specifying the generic type parameter using variable, so for example if you have variable $t containing "string" you can create new instance of Dictionary using the following expression: new Dictionary<:$t, $t:>; $t "string" new Dictionary<:$t, $t:>; As you expect, you can also declare new generic class that takes generic parameters in PHP using PHP/CLR extension. Because PHP doesn't require as strict type checking as for example C#, you can use default values to specify the default type that will be used if the type is not specified when calling the function or instantiating the class. The following code shows some examples: // Inherited dictionary class PhpDict extends Dictionary { /* ... */ } // Inherited list with default type parameter class PhpListobject extends i’List’ { /* ... */ } // Function with one type parameter function PhpFunc { /* ... */ } Another very important concept in .NET that doesn't have good equivalent in PHP language are attributes that you can use to annotate source code and to add some additional information to your classes, methods, etc. Attributes are used for many important scenarios - for example if you are creating web service you use WebServiceAttribute to anotate the class and WebMethodAttribute to annotate all methods that you want to expose. WebServiceAttribute WebMethodAttribute The support for attributes is currently a bit limited (if you want to write web services in PHP you'll have to wait for the next build), so I will use simpler example to demonstrate using attributes with PHP. In the example I will use DescriptionAttribute for adding comment (that can be accessed at run-time) to the PHP function: DescriptionAttribute <?php import namespace System:::ComponentModel; [Description("Description for the function foo")] function foo($a) { echo $a; } ?> As you can see, the syntax is the same as in C#. We are also planning to support named parameters with C#-like syntax, but as I mentioned this is still under development (If you are considering using Phalanger and need to use this feature, let us know so we can focus on what users need!). We also introduced two pseudo-attributes that are treated differently by the compiler - you can use them to instruct compiler, how the generated code should look like. The first attribute is [AppStatic] that instructs compiler to compile field as a static field shared across the whole application (note that other static fields in PHP are shared only per-request, which corresponds to the thread-static fields in C#). The [Export] attribute controls the structure of compiled class to make it accessible from other .NET languages like C#. I will talk about this attribute later. The following example shows usage of [AppStatic] attribute. If you put the following code in script handled by Phalanger as a web application it will count requests (until the application is restarted by IIS): [AppStatic] [Export] <? class Counter { [AppStatic] public static $N; } // display and increment counter value echo Counter::$N; Counter::$N++; ?> There are also a few other extension that we will not discuss in detail, so I will write just a short overview of these features availble in PHP/CLR. We added support for partial classes (this makes sense only in pure mode), because this is important to allow working with ASP.NET and other technologies that generate part of the source code in .NET 2.0. We're also working on adding properties (with getter and setter method), because this is useful when inheriting from CLR class. Currently you can override inherited property only by creating class member (which is PHP equivalent to the .NET field) with the same name. And finally, we also announced that we are working on supporting the LINQ project [^] as part of PHP/CLR to make data access in PHP even easier. You already seen a few examples that demonstrated working with .NET objects in PHP. The most of the previous examples (you can get the full versions in attached zip file) used legacy compilation mode, which is just easier to use for simpler tasks. As you can see from the previous examples you can "inject" code that uses .NET CLR objects to any PHP application including complex PHP applications, because it doesn't matter whether you use legacy mode (PHP compatible) or pure mode (only in Phalanger). Thanks to this possibility you can for example use your data access layer written in C# from PHP application that presents the content to the user! Let's look at the sample application (the full source code is one of the attached demos) that uses layered architecture and has data access layer/business logic written in C# and presentation layer written in PHP. The application is very simple and it uses products and categories from the SQL Server Northwind database. The data layer contains classes that represent product and category with several properties and class Data that is used for reading data from database. The structure of the classes is following: Data The Data class contains public methods for returning all categories (GetCategories), category specified by its ID (GetCategory), all products in category (GetProducts) and one product by its id (GetProduct). All data access methods return generic List with type parameter set to Product or Category. For example, the method for reading categories looks like this: GetCategories GetCategory GetProducts GetProduct Product Category // Returns all categories public List<Category> GetCategories() { List<Category> ret = new List<Category>(); using(SqlConnection cn = new SqlConnection(connStr)) { // Select all categories from database cn.Open(); SqlCommand cmd = new SqlCommand ("SELECT [CategoryID], [CategoryName] FROM [Categories]", cn); using (SqlDataReader reader = cmd.ExecuteReader()) { // Add all categories to the list while (reader.Read()) { ret.Add(new Category((int)reader["CategoryID"], (string)reader["CategoryName"], GetTheme( (int)reader["CategoryID"]))); } } } return ret; } Now that we have data-access layer we can look how to use it from PHP. First you need to create Visual Studio project (however you can just create directory mapped in IIS and put all your files in it) - in the menu select File - New Project and then in the Phalanger category select PHP Web Application. Probably the most difficult part is to configure Phalanger correctly. You already saw how to configure HTTP handler in web.config, how to enable PHP/CLR language extensions and how to add reference to assembly that you want to use in PHP code, so you know everything to do this correctly. The web.config file looks like this: web.config <?xml version="1.0"?> <configuration> <!--<span class="code-comment"> configure ASP.NET --></span> <system.web> <httpHandlers> <add verb="*" path="*.php" type="PHP.Core .PageFactory, PhpNetCore, Version=2.0.0.0, Culture=neutral, PublicKeyToken= 0a8e8c4c76728c71" /> </httpHandlers> </system.web> <!--<span class="code-comment"> configure Phalanger --></span> <phpNet> <compiler> <set name="LanguageFeatures"> <add value="PhpClr" /> </set> </compiler> <classLibrary> <add assembly="mscorlib" /> <add assembly="DemoDataLayer" /> </classLibrary> </phpNet> </configuration> You can see that in the classLibrary section of the config file we reference mscorlib assembly (that contains basic .NET classes) and DemoDataLayer assembly which is the assembly containing C# code that I described earlier. This assembly must be placed in the bin directory of the web application, so Phalanger can reference it or it can be signed using strong name key and placed in the GAC (in this case you'll have to include full assembly name in config file). mscorlib DemoDataLayer bin Now we can write PHP script that will display the list of categories on the project home page: <? // load data layer import namespace DemoDataLayer; $dl = newGetCategories(); ?> <html><body> <h1>Categories</h1> <ul> <? // Write link to detail for every category foreach($categories as $c) { ?> <li><a href="products.php?id=<? echo $c-> ID ?>"><? echo $c->Name ?></a>< /li> <? } ?> </ul> </body></html> The first line contains import namespace directive that makes it possible to use classes from data access layer without specifying the full namespace every time, after that the instance of Data class from the data access layer is created and the list of all categories is populated from the database using the GetCategories method and stored in $categories variable. Later when we need to print all the categories we can use standard PHP foreach construct to enumerate over all items in the returned list. As you would expect, you can read all properties declared in C# using the PHP syntax, so if you want to print the name of the category you can simply write echo $c->Name. import namespace $categories foreach echo $c->Name The source code of more complete example can be found in the attached demos. Combining data access layer written in C# with presentation layer in PHP is very powerful, because it gives you the safety of C# where you need it and the simplicity and flexibility of PHP where you can benefit from it. In the introduction I wrote about the differences between legacy and pure mode. If you want to use existing PHP source (developed for standard interpreter) without modifications you have to use legacy mode, but when you want to develop new PHP project you can consider using pure mode. The pure mode is required if you are developing application based on ASP.NET 2.0 and it is recommended for developing Windows Forms applications too. It also gives you a possibility to make objects written in PHP available to other .NET languages, because you can instruct compiler to generate overloads that can be easily used from C#. I will start with an example that shows how to write object accessible from C#. When compiling PHP objects, the class generated by Phalanger doesn't contain methods with arguments that you would expect - the reason for this is that PHP is dynamic language and there is internally quite complex mechanism for method invocation. For example if you compile class called Test with method Foo($arg), the signature of method produced by Phalanger is following (Phalanger even generates two different methods!): Test Foo($arg) // First generated overload public virtual object Foo(ScriptContext ctx); // Second (static) method public static object Foo(object instance, PhpStack stack); I didn't want to scare you with the previous example, I just wanted to explain why calling PHP objects from C# wouldn't be as simple as it might look if we didn't implement special option to makes it easy! This option is called [Export] attribute and you can use it for telling Phalanger that you want to use class from another .NET language. The following sample shows class written in PHP that uses PHP possibility to create instance of object or invoke method by its name - it is called indirect method access in PHP. For example if you have object stored in variable $obj and method name stored in variable $method, you can call method by name using $obj->$method(). In C# you have to use reflection to implement this. The class (I'll call it DynamicObject) has constructor that takes name of the type to create and method Call that invokes member method of the object: $obj $method $obj->$method() DynamicObject Call <? namespace PhpClassLib { // Export tells compiler to generate methods that // can be used from other .NET languages [Export] class DynamicObject { var $obj; // Creates object by class name function __construct($obj) { $this->obj = new $obj; } // Dynamically calls method function Call($name) { return $this->obj->$name(); } } } ?> After compiling the code (either using Visual Studio and creating new Phalanger Class Library or using command line phpc /target:dll /pure PhpClassLib.cs) you can reference the compiled dll from C# project. If you open the library in object browser you'll see that Phalanger added also following methods (in C# syntax): phpc /target:dll /pure PhpClassLib.cs // Constructor public DynamicObject(object obj); // Call method public object Call(object name); It is obvious that in language with no static typing, the arguments and return types of the functions must be the object type. The following example shows how you can use the class written in PHP from C# project to dynamically create instance of Random class and call its Next() method: object // Note that the name passed to the object uses PHP namespace notation DynamicObject obj = new DynamicObject("System:::Random"); int n = (int)obj.Call("Next"); Console.WriteLine("Returned = {0}", n); And you didn't have to use any class from the System.Reflection namespace! This is only one of many interesting uses of the [Export] functionality. You could also use it if you want to use some functionality implemented in one of large number great PHP open source projects. The source code of the project needs to by modified a little (to make sure that it doesn't depend on inclusions and it doesn't contain any global code and then it is ready to be compiled into .NET assembly using pure Phalanger compilation mode and you can use it from any .NET language. System.Reflection You can also use Phalanger to develop Windows Forms applications. WinForms are interesting topic because it requires creating event handlers. Our implementation of event handlers doesn't require any modifications to the language, but it is significant part of allowing PHP to interoperate with .NET classes. Many people write Web Applications in PHP, but what about writing Web Browser? It isn't that difficult, but I'll start with typical "Hello world!" example. You can find the web browser sample in attached demos (yes, it is based on IE ActiveX control and no, it doesn't support tabbed browsing currently ). I made the sample as simple as possible, so I put the Main static function (the entrypoint) inside the MainForm class, which represents the window. The class contains constructor which creates controls using the powerful CreateCtrl function (I will talk about it later) and it also contains btnClicked function that is used for handling Click event of the button. MainForm CreateCtrl btnClicked Click <? import namespace System; import namespace System:::Drawing; import namespace System:::Windows:::Forms; class MainForm extends System:::Windows:::Forms:::Form { function __construct() { // Form properties $this->ClientSize = new Size(400, 400); $this->Text = 'PHP Hello world!'; // Create button $btn = CreateCtrl("Button", array( "Left" => 10, "Top" => 10, "Width" => 380, "Height" => 380, "Text" => "Click me!"Add($btn); // Set event handler $btn->Click->Add (new EventHandler(array($this, "btnClicked"))); } // Show message box when button is clicked function btnClicked() { MessageBox::Show("Hello world!"); } // Entry-point function static function Main() { // Enable XP visual styles and start with MainForm Application::EnableVisualStyles(); Application::Run(new MainForm()); } } ?> In the previous code we used the CreateCtrl function, which I consider as very interesting! It is a function that can't be written in statically typed languages that easily. It accepts name of the control you want to create and associative array of names and values that you want to assign to the property with specified name. It is not a part of standard library, so you have to write it yourself. It uses indirect access to the properties that I mentioned earlier - this means that if we need to set Text property of an object $ctrl and we have variable $name that contains string "Text" we can also write $ctrl->$name = "Something" (the syntax for direct access is $ctrl->Text = "Something". The complete function looks like this: Text $ctrl $name "Text" $ctrl->$name = "Something" $ctrl->Text = "Something" // Helper WinForms function function CreateCtrl($name, $props) { // Create instance of control with specified name $ctl = new $name; // Set all control properties foreach(array_keys($props) as$prop = $props[$prop]; return $ctl; } You may be wondering how this works internally when it is compiled as .NET assembly. The invocation itself doesn't use Reflection which makes it very efficient. It consumes some CPU when first indirect call is used, to generate some internal data structures, but later it works very well. This would be probably a topic for another article, so I won't describe the details here. Now I'd like to show how you can use PHP as a language for developing ASP.NET 2.0 application. You can also visit our web site and download well known application - Personal Web Site StarterKit ported to PHP (See our releases page [^]). By ASP.NET 2.0 application I mean an application that is based on the ASP.NET 2.0 object model that you can use with C# or VB.NET including code-behind, ASP.NET controls, master pages, themes etc. This is useful if you want to use ASP.NET object model, but you prefer PHP as a language for some reason - for example you have big experiences with PHP or you want to use some code written in PHP that you already have. To create new ASP.NET 2.0 Phalanger application, select File - New - Web Site in Visual Studio, in the languages box select PHP and then choose "ASP.NET Web Site". The template contains two files - Default.aspx which contains ASP.NET markup and Default.aspx.php which contains code-behind class. Let's look at the following example: Default.aspx Default.aspx.php <%@ Page Language="PHP" CodeFile="Default.aspx.php" Inherits="DefaultPage" %> <html><head runat="server"> <title>Phalanger ASP.NET Demo</title> </head><body> <form id="form" runat="server"> <!--<span class="code-comment"> Demonstrates inline PHP code (use standard ASP.NET <% .. %> --></span> <% // Prints header with random color srand((double)microtime()*1000000); $colors = array("#800000", "#008000", "#000080", "#606000", "#600060", "#006060"); echo "<h1 style=\"color:".$colors[rand(0,6)]. "\">Phalanger ASP.NET Demo</h1>"; %> <!--<span class="code-comment"> Some ASP.NET controls --></span> Enter your name: <asp:TextBox <asp:Button<br /> <h2><asp:Label</h2> </form> </body></html> This source shows the default.aspx file. It contains standard ASP.NET @Page directive with the Language attribute set to PHP, you can also see some standard ASP.NET controls like <head runat="server" />, form, Button, Label and TextBox. The source also shows that you can use PHP as a language for the in-line code (as you can use C# or VB.NET), however you have to use ASP.NET style tags for embedding the code, because the whole page is processed by ASP.NET and Phalanger is used only for compilation. default.aspx @Page Language PHP <head runat="server" /> Even though you have to use ASP.NET style tags, you can use any PHP functions, because Phalanger implementation is built on top of ASP.NET framework, so most of the function will integrate well with ASP.NET. If you're using ASP.NET Phalanger compiles the source code in pure mode which means that you can't use include, but other functions work well inside in-line code. This is interesting feature if you want to copy some functionality from an existing PHP application. Let's look at the code-behind class now: <? import namespace System; // Partial code-behind class partial class DefaultPage extends System::Web::UI::Page { // Called when user clicks on the button function btnOk_Click($sender,$e) { // lblOutput and txtName are declared in // second part of partial class $this->lblOutput->Text = "Hello ".$this->txtName->Text."!"; } } ?> As you can see, we need to use partial class here, because ASP.NET generates the second part of the class automatically. The second part of the class contains class members/fields (like lblOutput) for every server control on the page which makes it possible to access them in code-behind. For more examples of using PHP with ASP.NET look at the Personal Web Site StarterKit mentioned earlier. partial lblOutput The Phalanger version 2.0 supports the Mono platform (in the first version it was impossible, because part of Phalanger was written in Managed C++). The biggest limitation is, that you can't use native extensions, which are supported only on Windows. There are a few more issues under Mono, but we're working on resolving these. Mono allows many interesting scenarios - you can use Phalanger with Apache web server and mod-mono extension that allows you to run PHP web applications powered by Phalanger, or you can use PHP for developing portable Mono applications. You can also use any Mono library from Phalanger, so you can for example develop GUI application using the Gtk# library. Because Phalanger compiles PHP applications to the CLR the execution of applications is faster when compared to standard PHP interpreter. The efficiency relies on the Phalanger runtime and the CLR itself. Because several features that allow better compilation of dynamic languages were added in the 2.0 version, the Phalanger 2.0 is faster than the 1.0 version. We tried two kinds of performance tests - the micro-benchmarks show how fast is the execution of the most important elementary operations (like calling a function, calling function by name, array access, etc.) on Phalanger and PHP interpreter. The results are very good - from the 25 tests in total, Phalanger is faster in 19 tests and the difference in the 6 remaining tests is very small. The second test compares performance of the PhpBB forum application running on PHP and Phalanger. The results show that Phalanger was able to serve almost two times more pages per second! The Phalanger project started at the beginning of the year 2003 as a student project code-named PHP.NET at Faculty of Mathematics and Physics [^], Charles University in Prague [^], Czech Republic. The members of the project during the development of first version were Tomas Matousek [^], Ladislav Prosek, Vaclav Novak, Pavel Novak, [^], Jan Benda [^], and Martin Maly [^]. The aim of the project was to find out whether the compilation of dynamic languages (particularly the PHP language) is possible on .NET Framework and whether it could result to any performance improvements when confronted with the interpreter and various acceleration tools. After successful defense, the members of the project team continued to contribute to Phalanger on volunteer basis for more then a year. The goal was to provide a functional compiler and runtime compatible with PHP versions 4 and 5 and the final version 1.0 was released in February 2006. In March 2006, Tomas Matousek and Ladislav Prosek started to design and implement the 2nd version of Phalanger. Based on their presentations of Phalanger at the Compiler Lab in Redmond, they received a generous support from Microsoft Corporation. The version 2.0 is based on the previous one, however, some parts were completely redesigned and rewritten and it introduced the new PHP/CLR language extensions. In October 2006 Tomas and Ladislav moved to Redmond and started working at Microsoft in the CLR team and Tomas Petricek become the new project leader and started working with the new development team on completing the 2.0 release as well as publishing more articles about the Phal.
http://www.codeproject.com/Articles/17311/Phalanger-PHP-for-NET-Introduction-for-NET-develop?fid=379092&df=90&mpp=25&sort=Position&spc=Relaxed&tid=2047719
CC-MAIN-2014-23
refinedweb
5,891
53.92
Hide Forgot I had earlier reported problems seeing my CDROM drive when it has SCSI ID 0 (see bug 25997). Since then, I've been testing with the Rawhide kernel (2.4.0-0.99.23) which has been overall working just fine. However, I noticed that I can no longer mount my SCSI zip drive (/dev/sda4). This is the only SCSI "hard drive" I have. I also have a tape drive and CD-ROM drive. I can mount /dev/sda4 fine under the default Fisher kernel and under RedHat 6.2, but not under 2.4.0-0.99.23. Interestingly, /proc/scsi/scsi and the boot process both see the zip drive, and fdisk -l /dev/sda shows the sda4 partition. Attempting to mount says that /dev/sda4 is an invalid block device. My SCSI controller is an on-board AIC 7890. I have an ASUS P2B-LS motherboard with this chip on-board. The board's BIOS revision is 1012. From /etc/sysconfig/hwconf: class: SCSI bus: PCI detached: 0 driver: aic7xxx desc: "Adaptec|AHA-2940U2/W / 7890" vendorId: 9005 deviceId: 001f subVendorId: 9005 subDeviceId: 000f pciType: 1 I know there are issues with new beta AIC7xxx drivers. Do I need to be concerned about this? For now, I've gone back to the default Fisher kernel recompiled with apm changes (from bug 26261) and everything works fine. (My CD-ROM drive is no longer on ID 0.) There are no siginificant differences between dmesg output with these two kernels. (ACPI messages are not present in 0.99.23 since ACPI is turned off, and the CPU speed differs by a few thousands...) If I'm reading my logs right, you have the choice of the aic7xxx and aic7xxx_old drivers. Try the aic7xxx_old driver and see if it works. In our current source tree, we have the original aic7xxx as the aic7xxx driver, the new one as aic7xxx_new, and the original one has a few bug fixes. So when we come out with a new kernel package, please do test it and make sure that it fixes the problem. We (Red Hat) should really try to resolve this before next release. I have a little more information. My original report was slightly inaccurate. The actual situation is that you can't mount the zip drive if no disk was inserted during the boot process. The same modules are present in both cases and fdisk -l /dev/sda works in both cases, but if no disk was inserted while the system booted, you get an error that /dev/sda4 is not a valid block device. This problem occurs with both the stock Fisher kernel and the Rawhide kernel. It does not happen with an unpatched 2.4.1 kernel which seems to use a different aic7xxx driver from RedHat's kernel. Unloading and reloading the aic7xxx and sd_mod modules didn't help. OK, please try it with the 2.4.1-0.1.9 or later kernel when it gets to rawhide -- that should be in sync with the latest -ac releases in terms of what aic7xxx driver it is using. Thanks. I'd like to try with that kernel. Is there a way I can know when it is available other than continually checking rawhide? I'm also waiting for the new kernel to do some iptables testing. I'm sorry to say that this bug has NOT been fixed in Wolverine. Rawhide has a more recent kernel. Is this a regression relative to the 2.2 kernel? I know that some people find that the boot hangs if they do not have a disk inserted, and we're trying to fix that, but I'm not sure it's related. You could try echo "scsi add-single-device C B T U > /proc/scsi/scsi" where C is controller number, B is bus number, T is target (your zip disk) SCSI id, and U is your target lun (probably 0) to see if that helps. Alan reports known regressions regarding removeable devices fixed in the source code we are building for the next rawhide. 2.4.2-0.1.16 or later will have his known regressions fixed and be worth testing when it appears in rawhide. echo "scsi add-single-device 0 0 6 0" > /proc/scsi/scsi didn't work, but I'm not surprised since /proc/scsi/scsi already showed the zip drive and fdisk -l /dev/sda already worked. However, this made me think of something else which actually did work. After running the following C code: #include <sys/types.h> #include <linux/fs.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> int main() { int fd = open("/dev/sda", O_RDWR); if (fd == -1) { fprintf(stderr, "open device: %s\n", strerror(errno)); exit(2); } if (ioctl(fd, BLKRRPART, 0) == -1) { fprintf(stderr, "ioctl BLKRRPART: %s\n", strerror(errno)); exit(2); } return 0; } to force the system to reread the partition table (or running fdisk /dev/sda and hitting "w"), it was possible to mount /dev/sda4. I guess the kernel tries (unsuccessfully) to read the partion table at boot time and then forgets to reread it later when things change. Another piece of evidence that supports this is that if you eject this disk and insert another with a different partition table, you can't mount partitions on the new disk that didn't exist on the old disk until after you run the above program. It would be unsurprising if the removable device fixes will be in the kernel you mentioned since it looks from a casual perusal of the ac patches that 2.4.2-ac4 has code that rechecks the partition table of removable disks after it notices that they have been changed.... Anyway, I'll retest when a new kernel makes it to rawhide (and I notice it or see something about it here or on the wolverine list). Arjan, can you please double-check that those fixes went into 2.4.2-0.1.16? If not, please put them in place for the next build. Thanks! I can't reproduce this using the aic7xxx driver from kernel-2.4.2-0.1.19. Everything mis seen and works fine on bootup. This is with an 2930U2 controller. Tim Could you retry using the 2.4.2-0.1.19 kernel in rawhide and see if this problem still exists? This problem is fixed in the 2.4.2-0.1.19 kernel. "This problem is fixed in the 2.4.2-0.1.19 kernel." -> Closing as fixed in rawhide.
https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=27627
CC-MAIN-2019-39
refinedweb
1,112
74.08
This video tutorial explains the role of Loops in Python, their types: For, While, Nested Loops with syntax and practical programming examples: We learned about the four different Conditional statements in Python in our previous tutorial. Loops are powerful programming concepts supported by almost all modern programming languages. It allows a program to implement iterations, which basically means executing the same block of code two or more times. Though they are supported by all modern programming languages and provide similar basic functionality, their implementations and syntax may differ. The Full Training Series on Python will give you a brief idea of what Python is all about. What You Will Learn: - Python Loops Video Tutorial - What Are Python Loops - For Loop In Python - The While Loop - Nested Loop - Python Infinite Loops - Conclusion Python Loops Video Tutorial What Are Python Loops In Python, statements are executed in a sequential manner i.e. if our code is made up of several lines of code, then execution will start at the first line, followed by the second, and so on. However, there will be cases where we may want a block of code to execute several times until a condition is met. Thanks to loop statements, we can do just that. Given below is a flowchart that illustrates how a loop statement works. Based on the above diagram, a Python program will start at Start[circle], and the execution will proceed to the condition statement[Diamond], if the condition is TRUE, then the program will execute the code block. Execution will proceed again to the condition statement and the same process continues each time when the condition is TRUE. It only breaks out of the loop or stops executing the code block if the condition is FALSE, and in this case, the program will continue execution sequentially. Python has two types of Loops. These two types of loops can be used inside each other to generate nested loops(more on this later). General Use Of Python Loops In Python, loops can be used to solve awesome and complex problems. You will likely encounter problems that would require you to repeat an action until a condition is met(while loop works best here) or a problem that requires you to perform an action on a bunch of items(for loop works best here). For Loop In Python The for loop works well with iterable objects like lists, tuples, strings, etc. This way, we can step through these object’s items and manipulate their values based on our linking. The for loop is zero-indexed and has the following syntax. for in n: The condition in the for loop stays TRUE only if it hasn’t iterated through all the items in the iterable object(n). To better understand the for loop, we will address several examples and finally, we shall work on a practical example. Example 1: Print Numbers ranging from Start to End To achieve this, we will use the Python range function. This is how the flowchart will look like: def range_from_start_to_end(start, end): for i in range(start, end+1): print(i) if __name__ == "__main__": start = int(input("Enter a start number: ")) end = int(input("Enter an end number: ")) # Call our function to print the ranges range_from_1_to_20(start, end) Output In the above example, we used Python range, which is a function that returns a sequence of numbers, starting from a start number(0 by default), increments by a step(1 by default), and stops before an end number. For this example, we have the following: Parameters and Values for the Python range function So, our for loop will iterate through a sequence of numbers from 1 to 20, and for each iteration, it will print the number. The iteration stops when all the numbers in the sequence have been visited. Example 2: Determine if a number is a prime number. In this example, we will see why the for loop is so powerful and useful. Here, we will iterate through a sequence of numbers, and for each number, we will perform some computation to determine if a condition is TRUE or FALSE. It may help to know the conditions for a number to be prime. - The number is always positive, greater than 1. - Has no positive divisors other than 1 and itself. def isPrime(number): # rule 1: number should be positive, and greater than 1. if number > 1: # iterate over a range from 2 to half the number. for i in range(2, number//2): # rule 2: shouldn't have any positive divisor # order than 1 and itself. if(number % i) ==0: return False return True else: return False if __name__ == '__main__': number = int(input("Enter number to check if it's prime: ")) if isPrime(number): print("{} is a prime number".format(number)) else: print("{} is not a prime number".format(number)) Output when input is 13 Output when input is 10 Note: The if-else used in the above example is a conditional statement and not a loop. But just like the while loop(which we will cover soon), it uses the comparison operators for its condition. Example – Find Word Count In A Text Using The for Loop This example is all about counting how many times each word occurs in a text. There are so many ways in which this can be achieved but for this example, we shall use the for loop. We shall be counting the words from the text below. Hello, welcome to Software Testing Help. In this article:”Loops in Python”, you’ll learn about loops with practical examples. Great right? Make sure to follow along as we learn together. Happy coding! The first thing we shall do is to remove punctuations, whitespace, and all lowercase letters. We shall remove punctuation in the traditional way by identifying which punctuations exist in our text, and then use the for loop to replace them with an empty string. As the text is not much, we see that the punctuations are commas(,), period(.), question mark(?) , colon(:), double quotation mark(“) and apostrophe(‘). Given below is the code to replace them with an empty string. Note that we will not replace apostrophe. # replace punctuation(except apostrophe) and white spaces for punc in '.,\n?!"': text = text.replace(punc, '') # lowercase all letters. text = text.lower() Output Next, we shall split the text into a list of words separated by whitespace. # Split text into list of words separated by whitespaces(tab, newline) text = text.split() Output Finally, we will count and see how many times each word occurs in the splitted text. # initialize a dictionary to hold words:count wordsCount = {} # if a word is already a key in our dictionary, increment it's value. # If not, initialize it's value to 1. for word in text: wordsCount[word] = wordsCount.get(word, 0) + 1 Output We can clearly see some words to appear twice, and some only once. Let’s sort this dictionary by its value in descending order so that we can clearly differentiate. Here, we have used the Python sorted function, lambda expression, and dictionary comprehension. # Sort dictionary by value, in descending order wordsCount = {w: c for w, c in sorted(wordsCount.items(), key=lambda item: item[1], reverse=True)} Finally, we have used the for loop to clean, count, and sort the words in our text. Given below is the complete code. def word_count(text): # initialize a dictionary to hold words:count wordsCount = {} # replace punctuation(except apostrophe) and white spaces for punc in '.,\n?!"': text = text.replace(punc, '') # lowercase all letters. text = text.lower() # Split text into list of words separated by whitespaces(tab, newline) and apostrophe(') text = text.split() # if a word is already a key in our dictionary, increment it's value. # If not, initialize it's value to 1. for word in text: wordsCount[word] = wordsCount.get(word, 0) + 1 # Sort dictionary by value, in descending order wordsCount = {w: c for w, c in sorted(wordsCount.items(), key=lambda item: item[1], reverse=True)} print(wordsCount) if __name__ == '__main__': text = "Hello, welcome to Software Testing Help. In this article: \"Loops in Python\", \ you'll learn about loops with practical examples. \ Great right? Make sure to follow along as we learn together. \n \ Happy coding!" word_count(text) Final Output The While Loop The Python while loop executes a block of statements repeatedly as long as the condition is TRUE. We notice that it is a bit similar to the if statement. However, unlike the while loop, the if statement executes only once if its condition is TRUE. The while loop has the following syntax: While condition: expression(block of code) Unlike the for loop, the while loop doesn’t iterate over a sequence. It uses the comparison operators and booleans for its condition. Let’s look at some examples to better understand how it is used. Example 1: Print “Hello World!” a count number of times The while loop checks the condition(count < n), each time when it’s TRUE, it prints our “Hello world!” and increments the count. This is how the flowchart will look like: def print_count_times(n): # set count to 0 count = 0 while count < n: print("Hello World!") # increment count count += 1 if __name__ == '__main__': # number of times we want to print n = 10 # call our function to print n times. print_count_times(n) Output: Example 2: Find factorial of a number The factorial of a number is represented as n! and it has the formula 1*2*...*(n-1) The program checks if the number is 0 and returns 1(factorial of 0 is 1). Then the while loop checks the condition (n >=1) to see if our n is equal to 1 or greater than 1. Each time when this condition is TRUE, our program computes the formula in the loop block Let’s use the while loop to solve the factorial problem def factorial(n): if n == 0: # The factorial of 0 is 1. return 1 else: fac = 1 while n >= 1: # while this condition is TRUE # 1*2*3*...*(n-1) fac *= n # same as 'fac = fac * n' n -= 1 # same as 'n = n - 1' return fac if __name__ =='__main__': n = int(input("Find factorial of: ")) fac = factorial(n) print("Factorial of {} is {} ".format(n,fac)) Output Example – Find A Fibonacci Sequence Upto nth Term Using The While Loop A Fibonacci sequence has the formula. 0,1,1,...((n-1)th + (n-2)th) The first two numbers are 0 and 1, then the next numbers are the sum of the two previous numbers (n-1)th and (n-2)th. The Fibonacci sequence of 8 will be 0,1,1,2,3,5,8,13 def fibonacci(n_term): n1 = 0 # (n-1)th if n_term == 1: # if n_term term is 1, print 0 print(n1) else: count = 0 n2 = 1 # (n-2)th # Loop while 'count<n_term' is TRUE while count < n_term: print(n1) # save second term in a temporary variable temp = n2 # compute sum of the 2 previous numbers and assign to (n-2)th n2 = n1 + n2 # assign the temporary variable to (n-1)th n1 = temp # increment count count += 1 if __name__ == "__main__": n_term = int(input("Find Fibonacci of how many terms: ")) fibonacci(n_term) Output Our program first defines the first nth value (n1=0), then it checks if the n_term passed as an argument is equal to 1. If TRUE, it returns 0. Else, it defines two variables: - count=0: This will be used in the while loop to check the condition if the count is lesser than n_term(count < n_term) - n2=1: This is our second nth value. So far, we have 0,1 in our sequence(n1, n2). While the condition is TRUE: - The value of n2 gets assigned to a temporary variable(temp = n2). - The sum of the two previous numbers are calculated and assigned to n2(n2 = n1 + n2). - Our temporary value(n2 old value) is assigned to n1(n1 = temp). - Our count is incremented(count +=1), and the condition is checked again. At the end of the first iteration, we have 0,1,1 where: - n1 = 1 ( the first 1) - n2= 1 ( the second 1) This operation will repeat until the condition count<n_term becomes FALSE. Nested Loop The cool thing about Python loops is that they can be nested i.e. we can use one or more loops inside another loop. This enables us to solve even more complex problems. #1) Nesting for Loops for loops can be nested within themselves. The syntax below shows a 1-level nested for loop. for in n: # piece of code goes here for in n: # piece of code goes here Example 1: Use nested for loop to print numbers in patterns Let’s use the nested for loop to print the following pattern: 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 Each number is printed a number of times corresponding to its number itself. This is how the flowchart will look like: def print_numbers(): for i in range(1, 6): # outer loop for j in range(i): # 1st level inner loop print(i, end=" ") print('\n') if __name__ == '__main__': print_numbers() Output Our program works as follows: - The outer loop iterates through the range from 1 to 6 and for each item in that sequence. - It enters the inner loop where it iterates over a range of that item. - For each iteration of that item, it prints the item. - It only leaves the inner loop when it has completely iterated through a range of that item. - When it leaves the inner loop, it goes back to the outer loop and the process continues until it has completely iterated over its sequence. Example 2: Manipulate items of a nested list using a nested for loop A situation we will likely come across in Python is to access the items of a nested list. For example, take the nested list below. >>> [[3,4.0,2,8.4,6],[0,2,0.2,4,6],[9,3.5,0.32,5,4]] For this example, let’s write a program that will count the number of integers and floats in this nested list. def float_and_int_count(nested_list): float_count = 0 # set our float count to zero int_count = 0 # set our integer count to zero for l in nested_list: # outer loop accesses each list in the nested list for item in l: # inter loop accesses each item in the list if isinstance(item, int): # if item is an instance of int int_count += 1 # increment integer count elif isinstance(item, float): # if item is an instance of float float_count += 1 # increment float count # return a tuple return float_count, int_count if __name__ == '__main__': nested_list = [[3,4.0,2,8.4,6],[0,2,0.2,4,6],[9,3.5,0.32,5,4]] float_n, int_n = float_and_int_count(nested_list) print("Float count: {} \nInteger count: {}".format(float_n, int_n)) Output Our program works this way: - The outer loop accesses the first inner lists [3,4.0,2,8.4,6] in our nested list. - The inner loop accesses each item in this first inner list. For each item, it checks if it is a float or integer. If it is an integer, it increments the integer count (int_count). Else if it is a float, it increments the float count (float_count). - Once it has finished iterating through this first inner list, it then moves back to the outer loop and accesses the second list [0,2,0.2,4,6] and the same process continues until it has accessed all the inner lists. #2) Nesting While Loops While loops can be nested within themselves. The syntax below shows a 1-level nested while loop. while condition: # piece of code goes here while condition: # piece of code goes here Example 3: Use nested while loop to print stars(*) in patterns Let’s use nested while loop to construct the following pattern: * * * * * * * * * * * * * * * def print_pattern(n): i = 0 # initialize to zero for outer loop j = 0 # initialize to zero for inner loop while i <= n: # outer loop runs n times while j < i: # inner loop runs i times print("*", end=" ") j += 1 # increment before checking inner loop condition j = 0 # re-initialize after leaving inner loop i += 1 # increment before checking outer loop condition print('') if __name__ == '__main__': n = 5 print_pattern(5) Output Our program works as follows: - Variables are initialized (i=0, j=0, n=5) - Our outer loop checks the condition (0 <= 5) which is obviously TRUE. - Our inner loop checks the condition (0 < 0) which is obviously FALSE, so our program breaks out of the inner loop. - i is incremented and the outer loop checks again its condition (1 <= 5) which is TRUE. - Our inner loop checks the condition (0 < 1) which is TRUE. So a star(*) is printed and j is incremented and the inner loop condition is checked with (1 < 1) which is FALSE, thus breaks out of the inner loop. The process above continues until the outer loop condition becomes FALSE. Example – Numbers Spelling Game To round up with a nested loop, we will build an exciting game to help in evaluating the kid’s ability to recognize and spell numbers. The program displays random numbers on the screen and requests for the spelling of that number. It checks if the input is correct, then it displays another number. If the input is wrong, then it will send an error message and request another answer. import random # random contain 'shuffle' used to shuffle our list def word_spelling(): print("HELLO, WELCOME TO THE WORD SPELLING GAME.\n") print("SPELL AS MUCH NUMBERS AS YOU CAN TO GET MARKS\n") print("-----------------------------------------------\n") correct_score = 0 # keep record of correct spellings wrong_score = 0 # keep record of wrong spellings exceeding number of trials max_trials = 3 # maximum number of trials # A dictionary of numbers as keys and spellings as values. This can be expanded to increase its level of difficulty. number_spell = {0:"zero",1:"one",2:"two",3:"three",4:"four",5:"five",6:"six", 7:"seven",8:"eight",9:"nine",10:"ten"} # get the list of keys from the dict and shuffle them so that random numbers are displayed on the screen. number_spell_keys = list(number_spell.keys()) random.shuffle(number_spell_keys) # Our game starts here for number in number_spell_keys: # outer loop is a for loop which iterate through the keys trial_count = 0 # keeps track of number of trials while trial_count < max_trials: # inner loop is a while loop that checks if number of trials by the user exceeded the max # get user input spelling = input("Spell {}: ".format(number)) if spelling.lower() == number_spell[number]: # if user got it right, increment it's score and break out of the outer loop correct_score += 1 break else: # if not, increment number of trials and ask the user to try again trial_count += 1 print("Incorrect spelling. {} trials left\n".format(max_trials-trial_count)) else: # if while loop condition fails, increment wrong score and quit the inner loop print("Sorry! Number of trials Exceeded") wrong_score += 1 print("-------------------\nEND OF GAME\n") print("CORRECT SPELLING SCORE: {}\n".format(correct_score)) print("WRONG SPELLING SCORE: {}".format(wrong_score)) if __name__ == '__main__': word_spelling() Output The main functionalities of our for-loop and while-loop are: - The for loop iterates through a list of numbers that are presented to the user to spell. - The while loop checks if the number of trials has been exceeded. In this way, a user is given a maximum number of trials to get it right. We have seen two new concepts while-else, break(more on this later). The while loop and for loop originally have an else statement which only executes once when the condition is FALSE. Python Infinite Loops If we are not careful with how we implement our loops, then it can lead to an infinite loop i.e. the program will execute a block of code forever until our computer runs out of resources like CPU memory. Example 1: Infinite while loop def infinit_loop_1(): numb = 0 while numb < 5: print(numb) if __name__ == '__main__': infinit_loop_1() Output Note: To stop this program from running, use Ctrl+z or Ctrl+c on the terminal you used to run the code. Our code above implements an infinite while loop. However, this is by mistake because our while loop checks the condition numb < 5, but there is nowhere in the code that actually increments the numb’s value. Hence the value of numb is always zero and the condition keeps returning TRUE. So, the way to fix this is to provide a means to increment numb’s value. def infinit_loop_1(): numb = 0 while numb < 5: print(numb) numb += 1 # fix by incrementing numb's value if __name__ == '__main__': infinit_loop_1() Output A question may arise as are infinite loops really necessary? Spoiler alert: Yes they are. A server may be programmed to run continuously while serving the needs of clients. In gaming, an event may run until the user selects an action to quit or break the loop. Believe it or not, we actually used an infinite loop in the last practical example above. So, how do we deal with infinite loops? Python Break And Continue Statements As we explained above, there are cases where we will need to write intentional infinite loops. In these cases, we will see that the break and continue keywords are the backbone of infinite loops.. Example – Accumulate Numbers Until A Threshold Is Met Let’s consider a program that gets numbers from a randomly generated source and accumulate the numbers until a threshold is reached. The reason why this example requires an infinite loop is that we don’t know exactly how many iterations our program will need to perform for the accumulated numbers to reach the threshold. Our only savior is the Python if statement together with the break statement. Our if statement checks if the threshold is reached, then it breaks out of the loop if TRUE. Our program also requires that some restricted numbers shouldn’t be accumulated. So, if our program encounters these numbers, it should skip all the codes and return to the beginning of the loop. This is achievable with the continue statement. import random def acc_numbers(): acc_numb = 0 # initialize our accumulator threshold = 45 # define our threshold value Rejected_numbers = [4,0,1] # define our rejected numbers while True: # This is an uncontrolled condition. # our infinite while loop # return random integer number within 0 and 10. numb = random.randint(0, 10) # check if the number is in the list of rejected numbers if numb in Rejected_numbers: print("Not accepting ", numb) continue # skip all code blow it and return to the beginning of the while loop # add random number to our store acc_numb += numb # check if the accumulated number has reached threshold if acc_numb >= threshold: print("Threshold attended") break # break out of the loop. if __name__ == '__main__': acc_numbers() Output Frequently Asked Questions Q #1) How do you control a Loop in Python? Answer: In Python, you can control a loop with the following control statements: - The break keyword breaks out of a loop. - The continue keyword skips all the codes below it and returns to the beginning of the loop. These keywords are mostly used in an if statement that first checks if a condition is TRUE or FALSE. Q #2) What is the difference between for loop and while loop? Answer: A for loop is an iterator based loop, which steps through the items of iterable objects like lists, tuples, etc. While a while loop is a condition-based loop, that executes a block of statements repeatedly as long as its condition is TRUE. Q #3) Does Python do support until loop? Answer: Unfortunately, Python doesn’t support the do-while loop. Q #4) What are the two types of loops in Python? Answer: Python generally supports two types of loops: for loop and while loop. However, a third loop[nested loop] can be generated by nesting two or more of these loops. More About Python Loops Looping statements in python are used to execute a block of statements or code repeatedly for several times as specified by the user. Python provides us with 2 types of loops as stated below: - While loop - For loop #1) While loop: While loop in python is used to execute multiple statements or codes repeatedly until the given condition is true. We use a while loop when we don’t know the number of times to iterate. Syntax: while (expression): block of statements Increment or decrement operator In the while loop, we check the expression, if the expression becomes true, only then the block of statements present inside the while loop will be executed. For every iteration, it will check the condition and execute the block of statements until the condition becomes false. Example: number = 5 sum = 0 i = 0 while (i<number): sum = sum + i i = i+1 print(sum) Output: 10 Output: #2) For loop: For loop in python is used to execute a block of statements or code several times until the given condition becomes false. We use the for loop when we know the number of times to iterate. Syntax: for var in sequence: Block of code Here var will take the value from the sequence and execute it until all the values in the sequence are done. Example: language = [‘Python’, ‘Java’, ‘Ruby’] for lang in language: print(“Current language is: “, lang) Output: Current language is: Python Current language is: Java Current language is: Ruby Output: For loop using range () function: The Range () function is used to generate a sequence of numbers. For Example, range (5) will generate numbers from 0 to 4 (5 numbers). Example: language = [‘Python’, ‘Java’, ‘Ruby’] for lang in range(len(language)): print(“Current language is: “, language[lang]) Output: Current language is: Python Current language is: Java Current language is: Ruby Output: Conclusion In this tutorial, we saw the definition of loops, the types of Python loops, usage of for loop, and while loop with some examples. We also learned how nested loops are generated and finite loops as well and we came to know how to use the break and continue keywords. => Check ALL Python Tutorials Here PREV Tutorial | NEXT Tutorial
https://www.softwaretestinghelp.com/python/looping-in-python-for-while-nested-loops/
CC-MAIN-2021-21
refinedweb
4,374
59.84
Using the same variable as parameter and storage when calling a function in powershell Recently I had this problem. After investigating a lot of hours, finally I discovered that the problem was in using the same variable for: - Storing the value returned by the function - Pass it as a parameter to the function So taken into account below function: Function Create-Filter($filter) { $filter.Split(',') | ForEach-Object {"*.$($_.Trim())"} return } (Above function gets a string variable such as "csproj, vbproj" and converts it into *.csproj *.vbproj) ...below code is not working, variable $filter used for -Include parameter does not like to Get-ChildItem and it is returning nothing: $filter = "csproj, vbproj" $filter = Create-Filter ($filter) Get-ChildItem "D:\Path\To\My\Root\Folder" -Include $filter -Recurse Instead below one is working by using a different variable for storing and pass it as a parameter: $filter = "csproj, vbproj" $formattedfilter = Create-Filter ($filter) Get-ChildItem "D:\Path\To\My\Root\Folder" -Include $formattedfilter -Recurse ... now Get-ChildItem works. In other languages one can use the same variable for passing it as a parameter and storing the value returned by the function. So could you explain me why in powershell this does not work if one uses the same variable? 1 answer - answered 2019-06-17 18:59 mhu Not sure why your code won't work, as the return in your case is redundant and the result is put on the output stream. So the same code but refactored: function New-Filter { param ( [Parameter(Mandatory=$true)] [String[]] $filter ) return $filter.Split(',') | ForEach-Object {"*.$($_.Trim())"} } $filter = @("csproj, vbproj") $filter = New-Filter $filter Get-ChildItem -Path "D:\Path\To\My\Root\Folder" -Include $filter -Recurse See also questions close to this topic - How to disable concrete function onload page? How to globaly disable javascript function named for example ABC in JQuery after page loading? -. - Why won't my function work with parameters? I'm trying to make a typewriter effect for a web project, I tried making my own, which had parameters, and it didn't work for some reason. I found someone elses typewriter and tried to edit it to understand it better, but it didn't work with parameters.The original code used variables outside of the function that worked fine, but variables failed. Ive tried editing the functions in small ways that shouldnt matter, but it all fails in the end. //The Working Function var i = 0; var txt = "Old McDonald Had a farm"; var speed = 50; function typeWriter() { if (i < txt.length) { document.getElementById("demo").innerHTML += txt.charAt(i); i++; setTimeout(typeWriter, speed); } } typeWriter(); // The edited function that failed var i = 0; var text = "Old McDonald Had a farm"; var spe = 50; function typeWriter(txt, spe) { if (i < txt.length) { document.getElementById("demo").innerHTML += txt.charAt(i); i++; setTimeout(typeWriter, speed); } } typeWriter(text, spe); The edited code only outputs the first character than stops, I want it to do all of them. My web text editor doesn't like jQuery so finding an actual error is complicated -. - Getting the Difference of Time in a List of Dates Trying to calculate the difference between two lists of dates and output the difference. The dates were treated as an object that are a string I changed that but now I only get the dates. $TrimmedImport1 = $import1 -replace '"', "" | Set-Content -Path "$env:TEMP\Time Finished.csv" $TrimmedImport = $import -replace '"', "" | Set-Content -Path "$env:TEMP\Time Created.csv" $ContentSetter1 = Get-Content -Path "$env:TEMP\Time Finished.csv" $ContentSetter = Get-Content -Path "$env:TEMP\Time Finished.csv" foreach ($TimeConverted1 in $ContentSetter1) { [DateTime]$TimeConverted1 } "`n" foreach ($TimeConverted in $ContentSetter) { [DateTime]$TimeConverted } - How to upgrade PowerShell version from 2.0 to 3.0? I write "Add-migration Initial" in Package Manager Console window in Visual Studio 2015 and it says: EF Core commands do not support PowerShell version 2.0. Please upgrade PowerShell to 3.0 or greater and restart Visual Studio. I expected to be created a folder Migrations contains the database. - Calling multiple functions via parameters when running .ps1 script I have a .ps1 script that has multiple functions in it. Instead of running them all at once, I'd like the user to be able to put in which functions they'd like to run. e.g.: ./script.ps1 -func1 -func2 or ./script.ps1 -All I can get it to work by just comparing the user inputted parameter to a function name, but the problem is I would like the user to be able to put it in any order. Here's what I have working now, but I'm not sure if I can optimize it in some way. [CmdletBinding()] Param( [Parameter(Mandatory=$false)][String]$Param1, [Parameter(Mandatory=$false)][String]$Param2 ) function Test { Write-Host "Test Success" } function All { Write-Host "All Success" } If ($Param1 -eq "Test" -or $Param2 -eq "Test") { Test } If ($Param1 -eq "All" -or $Param2 -eq "All") { All } Instead of just having a bunch of 'if' statements with 'or' conditionals, I just watch the user to input a function as a parameter. I'm sure there's a way to do it with a switch or array but I'm not a great programmer. - How to resolve error "String not recognized as valid DateTime"? I have three date type variables passed from a batch file as strings. When they come over to the PS script, they are seen as: 20190710 112538 20190710 112538 20190710 The problem I am facing is that when I attempt to parse them, I receive an error stating that the string is not recognized as a valid DateTime. I have tried changing the culture to and invariant one and no difference. I am sure I am missing something. Could I get some help with parsing these strings successfully? Values Sent from here: set YYYY=%DATE:~-4% set MM=%DATE:~4,2% set DD=%DATE:~7,2% set HH=%time:~0,2% set NN=%time:~3,2% set SS=%time:~6,2% set MS=%time:~9,2% SET "_oStart=%YYYY%%MM%%DD% %HH%%NN%%SS%%MS%" SET "_PSScript=C:\xx\xx.ps1" SET "_oEnd=%YYYY%%MM%%DD% %HH%%NN%%SS%%MS%" SET "_oDateRan=%YYYY%%MM%%DD%" SET "_PSCMD=Powershell -ExecutionPolicy Bypass -File "%_PSScript%" -oStart "%_oStart%" -oEnd "%_oEnd%" -oDateRan "%_oDateRan%" Param( [String]$oStart, [String]$oEnd, [String]$oDateRan ) [DateTime]$DateRan = [DateTime]::ParseExact($oDateRan, "yyyyMMdd", $null) [DateTime]$StartTime = [DateTime]::ParseExact($oStart, "yyyyMMdd HHmmssff", $null) [DateTime]$End = [DateTime]::ParseExact($oEnd, "yyyyMMdd HHmmssff", $null) Error Message: Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime." - How to run powershell commands as an administrator on azure windows VM I am trying to create azure windows 2012 r2 server virtual machine and installing SQL Server and Microsoft SQL Reporting Services on that machine using Python SDK and Powershell. I am able to create Windows machine using python SDK, able to install Microsoft SQL Server without logging into the machine. However to Install Microsoft SQL Reporting Services on Azure Windows Virtual machines using remote Powershell scripts I have to login at least once to install these services through remote scripts. If I don't login at all the scripts are getting failed. I am feeling the problem is with execution-policy of powershell. Can anybody guide me how can we run powershell commands as an administrator on azure windows VM without logging into the machine a single time? Or How can set powershell execution-policy to remotesigned without logging into the Microsoft Azure Windows Virtual machine a single time? I am able to create virtual machine, install sql server automatically through Python SDK. Also able to install SSRS IF I login at least once using Remote powershell commands. But I don't login the powershell scripts throws "shell can not be started" This problem gets resolved once I logged into the virtual machine, the remote scripts works fine This installs SSRS SQLServerReportingServices.exe /quiet /norestart /IAcceptLicenseTerms /PID=$productId This configures SSRS on VM function Get-ConfigSet() { return (Get-WmiObject -namespace 'root\Microsoft\SqlServer\ReportServer\RS_SSRS\v14\Admin' -class MSReportServer_ConfigurationSetting -ComputerName localhost) } # Allow importing of sqlps module Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force # Retrieve the current configuration $configset = Get-ConfigSet $configset if(!$configset.isInitialized) I am using paexec to run these scripts remotely using username and password used while creation of the virtual machine. I am expecting this should work without logging into the machine because we want to deploy multiple solutions and we can't login to eavry virtual machine of every deployment to get it successful -++ } - How to use Get-ChildItem to filter out locked/being used by another process files? Is Get-ChildItemable to filter out the files which are in locked state? Such as logs files currently in use by application and Get-ChildItemshould skip on these files in results. Example: Get-ChildItem -Path C:\Logs\* # Maybe do pipelines condition here for filtering out locked files
http://quabr.com/56637236/using-the-same-variable-as-parameter-and-storage-when-calling-a-function-in-powe
CC-MAIN-2019-30
refinedweb
1,480
51.18
You are currently browsing legacy 2.5 version of documentation. Click here to switch to the newest 5.0 version. Boosting public class User { public string FirstName { get; set; } public string LastName { get; set; } } To perform a query that will return users that either FirstName or LastName is equal to Bob and to promote users (move them to the top of the results) that FirstName matches the phrase, we must first create an index with boosted entry. public class Users_ByName : AbstractIndexCreationTask<User> { public Users_ByName() { this.Map = users => from user in users select new { FirstName = user.FirstName.Boost(10), LastName = user.LastName }; } } Next step is to perform a query against that index. session.Query<User, Users_ByName>() .Where(x => x.FirstName == "Bob" || x.LastName == "Bob") .ToList(); Boosting is also available when using Search method. You can read more about it here.
https://ravendb.net/docs/article-page/2.5/csharp/client-api/querying/static-indexes/boosting
CC-MAIN-2020-45
refinedweb
139
68.26
Today i was trying to use eclipse 3.3 w/ pydev to develop an app with django, but i really couldn’t make the code-completion (the main reason (along with the debugger) i was using eclipse!). The main thing problem was that i had to add ALL folders to the pydev project settings. And, i didn’t have time (and patience) to add one folder by one to the config screen, sooo, i created this script to do that for me: #!/usr/bin/env python import dircache, os def listdr(_dir): try: dir_list = dircache.listdir(os.path.realpath(_dir)) dir_list = [_dir + "/" + d for d in dir_list] only_dirs = filter(lambda d: os.path.isdir(d), dir_list) file = os.path.realpath(_dir) print “<path>%s</path>” % file for dir in dir_list: listdr(dir) except: return if __name__ == “__main__”: listdr(”/usr/lib/python2.5/site-packages/django/”) This script will show all folders under /usr/lib/python2.5/site-packages/django/ with that tags <path>, ready to add to the .pydevproject configuration file (that’s under your project file).
http://fernandotakai.wordpress.com/2008/04/22/adding-auto-complete-to-a-django-pydev-project-on-eclipse/
crawl-002
refinedweb
177
66.94
12424/hyperledger-fabric-byfn-up-command-hangs-during-execution I am following the tutorial from here: The processing starts as usually but hangs and line it hangs says Creating cli.. I think cli is not getting created. I have stopped the process and run several times but I still get the same result. How can I solve this? Run the following command: sudo docker stop $(docker ps --all -q ) | docker rm $(docker ps -a -q) Next, restart your computer and restart docker service using the following command: sudo service docker start or systemctl start docker this should solve your problem. Try adding GODEBUG=netdns=go to the environment variables ...READ MORE You can follow these steps : In your ...READ MORE Open .env file in fabric-samples/first-network/ ...READ MORE Seems like you have not installed docker-compose. ...READ MORE Summary: Both should provide similar reliability of ...READ MORE This will solve your problem import org.apache.commons.codec.binary.Hex; Transaction txn ...READ MORE To read and add data you can ...READ MORE The error is caused because you're trying ...READ MORE Hyperledger Fabric v0.6 does not provide any ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/12424/hyperledger-fabric-byfn-up-command-hangs-during-execution
CC-MAIN-2019-47
refinedweb
201
61.33
Computers store and process all kinds of data. Strings are just one of the many forms in which information is presented and gets processed by computers. Strings in the C programming language work differently than in other modern programming languages. In this article, you'll learn how to declare strings in C. Before doing so, you'll go through a basic overview of what data types, variables, and arrays are in C. This way, you'll understand how these are all connected to one another when it comes to working with strings in C. Knowing the basics of those concepts will then help you better understand how to declare and work with strings in C. Let's get started! Data types in C C has a few built-in data types. They are int, short, long, float, double, long double and char. As you see, there is no built-in string or str (short for string) data type. The char data type in C From those types you just saw, the only way to use and present characters in C is by using the char data type. Using char, you are able to to represent a single character – out of the 256 that your computer recognises. It is most commonly used to represent the characters from the ASCII chart. The single characters are surrounded by single quotation marks. The examples below are all chars – even a number surrounded by single quoation marks and a single space is a char in C: 'D', '!', '5', 'l', ' ' Every single letter, symbol, number and space surrounded by single quotation marks is a single piece of character data in C. What if you want to present more than one single character? The following is not a valid char – despite being surrounded by single quotation marks. This is because it doesn't include only a single character inside the single quotation marks: 'freeCodeCamp is awesome' When many single characters are strung together in a group, like the sentence you see above, a string is created. In that case, when you are using strings, instead of single quotation marks you should only use double quotation marks. "freeCodeCamp is awesome" How to declare variables in C So far you've seen how text is presented in C. What happens, though, if you want to store text somewhere? After all, computers are really good at saving information to memory for later retrieval and use. The way you store data in C, and in most programming languages, is in variables. Essentially, you can think of variables as boxes that hold a value which can change throughout the life of a program. Variables allocate space in the computer's memory and let C know that you want some space reserved. C is a statically typed language, meaning that when you create a variable you have to specify what data type that variable will be. There are many different variable types in C, since there are many different kinds of data. Every variable has an associated data type. When you create a variable, you first mention the type of the variable (wether it will hold integer, float, char or any other data values), its name, and then optionally, assign it a value: #include <stdio.h> int main(void){ char letter = 'D'; //creates a variable named letter //it holds only values of type char // the single character 'D' is assigned to letter } Be careful not to mix data types when working with variables in C, as that will cause errors. For intance, if you try to change the example from above to use double quotation marks (remember that chars only use single quotation marks), you'll get an error when you compile the code: #include <stdio.h> int main(void){ char letter = "D"; //output: test.c:4:6: warning: incompatible pointer to integer conversion initializing 'char' with an expression of type 'char [2]' [-Wint-conversion] char letter = "D"; ^ ~~~ 1 warning generated. } As mentioned earlier on, C doesn't have a built-in string data type. That also means that C doesn't have string variables! How to create arrays in C An array is essentially a variable that stores multiple values. It's a collection of many items of the same type. As with regular variables, there are many different types of arrays because arrays can hold only items of the same data type. There are arrays that hold only ints, only floats, and so on. This is how you define an array of intss for example: int numbers[3]; First you specify the data type of the items the array will hold. Then you give it a name and immediately after the name you also include a pair of square brackets with an integer. The integer number speficies the length of the array. In the example above, the array can hold 3 values. After defining the array, you can assign values individually, with square bracket notation, using indexing. Indexing in C (and most programming languages) starts at 0. //Define the array; it can hold 3 values int numbers[3]; //assign the 1st item of the numbers array the value of 1 int numbers[0] = 1; //assign the 2nd item of the numbers array the value of 2 int numbers[1] = 2; //assing the 3rd item of the numbers array the value of 3 int numbers[2] = 3; You reference and fetch an item from an array by using the name of the array and the item's index in square brackets, like so: numbers[2]; // returns the value 3 What are character arrays in C? So, how does everything mentioned so far fit together, and what does it have to do with initializing strings in C and saving them to memory? Well, strings in C are actually a type of array – specifically, they are a character array. Strings are a collection of char values. How strings work in C In C, all strings end in a 0. That 0 lets C know where a string ends. That string-terminating zero is called a string terminator. You may also see the term null zero used for this, which has the same meaning. Don't confuse this final zero with the numeric integer 0 or even the character '0' - they are not the same thing. The string terminator is added automatically at the end of each string in C. But it is not visible to us – it's just always there. The string terminator is represented like this: '\0'. What sets it apart from the character '0' is the backslash it has. When working with strings in C, it's helpful to picture them always ending in null zero and having that extra byte at the end. Each character takes up one byte in memory. The string "hello", in the picture above, takes up 6 bytes. "Hello" has five letters, each one taking up 1 byte of space, and then the null zero takes up one byte also. The length of strings in C The length of a string in C is just the number of characters in a word, without including the string terminator (despite it always being used to terminate strings). The string terminator is not accounted for when you want to find the length of a string. For example, the string freeCodeCamp has a length of 12 characters. But when counting the length of a string, you must always count any blank spaces too. For example, the string I code has a length of 6 characters. I is 1 character, code has 4 characters, and then there is 1 blank space. So the length of a string is not the same number as the number of bytes that it has and the amount of memory space it takes up. How to create character arrays and initialize strings in C The first step is to use the char data type. This lets C know that you want to create an array that will hold characters. Then you give the array a name, and immediatelly after that you include a pair of opening and closing square brackets. Inside the square brackets you'll include an integer. This integer will be the largest number of characters you want your string to be including the string terminator. char city[7]; You can initialise a string one character at a time like so: #include <stdio.h> int main(void) { char city[7]; city[0] = 'A'; city[1] = 't'; city[2] = 'h'; city[3] = 'e'; city[4] = 'n'; city[5] = 's'; city[6] = '\0'; //don't forget this! printf("I live in %s",city); } But this is quite time-consuming. Instead, when you first define the character array, you have the option to assign it a value directly using a string literal in double quotes: #include <stdio.h> int main(void){ char city[7] = "Athens"; //defines a character array named city //it can hold a string up to 7 characters INCLUDING the string terminator //the value "Athens" is assigned when the character array is being defined //this is how you print the character array value printf("I live in %s",city); } If you want, istead of including the number in the square brackets, you can only assign the character array a value. It works exactly the same as the example above. It will count the number of characters in the value you provide and automatically add the null zero character at the end: char city[] = "Athens"; //"Athens" has a length of 6 characters //"Athens" takes up 7 bytes in memory,with the null zero included /* char city[7] = "Athens"; is equal to char city[] = "Athens"; */ Remember, you always need to reserve enough space for the longest string you want to include plus the string terminator. If you want more room, need more memory, and plan on changing the value later on, include a larger number in the square brackets: char city[15] = "Athens"; /* The city character array will now be able to hold 15 characters (including the null zero) In this case, the remaining 8 (15 - 7) places will be empty You'll be able to reassign a value up to 15 characters (including null zero as always) */ How to change the contents of a character array So, you know how to initialize strings in C. What if you want to change that string though? You cannot simply use the assignment operator ( =) and assign it a new value. You can only do that when you first define the character array. As seen earlier on, the way to access an item from an array is by referencing the array's name and the item's index number. So to change a string, you can change each character individually, one by one: #include <stdio.h> int main(void) { char city[7] = "Athens"; printf("I live in %s",city); //changing each character individually means you have to use single quotation marks //the new value has to take up 7 bytes of memory //indexing starts at 0, the first character has an index of 0 city[0] = 'L'; city[1] = 'o'; city[2] = 'n'; city[3] = 'd'; city[4] = 'o'; city[5] = 'n'; city[6] = '\0'; //DON'T FORGET THIS! printf("\nBut now I live in %s",city); } //output: //I live in Athens //But now I live in London That method is quite cumbersome, time-consuming, and error-prone, though. It definitely is not the preferred way. You can instead use the strcpy() function, which stands for string copy. To use this function, you have to include the #include <string.h> line after the #include <stdio.h> line at the top of your file. The <string.h> file offers the strcpy() function. When using strcpy(), you first include the name of the character array and then the new value you want to assign. The strcpy() function automatically add the string terminator on the new string that is created: #include <stdio.h> #include <string.h> int main(void) { char city[15] = "Athens"; strcpy(city,"Barcelona"); printf("I am going on holiday to %s",city); //output: //I am going on holiday to Barcelona } Conclusion And there you have it. Now you know how to declare strings in C. To summarize: - C does not have a built-in string function. - To work with strings, you have to use character arrays. - When creating character arrays, leave enough space for the longest string you'll want to store plus account for the string terminator that is included at the end of each string in C. - To place or change strings in character arrays you either: - Define the array and then assign each individual character element one at a time. - OR define the array and initialize a value at the same time. - When changing the value of the string, you can use the strcpy()function after you've included the <string.h>header file. If you want to learn more about C, I've written a guide for beginners taking their first steps in the language. It is based on the first couple of weeks of CS50's Introduction to Computer Science course and I explain some fundamental concepts and go over how the language works at a high level. You can also watch the C Programming Tutorial for Beginners on freeCodeCamp's YouTube channel. Thanks for reading and happy learning :)
https://www.freecodecamp.org/news/c-string-how-to-declare-strings-in-the-c-programming-language/
CC-MAIN-2021-49
refinedweb
2,224
69.11
Implement a XML Review UI that allow user to perform actions on XML files Review Request #9615 — Created Feb. 10, 2018 and updated. Unlike JSON files, order matters in XML files. For example, imagine this: <h1>This is a section</h1> <p>Some content.</p> <h1>Here's another section</h1> <p>More content.</p> <code>Some sample code.</code> If you order them, then you get: <code>Some sample code.</code> <h1>This is a section</h1> <h1>Here's another section</h1> <p>Some content.</p> <p>More content.</p> That doesn't make any sense. We also shouldn't order attributes. There may be a reason the author has put them that way. When working with XML, it's good to show the XML in a form that makes it easier to read the document, in a tree form, but we don't want to otherwise alter that content. These blank lines should remain. Check our style guide on Notion for where blank lines should go. Can you add a comment about why the score is 1 here, based on what we've diagnosed? osis a Python Standard Library module, so it should go in an import group after __future__but before django. See the style guideline on Notion for import groups. "XMLReviewUITests" No blank line between classand the docstring. We also tend to include the full module path in the docstring for unit tests, so the full one for XMLReviewUI. The blank line should go after. Helper functions in unit tests should be private (prefix with a _) and put at the end of the class. Typo, and this doesn't follow our documentation guidelines. Ideally, we wouldn't include data files, since that makes it harder to have self-contained tests and to provide variations on the tests. It's not even needed in this case, since SimpleUploadedFiletakes the data directly. This function should take the data, and that should be provided in calls to the method instead of opening a file. Each component of os.path.joinshould be a single path entry. No .or /. file_diretorymust also be its own parameter -- no concatenation, since that's the point of os.path.join. You want as little as possible in this withblock. Confine it to the SimpleUploadedFilecreation. Docstrings should be in the form of: """Testing <class>.<method> <condition>""" Like: """Testing XMLReviewUI.get_rendered_lines orders tag results""" Same in other tests. This is all part of the Python Standard Library, so it should be in the same import group. Alphabetical order. This would be: from django.utils import six from django.utils.six.moves import ... from django.utils.translation import ... This is part of the Python Standard Library, and should go in the appropriate import group. Lines are wrapping way too soon. This must describe the results of the method (a Yieldssection). See Notion for info on writing docs. We don't use the inline if .. else ..form. This should be expanded into a standard if/else. Docstrings must have a single-line summary. IT cnanot wrap. Others are wrapping too soon. This is going to show up wrong in the docs. If you want to show inline code, use double backticks around it. This format being shown here, though, is a bit confusing, and seems more like an implementation detail. It's better to describe this and then provide an example of a value separately. This will need a docstring in our standard format. So will other methods in this class. Double prefixes should never be used in Python, except for operators (like __eq__) or other special methods ( __str__, __repr__). Private methods should also go after all public methods. This needs a docstring. It's also in the wrong casing format. find_attributeswould be more correct. These can be combined into one conditional. This also needs a docstring and should be add_indent. Change Summary: Fixed issue indicated by Christian Checks run (1 failed, 1 succeeded) flake8 I don't have to much insight on what you are working on but I feel that there are a few things you can do to make this part of the code more maintainable and readable for others. All your testing happens in the get xml filefunction, but base on the nasme, that should be returning an xml file of sorts, not testing for nested XML. You don't verify if any exceptions are thrown here. Rather than waiting for a KeyErroror TypeErrorwhen in etree_to_dict, you should get an IOErrorand handle that. flow is really odd and there are no comments to explain what is happening in each block. You could use intermediate functions to make it obvious too. This docstring should explain the inputs expected and return values. You also need to say what type is expected for tbecause it makes the rest of this code a little unclear as we don't know what attributes are guaranteed to exist. Add a comment for why len(value) ==1:is important. Is it possible for strip()to return none? Why are you creating a new dict and adding t.tag to it? Is there any benefit over adding text to t.tag? confusing operation. You are reassigning an input to the return value of a function to which its intial input was the value you are reassigning. Maybe use an intermediate? You have attriband attrib_in, both of these side by side are a little confusing. Better names are required. You should add a comment to explain what is happening here. Along with providing a better name for the variable, you should add what argsand kwargsare representing in your docstring. Considering this is an IO Stream, is there possibility of not having a value by the end or have a possible IO error? You'll need to document the expected results and inputs. Should say Add indention on new line with an indent of the current depth plus one. what if the wrong type is passed in? Checks run (1 failed, 1 succeeded) flake8 I understand the _ is for localization? How exactly does that lookup work? Perhaps consider using enums for this and text Not sure this is needed. Why not call self._fixnamedirectly? It may be more clear if you put key[0] == "text"(or better yet use an enum) and add this as an andclause to the ifabove it to reduce nesting %smay round things (is this what you want?). Consider using %rif you don't want rounding. Have a look at this blog post for some more info.
https://reviews.reviewboard.org/r/9615/
CC-MAIN-2018-34
refinedweb
1,088
76.72
WallpaperLockState Since: BlackBerry 10.2.0 #include <bb/platform/WallpaperLockState> To link against this class, add the following line to your .pro file: LIBS += -lbbplatform The set of possible wallpaper lock states on the device. Overview Public Types Index Public Types The set of possible wallpaper lock states on the device. BlackBerry 10.2.0 - Unknown 0 The wallpaper lock state could not be determined. - Locked 1 The wallpaper is locked and cannot be changed by the user.Since: BlackBerry 10.2.0 - Unlocked 2 The wallpaper is unlocked and can be changed by the user.Since: BlackBerry 10.2.0 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
https://developer.blackberry.com/native/reference/cascades/bb__platform__wallpaperlockstate.html
CC-MAIN-2017-43
refinedweb
117
62.64
C++ <cwchar> - wctype_t Type The wctype_t is an implementation-defined wide character type. It represent distinct codes for all members of the wide character set specified among the supported locales. In C++, wctype_t is a distinct fundamental type and thus it is not defined in <cwchar> nor in any other header. In C, this is a typedef of an integer type. Example: The example below shows the usage of wctype_t type. #include <iostream> #include <cwchar> #include <cwctype> using namespace std; int main (){ //initiating a variable str of //wctype_t type wchar_t str[256] = L"Hello World!."; wcout<<"str contains: "<<str; return 0; } The output of the above code will be: str contains: Hello World!. ❮ C++ <cwchar> Library
https://www.alphacodingskills.com/cpp/notes/cpp-cwctype-wctype-t.php
CC-MAIN-2021-43
refinedweb
116
57.27
It's not the same without you Join the community to find out what other Atlassian users are discussing, debating and creating. I have looked at the script runner "Renames A user ID". How do I go about doing a bulk change of user ID's? I have over 400 user IDs that I need to change. Thanks Here's sample. You need to just execute the script in a loop: def ren = new com.onresolve.jira.groovy.canned.admin.RenameUser(); def input = [ ["admin","newname"], ["asd", "usernew"] ]; def result = "" for (e in input) { def args = [ (com.onresolve.jira.groovy.canned.admin.RenameUser.FIELD_FROM_USER_ID): e[0], (com.onresolve.jira.groovy.canned.admin.RenameUser.FIELD_TO_USER_ID): e[1], (com.onresolve.jira.groovy.canned.admin.RenameUser.FIELD_MERGE): false ]; result+=ren.getDescription(args, true) //Uncomment to actualy execute, the line above is for preview //result+=ren.doScript(args) } result Thanks for the response Boris. I have tried your script and also the script from this Scott Dudley from this question below The problem I am having is that both scripts are not updating the app_user table in the database. Which is causing the erorr User 'James.Jones' exists but has no unique key mapping. In Jira 6x you can update the user ID by editing the user in JIRA. This seems to be updating the column lower_user_name in the app_user table. When I run the scripts this is not updated and the way around it is to run these SQL statement and update the app_user table. INSERT INTO app_user (<id from previous query + 1>, 'username_that_caused_error' , 'username_that_caused_error' FROM app.
https://community.atlassian.com/t5/Jira-questions/Script-Runner-change-multiple-user-IDs/qaq-p/433455
CC-MAIN-2019-04
refinedweb
263
59.6
Units of measurement in domain design If you have business application of any decent size, your most important code probably resides in domain logic. When working with 3rd party code, you can always find an answer on stack overflow or official documentation, but your domain is all yours. Try to make it as simple and readable as possible, and it will always pay you back. Today I want to discuss one aspect of writing clean domain code: units of measurement. It is important for any domain (or sub-domain) where you operate some physical measurements. Problem statement Our toy example will be about cars and fuel consumption. You receive some data about the trip of your car, e.g. an instance of public interface ITrip { double FuelUsed { get; } double Distance { get; } } Now you want to calculate the fuel consumption rate of your trip. You write var fuelRate = trip.FuelUsed / trip.Distance; You get the value, but what is it? Let's say you want a value of liters per 100 kilometers. You can assume that FuelUsed is in liters, and Distance is in kilometers. To be more explicit you refactor your code public interface ITrip { double FuelUsedInLiters { get; } double DistanceInKilometers { get; } } var fuelRateLitersPer100Kilometers = trip.FuelUsedInLiters * 100.0 / trip.DistanceInKilometers; Now it's much more explicit, and probably good enough for such a small code example. For larger code bases, you will inevitably get into more problems: You will start measuring same things in different units. E.g. you will store the distance in meters in the database, so you'll have to multiply by 1000 somewhere in persistence layer. If you need to convert metric to imperial and back, you will get lots of constants here and there. String formatting will become a tedious task. Be sure to call a right formatter for each implicit unit. This does not work well. The code smell is called Primitive Obsession and we should avoid this in production-grade code. Instead, we want the succinctness of first example in combination with strong compile-time checks and well-defined operations. Defining the units I tried several options like generic classes for units, but I ended up having a struct per measurement. The code is very boring and repetitive, but it provides me with the strongest compile-time checks and nice readability. If you are too bored with typing, you can do some code generation or just use 3rd party that suits you. So, my end result looks like public interface ITrip { Volume FuelUsed { get; } Distance Distance { get; } } Let's see how Distance is defined (Volume will be almost exactly same): public struct Distance { private Distance(double kilometers) { this.Kilometers = kilometers; } public double Kilometers { get; } public double Meters => this.Kilometers / 1000.0; public static readonly Distance Zero = new Distance(0.0); ... } Several important things to notice here: It's a struct. It's immutable. Once an instance is created, its properties can't be changed anymore. Constructor is private. I don't actually want people to create instances directly: new Distance(123)reads pretty horribly, keep reading to see better options. Of course, default constructor is still public, but you can only create a zero value with it. Better way of creating zero distance is to call Zero static field. Instantiation So, how do we create measurement objects? Factory method The classic way is a set of static factory methods: public static Distance FromKilometers(double kilometers) { return new Distance(kilometers); } public static Distance FromMeters(double meters) { return new Distance(meters / 1000.0); } Usage is as simple as var distance = Distance.FromMeters(234); Extension method Imagine you have the following code which converts an integer value of a database result into our units trip.Distance = Distance.FromMeters(database.ReadInt32("TotalDistance") .GetDefaultOrEmpty()); Such a long expression reads better with a fluent interface like trip.Distance = database.ReadInt32("TotalDistance") .GetDefaultOrEmpty() .MetersToDistance(); MetersToDistance in this case is an extension method: public static class DistanceExtensions { public static Distance MetersToDistance(this double meters) { return Distance.FromMeters(meters); } } Operator with static class using C# 6 brings us a new language construct. Now we can import a static helper class using static Units.Constants; And then we can write something like var distance = 10.0 * km; where km is defined in that static class: public static class Constants { public static readonly Distance km = Distance.FromKilometers(1.0); } This may not look like idiomatic C#, but I think it's very good at least for writing unit tests: var target = new Trip { DistanceOnFoot = 5 * km, DistanceOnBicycle = 10 * km, DistanceOnCar = 30 * km }; target.TotalDistance.Should().Be((30 + 10 + 5) * km); For this to compile you just need to define the operator overload: public static Distance operator*(int value, Distance distance) { return Distance.FromKilometers(value * distance.Kilometers); } Conversion and printing More advanced unit conversions are easy with unit classes. A common use case would be to convert metric units to imperial system. All you need to do is to add another calculated property // Distance class private const double MilesInKilometer = 0.621371192; private const double FeetInMeter = = 3.2808399; public double Miles => this.Kilometers * MilesInKilometer; public double Feet => this.Meters * FeetInMeter; Another common task is printing (formatting) unit values into string. While you can (and should) implement some basic version of it in ToString() method, I advise against doing all the formatting inside the unit class. The formatting scenarios can be quite complex: - Format based on user preferences (metric/imperial) - Pick units based on the value (e.g. 30 m but 1.2 km, not 1200 m) - Localization to different languages - Rounding to some closest value If you do all that in the unit class, it's going to violate the single responsibility principle. Just create a separate class for formatting and put all those rules there. Unit derivation Once you write more unit classes, you will definitely want to derive the calculation result of two units into the third one. In our example, we want to divide Volume of fuel used by Distance to get fuel ConsumptionRate. There's no magic that you could do here. You will have to define ConsumptionRate class the same way you defined the other two, and then just overload the operation public static ConsumptionRate operator/(Volume volume, Distance distance) { return ConsumptionRate .FromLitersPer100Kilometers(volume.Liters * 100.0 / distance.Kilometers); } Of course, you'll have to define all the required combinations explicitly. If you defined Constants as described above, you'll be able to instantiate values in your tests in the following way: var fuelRate = 7.5 * lit / (100 * km); Should I use 3rd party libraries for that? It depends. Of course, people implemented all this functionality about 1 million times before you, so there are numerous libraries on GitHub. I would say, if you start a new project and you don't have a strong opinion about the unit code, just go grab the library and try to use it. At the same time, for existing code base, it might be easier to introduce your own implementation which would resemble something that you already use. Also, I have another reason for my own implementation. I'm using units all over the code base of domain logic, the very heart of the software, the exact place where I want full control. I find it a bit awkward to introduce a 3rd party dependency in domain layer. Like this post? Please share it!
https://mikhail.io/2015/08/units-of-measurement-in-domain-design/
CC-MAIN-2018-09
refinedweb
1,229
55.44
Contents: Using Thread Objects Synchronizing Multiple Threads Threads provide a way for a Java program to do multiple tasks concurrently. A thread is essentially a flow of control in a program and is similar to the more familiar concept of a process. An operating system that can run more than one program at the same time uses processes to keep track of the various programs that it is running. However, processes generally do not share any state, while multiple threads within the same application share much of the same state. In particular, all of the threads in an application run in the same address space, sharing all resources except the stack. In concrete terms, this means that threads share field variables, but not local variables. When multiple processes share a single processor, there are times when the operating system must stop the processor from running one process and start it running another process. The operating system must execute a sequence of events called a context switch to transfer control from one process to another. When a context switch occurs, the operating system has to save a lot of information for the process that is being paused and load the comparable information for the process being resumed. A context switch between two processes can require the execution of thousands of machine instructions. The Java virtual machine is responsible for handling context switches between threads in a Java program. Because threads share much of the same state, a context switch between two threads typically requires the execution of less than 100 machine instructions. There are a number of situations where it makes sense to use threads in a Java program. Some programs must be able to engage in multiple activities and still be able to respond to additional input from the user. For example, a web browser should be able to respond to user input while fetching an image or playing a sound. Because threads can be suspended and resumed, they can make it easier to control multiple activities, even if the activities do not need to be concurrent. If a program models real world objects that display independent, autonomous behavior, it makes sense to use a separate thread for each object. Threads can also implement asynchronous methods, so that a calling method does not have to wait for the method it calls to complete before continuing with its own activity. Java applets make considerable use of threads. For example, an animation is generally implemented with a separate thread. If an applet has to download extensive information, such as an image or a sound, to initialize itself, the initialization can take a long time. This initialization can be done in a separate thread to prevent the initialization from interfering with the display of the applet. If an applet needs to process messages from the network, that work generally is done in a separate thread so that the applet can continue painting itself on the screen and responding to mouse and keyboard events. In addition, if each message is processed separately, the applet uses a separate thread for each message. For all of the reasons there are to use threads, there are also some compelling reasons not to use them. If a program uses inherently sequential logic, where one operation starts another operation and then must wait for the other operation to complete before continuing, one thread can implement the entire sequence. Using multiple threads in such a case results in a more complex program with no accompanying benefits. There is considerable overhead in creating and starting a thread, so if an operation involves only a few primitive statements, it is faster to handle it with a single thread. This can even be true when the operation is conceptually asynchronous. When multiple threads share objects, the objects must use synchronization mechanisms to coordinate thread access and maintain consistent state. Synchronization mechanisms add complexity to a program, can be difficult to tune for optimal performance, and can be a source of bugs. The Thread class in the java.lang package creates and controls threads in Java programs. The execution of Java code is always under the control of a Thread object. The Thread class provides a static method called currentThread() that provides a reference to the Thread object that controls the current thread of execution. References Thread The first thing you need to do to make a Thread object useful is to associate it with a method you want it to run. Java provides two ways of associating a method with a Thread: For example, if you need to load the contents of a URL as part of an applet's initialization, but the applet can provide other functionality before the content is loaded, you might want to load the content in a separate thread. Here is a class that does just that: import java.net.URL; class UrlData extends Thread { private Object data; private URL url public UrlData(String urlName) throws MalformedURLException { url = new URL(urlName); start(); } public void run(){ try { data = url.getContent(); } catch (java.io.IOException e) { } } public Object getUrlData(){ return data; } } The UrlData class is declared as a subclass of Thread so that it can get the contents of the URL in a separate thread. The constructor creates a java.net.URL object to fetch the contents of the URL, and then calls the start() method to start the thread. Once the thread is started, the constructor returns; it does not wait for the contents of the URL to be fetched. The run() method is executed after the thread is started; it does the real work of fetching the data. The getUrlData() method is an access method that returns the value of the data variable. The value of this variable is null until the contents of the URL have been fetched, at which time it contains a reference to the actual data. Subclassing the Thread class is convenient when the method you want to run in a separate thread does not need to belong to a particular class. Sometimes, however, you need the method to be part of a particular class that is a subclass of a class other than Thread. Say, for example, you want a graphical object that is displayed in a window to alternate its background color between red and blue once a second. The object that implements this behavior needs to be a subclass of the java.awt.Canvas class. However, at the same time, you need a separate thread to alternate the color of the object once a second. In this situation, you want to tell a Thread object to run code in another object that is not a subclass of the Thread class. You can accomplish this by passing a reference to an object that implements the Runnable interface to the constructor of the Thread class. The Runnable interface requires that an object has a public method called run() that takes no arguments. When a Runnable object is passed to the constructor of the Thread class, it creates a Thread object that calls the Runnable object's run() method when the thread is started. The following example shows part of the code that implements an object that alternates its background color between red and blue once a second: class AutoColorChange extends java.awt.Canvas implements Runnable { private Thread myThread; AutoColorChange () { myThread = new Thread(this); myThread.start(); ... } public void run() { while (true) { setBackground(java.awt.Color.red); repaint(); try { myThread.sleep(1000); } catch (InterruptedException e) {} setBackground(java.awt.Color.blue); repaint(); try { myThread.sleep(1000); } catch (InterruptedException e) {} } } } The AutoChangeColor class extends java.awt.Canvas, alternating the background color between red and blue once a second. The constructor creates a new Thread by passing the current object to the Thread constructor, which tells the Thread to call the run() method in the AutoChangeColor class. The constructor then starts the new thread by calling its start() method, so that the color change happens asynchronously of whatever else is going on. The class has an instance variable called myThread that contains a reference to the Thread object, so that can control the thread. The run() method takes care of changing the background color, using the sleep() method of the Thread class to temporarily suspend the thread and calling repaint() to redisplay the object after each color change. References Runnable; Thread As shown in the previous section, you start a Thread by calling its start() method. Before the start() method is called, the isAlive() method of the Thread object always returns false. When the start() method is called, the Thread object becomes associated with a scheduled thread in the underlying environment. After the start() method has returned, the isAlive() method always returns true. The Thread is now scheduled to run until it dies, unless it is suspended or in another unrunnable state. It is actually possible for isAlive() to return true before start() returns, but not before start() is called. This can happen because the start() method can return either before the started Thread begins to run or after it begins to run. In other words, the method that called start() and the new thread are now running concurrently. On a multiprocessor system, the start() method can even return at the same time the started Thread begins to run. Thread objects have a parent-child relationship. The first thread created in a Java environment does not have a parent Thread. However, after the first Thread object is created, the Thread object that controls the thread used to create another Thread object is considered to be the parent of the newly created Thread. This parent-child relationship is used to supply some default values when a Thread object is created, but it has no further significance after a Thread has been created. A thread dies when one of the following things happens: The stop() method of the Thread class works by throwing a ThreadDeath object in the run() method of the thread. Normally, you should not catch ThreadDeath objects in a try statement. If you need to catch ThreadDeath objects to detect that a Thread is about to die, the try statement that catches ThreadDeath objects should rethrow them. When an object (ThreadDeath or otherwise) is thrown out of the run() method for the Thread, the uncaughtException() method of the ThreadGroup for that Thread is called. If the thrown object is an instance of the ThreadDeath class, the thread dies, and the thrown object is ignored. Otherwise, if the thrown object is of any other class, uncaughtException() calls the thrown object's printStackTrace() method, the thread dies, and the thrown object is ignored. In either case, if there are other nondaemon threads running in the system, the current program continues to run. References Errors; The try Statement; Thread; ThreadGroup In some situations, you need to kill a thread in a way that allows it to complete what it is currently doing before dying. For example, if a thread is in the middle of processing a transaction, you might want the transaction to complete before the thread dies. The Thread class provides support for this in the form of the interrupt() method. There are a number of methods in the Java API, such as wait() and join(), that are declared as throwing an InterruptedException. Both of these methods temporarily suspend the execution of a thread. In Java 1.1, if a thread is waiting for one of these methods to return and another thread calls interrupt() on the waiting thread, the method that is waiting throws an InterruptedException. The interrupt() method sets an internal flag in a Thread object. Before the interrupt() method is called, the isInterrupted() method of the Thread object always returns false. After the interrupt() method is called, isInterrupted() returns true. Prior to version 1.1, the methods in the Java API that are declared as throwing an InterruptedException do not actually do so. However, the isInterrupted() method does return True if the thread has been interrupted. Thus, if the code in the run() method for a thread periodically calls isInterrupted(), the thread can respond to a call to interrupt() by shutting down in an orderly fashion. References Other exceptions; Thread One of the attributes that controls the behavior of a thread is its priority. Although Java does not guarantee much about how threads are scheduled, it does guarantee that a thread with a priority that is higher than that of another thread will be scheduled to run at least as often, and possibly more often, than the thread with the lower priority. The priority of a thread is set when the Thread object is created, by passing an argument to the constructor that creates the Thread object. If an explicit priority is not specified, the Thread inherits the priority of its parent Thread object. You can query the priority of a Thread object by calling its getPriority() method. Similarly, you can set the priority of a Thread using its setPriority() method. The priority you specify must be greater than or equal to Thread.MIN_PRIORITY and less than or equal to Thread.MAX_PRIORITY. Before actually setting the priority of a Thread object, the setPriority() method checks the maximum allowable priority for the ThreadGroup that contains the Thread by calling getMaxPriority() on the ThreadGroup. If the call to setPriority() tries to set the priority to a value that is higher than the maximum allowable priority for the ThreadGroup, the priority is instead set to the maximum priority. It is possible for the current priority of a Thread to be greater than the maximum allowable priority for the ThreadGroup. In this case, an attempt to raise the priority of the Thread results in its priority being lowered to the maximum priority. References Thread; ThreadGroup A daemon thread is a thread that runs continuously to perform a service, without having any connection with the overall state of the program. For example, the thread that runs the garbage collector in Java is a daemon thread. The thread that processes mouse events for a Java program is also a daemon thread. In general, threads that run application code are not daemon threads, and threads that run system code are daemon threads. If a thread dies and there are no other threads except daemon threads alive, the Java virtual machine stops. A Thread object has a boolean attribute that specifies whether or not a thread is a daemon thread. The daemon attribute of a thread is set when the Thread object is created, by passing an argument to the constructor that creates the Thread object. If the daemon attribute is not explicitly specified, the Thread inherits the daemon attribute of its parent Thread object. The daemon attribute is queried using the isDaemon() method; it is set using the setDaemon() method. When a thread has nothing to do, it can call the yield() method of its Thread object. This method tells the scheduler to run a different thread. The value of calling yield() depends largely on whether the scheduling mechanism for the platform on which the program is running is preemptive or nonpreemptive. By choosing a maximum length of time a thread can continuously, a preemptive scheduling mechanism guarantees that no single thread uses more than its fair share of the processor. If a thread runs for that amount of time without yielding control to another thread, the scheduler preempts the thread and causes it to stop running so that another thread can run. A nonpreemptive scheduling mechanism cannot preempt threads. A nonpreemptive scheduler relies on the individual threads to yield control of the processor frequently, so that it can provide reasonable performance. A thread explicitly yields control by calling the Thread object's yield() method. More often, however, a thread implicitly yields control when it is forced to wait for something to happen elsewhere. Calling a Thread object's yield() method during a lengthy computation can be quite valuable on a platform that uses a nonpreemptive scheduling mechanism, as it allows other threads to run. Otherwise, the lengthy computation can prevent other threads from running. On a platform that uses a preemptive scheduling mechanism, calling yield() does not usually make any noticeable difference in the responsiveness of threads. Regardless of the scheduling algorithm that is being used, you should not make any assumptions about when a thread will be scheduled to run again after it has called yield(). If you want to prevent a thread from being scheduled to run until a specified amount of time has elapsed, you should call the sleep() method of the Thread object. The sleep() method takes an argument that specifies a minimum number of milliseconds that must elapse before the thread can be scheduled to run again. Sometimes it is necessary to control multiple threads at the same time. Java provides the ThreadGroup class for this purpose. Every Thread object belongs to a ThreadGroup object. By passing an argument to the constructor that creates the Thread object, the ThreadGroup of a thread can be set when the Thread object is created. If an explicit ThreadGroup is not specified, the Thread belongs to the same ThreadGroup as its parent Thread object.
https://docstore.mik.ua/orelly/java/langref/ch08_01.htm
CC-MAIN-2021-21
refinedweb
2,863
59.94
Before getting to the code I'm going to discuss the process of animating sprites. Animation in computer games is done much like it was done when the first animated cartoons came out. It is the process of repeatedly drawing one image after another to give the illusion that the image is changing. When done at an appropriate speed the person seeing the illusion will see the image changing. If you look at the image below the blue squares show the different images, or frames. There are three images in each row. The artist created the images so that you go from the first frame to the second frame to the third and then back to the first. That is the way I will be implementing the animation of the sprite. I will have a frame rate, the number of frames that will be drawn each second. I've found that five frames per second is a reasonable rate. I will be creating a class for this type of animation. You will of course want the sprite, with out the blue lines. Download the zip file below and decompress it. In version previous to XNA 4.0, right click the Content folder, select Add|Existing Item, navigate to the malefighter.png file and add it. In XNA 4.0 there is a separate content project. Right click the content project, select Add|Existing Item, navigate to the malefighter.png file and add it. Number of downloads: 466 You will now want to add in the class that controls the animation process. Right click your game project, select Add|Class. Name this class Animation. I will explain the code after you've read it. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; namespace AnimationTest { public enum AnimationKey { Down, Left, Right, Up } public class Animation : ICloneable { #region Field Region Rectangle[] frames; int framesPerSecond; TimeSpan frameLength; TimeSpan frameTimer; int currentFrame; int frameWidth; int frameHeight; #endregion #region Property Region public int FramesPerSecond { get { return framesPerSecond; } set { if (value < 1) framesPerSecond = 1; else if (value > 60) framesPerSecond = 60; else framesPerSecond = value; frameLength = TimeSpan.FromSeconds(1 / (double)framesPerSecond); } } public Rectangle CurrentFrameRect { get { return frames[currentFrame]; } } public int CurrentFrame { get { return currentFrame; } set { currentFrame = (int)MathHelper.Clamp(value, 0, frames.Length - 1); } } public int FrameWidth { get { return frameWidth; } } public int FrameHeight { get { return frameHeight; } } #endregion #region Constructor Region public Animation(int frameCount, int frameWidth, int frameHeight, int xOffset, int yOffset) { frames = new Rectangle[frameCount]; this.frameWidth = frameWidth; this.frameHeight = frameHeight; for (int i = 0; i < frameCount; i++) { frames[i] = new Rectangle( xOffset + (frameWidth * i), yOffset, frameWidth, frameHeight); } FramesPerSecond = 5; Reset(); } private Animation(Animation animation) { this.frames = animation.frames; FramesPerSecond = 5; } #endregion #region Method Region public void Update(GameTime gameTime) { frameTimer += gameTime.ElapsedGameTime; if (frameTimer >= frameLength) { frameTimer = TimeSpan.Zero; currentFrame = (currentFrame + 1) % frames.Length; } } public void Reset() { currentFrame = 0; frameTimer = TimeSpan.Zero; } #endregion #region Interface Method Region public object Clone() { Animation animationClone = new Animation(this); animationClone.frameWidth = this.frameWidth; animationClone.frameHeight = this.frameHeight; animationClone.Reset(); return animationClone; } #endregion } } I've broken the code into regions using the #region and #endregion preprocessor directives. It is just for organizational purposes, to group similar code together. There is a using statement for the XNA Framework to bring the base XNA Framework name space into scope because this class uses the Rectangle class. There is an enumeration called AnimationKey. It describes the different types of animations the sprite has. It can be down, up, left and right. You could have many more animations, like moving on the diagonals, jumping, or ducking. This class implements the ICloneable interface. The reason is you could have multiple sprites in the game that have the same lay out. It is better to store the animations in a master list of animations and return copies of them. This is a class so if you pass just the instance and you make changes it will affect the original. There are quite a few fields in this class. The first one, frames, is an array of rectangles for the source rectangles of the animation. If you look back at the image all of the animations for one direction are in the same row. The reason will become clear when I get to the constructor. The next field is an integer and holds the number of frames to animate per second. The next two fields are of type TimeSpan. They hold the length of each frame of the animation and the time since the last animation started. Using the TimeSpan structure gives you a finer degree of control over the animations than using a double or floating point value. The next field, currentFrame, is the index of the current animation in the array of rectangles. The last two fields, frameWidth and frameHeight, hold the height and width of the frames. The one downfall of this method is that all of the frames must have the same width and height. There is another method that you could use to animate the sprites but I believe this is the best approach. There are several properties in this class to expose the fields they represent. The first one is FramesPerSecond and it is used to get and set the number of frames the sprite will animate in one second. The get part is trivial, it just returns the value in the framesPerSecond field. The set part is a little more interesting. It does a little validation on the values passed in. The first check is to make sure that the value is not less than one. If it was you would get some pretty bizarre results. It also makes sure that the frame rate is not greater than sixty. This value is actually pretty high. Checking for a value of ten would probably be a better idea. After validating the values it sets the frameLength field. What is important here is you want to make sure you cast the framesPerSecond field as a double when you do the division. If you don't then integer division will be preformed and you will get either one or zero, depending on if framesPerSecond was one or not. You will often need to know what the current rectangle of the animation is so there is a property CurrentFrameRect to retrieve that. You will not only want to be able to get what the current frame is but also set it. You will again have to make sure that the value passed in is valid. I did that using the MathHelper.Clamp method which makes sure that the value is with in the minimum and maximum values, inclusive, passed in. There are also properties that get the width and height of the frames, FrameWidth and FrameHeight respectively. There are two constructors for this class, a public one and a private one. The public takes as parameters the number of frames for the animation, the width of each frame, the height of each frame, the X offset of the frame and the Y offset of the frame. The last two's purpose probably isn't obvious. If you go back to the image of the sprite sheet above you will see that it is split up into rows and columns. The first row of animations begins at coordinates (0, 0). The second row of animations begins at coordinates (0, 32). The third and forth at (0, 64) and (0, 96) respectively. As you can see as you move down in rows the Y value changes. This is the Y offset value. You could also have had the animations in two rows and two columns. In this case you would also have had an X offset. Later I will get to having more than just the walking animation and the X offset will be useful. The constructor then sets the frames, frameWidth, and frameHeight first. Then, in a for loop, it creates each of the rectangles to describe the frames for the animation. This is where the X and Y offsets become important. When you create the first animation you will be passing in the values 3, 32, 32, 0, and 0. For the second you will be passing in 3, 32, 32, 0, and 32. In the for loop to find the X coordinate in the sprite sheet for the rectangle you take the X offset and add the width of the frame times the frame counter, which is i the loop index. In this case since all of the animations or on the same row you can just use the Y offset value. The Width and Height values are set using the frameWidth and frameHeight values passed in. I then use the FramesPerSecond field to set the number of frames for the sprite to be 5. I then call the Reset method of the class which sets the animation in its starting position. The second private constructor is used when I implement the ICloneable interface. This constructor takes an Animation object as its parameter. This constructor sets the frames field of the new animation to the frames field of the old animation. It then sets the FramesPerSecond to 5 like the other constructor. There are two methods, Update and Reset, that are for controlling the animation of the sprite. The third method, Clone, implements the ICloneable interface. The Update method takes a GameTime parameter. This parameter measures how much time has elapsed since the last call to Update in the Game1 class. This is used to determine when it is time to move to the next frame of the animation. What I do is add the ElapsedGameTime property of the GameTime parameter to frameTimer. This is used to determine when to move to the next frame. It is time to move to the next frame when frameTimer is greater than or equal to frameLength so there is an if statement that checks for that. If it is you want to reset frameTimer to the zero position and move to the next frame. There is an nice mathematical formula next to calculate which frame to move to. In our case we have three frames that are at index 0, 1, and 2. If you add 1 to that you will have the values 1, 2, and 3. You then get the remainder of dividing those by the number of frames. Those values will be 1, 2, and 0. So if you are on frame 0 you will move to frame 1, from frame 1 to frame 2, and from frame 2 back to frame 0. The Reset method is very simple. It sets the current frame to be 0 and then sets the time back to 0 as well. The last method in this class is the Clone method. This method is from the ICloneable interface. This method returns a copy of the current animation. The first step is to create a new Animation object using the private constructor, passing in the current Animation object. The next step is to set the frameWidth and frameHeight fields. I call the Reset method to reset the Animation to the first frame. I then return the new Animation but the Clone method returns an object. When you use the Clone method of the Animation class you will have to cast the return value to be of type Animation. The next class I'm going to add is a class for an animated sprite. Right click your game project, select Add|Class. Name this new class AnimatedSprite. This is the code for that class. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace AnimationTest { public class AnimatedSprite { #region Field Region Dictionary<AnimationKey, Animation> animations; AnimationKey currentAnimation; bool isAnimating; Texture2D texture; Vector2 position; Vector2 velocity; float speed = 4.0f; #endregion #region Property Region public AnimationKey CurrentAnimation { get { return currentAnimation; } set { currentAnimation = value; } } public bool IsAnimating { get { return isAnimating; } set { isAnimating = value; } } public int Width { get { return animations[currentAnimation].FrameWidth; } } public int Height { get { return animations[currentAnimation].FrameHeight; } } public float Speed { get { return speed; } set { speed = MathHelper.Clamp(speed, 1.0f, 16.0f); } } public Vector2 Position { get { return position; } set { position = value; } } public Vector2 Velocity { get { return velocity; } set { velocity = value; if (velocity != Vector2.Zero) velocity.Normalize(); } } #endregion #region Constructor Region public AnimatedSprite(Texture2D sprite, Dictionary<AnimationKey, Animation> animation) { texture = sprite; animations = new Dictionary<AnimationKey, Animation>(); foreach (AnimationKey key in animation.Keys) animations.Add(key, (Animation)animation[key].Clone()); } #endregion #region Method Region public void Update(GameTime gameTime) { if (isAnimating) animations[currentAnimation].Update(gameTime); } public void Draw(GameTime gameTime, SpriteBatch spriteBatch) { spriteBatch.Draw( texture, position, animations[currentAnimation].CurrentFrameRect, Color.White); } #endregion } } There are using statements to bring a few classes of the XNA Framework into scope. There are a number of fields in this class. The first is a Dictionary<AnimationKey, Animation> to hold the animations of the sprite. I used a dictionary because you can only have one entry per key and it is easier than having to remember which animation was added when if you were to use a List<T>. The currentAnimation field is for the current animation of the sprite. The bool field isAnimating is used to tell if the sprite is currently animating so the animation should be updated in the Update method. The texture field is for the sprite sheet. The next two field are Vector2 fields and are for the position and velocity of the sprite. I will be controlling the speed the sprite moves across the screen using a motion vector. I will normalize the vector and then multiply it by a constant value, the speed field that holds the speed the sprite moves. There are properties to expose information about the sprite. CurrentAnimation is a get and set property for the currentAnimation field. The IsAnimating property is also a get and set property and is for the isAnimating field. You will often need to know the height and width of the sprite. The Height and Width properties return the height and width of the current frame of the animation. The Speed property is also get and set and exposes the speed field. The set part clamps the speed between 1 and 16 using MathHelper.Clamp. The Position property exposes the position field and is a read/write property, get/set. The Velocity property exposed the velocity field. It is get/set as well. However, the set part checks to see if the value passed in is Vector2.Zero because it normalizes the vector and you can't normalize a vector that has zero length. The constructor takes two parameters. A Texture2D for the sprite and a Dictionary<AnimationKey, Animation> for the animations. You don't have to pass a clone of the animations to the constructor as it will clone the animations passed in. The constructor sets the texture field to the texture passed in and then creates a new Dictionary<AnimationKey, Animation>. Then in a for each look it loops through all of the keys in the key collection of the dictionary passed in. Inside the loop it adds the key with a clone of the animation to the dictionary in the class. The Update takes the GameTime parameter to be able to update the animation. It checks to see if the sprite is currently animating. If it is it calls the Update method of the current animation. The Draw method takes three parameters. The GameTime parameter of our game's Draw method, a SpriteBatch between calls to Begin and End. To draw the sprite I use the overload that takes the texture for the sprite, a Vector2 for its position, a source rectangle, and the tint color. With all of these classes, we can now add in an animated sprite. You will need a couple fields in your Game1 class. You will want to check for keyboard and game pad input so you will need fields to hold the keyboard state and the game pad state. Game pad input is optional but I'm including it for those who may be interested. You will also want an AnimatedSprite field. Add these fields to the Game1 class with the SpriteBatch field. KeyboardState keyboardState; GamePadState gamePadState; AnimatedSprite sprite; Next you will want to load in the image for the sprite, create the animations for the sprite and create the animated sprite. That is best done in the LoadContent method. You can change that method to the following. protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); Dictionary<AnimationKey, Animation> animations = new Dictionary<AnimationKey, Animation>(); Animation animation = new Animation(3, 32, 32, 0, 0); animations.Add(AnimationKey.Down, animation); animation = new Animation(3, 32, 32, 0, 32); animations.Add(AnimationKey.Left, animation); animation = new Animation(3, 32, 32, 0, 64); animations.Add(AnimationKey.Right, animation); animation = new Animation(3, 32, 32, 0, 96); animations.Add(AnimationKey.Up, animation); sprite = new AnimatedSprite( Content.Load<Texture2D>("malefighter"), animations); } So, what the code does is create a new Dictionary<AnimationKey, Animation> to hold the animations for the sprite. You could have easily had this as a field if you had multiple sprites but this servers the purpose of the tutorial. The next step is to create each of the individual animations and add them to the dictionary. The animations in the sheet are the down, left, right and then up animation. There are three frames per animation and they are 32 pixels by 32 pixels. The offset for X is always 0 and the offset for Y starts at 0 then increases by 32 for each animation. After creating the dictionary I create the sprite passing in the texture and the dictionary. Now you will want the sprite to move and animate according to the player, or possibly computer controlled objects but for this tutorial the player controls the sprite. You will want to get the player's input in the Update method and based on their input move the sprite. Change the Update method to the following. protected override void Update(GameTime gameTime) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); Vector2 motion = new Vector2(); keyboardState = Keyboard.GetState(); gamePadState = GamePad.GetState(PlayerIndex.One); if (keyboardState.IsKeyDown(Keys.Down) || gamePadState.IsButtonDown(Buttons.LeftThumbstickDown)) { sprite.IsAnimating = true; sprite.CurrentAnimation = AnimationKey.Down; motion.Y = 1; } else if (keyboardState.IsKeyDown(Keys.Up) || gamePadState.IsButtonDown(Buttons.LeftThumbstickUp)) { sprite.IsAnimating = true; sprite.CurrentAnimation = AnimationKey.Up; motion.Y = -1; } if (keyboardState.IsKeyDown(Keys.Left) || gamePadState.IsButtonDown(Buttons.LeftThumbstickLeft)) { sprite.IsAnimating = true; sprite.CurrentAnimation = AnimationKey.Left; motion.X = -1; } else if (keyboardState.IsKeyDown(Keys.Right) || gamePadState.IsButtonDown(Buttons.LeftThumbstickRight)) { sprite.IsAnimating = true; sprite.CurrentAnimation = AnimationKey.Right; motion.X = 1; } if (motion != Vector2.Zero) { sprite.IsAnimating = true; motion.Normalize(); sprite.Position += motion * sprite.Speed; } else { sprite.IsAnimating = false; } sprite.Update(gameTime); base.Update(gameTime); } I first create a Vector2 called motion to hold the players input. The way I handled input certain directions take precedence over others. I find the sprite looks better if you use the horizontal animations for diagonals rather than the vertical ones. Also, the down animation takes precedence over the up and the left over the right. If I was just using the game pad I wouldn't have this problem as I can read the left thumb stick and just process that. I'm using keyboard input as not everybody has a game pad that works with Windows. The next thing I do is get the current state of the keyboard and the game pad for player one. I then check if the down arrow key is being pressed or the left thumb stick is being pushed down. If that is true I set that the sprite is animating, its animation to down, and the Y component of motion to 1 as Y increases as you move down the screen. In the else I check to see if the up arrow key is being pressed or the left thumb stick is being pushed up. If that is true I set that the sprite is animating, its animation to up, and the Y component of motion to -1. By using an or for the comparison if either, or both are true, the animation will take place. In C# if the first is true, the second is ignored as it doesn't need to be evaluated. So, if the player is pressing the down key and the left thumb stick down the sprite only moves one unit per frame instead of two. I then check if the left arrow key is being pressed or the left thumb stick is being pushed down. If that is true I set that the sprite is animating, its animation to left, and the X component of motion to -1 as X increases as you move right across the screen. In the else I check to see if the right arrow key is being pressed or the left thumb stick is being pushed right. If that is true I set that the sprite is animating, its animation to right, and the X component of motion to 1. After gathering all of the input I check to see if the motion vector is not the zero vector. Again, I'm normalizing the vector and you can't normalize a vector that has zero length. After normalizing the vector I update the sprite's position by multiplying the motion vector by the speed of the sprite. If the motion vector was the zero vector then there was no movement so I set the sprite to no longer animate. The last thing I do is call the Update method of the sprite so it will update the animation. That just leaves drawing the sprite. All I did was in between calls to Begin and End of the sprite batch is call the Draw method of the sprite passing in the game time and the sprite batch. This is the Draw method. protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); sprite.Draw(gameTime, spriteBatch); spriteBatch.End(); base.Draw(gameTime); } Well, that was a rather long tutorial on animating a sprite. It is a powerful technique and can easily be added to your games. Something you can do is have a class PlayerSprite that inherits from AnimatedSprite and handle all of your input inside of that class to keep input related to the sprite with the sprite.
http://www.dreamincode.net/forums/topic/204801-frame-animation-with-xna/
CC-MAIN-2016-44
refinedweb
3,740
57.37
...Read More » MVC is dead – what comes next? React.js, Elm, Cycle.js, and other UI frameworks introduced a new way of building user interfaces. By applying principles from functional reactive programming to UI development, they even changed how we think about user interfaces. In no time, these approaches have simply smashed the seemingly inevitable dominance of MVC and its siblings (MVP, MVVM etc.). This article, which is the first in ...Read More » Java EE 8 MVC: Global exception handling In the previous previous posts we learned about various ways to access request information (e.g. query or path parameters) in Java EE MVC. This post shows how to apply global exception handling to an MVC application. Assume we have a controller method that might throw an IllegalArgumentException: @Controller @Path("illegal-argument") public class ExceptionController { @GET public String doWork() { // code that might throw an IllegalArgumentException } } We could now add a .. » MVC 1.0 in Java EE 8: Getting started using facelets MVC 1.0 is an action-based Model-View-Controller web framework, which will be a part of future Java EE 8. It will live side by side with component-based JSF framework and will provide an alternative for building HTML+javascript oriented applications with full control over URLs. This post summarizes what needs to be done in order to use Facelets instead of default JSP .. » Three steps to follow MVC while building Java Web application Step ...Read More »
https://www.javacodegeeks.com/tag/mvc/
CC-MAIN-2017-09
refinedweb
240
56.05
Lin, There may be a way around it...i need to re-read this entire thread. will do later today. thanks, dims On 3/16/07, Lin Sun <linsun.unc@gmail.com> wrote: > Hi, thanks everyone for their input! I really like this list - it is > very friendly! :-) > > Jeff, I'd be happy to do it... a bit booked today but I should be able > to come up with a patch soon to handle the 2nd case where wsdlLocation > is specified in webservice annotation. > > As for the first case (when wsdl file doesn't exist), my understanding > is that Axis2 doesn't have such a tool with JAX-WS features. This is a > big feature, not just a bug.:-( The Java2WSDL tool is the only tool > that I am aware of in Axis2 and it doesn't do annotation. That's the > only reason why I propose to use the wsgen tool provided by sun. > > Lin > > > Jeff Genender wrote: > > Yup...filling in the PortInfo map with some of the WebService annotation > > info (minimally the wsdl location) should get us past this issue. > > > > If Lin doesn't do it I may give it a SWAG this morning. > > > > Jeff > > > > Jarek Gawor wrote: > >> If Axis2 has a tool to generate WSDL from Java code (with annotations) > >> then we should definitely used that. Hopefully, it also has good > >> programmatic API so that we can call it at runtime (or at deployment > >> time) and generate the WSDL dynamically to a file or a byte array or > >> whatever. In G we would just check if the @WebService annotation has > >> wsdlLocation attribute set (there is a bit of logic to that) and call > >> that tool only if it is not. I don't think we should do anything more > >> then that in G. That is, I don't think we should write any code in G > >> to generate WSDL from Java code. > >> > >> Jarek > >> > >> On 3/15/07, Lasantha Ranaweera <lasantha@opensource.lk> wrote: > >>> Hi Lin, > >>> > >>> I checked your email in the Axis2 dev list and I am also not sure > >>> whether this is a bug or a missing feature in the Axis2 (since I didn't > >>> go through the problem deep). If this is a bug we might able to help > >>> Axis2 source code too (as I did couple of times with my patches) ;-) . > >>> Make sure to cross link issues in JIRA in such situation. Otherwise as > >>> Jeff mentioned we might need to implement in the G side if the Axis2 > >>> doesn't have any plans of support the feature soon. > >>> > >>> Regarding your last part of reading annotations have a look at > >>> JAXWSUtils.java file comes in a org.apache.geronimo.jaxws package, I > >>> think it has a way of reading such annotations (line 86). > >>> > >>> Thanks, > >>> Lasantha > >>> > >>> Lin Sun wrote: > >>>> Hi Jeff, > >>>> > >>>> Yes I totally agree that the tool needs to be for axis2 only and > >>>> handled during deployment time! Basically, during deployment of the > >>>> module, we'll invoke the tool on the fly and generate the .wsdl file > >>>> for the user, and set the PortInfo's wsdlLocation property. Then the > >>>> code will be executed as if the .wsdl is provided by the user, which > >>>> we know works right now. I was just trying to run the tool > >>>> stand-alone first to make sure it is good for our need.:-) I'll > >>>> investigate if there is any license issue. > >>>> > >>>> Also, this doesn't cover the second scenario, when .wsdl file is > >>>> provided but the location of the .wsdl file is specified in > >>>> annotation but not in webservices.xml. In this case, we 'll need to > >>>> figure out the location of the .wsdl file from annotation (not sure > >>>> how to do that yet) and set the PortInfo's wsdlLocation property. > >>>> > >>>> Thanks, > >>>> > >>>> Lin > >>>> > >>>> Jeff Genender wrote: > >>>>> I think this is supposed to happen on deployment, not from a tool. If > >>>>> Axis is not going to handle this, then this code will need to be > >>> written > >>>>> in the Axis2 deployer for Geronimo. Currently CXF does handle > >>>>> Webservice annotations, so this type of deployment code would be an > >>>>> Axis2 only necessity. I think the PortInfo objects will need to be > >>>>> filled out before handing off to Axis2. > >>>>> > >>>>> Jeff > >>>>> > >>>>> > >>>>> Lin Sun wrote: > >>>>>> Hi Jeff/Lasantha, > >>>>>> > >>>>>> I just posted this prob on axis2-dev list [1]. Currently the > >>>>>> Java2WSDL > >>>>>> tool which is what is being used to generate the targetnamespace > >>>>>> doesn't > >>>>>> seem to handle any of the annotation stuff... not sure if it will > >>> ever > >>>>>> handle.:-( > >>>>>> > >>>>>> An alternative is to use the sun's wsgen tool provided by > >>>>>> jaxws-tools.jar to generate the wsdl file from Java in the geronimo > >>>>>> integration code. I tried to use the tool and it did generate the > >>>>>> targetnamespace correctly. > >>>>>> > >>>>>> [1]: > >>>>>> > >>>>>> Lin > >>>>>> > >>>>>> Jeff Genender wrote: > >>>>>>> Lasantha Ranaweera wrote: > >>>>>>>> Not exactly sure whether I am getting your problem exactly or not > >>>>>>>> :-( . > >>>>>>>> > >>>>>>>> Line 99 decides whether application archive contains WSDL file > >>> or not > >>>>>>>> (according to Axis2 builder). If it is there we are going to fill > >>>>>>>> WSDL > >>>>>>>> information from G side. Otherwise it will be handed over to Axis2 > >>>>>>>> side > >>>>>>>> (services with annotations). So looking at your problem regarding > >>>>>>>> annotations what I say is it should be handled by Axis2 (all the > >>>>>>>> validation & execution stuff). The annotation processing will be > >>>>>>>> handled > >>>>>>>> as a web service receives SOAP requests. Starting point for JAXWS > >>>>>>>> based > >>>>>>>> SOAP messages is receive() method of JAXWSMessageReciever. > >>>>>>>> > >>>>>>> The problem is, Axis2 is generating a wsdl upon the client request > >>>>>>> for a > >>>>>>> wsdl, and not looking at the WebService annotation to get the wsdl's > >>>>>>> location. The code step through below shows the problem clearly. > >>>>>>> > >>>>>>> > >>>>>>>> HTH. > >>>>>>>> > >>>>>>>> Lasantha > >>>>>>>> > >>>>>>>> Jeff Genender wrote: > >>>>>>>>> o.a.g.Axis2WebserviceContainer, line 99. A not-filled in > >>> PortInfo is > >>>>>>>>> passed in since G is not processing a WebService annotation, and > >>>>>>>>> thus an > >>>>>>>>> AxisService.create is called on line 104. > >>>>>>>>> > >>>>>>>>> When Axis2WebserviceContainer.getWsdl() is ultimately called, > >>>>>>>>> doService2() is called (line 212), then to processGetRequest (line > >>>>>>>>> 398), > >>>>>>>>> leading us to line 435 where the PortInfo is checked as to > >>> whether a > >>>>>>>>> wsdl file has been passed in or not. If it has, it spits out the > >>>>>>>>> wsdl. > >>>>>>>>> If it has not, then the AxisService.printWsdl() is called and > >>> that > >>>>>>>>> call > >>>>>>>>> spits out a generated wsdl. > >>>>>>>>> > >>>>>>>>> The crux here is that the PortInfo object does not have all of > >>>>>>>>> the info > >>>>>>>>> filled in such as seiClass, wsdl file, etc. That stuff would > >>>>>>>>> have been > >>>>>>>>> gotten from examining the WebService annotation. > >>>>>>>>> > >>>>>>>>> The question is, where does that examination or, should that > >>>>>>>>> examination, take place? Geronimo or Axis2? > >>>>>>>>> > >>>>>>>>> Jeff > >>>>>>>>> > >>>>>>>>> Lasantha Ranaweera wrote: > >>>>>>>>> > >>>>>>>>>> Jeff, > >>>>>>>>>> > >>>>>>>>>> Sorry for a late reply due to my time stamp difference and don't > >>>>>>>>>> know > >>>>>>>>>> exactly you have solved this problem right now or not. Anyway > >>> here > >>>>>>>>>> is my > >>>>>>>>>> comment. > >>>>>>>>>> > >>>>>>>>>> Since you haven't given me exact source code I won't be able to > >>>>>>>>>> point > >>>>>>>>>> you in to the exact source code in the Axis2. May be remote > >>>>>>>>>> debugging > >>>>>>>>>> ... ;-) . > >>>>>>>>>> > >>>>>>>>>> Thanks, > >>>>>>>>>> Lasantha > >>>>>>>>>> > >>>>>>>>>> Jeff Genender wrote: > >>>>>>>>>> > >>>>>>>>>>> Ok... > >>>>>>>>>>> > >>>>>>>>>>> I am pretty certain at this stage that the WebService annotation > >>>>>>>>>>> is not > >>>>>>>>>>> getting processed. Can you point me to the code that handles > >>>>>>>>>>> this in > >>>>>>>>>>> Axis2? > >>>>>>>>>>> > >>>>>>>>>>> Thanks, > >>>>>>>>>>> > >>>>>>>>>>> Jeff > >>>>>>>>>>> > >>>>>>>>>>> > >>>>>>>>>>> > >>>>>>>>>>> Jeff Genender wrote: > >>>>>>>>>>> > >>>>>>>>>>> > >>>>>>>>>>>> Thanks...this is very helpful. > >>>>>>>>>>>> > >>>>>>>>>>>> Then by this, looking at the PortInfo, it appears as though > >>> it is > >>>>>>>>>>>> not > >>>>>>>>>>>> stuffing in the WSDL file, which tells me it's a G thang ;-) > >>>>>>>>>>>> > >>>>>>>>>>>> Jeff > >>>>>>>>>>>> > >>>>>>>>>>>> Lasantha Ranaweera wrote: > >>>>>>>>>>>> > >>>>>>>>>>>>> Hi Jeff, > >>>>>>>>>>>>> > >>>>>>>>>>>>> To my understanding if we have given a WSDL in an archive it > >>>>>>>>>>>>> should get > >>>>>>>>>>>>> the priority than the information in the annotations. > >>>>>>>>>>>>> > >>>>>>>>>>>>> In Axis2 integration there are two parts of implementation > >>> with > >>>>>>>>>>>>> one for > >>>>>>>>>>>>> with WSDL which is mainly handling by G side while with > >>>>>>>>>>>>> annotations > >>>>>>>>>>>>> from > >>>>>>>>>>>>> Axis2. For me it is something missing in G side. > >>>>>>>>>>>>> > >>>>>>>>>>>>> Somebody in the list please correct me if I am wrong here . > >>>>>>>>>>>>> > >>>>>>>>>>>>> Thanks, > >>>>>>>>>>>>> Lasantha > >>>>>>>>>>>>> Jeff Genender wrote: > >>>>>>>>>>>>> > >>>>>>>>>>>>>> Hi, > >>>>>>>>>>>>>> > >>>>>>>>>>>>>> I have noticed when I deploy a war file (with a WSDL), I > >>> have a > >>>>>>>>>>>>>> certain > >>>>>>>>>>>>>> target name specified both in the WSDL and in the code that > >>>>>>>>>>>>>> uses a > >>>>>>>>>>>>>> WebService annotation. > >>>>>>>>>>>>>> > >>>>>>>>>>>>>> However, when I go retrieve the WSDL, I notice the target > >>> name > >>>>>>>>>>>>>> seems to > >>>>>>>>>>>>>> be munged according to the package name (backwards) of the > >>> code > >>>>>>>>>>>>>> that > >>>>>>>>>>>>>> contains the WebService annotation. > >>>>>>>>>>>>>> > >>>>>>>>>>>>>> Example... > >>>>>>>>>>>>>> > >>>>>>>>>>>>>> I have include a WSDL called Hello.wsdl that is in the war > >>> file > >>>>>>>>>>>>>> in the > >>>>>>>>>>>>>> web-inf/wsdl directory and starts with: > >>>>>>>>>>>>>> > >>>>>>>>>>>>>> <wsdl:definitions > >>>>>>>>>>>>>> > >>>>>>>>>>>>>> ... > >>>>>>>>>>>>>> > >>>>>>>>>>>>>> I have a HelloWorld.java that has this: > >>>>>>>>>>>>>> > >>>>>>>>>>>>>> package test.mypackage; > >>>>>>>>>>>>>> > >>>>>>>>>>>>>> import javax.jws.WebMethod; > >>>>>>>>>>>>>> import javax.jws.WebService; > >>>>>>>>>>>>>> > >>>>>>>>>>>>>> @WebService(name="HelloWorld", targetNamespace = > >>>>>>>>>>>>>> "") > >>>>>>>>>>>>>> public class HelloWorld { > >>>>>>>>>>>>>> > >>>>>>>>>>>>>> @WebMethod > >>>>>>>>>>>>>> public String sayHello(String me){ > >>>>>>>>>>>>>> return "Hello "+me; > >>>>>>>>>>>>>> } > >>>>>>>>>>>>>> } > >>>>>>>>>>>>>> > >>>>>>>>>>>>>> However, when I request the wsdl...I get something like this: > >>>>>>>>>>>>>> > >>>>>>>>>>>>>> <wsdl:definitions > >>> > >>>>>>>>>>>>>> ... > >>>>>>>>>>>>>> > >>>>>>>>>>>>>> Notice the targetnamespace was munged and changed from it's > >>>>>>>>>>>>>> originally > >>>>>>>>>>>>>> declared namespace of "". I > >>>>>>>>>>>>>> want the > >>>>>>>>>>>>>> one > >>>>>>>>>>>>>> that is both declared in the included wsdl (or the one > >>> declared > >>>>>>>>>>>>>> in the > >>>>>>>>>>>>>> annotation). > >>>>>>>>>>>>>> > >>>>>>>>>>>>>> Is this a facet of Axis2 or is Geronimo not passing a proper > >>>>>>>>>>>>>> PortInfo > >>>>>>>>>>>>>> object with the necessary stuff filled in? > >>>>>>>>>>>>>> > >>>>>>>>>>>>>> Any light on this subject would be greatly appreciated ;-) > >>>>>>>>>>>>>> > >>>>>>>>>>>>>> Thanks, > >>>>>>>>>>>>>> > >>>>>>>>>>>>>> Jeff > >>>>>>>>>>>>>> > >>>>>>>>>>>>>> > >>>> > >>>> > >>> > > > > -- Davanum Srinivas :: :: Oxygen for Web Services Developers
http://mail-archives.apache.org/mod_mbox/geronimo-dev/200703.mbox/%3C19e0530f0703160646i125790edr36c8ad26d5e10901@mail.gmail.com%3E
CC-MAIN-2017-22
refinedweb
1,505
65.01
Java Applets Hello friends today we learn to make Java First Applet Program or the concept of applet programming. Applet are small program that run in web browser or applet are small program that is intended not to be run on its own ,but rather to be embedded inside another program or application. The applet class must be the super class of any applet that is to be embedded in a web page or viewed by the java applet viewer. Java applet runs on client side within the browser using JRE (java runtime environment) at client machine when it’s embedded in any webpage requested by client. Applet can run under any web browser their execution is dependent on client as they require JRE. For we have to first include java.applet package and then extend Applet class to make any applet program there are three simple steps 1) Write applet code file and save with .java extension. 2) Make html file to run applet in web browser. 3) Then run the program by using i) AppletViewer tool. ii) Run html file in java enabled browser. Now friends we can start coding but before it please check these conditions 1) Is jdk is installed on your pc. 2) Is path variable for jre is set. If this condition is fulfilled then we can start coding EXAMPLE CODE 1.) Java code import java.applet.*; import java.awt.*; public class APP extends Applet { public void paint(Graphics g) { g.drawOval(50,50,75,75); } } 2.) Html code Now we have to run applet program there are two way 1) Run by using appletviewer tool. 2) Run by just open html file in java enabled browser. Save code file as APP.java. Save html file as APP.html Open cmd and compile the code file using javac command as:= javac APP.java Now run applet by code := appletviewer APP.html ::::::::::::::::::::::OUTPUT:::::::::::::::::::::::::::: 1) output of Applet by using appletviewer tool. 2) output of Applet by run html file in java enabled browser.
http://buffercode.in/java-first-applet-program/
CC-MAIN-2017-09
refinedweb
338
74.08
LLVM Clang Compiler Now C++11 Feature Complete 291 An anonymous reader writes "With the latest development work on Clang ahead of the release of LLVM version 3.3, Clang is now C++11 feature complete. The last remaining features of the ISO C++11 feature specification have been implemented. C++11 support for GCC is also more or less complete." Thank you, Apple! (Score:5, Insightful) Regardless of what you may personally think about Apple, they have made some very valuable contributions to LLVM and Clang. So I just want to say, thank you, Apple. Your generosity has touched my heart, and made C++11 a reality. Re:Thank you, Apple! (Score:5, Insightful) What makes you think it has anything to do with generosity? Assuming he's not a shill (in which case the answer would be his pay check), propaganda, stupidity and things like ESR's essay saying that the GPL is no longer needed. For a time, up to a few years ago it looked like programmers could become truly independent of the companies they work directly for, a bit like graphic artists, shop keepers, SAP specialists and so on. The basis of this would be that most companies would use the same FOSS software, sharing that from company to company. The vast efficiency gain would have been shared between the (no longer) customers of big IT companies like Microsoft and the programmers. Software would start to advance at the rate that benefitted its users, not the people stealing from them. Apple, and to a large extent Google, have come with new business models where they take the output of that process and rebundle it in a way which allows them to avoid sharing the key features which differentiate their products. In Google's case by keeping the most important bits on servers where you can't access it. In Apple's case by adding proprietary GUIs and other features which mean that nobody else can the free stuff and compete with them.. It is not a coincidence that we keep getting stories about there being lots of non-GPL software coming out etc. The shills want us to give them everything we have for free and have no need to return to the community. Correct answer: License under the AGPLv3 [gnu.org] whenever you can and only back off to the GPL or LGPL, let alone MIT licenses when someone gives you a really compelling benefit for doing so. Nothing could be more wrong (Score:5, Insightful). Nothing could be further from the truth. By basing XCode on LLWM, it makes it EASIER to write third-party tools that can properly work over the source true with the same rich understanding of context. Prior to LLVM, when XCode was based more on GCC, XCode was the only thing that understood why it was parsing code the way it was for display and code completion. Now that any tool can have access to the same AST for the code that XCode is seeing, other software can act in ways that make sense for the code. More advanced re-factoring tools are now possible, thanks in large part to LLVM... Apple could have easily just built something like LLVM into XCode and left it totally proprietary. Re:Nothing could be more wrong (Score:4, Informative) The answer to that is simple. Yes it is, but it is not the answer you gave. If Apple cared about pushing out BSD and Linux, wouldn't they put more than a token effort into OS X server? Apple doesn't need to push Linux of the desktop, because the desktop has become irrelevant. No, the simple answer is that even if you could just use all the GCC code you liked any way you wanted, the way GCC is built does not lend itself to being part of other tools. As in, it's not so easy to just parse some arbitrary code and get a sense of where the tokens are at. In reality the "huge savings" came about in writing a whole new compiler chain from scratch, which was easier overall than trying to get GCC parsing integrated into anything else! The side benefit going forward is a WAY better compiler design that can integrate new ideas very quickly, and as I said be used as part of many different tools. Re: (Score:3) Apple, and to a large extent Google, have come with new business models where they take the output of that process and rebundle it in a way which allows them to avoid sharing the key features which differentiate their products. Um what? Clang is open source. WebKit was open sourced by Apple. Under the GPL they are only obligated to release modifications to the original KHTML base code. They are under no obiligations to release JavascriptCore or WebCore but they did. Apple didn't have to hire Michael Sweet and have him keep developing cups. In Apple's case by adding proprietary GUIs and other features which mean that nobody else can the free stuff and compete with them. It means you can't use their stuff which they want to keep proprietary. But you are free to compete to develop your own. Also under the BSD license which OS X is derived, Apple doesn't eve Re: (Score:3) WebKit is based on KHTML. Sure Apple could close source their code further but then they would have to keep updating their branch to match the open fork. That takes a non-insignificant amount of time and effort. WebKit consists of KHTML code plus Apple's changes and Apple's other code. Prior to 2005, Apple did not release the proprietary parts as they did not have to. Apple did not have to release it as open source but they did anyway. They don't have to match anyone's open fork of their code if they kept it closed. Over time people will realize why a compiler shouldn't be BSD licensed. There is a reason why other BSD licensed compilers died on the vine. Every hardware vendor will want a closed fork for their own architecture which never gets updated properly. And who is stopping you from forking a competing compiler based on it? Absolutely no one. The very practical reason that Apple went with Clang/LLVM was that Objective-C development under GCC was bec Re: (Score:2) I don't see what you're complaining about. I've developed software under MIT licenses and got paid for it. Apple or someone pays LLVM developers as well. I don't like the proprietary products Apple is creating with open source software, but the solution to that is just not to buy their products and tell others not to buy their products. Re: (Score:3, Interesting) It has long been accepted fact that GPL does hurt open source in the long run. Normally I ignore obviously wrong unmoderated AC posts, however this one is an interesting example. Why would a non logged in user see my post, which is still at normal level, so quickly as to be the first person to comment? Remember that posts for logged out users sort according to moderation not time of posting. Even if this had already reached the static page it would be way down at the bottom. Why the "long been accepted fact" rather than something like a link to an argument or "it seems pretty cle Re: (Score:3) There may be a fair number of people who agree with this position, but it's never come close to being "accepted". In fact, anyone who knows the history of computing knows that originally most software was distributed under completely free licenses. That world was completely destroyed by proprietary software in the '70s and '80s and it was only the arrival of the GPL and GCC in particular which allowed, for example, the BSD operating systems to become self hosting and self sustaining. Very true, BSD has a lot to thank GCC and the GNU project for. And not just BSD. It doesn't really matter which UNIX flavor you install today, most of them include or optionally provide the GNU userland. Think about it. Why are these people trying to persuade you of something which is against your interests? Which interests? If you release your software under the BSD license you can never put it back under the AGPL. The opposite is never true. If there turns out to be a true benefit later, you can always opt to change over. The answer is simple. They want something from you. Make sure you get something in return before you give it out. Money maybe; better benefit for your and your children's future. I'm not an expert on either of those licenses, but do you really mean that you can't change BSD to AGPL? In that case that's news to me. Re: (Score:2) You can give out your virginity once only. If you licence under BSD, anyone can take your code and run with it. If you later relicence to GPL, companies can still use the earlier BSD licensed code instead of following the GPL rules. 1) If you license BSD, companies can use the code, and if they sprinkle their own code on top and distribute the software, nobody can take t Re: (Score:2) True as well, and important too that we don't forget. When we put aside our differences we find that we're all really into it for the same thing. Re: (Score:3) I've yet to see that 'fact' supported by anyone with proper understanding of the issues and no axe to grind. Re: (Score:3) Well, it is GPL software and it is effectively being redistributed to 3rd parties. Oh good, we've devolved into petty name-calling already! Re: (Score:2) What freedom would that be? Re: (Score:3) The GPL was not created for developers, it was made for the people after the developers. Re: (Score:2) The GPL allows free modification of the software, which is valuable to developers. The GPL allows non-developers to engage (hire or convince) any developer of their choice to modify the software for them. For example, take a game like SimCity [wikipedia.org], which has had all sorts of braindead problems. If this game had been released under the GPL instead, then any slashdotter who can program could have fixed a couple of the more glaring issues and made the gam Re: (Score:3) Exactly -- understanding the purpose of the GPL requires nothing more than reading RMS' very old rant about printer drivers. Re: (Score:2) Banditry? How is it "banditry"? People offer you software under some license. It's your choice whether you use it or not. Re: (Score:2) If it makes sense that the GPL should apply regardless of the particular core a piece of GPL'd software runs on, then it makes sense that the GPL should apply regardless of the particular server Re:Thank you, Apple! (Score:5, Interesting) Oh I don't think anyone thinks it's evil, just that it's pure self-interest rather than generosity. GCC's phenomenal popularity has led to its maintainers growing massive egos and behaving like total cunts. Bugs are introduced faster than Red Hat and Apple can get patches for them accepted, and they have a nasty habit of not looking at bug reports, then closing them due to inactivity without actually fixing them. Apple probably likes the idea of being able to make closed-source forks of a compiler, too. Nothing evil, but not really generous either. Re:Thank you, Apple! (Score:4, Insightful) just that it's pure self-interest rather than generosity. So what? As long as good things get done, what difference does it make what the motivations are? If anything, selfish motivations are superior because they are more sustainable. I hope that other companies look at Apple's example, and come to understand that participation in Open Source is in their self interest too. Re: (Score:2, Flamebait) Oh I don't think anyone thinks it's evil, just that it's pure self-interest rather than generosity. Which is the same reason anyone that contributes to open-source does it. Self-interest. So why are Apple being singled out? Re: (Score:3, Informative) Because the AC in the initial post in this thread did. Re:Thank you, Apple! (Score:5, Insightful) If it was purely about disappointment with the GCC maintainers and their unwillingness to fix issues, accept patches, accept features Apple needs etc etc, it would have made more sense to take the well-developed GCC codebase and fork it. Get others who are also disappointed with the slow-pace of mainline FSF GCC to start supporting the new fork too and eventually the fork will most likely either take over as the de-facto implementation (with everyone shifting to it instead of the FSF GCC ala what happened with X when everyone shifted from XFree86 to x.org) or will get merged back into FSF mainline along with promises to make things better. But of course its not just about Apple hating the GCC devs. Its also about the fact that if Apple was to continue using/developing/distributing GCC (or a number of other pieces of software such as Samba) then they would have to either fork a really old version (not a viable option) or start shipping versions new enough that they are covered under the GPL version 3. And Apple cant ship GPL3 code because of the very broad patent grant clauses in there (which Apple cant accept because it would potentially let their competitors use such as Google use some of their patents for free) Re: (Score:3, Insightful) Re:Thank you, Apple! (Score:5, Informative) Re: (Score:2) Re: (Score:3) Apply only contributes because then they don't have to spend effort every time they want to merge their private fork with the upstream. Go to WWDC and talk with the actual developers working on it. That's not the case at all. It *IS* true that Apple gains from less merging work by contributing code. But be realistic; there are real coders working on these things at Apple and just like ANY coder, they are happier the more people get to use their work. Developers that work at Apple are not mustache-twilrling Re: (Score:2) If the LLVM/Clang developers had have more forethought and picked GPL they could have forced Apple though court to release those changes. Clang was created by Apple. Why would they want to take themselves to court? Re: (Score:2) Of course there's no private fork on the web, then it wouldn't be very private. If it were so private they weren't distributing the binary, they wouldn't have to distribute the source with GPL either. And there's no secret to what clang they are distributing: clang -v Apple LLVM version 4.2 (clang-425.0.28) (based on LLVM 3.2svn) Target: x86_64-apple-darwin12.3.0 Thread model: posix Re: (Score:2) BSD (Score:2, Insightful) One of the great things about Clang and LLVM are they are BSD licensed rather than GPL. Re: (Score:2, Insightful) So are you seriously trying to start this flamewar again? Do you have nothing else to say? Re: (Score:2) Re: (Score:2, Insightful) 1) The BSD license (and similarly liberal licenses) promotes freedom for everybody, while the GPL goes out of its way to restrict freedom (namely, the freedom to not redistribute modified code).. 2) The BSD license is used by developers who are interested in creating high-quality software, rather than partaking in ideological squabbles. So people who are not interested in licensing considerations don't think about it much; a tautology. 3) The BSD license is attractive to commercial users, who often provide very valuable financial and personnel support, and who still end up contributing their work back to the community. This is true of the GPL and LGPL as well; both of which ensure that those commercial users actually do give back where t Re:BSD (Score:5, Insightful) The only freedom this limits in practice use is the freedom to profit off the work of others. Why is that so bad? If I'm writing code to share, I want others to use it. In that sense they are profiting, with code that works better/is more popular/comes out sooner. Just because some people ALSO profit monetarily should not matter to me in the slightest, again I am just happy someone could use the code I wrote. I am not a supported of IP as a concept in general but it exists; to that end GPL has succeeded in ensuring there is a workable free ecosystem that I really don't think would exist with out it. There are countless existing examples showing it does work: BSD UNIX itself, Webkit, and the very Clang under discussion. It is crazy to claim it does not work. Just because the GPL works fine as designed, does not mean a BSD approach cannot ALSO work. So people who are not interested in licensing considerations don't think about it much; a tautology. No; people who are not interested in the political aspect of licenses are forced to think about it anyway. By choosing BSD it reduces the amount of thought put into the license to the minimum, because it is the one with the greatest political freedom. This is true of the GPL and LGPL as well; As someone who writes some commercial software it is NOT true of the GPL3. It is true of the LGPL - which is why the FSF is trying to get rid of it. both of which ensure that those commercial users actually do give back No they don't. They just ensure that someone COULD legally go after them. But there are lots of violations we already see all over the place. As a company choosing the BSD is useful because you can be sure you are not in violation if someone forgets to contribute code back. People in companies who change open source code contribute back not because of the license, but because they don't want to risk changes being over-written in the future when updates are applied. It's (a) extra work and (b) (far more likely) something that has to be remembered or become process. Either way it's very likely that in a few years someone will forget and then disaster will follow. So companies have natural motivation far greater than the legal motivation to contribute source back. Yes and this is really unfortunate. In no way is it unfortunate. It's a good thing for ALL open source licenses that more people are comfortable using and sharing force. To start with, the GPL was needed to get people generally understanding that code should come back, and to provide some solid bases of code that were free. But at this point, the BSD is more useful to more fully open up companies to using open source in everything. Then after some time, the GPL can come into wider play again when companies understand that sharing source code works for everyone. So at this point BSD is doing more to help GPL than the GPL itself is. Re: (Score:2). How incredibly shorts sighted and ignorant of you. If the say ... the standard IP implementation that ... EVERYONE ON THE FUCKING PLANET users was GPL'd instead of BSD'd ... then we would have unique IP networking implementations across every OS on the planet, assuming that the Internet would exist yet in the first place since Cisco isn't going to jump on your GPL'd protocol since they can't do nearly as much neat tricks to make them a viable company. Its sad that you don't realize what a chilling effect GPL Re: (Score:2) We do, actually. The BSD TCP/IP stack isn't actually a part of windows. None? Or do you mean, "acceptance by companies that are willing to take but unwilling to contribute"? Care to come back when you're capable of coming up with an actual point rather than a spittle-flecked rant with little substance? Re: (Score:2) Or do you mean, "acceptance by companies that are willing to take but unwilling to contribute" There's nothing intrinsically wrong with being willing to take but unwilling to contribute, as long as the software's author is okay with that. Since software is free to replicate, it doesn't hurt the software's author or anyone else if a company uses it, and it might even help (e.g. if more companies use the software, it allows the software to be more thoroughly tested and debugged, and may help it become a de facto standard). That said, if the author of the software doesn't like "freeloaders", the author Re: (Score:2) If the say ... the standard IP implementation that ... EVERYONE ON THE FUCKING PLANET users was GPL'd instead of BSD'd ... then we would have unique IP networking implementations across every OS on the planet First of all, we do have unique IP networking implementations across most OSes on the planet. Second, the spread of that particular implementation was a disaster anyway because the BSD sockets interface sucks. Ever seen Plan 9 interface? But no, now we have a "universal" API...doesn't matter that it sucks, as long as it's "universal". ...or not? Re: (Score:2) Neither option is always suitable for everybody.. Re: (Score:2) BSD in no way takes options away downstream. Everyone will have access to the BSD code. You may not get access to some new code that was combined with it ... but that code was never BSD code ... you never had access to it ... nothing was 'taken away from you' because you didn't have it in the first place. GPL doesn't 'keep people from taking things away from you' it forces them to give it to you. If you think GPL is about freedom, why is it such a long list of restrictions compared to AT WORST, the 4 a BSD lic Re: (Score:2) I hate feeding worthless trolls, but here goes anyway: You aren't forced to give away your source. If you're going to make modifications to GPL code, you should be fully aware of what the terms of redistribution are. Anything else means you're a damned, willful fool. And? Don't enter a contract if A long time FSF supporter disagrees with you (Score:5, Interesting) I hate feeding worthless trolls, but here goes anyway: As a GPL supporter, I must protest that your arrogance does not reflect the views of all of us. You aren't forced to give away your source. That's pretty much the whole point of the GPL. Source changes you make MUST be contributed back. Yes it's nice for the ecosystem but it's an onerous legal burden that you can easily get wrong if you forget something. Why have that kind of legal exposure if you don't have to? That's what companies are thinking when looking at both licenses. You are writing as if companies and even individual coders are operating in the legal climate of 20 years ago; we are not. And? Don't enter a contract if you don't want to be bound by its terms. AND that is the reason why so many are choosing BSD now. Because they don't. Are you the sole arbiter of such things? How is pointing out plain fact being an "arbiter" of anything? He is pointing out quite accurately how changing code in a BSD code base gives you more options than changing code in a GPL code base. If you claim otherwise you do not even understand the point of the GPL, never mind the exact legal conditions it adds. On the contrary, the GPL guarantees freedom I have been a member of the FSF for decades now. I fully support RMS in any discussion that arises. You are wrong. It does NOT guarantee freedom for people actually writing code. It binds them in specific ways. Now those ways are practically helpful for future users, but in no sense is anyone getting "more freedom" from a license that is specifically restrictive. Even though future users technically gain some freedom to use code from people who contributed (which is what you really mean but obscure by trying to change the definition of freedom to your own), they give back any gains they had because (a) people who would have written code not being able to contribute to that project because of the license, and (b) they lose any freedom to make further changes without contributing back. Oh good, you preserved this little lie. That was the only part I really agree with. You can easily make money using open source software and contributing back. It just happens to be much easier to do so using code with BSD licenses (even when you are giving back in either case). As a consultant MOST companies (nearing 100%) will not let me use GPL code when writing for them, but they will let me use BSD without issue - even though I explicitly add in any consulting contract that any modifications I make must be contributed back to any open source code I modify. The companies don't care about library changes going back, I've not had one company care about that. What they ALL care about is the legal danger of having all code they have worked on having to be released because any component is GPL, or possibly just being sued because of any change made to a GPL module by some later low-level maintainer. THAT is the REALITY on the ground of where the GPL is today. Typical trolling AC, leading on for a while and blow it with a personal attack. I'm not posting AC, I'm posting with the weight of being a full-time software developer for decades who has worked with, and contributed code to open source code with all kinds of licenses for years. Just to warn you I have no intention of reading anything further you write as I'm sure it will simply be more insults directed at me. I just wanted an impressionable younger generation to realize that your nonsense, arrogance and general ugliness does not reflect the views of all FSF and GPL supporters. Really you CAN support the GPL without some kind of maniacal world-view wherein restrictions are really freedom. There is still a valid point to the GPL, it was especially useful many years ago top open up people to the idea of open source. But that works is done and we are in a new phase where to spread TRUE freedom the GPL has to sit back for a while and let the BSD soften up ground it cannot reach. At some point in the future it will be possible to layer back in more GPL use, but that time has not yet come. Consider my points again. (Score:4, Insightful) You are not a GPL supporter you are an astroturfing troll. Go away. I have supported free software, and RMS specifically, on Slashdot for years. If I am astroturfing, for who? And why would I do that for decades? Instead I am exactly what I say - a long-time software developer, currently an iOS consultant but before that an IT developer for over a decade and also a computer science graduate, who has cared deeply about the programming industry as a whole for a long, long time. I will not go away because other people need to know practical realities that all too many people on Slashdot want to ignore. I am here to help inform and guide those that people stuck in their ways would mislead. I would insult you in return at this point but the topic is too profoundly important for insult. Nobody is forcing you to benefit from my work. If you want to use my work in your product without obeying the GPL Why are you overlooking the many points I made? 1) I don't want to benefit from your work without obeying the GPL. As I said in all my contracts I explicitly state that any code changes I make to open source libraries I am allowed to send those changes back in. In summary to be very clear, I WANT to send you back changes and obey the GPL. That is 100% not the problem in anything I've ever run across. 2) As I stated the real problem is that a company or client does not want the legal exposure - even if they INTEND to give you back all changes, mistakes happen and they may simply forget. Far more likely is that in five years, someone maintaining the code base will not realize they are in a GPL protected portion of code (because it is VERY easy to stop in a debugger and change a line of code without looking at the header) and then also they have made a change they were supposed to contribute back and now have not. So there is an endless source of potential liability that they simply do not have with BSD code, where the expectation is that code will be given back but nothing will happen if you don't or forget. 3) Some changes never make it back but they are not from people who would have used your GPL code anyway; in the meantime you DO get many changes back from people who also would not have used your GPL code but like to contribute changes. 4) Nobody is forcing me to use your work. But you are forcing me to take on legal responsibility if I choose to use your GPL'ed work, beyond the mere technical effort needed to integrate your code. In my own code for my own company I do not mind at all using GPL code but for many other companies that is simply a non-starter, so your code just does not get used. You need to think about it from your side; are you producing the code to help people or not? I BSD license my own code because the reason I share is only to help others, not for the drive to have others grow my project. I don't care if parts of my code get folded into other things, or enhanced beyond all recognition into a thing of beauty that I will never see. The important part is that I helped in some way to make that possible; to for a brief time stand against entropy and for progress. Basically the problem is less with the GPL, and more with the legal climate in the U.S. especially (but really the whole world now) that is making the GPL less practical to use. Under such conditions the BSD works better as an explicit promise that you want other people to enjoy code and you have no intent or (much more importantly) CAUSE to sue someone who likes your code. It still communicates the desire that people send changes back; it just does not impose a non-technical and therefore unwelcome burden on the user. In fact it specifically relieves them of that unwelcome burden that is present in almost any other case! Re: (Score:2) Indeed. I'm a bigger fan of the GPL in most cases, but there is room enough in the world for both camps (crazy talk, I know). Now you have your compiler under a suitable license for you and your fellow travelers. Re: (Score:2) GPL is probably a better license for a compiler, if only because it prevents the stupid proliferation of proprietary extensions that have plagued the compiler market. Re: (Score:2) Re: (Score:2) I work for a MIPS vendor (Cavium) and I know we push almost all of our extensions upstream and we ship very recent versions to customers. We're currently shipping 4.7 to customers. This includes support for the Cavium OCTEON proprietary assembly instructions as well (encryption, hashing, load/store indexed and atomic instructions). There is a lot of active GCC development where I work and in fact we are looking for more GCC developers for both MIPS and ARM. Similarly we work hard to push all of our stuff ups Re:BSD (Score:5, Insightful) What exactly is the advantage of a BSD license for a compiler? Re: (Score:2) You can freely distribute clang. You can contribute back to clang. It's probably easier to contribute back since the code isn't a monolithic mess. It makes no difference to me as a user whether my compiler is GPL or BSD licensed. But those license decisions affect the compiler architecture which affects the compiler. Clang/LLVM are modular for technical reasons. They don't care if you "steal" a component. GCC is monolithic for political reasons. RMS is afraid you'll use it without giving back. What Re: (Score:2) GCC is monolithic for political reasons. RMS is afraid you'll use it without giving back. How does the design of GCC prevent anyone from *using* it without giving back? Re:BSD (Score:5, Interesting) Well the GPL specificly isn't a problem here, however it is really nice to have an alternative to GCC that actually encourages and facilitates reuse of their code rather than one that puts up deliberate obsticles to reuse even by other free software projects. One of the big reasons that CLang was created was because there were some free software developers that wanted to integrate high quality front-ends (parser, etc) into other projects like IDEs, LLVM, and such. They prefered to work together with GCC to share the effort, but GCC refused. They were so paranoid about proprietary applications using GCC code that they refused to seperate the front-end into a GPL library that GPL applications could use. Their rational was that someone could easily write a GPL wrapper application around that GPL library that just serialized the data to/from a text representation, which could then be legally used with a proprietary application. In their mind, it was more important to make it difficult for proprietary applications to use their code than to make it easy for free software to use their code. So LLVM was forced with the decision to either fork GCC or write their own. GCC was never designed with front-end modularity in mind, and a lot of changes would be necessary to do so. Once that massive refactoring was complete, it would be difficult to share improvements between the two codebases. Between that and some compelling technical reasons they chose go write their own and CLang was born. Re: (Score:2) For most of us it doesn't matter at all. Re: (Score:2) Well they didn't exactly "switch" to Clang. They created Clang. Re: (Score:2) Maybe the IDE vendors should release their software under a compatible license. Profit! OpenMp (Score:2) Re: (Score:2) More complete? (Score:3) How can something be more Complete? I can understand less complete. Does this imply knowledge of the future? Just wait until... (Score:3) The next version will be NP-complete. Re: (Score:2) This kind of comment is what keeps me coming back to /. - It's pedantic - The editors never edit out basic typos, let alone subtle grammar or phrasing - It's the first post to be modded up - You must be new here Thanks goombah99, keep up the good work! Re: (Score:2) P.S. Sheldon Cooper is that you? Is there an in-print specification of C++11? (Score:2) Re: (Score:2) The fourth edition of The C++ Programming Language with c++11 coverage will come out next month. (ISBN: 978-0321563842) There are already general books on c++ that cover the new standard, like C++ Primer 5th edition. C++11: language and library? (Score:2) The standard specifies compiler behavior and the run-time library behavior. I know GCC has been pretty up to date with respect to the language features, but there are still some "Partial" and "No" entries in the run-time library implementation's C++11 status [gnu.org]. Is Clang's library implementation complete with respect to the C++11 standard? Re:Linux (Score:5, Interesting). GCC just became too popular for its own good, and that inflated the egos of the maintainers to the point where they don't give a shit about users. CLANG is still in the state where it's fighting for market share, so they have to care about users to get any traction, but if it becomes popular enough, it will probably go the same way as GCC. Going slightly off-topic, Apple (principal CLANG contributor) is a lot like GCC. Back when they had almost no market share, they actually cared about users and did awesome shit. But now they have some traction they're a bunch of cunts. Tiger was a questionable update, and every OSX update since has been a load of shit. Mountain Lion makes the UI really annoying, and OSX Server is now completely useless. Final Cut Pro X is a steaming turd when the old Final Cut Pro was best in class software. Old iMovie wasn't great but it was usable. New iMovie has destructive editing, no proper timeline, and is completely useless for any half serious work. And they've made it so you can't run old iMovie or Final Cut on new versions of OSX, and you can't run old OSX on new machines. I'm waiting for them to do the same thing to Logic. Even Microsoft kind of cared about users back when they were the underdog. They developed customised BASIC implementations for all the microcomputer manufacturers, DOS was for the most part better than CP/M '86, and Office for Mac kickstarted the platform. Everyone knows where market domination led them. TLDR: market domination is the worst thing that can happen to anyone. Re: Linux (Score:3) The phenomenon is not just restricted to IT companies. It's the borken part of human nature. Te Greeks calledit 'hubris'. Re: (Score:2). Or maybe it's just another sign of Sparc/Solaris' slide into... well, not irrelevancy but a hardware/software niche that neither developers or maintainers actually have. OpenSolaris is gone, Oracle is probably not doing much if anything to support GCC so how much of it is added hubris and how much of it is increasing obscurity? I just tried a search for SPARC on eBay and ignoring parts there's maybe 150 servers for sale. That's somewhat more than Commodore 64 and Amiga 500, but it's still rare/vintage. Yes, Re: (Score:2) If only there was a company whose job was to make gcc/gdb ports to every platform on earth, with contracted deals with the platform makers (Intel, Sun, Sega, Sony, Hitachi, etc.) ... such that gcc provided C, C++, and even some Objective-C support, uniformly across platforms, with as much platform specific optimization as possible. Oh... wait. There was such a company. Until Redhat bought them and killed them. (Cygnus Support / Cygnus Solutions, purchased by Redhat in very late 1999/ early 2000 because RH w Re: (Score:2) Speaking as someone who actually attempted to hack on GCC in the past (and who actually has a copyright assignment on file with the FSF) I concur with your statements about how crap GCC development has become. I wanted to add Windows thread-local-storage support to GCC (the OS-level logic behind the Visual C++ __declspec(thread) keyword) and even understanding the mess that is the GCC codebase was annoying, let alone trying to find out the right way to get the code to output the necessary assembler into the Re: (Score:2) I use "__thread" in gcc. Did that not work for you? Re: (Score:2) Tiger was a questionable update, and every OSX update since has been a load of shit. Point of order: Snow Leopard was actually pretty good. It may be the best OS/X of all of them, in fact. Re: (Score:2) Re: (Score:2) Final Cut Pro X is a steaming turd when the old Final Cut Pro was best in class software. Honestly, I know a lot of video editors (I'm not one of them) who would not consider Final Cut Pro best in class. They complained about it constantly. Strangely enough, those are the same people who complained about FCPX. Most of the people who are complaining FCPX switched to Premiere a years ago, and complain constantly even though they're not using FCPX. It's mostly to continue justifying their transition to Premiere when FCS got long in the tooth. "Well of course I made the right choice in switching to A Re: (Score:3) How on earth are you going to have threads in DOS? The same way you always have the same way its done on every embed platform. A private to your application threading model. There is nothing to stop you from implementing any kind of scheduling your want on top of DOS as it does not do any, and nothing that will stop you from doing whatever you like with interrupts, software or otherwise. You also have the long long int type, where if you need to use that on a 32bit system, it will need emulated yes. Just like what used to be done for floats and 32-bit values on x86 DOS platforms. Re: (Score:3) It also becomes harder to build a working compiler for anything other than Linux Now, it is even less possible. I like to bring up DOS as an example that can't even fit the paradigm of the C++11 specification. How on earth are you going to have threads in DOS? This can be done with user space threads [wikipedia.org] You also have the long long int type, where if you need to use that on a 32bit system, it will need emulated long long int existed as for quite some time, gcc and msvc support in on 32 bit platforms. Re: (Score:3) Re: (Score:2) 32 bit shared-libs (yes, moving to a unix-ish architecture) What part of shared libs is related to UNIX other than 'yes, it supports it'. What OS doesn't support shared libs? Since it doesn't have to be a function of the OS any more than threading does, I don't see how such a statement is relevant. DOS supports DLLs too you know. Re: (Score:2) It seems you're really arguing that some of the releases had some deprecations that you didn't like (nothing you listed affected our company at all--I applauded deprecation of AppleTalk!) and some that effected a relatively small number of users (I'd never heard of anything you mentioned). Every Apple point release I've ever used has had some bugs--hardly unique to post-Tiger. I would argue that OSX 10.0, 10.1, and 10.2 were effectively betas that lacked critical features and were not usable in production en Re: (Score:2) I do, incidentally, feel that 10.4 was the pinnacle of OSX GUI. We still have one PPC 10.4 (dual 1.25ghz G4--tells you how old the machine is!) running 24/7 for a server app that has some PPC-only extensions -- so no rosetta. I VNCed in the other day and it has such a pleasant appearance compared to flat monochrome grey crap in post-Lion OSX. Re: (Score:2) Re: (Score:2) Torvalds only cares about the kernel, and some diving app. A distribution can chose any userland it wants. This Entire Thread (Score:2) Re: (Score:2) Ironically mirroring gcc itself.... Re: (Score:3) Re: (Score:3) I don't see why C++ needs language-based or standardized garbage collection support The C++ standard doesn't specify GC, it merely relaxes the constraints on when destructors are called and when memory is reclaimed in such a way that an implementation using garbage collection is now possible. This is more a standard library issue than a compiler one, although in theory a compiler might use GC-managed storage for objects with automatic storage. This support basically means that if you take C++ code and link it against the operator new() implementation provided by the Boehm GC it remains a Re: (Score:2) Re: (Score:2) It's likely to be very difficult, depending on how the GC is implemented. It would be easy to mix if you don't share objects between thread, but then you may as well use different processes. Mixing different GC policies in a single application is usually quite difficult, but it's possible if your primitive operation is reference counting and you create a full GC by adding concurrent cycle detection. You can then control at different granularities when the cycle detector is run. This gives you realtime a Re: (Score:2) I don't have a problem with the standard allowing for garbage collection, but I'm curious what types of real-world use cases make GC for C++ more convenient that explicit storage management? The combination of STL and destructors-free-memory (on the frew occasions you need non-STL datastructures) seems convenient enough to me. Re: (Score:2) OK - Thanks. I guess reference counting would work in those situations too. An alternative to GC would be an STL replacement with reference count-based destruction. Re:except for garbage collection (Score:5, Interesting) I don't see why C++ needs language-based or standardized garbage collection support. Well, I wrote my own Hash Map implementation. Before that I had my own Linked Lists too. Before C++ came along I even maintained my own OOP implementation in C with a spiffy pre-processor to convert syntactic sugar into the equivalent ugly object oriented C code riddled with namespace prefixes, indecipherable pointer math for dynamic (virtual) functions (actions), and statically complied variable (property) look-up tables for run-time type inspection (reflection). It led to incompatibilities between codebases -- My Entities+C wouldn't be compatible with your C+OOP. Hell, we didn't even use the same terminology, or necessarily even support the same feature sets. The point is, I wasn't the only one who was doing that (see also: Objective C). There were lots of us, it was a huge waste of duplicated effort. So many, in fact, that C++ was born, and the STL too, And now C++11 has Hash Maps, I don't need to maintain my own going forward (use unordered_map). This means I don't have to worry if the hashmap implementation I used is compatible with another library's or if it'll run on another compiler or what its performance guarantees are. I can just use the language implementation -- which while not always optimal, is usually good enough -- and if I need to I can implement my own version tailored for my specific use case. So The same reasoning is used for including a garbage collector / local memory pool management. Calling into the kernel code every allocation / deallocation of dynamic memory is slow. Yeah, you can override the new operator and/or create your own replacement allocator, but here's the thing: You can add OOP to C, and build your own collection APIs too. That's lame boorish work, not really beneficial to create that if we can avoid doing so, since the program itself typically isn't enmeshed deeply with the memory management details. We're better off if GC is already done, standardized, tailored to work well within the system we're compiling on, and completely optional for folks like you who would rather jump a codebase to a whole new language rather than add a GC... Maybe once you've written a few GCs in C++ more times than you care to count then you'll have a different perspective -- Oh, but wait, we don't need your perspective, it's in the standard. The feature we all decided we should have will be supported. I think you're underestimating the kinds of applications where we could use such features, or the actual need / demand of the feature itself, and even the "level" of the language as you define it I find suspect. I mean, C++ is right up there with the highest of the high level languages, bucko. EA (the game company) created their own STL replacement basically just to add a GC and hashmaps, because they were tired of reimplementing these features IN EVERY DAMN GAME. Now, games aren't the only applications being made, but you get the point. EA didn't employ the only set of programmers doing this -- Take me for example. That is to say, I write bytecode interpretors & VMs for my compilable embeddable languages that are little more than macro assemblers during their 1st iterations. That's low level coding, sometimes even translatable into machine code (depending on the language) and even a few of the ASM-like languages I've made have garbage collection built in. That is to say: GC is not a bullet point that exclusive to any "level" of programming language. I'd consider it a BASIC feature. Re: (Score:2) malloc does not call into the kernel. Re:except for garbage collection (Score:4, Interesting) The most unfortunate thing with the latter case is that when you really attempt to treat it like compiled Javascript, the gotchas with C++ is long enough to fill a thick book (literally). Re: (Score:3, Insightful) C++ is now split into two factions; low-level C++ where you use it like C with classes, and high-level C++, where the language is treated like compiled javascript. What you mean by "split"? The main advantage of C++ is that it provides so many levels and paradigmas that one can smoothly shift the code around at a large scale, either in space or time. This also allows for real refactoring of the code and introducing new conceptual levels "inside" the language. Re:except for garbage collection (Score:4, Insightful) You didn't mention the actually good way to use C++. Expose elegant and easy to use interfaces that hide all the tricky optimizations that were required for performance. The business logic or your library clients never see a pointer. At the same time you are unconstrained about what you can do when you need to. The only way you can do that in most languages is to write the optimized code in one language, like C or assembler, and the high level code in some other language. Huge problem there is the overhead of cross-language dispatch (at minimum, no inlining) which means that the operations you expose have to be coarse grain and you have to somehow deal with accessing foreign memory layouts or you have to copy data. C++ simply doesn't have these problems. Templates is a huge feature designed in part for safety, but more-so to allow an extremely fine grained interface to your optimized code with no performance penalty. Migration of code is also no problem since your optimized and inefficient code are in the same language. You may have just been only exposed to poor C++ programmers, but more likely I think you simply do not have a full appreciation for what can be done in C++. Re: (Score:2) From my own benchmarks, clang behaves like gcc at one optimization level lower, both for compilation speed and speed of the resulting binary. It's support for C++ has been rife with bugs, but things have improved a lot, so clang gets roughly close to gcc (other than highest, rarely used levels of optimization), except for two areas: warnings (clang produces tons of bogus ones), and portability (clang supports only i386, amd64, 32 bit arm, big-endian mips, s390, while gcc does pretty much everything). Re: (Score:2) The most special cased POS I have seen in a long time. To be fair, any compiler is eventually going to end up reflecting the qualities of the language it is compiling. :P Re:Executable performance (Score:4, Interesting) I wish I knew what specific optimizations give MSVC its performance gains. What I do know is that it''s not trivial. For encryption and compression libraries, MSVC compiled libraries give me a 20% speed gain over GCC. I really want to supply my projects built with a completely open-source tool chain, but I can't justify taking that kind of performance hit for that. I suspect MSVC produces better performing code less because of any one particular optimization and more because it is way more tightly coupled with the x86/AMD64 architecture. Most open-source compilers are three stage. Front end (language), a (generic) optimizer, and the back-end machine code emitter. The front end and optimizer stages don't know what sort of code will be emitted, so they can't make any assumptions. Does a particular construct cause cache misses? Does it invoke Intel's replay system? They don't know or care. It's only the emitter at the very last stage that is processor-aware, and by then there is only so much you can do. MSVC, on the other hand, is processor-aware from stem to stern. It can make CPU-specific assumptions at a very early stage and can take far greater advantage of SIMD instructions. Compilers were much better when each one was for one architecture only. When they didn't mess around with intermediary bytecode, and were intended to one thing only - take language X and turn it into machine code Y. Re:Executable performance (Score:4, Informative) You might want to try the Intel compiler. This was three years ago but it produced obviously faster results than either gcc or msvc. Re: (Score:3) eh, gcc doesn't even follow C99, it's a half-assed C89 Are there any issues other than those mentioned in the GCC developers' status of C99 features in GCC [gnu.org] page? with all kinds of weird extension Well, yes, if you specify --std=c99, "When a base standard is specified, the compiler accepts all programs following that standard plus those using GNU extensions that do not contradict it." [gnu.org] You'd need -Wpedantic to get warnings about all GNU extensions and -pedantic-errors to get them as errors.
http://developers.slashdot.org/story/13/04/20/1256236/llvm-clang-compiler-now-c11-feature-complete?limit=0
CC-MAIN-2015-18
refinedweb
9,208
69.72
Eric, 135 is less than 256, so it is possible to get 135 out of a max 256. Can you post the exact loop that get the overflow issue? Eric, you don't have to be sorry about it, it happens. I tested the For Next on macOS and the test run just freeze. If I change to 254 then there is no problem. I did a test with uint16 and 0 to 65535 and got the same. I don't know much of how Xojo works, do you think that the for next go to that value (255 or 65535) and execute the code inside of it and the problem is when it gets to 'Next' that it tries to go to 256 (or 65536) and those values are not valid? so it goes to 0 again (thank you Andre). ETA: just used this code and it works, it looks like the last Next is the problem: For X As UInt8 = 0 To 255 Dim strAnything As String = "Hello World" if x = 255 then exit // this way Next will not try to increment X beyond Uint8 limit Next ETA2: Thank you Andre, good to know. The problem is that uint8 can only hold values upto 255, if the uint8 variable = 255 and you add 1 the value becomes 0 again and the next will start the loop all over again. In this case you should use a variable with at least 16bits to prevent the problem. The real problem is that Xojo doesn't support overflow for integer variables. The moral: if you use an integer as a loopcounter be sure to use the type that can handle the whole range of the loop. Agreed. But there are 256 numbers in a uint8 not 255 so it's counter-intuitive that For x as uint8 = 0 to 255 should be a problem. I do this type of thing often with Do loops after all using the full range of the variable. However I am comforted by the fact I haven't gone crazy and that others see it too! Right, but the last next will try to increase the value of x but because x is limited to a max of 255 it will go round to zero again. In a do loop the check for the value of x is at the end of the loop and as soon the var x is 255 it will not be increased anymore and the loop will end. In that case x will never be asked to take a value higher than that 255. OK but I don't recall having this problem with For..Next in my VB days nor with Open/Libre Office. It's counter-intuitive which is why I'm heading back to Do loops. In my real-world situation the debugger caught the exception but in my example code the test run went into hyperspace like Alberto's mac. That is not a good look since For...Next isn't exactly new, but at least the platforms are consistent! In most programs in VB i have seen the variables were dimmed as integer and that integer has a much bigger range and would never show a problem with ranges from 0 to 255. I have never done anything with Open Office, so i cann't comment on that. It could be that do loops are a little bit less efficient because you need extra code to increment the loopcounter yourself, but with this smal range it will hardly be measurable. So there is nothing against using them. I tested this on Windows and it shows exactly the same behaviour. At least you now know where the problem is and you can be sure you are absolutely not getting crazy. :D This post may help: Thanks for the link Jason. Although somewhat unintentional, I'm glad the uint data types were included in mainstream Xojo. For me, they are important for allowing interoperability between bitwise, mathematical and string bin() and val(&b 32bit) functions. Otherwise bitwise operations would be much harder to use with signed integers. However in this case I was using uint to catch overflow errors which would not stop execution and could otherwise go unnoticed leading to difficulties in debugging, since signed integers are capable of greater and/or signed negative ranges that my application should not allow or have to deal with. Therefore I think For...Next deserves access to the full range of unsigned integers expressly dimensioned by programmers for counting purposes., so that when dealing with a byte one can use an uint8 loop for example. Until that day comes I'll stick with Do...Loop with counters. @Eric W Therefore I think For...Next deserves access to the full range of unsigned integers expressly dimensioned by programmers for counting purposes., so that when dealing with a byte one can use an uint8 loop for example. uint8 can hold integers from 0 to 255, which is 256 distinct values. It's not big enough to hold a value of 256 (9 bits). Start with 0 as the 1st value, counting by 1, the 256th 'value' will be 255. The For...Next adds 1 to the counter at the bottom of the loop, THEN it checks if the counter is greater than the limit. A UInt8 counter will fail (or reset to 0) when it tries to increment to 256. A UInt8 counter will fail (or reset to 0) when it tries to increment to 256. '' I would like this to be so but it overflows before incrementing to 255. Please run the example code above to verify this with uint8 counters. Anyway, Do...Loop has no such issue if incrementing at the bottom and one's code is clearer too. On windows X rolls over to 0 after 255, endless loop. Yes John you are right, this is very yesterday's problem for me, sorry. So picking up the thread, we can put Alberto's code contributed above in the loop to remedy Xojo's uint For...Next if x = 255 then exit // this way Next will not try to increment X beyond Uint8 limit Which as far as I know is the only For..Next in the known universe to need such remedy. Kind of defeats the purpose of For..Next doesn't it? So use Do...Loop with uints instead I say unless one is testing for a condition anyway. @Eric W Which as far as I know is the only For..Nextin the known universe to need such remedy. Are you sure? I tried a small test in C: #include <stdio.h> #include <stdint.h> int main(int argc, char **argv) { uint8_t i; for (i = 0; i <= 255; i++) { printf("%d\n", i); } printf("Finally %d\n", i); return 0; } On my Mac (compiler idents as "Apple LLVM version 9.0.0 (clang-900.0.39.2)"), the loop never ends. If coded as for (i=0; i <256; i++) the compiler throws "warning: comparison of constant 256 with expression of type 'uint8_t' (aka 'unsigned char') is always true." I'm not a C guy but aren't you incrementing before the print statement so that your 0 index has already turned to a 1 in the first loop? In BASIC dialects For 0 starts the first pass of the loop with the index value of 0, For 1 starts the first pass of the loop with the index value of 1. Or am I mistaken about this? To quote Xojo's language reference for example : By default the counterValue is changed by 1 at the end of each loop (when the Next statement is reached or a Continue is invoked within the loop. [Emphasis added] for (i = 0; i <=255; i++) { printf("%d\n", i); } It starts printing at 0, not 1, as i is equal to 0 the first time through. But the important thing is what happens when i = 255. Note that i is incremented before the test, so it goes from 255 to 0 before the <=255 test is performed. When reading your code from left to right it looks like i is incremented after the test but I take your word for it. But if in the case of For..Next (not being C/C++) the increment only happens "when the Next statement is reached" - as Xojo's Language Reference puts it - then the test in Xojo must occur after the increment to keep the For...Next rules of the language consistent and in tact; and which increment should not occur if the specified valid range is already exhausted! However, using Do...Loop instead of For...Next makes for more explicit code with better control IMHO. And if I were king of the universe I would abolish For...Next which of course Xojo Inc. can't.
https://forum.xojo.com/46463-for-next-strange-things-happening/6
CC-MAIN-2018-30
refinedweb
1,483
80.11
I've been trying to understand the pygame.display.update function in the context of only updating 'dirty' rectangles. An example of how I've been calling the function is: pygame.display.update(pygame.Rect(0, 0, 50, 50)) However, I am finding this doesn't update that 50x50 rectangle from the origin as expected but still updates the whole display as if there was no argument. Any ideas? Is pygame.Rect an appropriate rectangle to use? Here is the very basic code I've been testing. Thanks for any advice. import sys, pygame size = width, height = 500, 500 pygame.init() Surface = pygame.display.set_mode(size) pygame.display.init #Draw a red rectangle first pygame.draw.rect(Surface, (255, 0, 0), (0,0,300,300)) pygame.display.update() #Draw a smaller green one and update only half it's length so only half should appear? pygame.draw.rect(Surface, (0, 255, 0), (0,0,100,100)) pygame.display.update(pygame.Rect(50, 50, 50, 50)) while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() continue
http://www.dreamincode.net/forums/topic/184546-problem-using-pygamedisplayupdate/
CC-MAIN-2018-09
refinedweb
181
70.6
Important: Please read the Qt Code of Conduct - Install debugger engine I'm an old user of Visual studio express 2015 for C++ under Windows 10. I now try to install Qt for making Android apps, having come so far as to build and run the welcome example programs with output on the laptop screen. When I try to Start debugging I get the message "Unable to create a debugger engine ...". Also under Tools->Options->Build&run->Debuggers there is none auto-detected. I have followed every step in Setting up debugger in the Qt documentation (installing Debugging tools for Windows/CDP and Symbol server, setting CDP paths, etc etc). Can I have a hint of what is wrong? Thx in advance for any advice. Per Anders Hi and welcome to devnet, Do I understand you correctly, you are trying to setup your environment for Android development but want to use VS2015 for compiling the application ? In any case, what exact version(s) of Qt did you install ? @SGaist Yes, I want to build for Android and use the Visual studio compiler (as suggested by the installation). I have installed 5.6, 5.7 and 5.8 (with msvc2015_64). - SGaist Lifetime Qt Champion last edited by SGaist You can't do that like that, Android development requires the Android SDK and NDK. You can find more information on how to setup your machine for Android development in the Getting Started with Qt for Android chapter of Qt's documentation. @SGaist I have also installed Android SDK and NDK, as well as Android SDK tools, JDK, Gradle and USB drivers. And Qt for Android development ? @SGaist I think so ... Qt Creator -> Tools -> Options -> Devices -> Android says "Found 10 toolchains for this NDK. " and after "Automatically create kits ..." it says "Warning Qt versions for 5 architectures are missing." I do not succeed to add Qt versions selecting Options -> Build&Run -> Qt versions. Is that a clue? I have C:\Qt\5.8\msvc2015_64\bin\qmake.exe (and corresponding for 5.7 and 5.6) auto-detected there. You have installed Qt for Visual Studio 2015. You need to install Qt for Android. If you used the online installer, just start the maintenance tool and add Qt for Android. @SGaist Thank you -- that helped. Now the problem is that, when I try to run the untitled project appearing when you create a new project, qglobal.h seems to be missing and I cannot find it anywhere in my installation. " C:\Qt\5.8\android_x86\include\QtCore\qglobal.h:45: error: type_traits: No such file or directory include <type_traits> " - jsulm Lifetime Qt Champion last edited by @jsulm PS I can see now that it is not qglobal.h that is missing, but type_traits, as well as cstddef, algorithm and maybe others. Which version of the NDK did you install ? Take a look at the Kit you are using. Check whether there's any warning or error message related to the NDK. They've had some disruptive update recently which might be a possible cause. @SGaist Under Devices -> Android, after Android NDK location I have a warning "Qt versions for 3 architectures are missing". No other warnings. I saw somewhere (can't find it again) about a problem similar to mine, related to NDK version 13, related to the order of includes in GCC. However no solution was presented. Where in my installation are type_traits, cstddef and algorithm supposed to be found? How do I give the appropriate directive in the .pro file (or anywhere)? May type_traits, cstddef and algorithm not be installed (Windows search can't find them)?? These files should be provided by the Android SDK/NDKs The tool chains missing is a warning that is harmless in the sense that you are not likely going to build your application for these missing architectures. Unless of course the warning concerns the targets you want to build for. @PA-F Sorry -- I should have given some further information to give you a chance to help. When I try to build untitled.pro I get the messages: In file included from C:\Qt\5.8\android_x86\include/QtGui/qtguiglobal.h:43:0, from C:\Qt\5.8\android_x86\include\QtGui/qguiapplication.h:43, from C:\Qt\5.8\android_x86\include\QtGui/QGuiApplication:1, from ..\untitled\main.cpp:1: type_traits: No such file or directory In qglobal.h there are error marks for include <type_traits> include <cstddef> and #include <algorithm> but not for #include <stddef.h> #include <QtCore/qconfig-bootstrapped.h> #include <QtCore/qconfig.h> #include <QtCore/qtcore-config.h> #include <QtCore/qsystemdetection.h> #include <QtCore/qprocessordetection.h> and #include <QtCore/qcompilerdetection.h> For instance <stddef.h> is found in c:\android\android-ndk-r13b\toolchains\x86-4.9\prebuilt\windows-86_64\lib\gcc\i686-linux-android\4.9.x\include\stddef.h Does this give you any idea? Following that wiki entry, recent versions of the Android NDK are problematic. It is recommended to use ndk-r10e.
https://forum.qt.io/topic/75083/install-debugger-engine
CC-MAIN-2021-21
refinedweb
832
60.61
mimomimo - Multiple input and multiple output (as opposed to functions where inputs and outputs are always synchronised) - Less memory (because of streaming) MiMo is a multi-input multi-output Python streaming library. It allows users to define a stream with multiple inputs and multiple outputs and run them completely from beginning to end. Back-pressure has also been implemented to prevent too much memory from being used. UsageUsage There are two core components in MiMo; the Stream and the Workflow. Streams to the computational processing but do not handle how the data is passed between streams. Workflows pass the data around streams but do no processing of their own. To create a workflow, the user needs to implement streams and pipe them together. StreamsStreams Implementing a stream can be done through inheriting a sub-class from the Stream class or creating a Stream class with a custom function as the fn parameter. The following code shows two implementations of a stream that will produce the numbers from 0 to 99. from mimo import Stream # Method 1 (inheritance) class MyStream(Stream): IN = [] OUT = ['entity'] async def run(self, ins, outs): for item in iter(range(100)): await outs.entity.push(item) # Method 2 (constructor) my_stream = Stream(outs=['entity], fn=my_stream_fn) async def my_stream_fn(ins, outs, state): for item in iter(range(100)): await outs.entity.push(item) There are a few things to note about the run function. 1. It must be asynchronous, ie. it must be defined wth the async def keywords. 2. It takes two parameters, ins and outs, that contain the input streams and the output streams. The names of the input and output streams are defined by the IN and OUT member variables or overridden using the ins and outs of the initialisation function. Accessing the input and output streams can be done through the attributes. From the example above, accessing the entity output stream can be done with outs.entity. 3. Input streams can be popped and peeked and this must be done using the await keyword. Input streams haven't been used in the above example, but the entities in the stream can be accessed one at a time with the functions pop and peek. Popping an entity will remove it from the input stream, and peeking will look at the top-most entity without removing it from the stream. Input streams can also be iterated using the async for looping construct. 4. Output streams can be pushed and must also use the await keyword. Pushing an entity to an output stream will make it available to any connected downstream streams. WorkflowsWorkflows Workflows are created by piping streams together. First a workflow must be instantiated and populated with the desired streams. The steps returned by populating a workflow can then be used to make the connections between the streams using the pipe function. The function returns the stream being piped to, so pipe calls can be chained. The workflow can be run by calling the start function. from mimo import Stream, Workflow def main(): workflow = Workflow() step1 = workflow.add_stream(Stream(outs=['a'])) step2 = workflow.add_stream(Stream(['b'], ['c'])) step3 = workflow.add_stream(Stream(['d'])) step1.pipe(step2).pipe(step3) print(str(workflow)) workflow.start() if __name__ == '__main__': import sys sys.exit(main())
https://libraries.io/pypi/mimo
CC-MAIN-2018-34
refinedweb
546
64.91
This never breaks My problem is with the atoi function, it never detects a '0' being entered.My problem is with the atoi function, it never detects a '0' being entered.Code:#include <iostream> #include <vector> #include <stdlib.h> #include <fstream> using namespace std; typedef vector<char*> CV; CV CharacterVector; ofstream fout; int main(void) { fout.open("crap.db"); int Number = 0; for( ; ; ) {{//stupid smily face arg CharacterVector.push_back(new char[50]); cout << "enter a character array "<< endl; cin.getline(CharacterVector[Number], 50); if(!atoi(CharacterVector[Number]) == 0) { cout << "You have chosen to quit" << endl; break; } else { fout << CharacterVector[Number] << endl; Number++; } }} fout.close(); return 0; } This is kind of sad, I have been programming for a year now and I am still doing stupid stuff like this. What are your opinions, do you think someone who has been programmign for a year should still be doing stupid stuff like this?
https://cboard.cprogramming.com/cplusplus-programming/24150-never-stops-some-reason.html
CC-MAIN-2017-47
refinedweb
151
58.18
A moving average is a technique that can be used to smooth out time series data to reduce the “noise” in the data and more easily identify patterns and trends. The idea behind a moving average is to take the average of a certain number of previous periods to come up with an “moving average” for a given period. This tutorial explains how to calculate moving averages in Python. Example: Moving Averages in Python Suppose we have the following array that shows the total sales for a certain company during 10 periods: x = [50, 55, 36, 49, 84, 75, 101, 86, 80, 104] Method 1: Use the cumsum() function. One way to calculate the moving average is to utilize the cumsum() function: import numpy as np #define moving average function def moving_avg(x, n): cumsum = np.cumsum(np.insert(x, 0, 0)) return (cumsum[n:] - cumsum[:-n]) / float(n) #calculate moving average using previous 3 time periods n = 3 moving_avg(x, n): array([47, 46.67, 56.33, 69.33, 86.67, 87.33, 89, 90]) Here is how to interpret the output: - The moving average at the third period is 47. This is calculated as the average of the first three periods: (50+55+36)/3 = 47. - The moving average at the fourth period is 46.67. This is calculated as the average of the previous three periods: (55+36+49)/3 = 46.67. And so on. Method 2: Use pandas. Another way to calculate the moving average is to write a function based in pandas: import pandas as pd #define array to use and number of previous periods to use in calculation x = [50, 55, 36, 49, 84, 75, 101, 86, 80, 104] n=3 #calculate moving average pd.Series(x).rolling(window=n).mean().iloc[n-1:].values array([47, 46.67, 56.33, 69.33, 86.67, 87.33, 89, 90]) This method produces the exact same results as the previous method, but it tends to run faster on larger arrays. Note that you can also specify any number of previous time periods to use in the calculation of the moving average. For example, perhaps you’d rather use n=5: #use 5 previous periods to calculate moving average n=5 #calculate moving average pd.Series(x).rolling(window=n).mean().iloc[n-1:].values array([54.8, 59.8, 69. , 79. , 85.2, 89.2]) The more periods you use to calculate the moving average, the more “smoothed” out the moving average line will be.
https://www.statology.org/moving-average-python/
CC-MAIN-2022-21
refinedweb
420
51.07
I want to animate in Flash for an Ipad app. I run off a Macbook Retina. My document size is 2048 x 1536 @ 264DPI. When i preview my animation the flash player gets cut off. Flash does not give me the option to zoom out. Any suggestions? Set your stage to scale (but you know that will reduce performance and clarity of the bitmaps), nonetheless let you view it on a screen smaller than your target. If it's just a FLA project, on your first frame in an empty frame set the StageScaleMode and StageAlign: import flash.display.StageScaleMode; import flash.display.StageAlign; stage.scaleMode = StageScaleMode.NO_BORDER; stage.align = StageAlign.TOP_LEFT; Sometimes I work on AIR kiosks on my laptop just to troubleshoot and it's not a HD screen so I need to scale it down to see the whole thing. NO_BORDER will scale but maintain aspect ratio. When you're done just remove those lines of code.
http://forums.adobe.com/thread/1181852
CC-MAIN-2014-10
refinedweb
160
83.15
41792/excel-attachments-inside-another-excel-file-handling The print() is getting called multiple times ...READ MORE With pandas it is possible to get ...READ MORE You use os.walk() module of python for ...READ MORE Here you go: import glob path_to_excel_files = glob.glob('path/to/excel/files/*.xlsx') for ...READ MORE Some services require table data in CSV ...READ MORE Hi @Rashmi! I read your code and there ...READ MORE There are 2 libraries used to handle ...READ MORE for write, read,append data in file check ...READ MORE You can use pandas module to do ...READ MORE I have used file handling for smaller ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/41792/excel-attachments-inside-another-excel-file-handling
CC-MAIN-2021-21
refinedweb
115
80.58
Change default template vldpersonals työt I have set up a Bitnami Wordpress Multisite and I need someone to help me change the domain. I already have the DNS records updated but it is redirecting to local IP not to correct domain. Please bid if you have experience. ...then user will move selected area on product image. 3) MATERIAL: Customer will select a material that has different prices per m2 for printing ("Standard Wallpaper" will be default, "Sticker" and "Premium Wallpaper" will be alternatives. These material types should be on admin panel so we can edit, add or delete.) NOTES 1) CALCULATING PRICE: After all My crypto trading bot uses a cross line strategy now. I need this changed so that t...is above the large EMA line. I want a friendly, intelligent coder to work on this. It should be a quick and easy project for anyone that know javascript. It is just a small change. So if you plan to bid an outrageous amount, such as $100 or more, don't waste my time. ...create for me (or help me find/implement a currently existing product or software) that can do the following: 1. Open a program from my desktop 2. Adjust one setting from its default to what I need 3. Click start to run the program 4. Close the program after its been running for 45 minutes (or some other time I can adjust) 5. Reopen the software immediately Need to create a responsive Joomla template. Please see the attached document for the site link. This needs to be completed by 5/15/19 Budget is $140 .. installed. So that in the “cart” it has to be remov... I am looking for someone who can create a beautifull psd template for a website like [kirjaudu nähdäksesi URL:n] Can you help me with this? Please comment with your price and examples of previous work. ...with the central Fish guide database when there is a data or wifi connection available. There will be an automatic synchronization feature which will be set to «wifi only» by default and which can be modified or disabled in the app settings. The user interface of the app will be child friendly. The apps, including updates, can be distributed via the Namoi Need an expert to develop BOOTSTRAP HTML 5 [kirjaudu nähdäksesi URL:n] WORDPRESS THEME .ExpertS ONLY!! video format ability Issue: If there are othe... ...following field : 1) The date: the guest can not select the past date and can not select the date that mentioned in after early booking setting . Default booking date is today. 2) the party size. Default size is 2. 3) the time and discount : the time should be time picker as in the attachment and in the link. the guest can not select the past time.. ...already available 8. Change password for both employers and job-seekers (already available) 9. All the functions available for the employers available in the theme [kirjaudu nähdäksesi URL:n] 10. Implementing the existing rating system and the recruitment lifecycle system in the new theme if not available by default. 11. Payment gateway .. We are a sales training organisation in consultative selling skills. We are in the process of building a mobile app for sales people in consultative selling. Pls visit [kirjaudu nähdäksesi URL:n] for some more information .. Custo...page image thumbnail alignment need you to change the wording on a small website. Content must be similar to original but still pass Copyscape. A small 2 page website. Type "massage" into your offer to show me that you've read this. I have moved my business, on my website the " Locate me" is at the old location. Need it updated so it will reflect the new location! take the arrowhead out of the logo and leave only the flame. please provide an outline of the flame and one colored in black. all artwork provided must be vector format so that i may use it for printing purposes. Thank you ...mobile. Languages The website will be translated into different languages in future so provide a dropdown on the top right-hand corner of the screen to select the language - default English. All text will need to be stored so that this is possible. Some questions you should consider if you're interested: Have you done anything similar to this before? ...replace the YouTube video call above, which I did... <video poster="[kirjaudu nähdäksesi URL:n]" id="myvideo" class="video-js vjs-default-skin vjs-16-9 vjs-big-play-centered" controls <source src="[kirj... ...are often not ...2. We want to show 3 different values on the map (finances, economic freedom, law freedom), but CSV structure (years and countries) will be the same for all of them 3. The default view should consist of countries colored to show value 1 (finances) 4. Color values and ranges should be changeable for site admin (it could be some *.csv file, etc. what is I need a Forum Template Customization: logo change, icon change, font change, advertising, age verification form box, email contact box. Forum Template Used [kirjaudu nähdäksesi URL:n] requirements: phpBB 3.0.x, phpBB 3.1.x, phpBB 3.2.x, html, css, photoshop.... ...data for one listingid as an alternative to the default (all) 3.A /post-order/v2/cancellation/search [kirjaudu nähdäksesi URL:n] add a simple uncommentable set of lines which will retrieve the data for one item_id as an alternative to the default (all) 3.B /post-order/v2/cancellation # 1 (request I have an adobe illustrator file that i need to change everything in blue to this orange code #E84A22 to match my website ...small VBScript which will do the following: 1. When user opens the word template a formular should popup (See the sample formular in attached Word already created) 2. User can select 5 different locations, fax numbers and further options to hide logo and folding mark and to change the font. 3. Depending on the selection of the location the fax number ...symbolic red circle with white X cross on transparent 1. I have a new web template I would like to use for website I will provide to you. Replace current site with new web template [kirjaudu nähdäksesi URL:n] 2. Add signup and login 3. Add API documentation to web template (I will give in word document) make API documentation look nice. ...required. You are requested to help us successfully compile the default code from where we shall take on the same. any further customization if required can be discussed later seprately but the scope of this development shall be to successfully compile and build the exe files from the default source of the below 2 projects [kirjaudu nähdäksesi URL:n] Need turn around in 24-48 hours . We have done the html/css (bootstrap) and need the following theme layouts implemented into magento2. Attached i...(bootstrap) and need the following theme layouts implemented into magento2. Attached is PDF with some screenshots and references. 1.)Home Page 2.)Category Page 3.)Product Page 4.)Default CMS Page Rekisteröidy tai kirjaudu sisään nähdäksesi tiedot. You can check the link ( [kirjaudu nähdäksesi URL:n] ) ... I have a Wordpress multisite installation hosted on Siteground.com. Currently the Domain name on this WP multisite is marklumber.site. I need to change the domain name to marklumber.com. I already have purchased the domain on Godaddy so what I need is the domain to be linked and after make the changes in the WP multisite database regarding the URL so ...[kirjaudu nähdäksesi URL:n](); $[kirjaudu nähdäksesi URL:n]('bibiona'); $]('Tibipporto clienti '); $[kirjaudu nähdä... Hello, i would like you to change the namespace from [kirjaudu nähdäksesi URL:n] to some other name. ...bit about global climate change to help me write an article about where we were about 30 years ago and where we are today. I have a basic outline and structure. The article will focus on some specific info from 1988 and compare to today. It will show what one specific group of people are doing now to help combat climate change and I have a lot of the Implementation of SimpleInjector with ASPNet default authentication in MVC C#. The default authentication is already in place when you create a new MVC project. You need to implement SimpleInjector in this project. Our tests give us some errors in the [kirjaudu nähdäksesi URL:n] declarations. Developer need to already done it before in another project (Not i want change add to cart button with pluss minus quanity option Task: An already finished Excel template should be reproduced see pictures. Approx. 5 pages. with corresponding input fields. Simple formulas. Three sentence. Output of the file for printing approx. 5 pages. That was it. ...login with these credentials and fill in their settings on there normal setting changing form we have Another small change will be there needs to be a change password form on the settings tab for barbers now this is a small change and doesnt require too much i would appreciate you reading my job and giving a reasonable quote, you could be the best ...categorization a. 3 level categorization of products b. Search by any of the category c. Extensive filters for each category 5. Search functionality 6. Webshop functionalities (default packages included) a. Registration b. Shopping basket c. Order d. Payment systems e. Etc. 7. Development of an API for connection of the application to the same dataset and Please read first,...this see this project code from github[.]com/4x11/build69/blob/master/jni/util/[kirjaudu nähdäksesi URL:n] you will found "cp1251_to_utf8" i think this code convert cp1251 to utf8 but i want change to "iso8859_11_to_utf8" (ISO−8859-11 to utf8) Because I want this app to support Thai language, I need someone to help me to fix abo...
https://www.fi.freelancer.com/job-search/change-default-template-vldpersonals/4/
CC-MAIN-2019-22
refinedweb
1,647
66.13
Solution: [Before you read any further, I think there is an official editorial for this round which may explain the approach to this problem better.] The problem looks innocent enough, but actually it is quite a tedious one. Nevertheless, it links several interesting techniques and I find this problem quite interesting eventually. First of all, we need a general strategy to find the two vectors with smallest intersection angle. Dot product will be the most natural tool for the job. However, doing pair-by-pair comparisons will take O(N^2). So a better idea is to sort the vectors first in terms of their anti-clockwise angles with a common axis, i.e. positive x-axis in this solution. After sorting, we do a linear pass and compute all pairs of consecutive vectors, and finally output the pair with smallest angle. How to perform the sorting? For a given vector v, we can compute its cosine given by \(\cos{\left( \frac{v[0]}{length(v)} \right)}\), where length(v) = \(\sqrt{v[0]^2+v[1]^2}\). Sorting is then simply comparing the cosine values and simple checks whether v belongs to the upper or lower quadrant of the Euclidean space. However, using square root function and performing double precision arithmetic will lead to loss of precision errors (trust me, been there, done that). So we will attempt to perform the computation precisely. Instead of using cosine function, we will develop a function \( G: \mathbb Z^2 \to \mathbb Z^2 \) as \(G(v) = (\text{sign}(v[0]) \times v[0]^2, v[0]^2+v[1]^2) \) if \(v[1] >= 0\), and \(G(v) = (-\text{sign}(v[0]) \times v[0]^2 - 2(v[0]^2+v[1]^2), v[0]^2+v[1]^2) \) otherwise. G maps vector v to (p,q) a rational number \(\frac{p}{q}\). It is basically a transformation of the graph \(\cos(\theta)\) to \(f(\theta) = \cos^2(\theta)\), and from \(f(\theta)\) to \(g(\theta)\) where we output: 1. \(f(\theta)\) when \( \theta \in [0, \frac{\pi}{2}]\) 2. \(-f(\theta)\) when \( \theta \in [\frac{\pi}{2}, \pi]\) 3. \(f(\theta)-2\) when \( \theta \in [\pi, \frac{3\pi}{2}]\) 3. \(-f(\theta)-2\) when \( \theta \in [\frac{3\pi}{2}, 2\pi]\) You can check that g is indeed equivalent to G and that g is monotonic decreasing, hence it can be used as comparison function for sorting. How to compare two rational number (a,b) and (p,q) without resorting to double precision arithmetic? Easy, it is simply done by checking if the relation aq < pb holds. Since each a,b,p and q is less than \(10^8\), their multiplication fits a 64 bit long long type. Now after we sorted the vectors, we need a way to compare whether two consecutive vectors form the smallest intersection angle. We can use dot product, but similarly we are faced with the square root function, hence we will need to get rid of it. Hence we use the squared version of the dot product relation: \(T(v,w) = (\text{sign}(v[0]w[0]+v[1]w[1]) \times (v[0]w[0]+v[1]w[1])^2, (v[0]^2+v[1]^2)(w[0]^2+w[1]^2)) \), where T maps a pair of vectors (v,w) to a pair of integers (p, q) where \(\frac{p}{q}\) is squared dot product value of (v,w), preserving the sign of the numerator. T preserves the monotonic relation by which larger T(v,w) means smaller intersection angle between v and w. Hence our aim is to find (v,w) with the largest T. It hence reduces to performing rational number comparison (a,b) and (p,q) where each a,b,p,q is 64 bit integer. However, the multiplication result cannot be contained in another 64 bit integer, hence we need to devise a way to do this. The way to do this can be thought of as a special case of big integer computation. We split each of the 64 bit integer into two 32bit integers, and perform polynomial multiplication (of basis \(2^32\)). The comparison of aq < bp is then equivalent to lexicographical comparison. Implementation: #include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <utility> using namespace std; int n; vector<pair<pair<long long,long long>,int> > a; bool fn(pair<pair<long long,long long>,int>& lhs, pair<pair<long long,long long>,int>& rhs) { long long x[] = {lhs.first.first, rhs.first.first}; long long y[] = {lhs.first.second, rhs.first.second}; long long p[2], q[2]; for(int i=0;i<2;++i){ p[i] = x[i]*x[i]*(x[i]<0?-1:1); q[i] = x[i]*x[i] + y[i]*y[i]; if (y[i] < 0) p[i] = -p[i] - q[i]*2; } return p[0]*q[1] < p[1]*q[0]; } void mult(long long p, long long q, long long res[3], int* sign) { *sign = (p >= 0 ? 1 : -1) * (q >= 0 ? 1 : -1); p *= (p < 0 ? -1 : 1); q *= (q < 0 ? -1 : 1); long long a[] = {p>>31, q>>31}; long long b[] = {p&((1LL<<31)-1LL), q&((1LL<<31)-1LL)}; res[0] = b[0]*b[1]; res[1] = a[0]*b[1]+a[1]*b[0]; res[2] = a[0]*a[1]; for(int i=0;i<2;i++){ if(res[i] >= (1LL<<31)) { res[i+1] += res[i] >> 31; res[i] &= (1LL<<31)-1LL; } } } bool cmp(long long a[3], long long b[3]) { return a[2] != b[2] ? a[2] < b[2] : (a[1] != b[1] ? a[1] < b[1] : a[0] < b[0]); } bool less_than(long long p0, long long q0, long long p1, long long q1) { int sign[2]; long long res[2][3]; mult(p0,q1, res[0], &sign[0]); mult(p1,q0, res[1], &sign[1]); if(sign[0] != sign[1]) return sign[0] < sign[1]; if(sign[0]>0) { return cmp(res[0], res[1]); } else return cmp(res[1], res[0]); } int main(){ scanf("%d",&n); int x,y; for(int i=0;i<n;++i){ scanf("%d%d",&x,&y); a.push_back(make_pair(make_pair(x,y),i+1)); } sort(a.begin(), a.end(), fn); long long mp = -2, mq = 1; int ai = -1, aj = -1; for(int i=0;i<n;++i){ int j = (i==n-1?0:i+1); long long x[] = {a[i].first.first, a[j].first.first}; long long y[] = {a[i].first.second, a[j].first.second}; long long p = x[0]*x[1]+y[0]*y[1]; p *= p * (p < 0 ? -1 : 1); long long q = (x[0]*x[0]+y[0]*y[0]) * (x[1]*x[1]+y[1]*y[1]); //if (mp*q < mq*p) { //if(1.0L*mp/mq < 1.0L*p/q){ if(less_than(mp, mq, p, q)){ mp = p; mq = q; ai = a[i].second; aj = a[j].second; } } printf("%d %d\n", ai, aj); return 0; }
https://abitofcs.blogspot.com/2015/12/codeforces-education-round-1-c-nearest.html
CC-MAIN-2018-13
refinedweb
1,170
64.1
Tracking mouse movement during Button pressed I want to track mouse/touch movement (coordinates inside the Window or more specifically inside a MouseArea inside the main view) while a Controls 2 Button is pressed down. The movement starts when the user presses the button down. Then he/she moves mouse/finger while the button is pressed, inside the MouseArea which is larger than the button. Then he/she releases it. I have several such buttons close to each other and the user can move the mouse/finger freely in the screen so that it can go above other similar buttons and other items. The MouseArea itself isn't important, only that I can track the mouse movement while a button is pressed so that I can send forward information about movement. Is there any simple way to do it? If not, how about a non-simple way? - raven-worx Moderators @Eeli-K most examples of MouseArea are covering this no? Actually thats almost the whole purpose of the MouseArea element I have read the documentation back and forth but haven't looked at all possible examples in Qt's example app collection. I don't know how to let the MouseArea receive all the position changed events and simultaneously propagating all the events to other items so that other item's behavior doesn't change. Maybe the greatest problem is that I can't use MouseArea { onPressed: {mouse.accepted = false} } to propagate events to other items because then the area stops reveiving events, as the documentation says. So what's left to do is to find the item which is under the event coordinates (by handling coordinate conversion and item child structrue) and "manually" handling its properties. Then I would have to replicate every item's behavior in the MouseArea event handling code. So I repeat my problem: is there a way to receive mouse coordinates in MouseArea (or in some other way) but let the UI work exactly as it works without the MouseArea, in a simple way which doesn't require knowledge about the other parts or the exact structure of the UI? - raven-worx Moderators @Eeli-K Does the following do what you want? MouseArea { anchors.fill: parent propagateComposedEvents: true onClicked: { mouse.accepted = false } onPositionChanged: { console.log( mouse.x + "," + mouse.y ) mouse.accepted = false } } @raven-worx said in Tracking mouse movement during Button pressed: @Eeli-K Does the following do what you want? Unfortunately not. Here's a small application... import QtQuick 2.7 import QtQuick.Controls 2.0 import QtQuick.Layouts 1.0 ApplicationWindow { visible: true width: 640 height: 480 Item { anchors.fill: parent MouseArea { id: mouseArea z: 2 anchors.fill: parent propagateComposedEvents: true onClicked: { console.log("clicked on area") mouse.accepted = false } onPositionChanged: { console.log("mouse position changed", mouse.x, mouse.y); mouse.accepted = false } onPressed: { console.log("mouse pressed on area") //mouse.accepted = false } } Button { id: button onPressedChanged: { console.log(button.pressed) } onClicked: { console.log("buttonClicked") } } } } MouseArea.onPressed either has "mouse.accepted = false" or not. In both cases it doesn't do what I want. Either Button doesn't get all the events or the MouseArea doesn't get the following events. I think I found a satisfying solution. Button { MouseArea { id:buttonMouseArea anchors.fill: parent onPositionChanged: { console.log("mouse position changed on button area", mouse.x, mouse.y); } onPressed: { mouse.accepted = true button.down = true } onReleased: { mouse.accepted = true button.down = false } ... The secret is that when the button is pressed the mouse area receives events even outside the area (actually even beyond the application window on desktop!). Therefore it works as I want it to.
https://forum.qt.io/topic/73368/tracking-mouse-movement-during-button-pressed
CC-MAIN-2018-05
refinedweb
603
60.21
Combinations… This is a math/geeky/computer post of something relatively simple, but it arose in the wild in a program that I wrote several years ago, and when I saw it again, it confused me, and I spent a bit of time thinking about it, and I thought I might just write it up. If math/geeky/computer stuff bores you, perhaps you should move on. If I’ve still got you, today’s post is about combinations, a topic that arises in lots and lots of computer programs. For instance, the program that spawned this post was this program for computing the number of possible positions in a game of checkers that I did back in 2009. It uses a function called “comb” which takes two arguments a and b, which computes the number of different ways of selecting b objects from a collection of a objects. Here’s the implementation from that post: def fact(n): if n == 0: return 1 else: return n*fact(n-1) def comb(a, b): return fact(a) / (fact(b)*fact(a-b)) If you’ve done a lot of programming, this probably seems fairly obvious to you. This is one of those formulas that I don’t have to think about: I learned it so long ago that I don’t even remember how I originally learned it. It might have been when I first learned about Pascal’s Triangle back in grade school. I probably learned the formula to compute these coefficients using the factorial function, and I’ve probably used it dozens and dozens of times in various contexts. But really, when I thought about it, the factorial function doesn’t seem to me to be completely obvious when staring at the triangle. When I first learned about Pascal’s triangle, the rules were something like this. First, write down a at the top, then write a bunch of rows underneath it, each row containing one more number so they form a triangle. The first and last number in each row needs to be a one. The other entries are the sum of the numbers above and to the left and above and to the right. If you think of the number of path starting at the root, and reaching the desired new node, it’s clear that it’s the sum of the number of paths reaching the node above and to the left, and above and to the right. Pascal’s Triangle Which brings me to a different chunk of code. In the posting above, I had mentioned that I had written a program to compute the number of possible checkers positions before, but had lost the code, causing me to write the code above. Butr recently I found that original code. But this code didn’t contain the factorial/comb implementation above. It had code that looked like this. def c(a, b): if b == 0 or b == a: return 1 r = c(a-1, b-1) + c(a-1, b) return r At first, this seemed less familiar to me. But if you think about Pascal’s triangle, this is exactly what I described above. If you think of trying to compute the bth number in the ath row, it’s just the sum of the numbers in the row above, to the left and right. And this works! If you compute c(52, 5), you can verify that there are 2598960 ways to deal a 5 card poker hand from a single deck. In a way, this code seems more elegant to me: what was with all that multiplication and division stuff up above? But there is a problem: performance. A moment’s thought should reveal why that should be the case. This code only returns 1, or the sum of two other terms. That means to come up with the 2598960, it bottoms out that recursion… 2598960 times. Modern computers can count that high, even by ones, even in python rather quickly. It took about 1.4s to compute. But to compute c(52, 6) takes about 7 times longer (because the number is roughly 7x larger). Computing c(52,13) is out of the question with that code. But my original program computed the number of combinations this way, and was reasonably efficient. What gives? Well, I lied. The code in my npos program wasn’t exactly like that. Here’s the complete code: #!/usr/bin/env python # # some programs to compute the number of legal positions in checkers # import locale locale.setlocale(locale.LC_ALL, "") mem = {} def c(a, b): if b == 0 or b == a: return 1 if mem.has_key((a, b)): return mem[(a, b)] r = c(a-1, b-1) + c(a-1, b) mem[(a, b)] = r return r def num(b, bk, w, wk, f): r = c(4,f)*c(24,b-f)*c(28-(b-f),w)*c(32-b-w,bk)*c(32-b-w-bk,wk) return r def np(n): total = 0 for b in range(min(n, 12)+1): for bk in range(min(n, 12)-b+1): for w in range(min(n-b-bk, 12)+1): for wk in range(min(n-b-bk, 12)-w+1): for f in range(min(b, 4)+1): total += num(b, bk, w, wk, f) return total - 1 tot = {} for n in range(25): tot[n] = np(n) maxnew, maxtot = 0, 2**64-1 for n in range(1, 25): new = tot[n] - tot[n-1] newstr = locale.format("%d", new, True) totstr = locale.format("%d", tot[n], True) maxnew = max(maxnew, len(newstr)) maxtot = max(maxtot, len(totstr)) print " N%s" % "possible positions".center(maxnew) print (maxnew+3)* '-' for n in range(1, 25): new = tot[n] - tot[n-1] newstr = locale.format("%d", new, True) print "%2d %s" % (n, newstr.rjust(maxnew)) print (maxnew+3)* '-' totstr = locale.format("%d", tot[24], True) Can you spot the difference? The c function is memoized. The vast majority of invocations of the function have been evaluated once before. So, this code remembers the value of each invocation, and before computing, looks up the result to see if we’ve computed it before. An obvious way to implement this lookup would be as a two dimensional array, but Python’s dictionary types are quick and easy. When the program is run, it stores stores 306 values. With this added, the entire program, which counts 500,995,484,682,338,672,639 positions executes in just about 1 second on my laptop. And while it does rely on bignum arithmetic, it doesn’t require multiplication or division: just addition works fine. I like it. Comment from Matthew Denson Time 1/5/2014 at 3:27 pm Hi Mark, I enjoyed this post. It is quite timely, as I am reading SICP (finally) and am in the early section (1.2.2) that discusses tree recursion and introduces memoization. As a result I recognized it (and could name it.) In a month or two that may not be true anymore. 73 Matthew
http://brainwagon.org/2014/01/04/combinations/
CC-MAIN-2015-40
refinedweb
1,186
71.24