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
Eventloops and PyZMQ¶ As of pyzmq 17, integrating pyzmq with eventloops should work without any pre-configuration. Due to the use of an edge-triggered file descriptor, this has been known to have issues, so please report problems with eventloop integration. AsyncIO¶ PyZMQ 15 adds support for asyncio via zmq.asyncio, containing a Socket subclass that returns asyncio.Future objects for use in asyncio coroutines. To use this API, import zmq.asyncio.Context. Sockets created by this Context will return Futures from any would-be blocking method. import asyncio import zmq from zmq.asyncio import Context ctx = Context.instance() async def recv(): s = ctx.socket(zmq.SUB) s.connect('tcp://127.0.0.1:5555') s.subscribe(b'') while True: msg = await s.recv_multipart() print('received', msg) s.close() Note In PyZMQ < 17, an additional step is needed to register the zmq poller prior to starting any async code: import zmq.asyncio zmq.asyncio.install() ctx = zmq.asyncio.Context() This step is no longer needed in pyzmq 17. Tornado IOLoop¶ Facebook’s Tornado includes an eventloop for handing poll events on filedescriptors and native sockets. We have included a small part of Tornado (specifically its ioloop), and adapted its IOStream class into ZMQStream for handling poll events on ØMQ sockets. A ZMQStream object works much like a Socket object, but instead of calling recv() directly, you register a callback with on_recv(). Callbacks can also be registered for send events with on_send(). Futures and coroutines¶ PyZMQ 15 adds zmq.eventloop.future, containing a Socket subclass that returns Future objects for use in tornado coroutines. To use this API, import zmq.eventloop.future.Context. Sockets created by this Context will return Futures from any would-be blocking method. from tornado import gen, ioloop import zmq from zmq.eventloop.future import Context ctx = Context.instance() @gen.coroutine def recv(): s = ctx.socket(zmq.SUB) s.connect('tcp://127.0.0.1:5555') s.subscribe(b'') while True: msg = yield s.recv_multipart() print('received', msg) s.close() ZMQStream¶ ZMQStream objects let you register callbacks to handle messages as they arrive, for use with the tornado eventloop. send()¶ ZMQStream objects do have send() and send_multipart() methods, which behaves the same way as Socket.send(), but instead of sending right away, the IOLoop will wait until socket is able to send (for instance if HWM is met, or a REQ/REP pattern prohibits sending at a certain point). Messages sent via send will also be passed to the callback registered with on_send() after sending. on_recv()¶ ZMQStream.on_recv() is the primary method for using a ZMQStream. It registers a callback to fire with messages as they are received, which will always be multipart, even if its length is 1. You can easily use this to build things like an echo socket: s = ctx.socket(zmq.REP) s.bind('tcp://localhost:12345') stream = ZMQStream(s) def echo(msg): stream.send_multipart(msg) stream.on_recv(echo) ioloop.IOLoop.instance().start() on_recv can also take a copy flag, just like Socket.recv(). If copy=False, then callbacks registered with on_recv will receive tracked Frame objects instead of bytes. Note A callback must be registered using either ZMQStream.on_recv() or ZMQStream.on_recv_stream() before any data will be received on the underlying socket. This allows you to temporarily pause processing on a socket by setting both callbacks to None. Processing can later be resumed by restoring either callback. on_recv_stream()¶ ZMQStream.on_recv_stream() is just like on_recv above, but the callback will be passed both the message and the stream, rather than just the message. This is meant to make it easier to use a single callback with multiple streams. s1 = ctx.socket(zmq.REP) s1.bind('tcp://localhost:12345') stream1 = ZMQStream(s1) s2 = ctx.socket(zmq.REP) s2.bind('tcp://localhost:54321') stream2 = ZMQStream(s2) def echo(stream, msg): stream.send_multipart(msg) stream1.on_recv_stream(echo) stream2.on_recv_stream(echo) ioloop.IOLoop.instance().start() flush()¶ Sometimes with an eventloop, there can be multiple events ready on a single iteration of the loop. The flush() method allows developers to pull messages off of the queue to enforce some priority over the event loop ordering. flush pulls any pending events off of the queue. You can specify to flush only recv events, only send events, or any events, and you can specify a limit for how many events to flush in order to prevent starvation. install()¶ Note If you are using pyzmq < 17, there is an additional step to tell tornado to use the zmq poller instead of its default. ioloop.install() is no longer needed for pyzmq ≥ 17. With PyZMQ’s ioloop, you can use zmq sockets in any tornado application. You can tell tornado to use zmq’s poller by calling the ioloop.install() function: from zmq.eventloop import ioloop ioloop.install() You can also do the same thing by requesting the global instance from pyzmq: from zmq.eventloop.ioloop import IOLoop loop = IOLoop.current() This configures tornado’s tornado.ioloop.IOLoop to use zmq’s poller, and registers the current instance. Either install() or retrieving the zmq instance must be done before the global * instance is registered, else there will be a conflict. It is possible to use PyZMQ sockets with tornado without registering as the global instance, but it is less convenient. First, you must instruct the tornado IOLoop to use the zmq poller: from zmq.eventloop.ioloop import ZMQIOLoop loop = ZMQIOLoop() Then, when you instantiate tornado and ZMQStream objects, you must pass the io_loop argument to ensure that they use this loop, instead of the global instance. This is especially useful for writing tests, such as this: from tornado.testing import AsyncTestCase from zmq.eventloop.ioloop import ZMQIOLoop from zmq.eventloop.zmqstream import ZMQStream class TestZMQBridge(AsyncTestCase): # Use a ZMQ-compatible I/O loop so that we can use `ZMQStream`. def get_new_ioloop(self): return ZMQIOLoop() You can also manually install this IOLoop as the global tornado instance, with: from zmq.eventloop.ioloop import ZMQIOLoop loop = ZMQIOLoop() loop.install() PyZMQ and gevent¶ PyZMQ ≥ 2.2.0.1 ships with a gevent compatible API as zmq.green. To use it, simply: import zmq.green as zmq Then write your code as normal. Socket.send/recv and zmq.Poller are gevent-aware. In PyZMQ ≥ 2.2.0.2, green.device and green.eventloop should be gevent-friendly as well. Note The green device does not release the GIL, unlike the true device in zmq.core. zmq.green.eventloop includes minimally patched IOLoop/ZMQStream in order to use the gevent-enabled Poller, so you should be able to use the ZMQStream interface in gevent apps as well, though using two eventloops simultaneously (tornado + gevent) is not recommended. Warning There is a known issue in gevent ≤ 1.0 or libevent, which can cause zeromq socket events to be missed. PyZMQ works around this by adding a timeout so it will not wait forever for gevent to notice events. The only known solution for this is to use gevent ≥ 1.0, which is currently at 1.0b3, and does not exhibit this behavior. zmq.green is simply gevent_zeromq, merged into the pyzmq project.
http://pyzmq.readthedocs.io/en/latest/eventloop.html
CC-MAIN-2017-47
refinedweb
1,184
68.16
Red Hat Bugzilla – Bug 188984 import schema from openldap : syntax oid problem Last modified: 2008-08-11 19:46:12 EDT Description of problem: Converted in ldif and started the server with it. (you will need this too :) # /opt/fedora-ds/slapd-afed/start-slapd [13/Apr/2006:14:17:09 +0200] dse - The entry cn=schema in file /opt/fedora-ds/slapd-afed/config/schema/98supann.ldif is invalid, error code 21 (Invalid syntax) - attribute type supannCivilite: Unknown attribute syntax OID " 1.3.6.1.4.1.1466.115.121.1.44" [13/Apr/2006:14:17:09 +0200] dse - Please edit the file to correct the reported problems and then restart the server. Version-Release number of selected component (if applicable): Fedora Core 4 Directory Server 1.02 How reproducible: Convert in ldif Try to start FDS with it. Additional info: Managed to resolve the pb by replacing the oid with 1.3.6.1.4.1.1466.115.121.1.15 *** This bug has been marked as a duplicate of 196918 *** Bug already CLOSED. setting screened+ flag
https://bugzilla.redhat.com/show_bug.cgi?id=188984
CC-MAIN-2017-17
refinedweb
180
56.96
A utility for converting package:js objects to Maps and Lists This was a workaround for dart-lang/sdk issue #27079 but now can be used to convert opaque JS lists and maps. Also exposes JSON.stringify() as stringify() see test/jsifier_test.dart for an example Please file feature requests and bugs at the issue tracker. Add this to your package's pubspec.yaml file: dependencies: jsifier: "^1.1.0" You can install packages from the command line: with pub: $ pub get Alternatively, your editor might support pub get. Check the docs for your editor to learn more. Now in your Dart code, you can use: import 'package:jsifier/jsifier.dart'; We analyzed this package on Jun 12, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using: Detected platforms: web, other Primary library: package:jsifier/jsifier.dartwith components: js. Package is getting outdated. The package was released 94 weeks ago. jsifier.dart. Fix analysis and formatting issues. Analysis or formatting checks reported 1 hint. Strong-mode analysis of lib/src/jsifier_base.dartgave the following hint: line: 14 col: 33 'JSON' is deprecated and shouldn't be used.
https://pub.dartlang.org/packages/jsifier
CC-MAIN-2018-26
refinedweb
194
53.27
recvmsg - receive a message from a socket #include <sys/socket.h> ssize_t recvmsg(int socket, struct msghdr *message, int flags); The recvmsg() function shall receive a message from a connection-mode or connectionless-mode socket. It is normally used with connectionless-mode sockets because it permits the application to retrieve the source address of received data. The recvmsg()msg() function shall receive messages from unconnected or connected sockets and shall return the length of the message. The recvmsg() function shall return the total length of the message., and MSG_TRUNC shall be set in the msg_flags member of the msghdr structure.msg() shall block until a message arrives. If no messages are available at the socket and O_NONBLOCK is set on the socket's file descriptor, the recvmsg() function shall fail and set errno to [EAGAIN] or [EWOULDBLOCK]. In the msghdr structure, the msg_name and msg_namelen members specify the source address if the socket is unconnected. If the socket is connected, the msg_name and msg_namelen members shall be ignored. The msg_name member may be a null pointer if no names are desired or required. The msg_iov and msg_iovlen fields are used to specify where the received data shall be stored.. Upon successful completion, the msg_flags member of the message header shall() shall return the length of the message in bytes. If no messages are available to be received and the peer has performed an orderly shutdown, recvmsg() shall return 0. Otherwise, -1 shall be returned and errno set to indicate the error. The recvmsg(). - [ECONNRESET] - A connection was forcibly closed by a peer. - [EINTR] - This function was interrupted by a signal before any data was available. - [EINVAL] - The sum of the iov_len values overflows(), recv(), recvfrom(), select(), send(), sendmsg(), sendto(), shutdown(), socket(), the Base Definitions volume of IEEE Std 1003.1-2001, <sys/socket.h> First released in Issue 6. Derived from the XNS, Issue 5.2 specification.
http://pubs.opengroup.org/onlinepubs/009695399/functions/recvmsg.html
CC-MAIN-2015-22
refinedweb
317
56.05
In this post we’ll extend the “Actor” class to include a few more useful properties. We’ll start of by creating a new folder under the “Models” folder called “Interfaces”. In this new folder, create an interface called “IEntity”. Add the following namespaces: using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; The interface will look like below: interface IEntity { BoundingBox BoundingBox { get; } Model Model { get; set; } Vector3 Position { get; set; } Vector3 Rotation { get; set; } Vector3 Scale { get; set; } } That’s all we need for the interface. Now we just need to hook that up with the “Actor” class. Open the “Actor” class and change the class declaration to: public class Actor : IEntity We need to add in the new properties from the interface into our “Actor” class: public BoundingBox BoundingBox { get { return new BoundingBox(Position - Scale / 2f, Position + Scale / 2f); } } public Vector3 Position { get { return position; } set { position = value; } } public Vector3 Rotation { get { return rotation; } set { rotation = value; } } public Vector3 Scale { get { return scale; } set { scale = value; } } That’s it. We now have a calculated BoundingBox for our model which will come in handy when we introduce the Physics part of the engine.
https://projectvanquish.wordpress.com/tag/models/
CC-MAIN-2017-22
refinedweb
195
50.57
Hi.. I'm programming c-code and all methods is working fine.. Then I would like to include headers and global values which should be possible to be edited through every existing file.. But when I include one of my files in the makefile it says: The makefile looks like thisThe makefile looks like this# make ---> make: Circular staff.o <- staff.o dependency dropped. ---> make: `edit' is up to date. The staff.h looks like this..The staff.h looks like this..objects = main.o drive.o staff.o edit : $(objects) cc -lm -o edit $(objects) main.o : global.h drive.o : drive.h global.h staff.o : staff.o global.h .PHONY: clean clean : rm edit $(objects) If anybody know what might be the problem, please write..If anybody know what might be the problem, please write..#include <stdio.h> #include <string.h> #include <stdlib.h> #ifndef STAFF_H #define STAFF_H // Staff.c char *find_staffmember (char *, char[], int); //char *appendchar(char *, size_t, char); int staff_update(char[], char[], char[]); #endif - Danny
https://cboard.cprogramming.com/c-programming/90825-makefile-problem.html
CC-MAIN-2017-22
refinedweb
170
78.04
import org.apache.http.client.methods.HttpPost importHow to continuously poll the server for incoming response using these APIs?Hi I am trying to connect to moodle with this example and i am just getting the login page as response after the http post request. Home » Blog » Java » Java Socket Programming Socket Server, Client example.For example, tomcat server running on port 8080 waits for client requests and once it get any client request, it respond to them. Http client and server. What is HTTP?This is a simple example: a HTTP client. Yes, you can now make HTTP requests as well as serve them. The client is asynchronous and uses the same event handling paradigm. You may run both client and server application in 2 CMD windows. Enter a message in the client and it will send to the server.May, 9th 2012. OpenSSL HMAC Hasing Example in C. February, 26th 2013. Compiling and Installing OpenSSL for 32 bit Windows. HTTP servers and clients. tornado.httpserver — Non-blocking HTTP server. tornado.httpclient — Asynchronous HTTP client.This module provides a simple command-line interface to fetch a url using Tornados HTTP client. Example usage HttpResponseMessage response await client.PutAsJsonAsync( ". api/products/product.IdSets the base URI for HTTP requests. Change the port number to the port used in the server app.Note that HttpClient can throw exceptions for other reasons — for example, if the request times out. 16.9.7 Byte Stream Connection Server Example. The server end is much more complicated. Since we want to allow multiple clients to be connected to the server at the same time, it would be incorrect to wait for input from a single client by simply calling read or recv. The server interprets the message headers and most of them are transformed into HTTP headers and sent back to the client together with the message-body.The eval scheme can seriously threaten the integrity of the Erlang node housing a web server, for example Example: A Simple HTTP Server. RMI: Remote Method Invocation.A simple HTTP server that generates a Web page showing all of the data that it received from the Web client (usually a browser). Event-driven I/O HTTP Client Server for Clojure: small, efficient, Ring-compatible. Asynchronous and websocket supported.HTTP Streaming example. First call of send!, sends HTTP status and Headers to client. This is a two-process example demonstrating simple asynchronous message delivery between a client and server process. Both asynchclient.c and asynchserver.c files share the same header, asynch server.h, to find each other using the registered name The server can accept connections from multiple clients. For each client, the server just echoes what a client sends it.In the example, the clients address and port are saved in an array, and in general a server will keep some sort of state about each client. ChatInterface client new Chat(name) ChatInterface server (ChatInterface)Naming.lookup("rmiYou have to put VM arguments like this java -cp rmiserver.jar:/var/www/html/classes/compute.jar -Djava.rmi. server.useCodebaseOnlyfalse -Djava.rmi.server.codebasehttp "Run the Fortune Client example now.")tr("Computers are not intelligent. They only think they are.") Our server generates a list of random fortunes that it can send to connecting clients. Whats the point?Clients send requests using an HTTP method request.The httpserver package provides higher-level building blocks.several examples that show how easy it is to write Dart HTTP servers and clients. Basic Server/Client Example using Windows Communication Foundation (WCF) programming Author: HasanI want to make a very simple Server/Client application. Microsoft offers a great tool called WindowsStep 1 Create a URI to serve as the base address. Dim baseAddress As New Uri(" http For example, The HTTP request that is sent when you perform a search on MDN for the term " client server overview" will look a lot like the text shown below (it will not be identical because parts of the message depend on your browser/setup). Android Chat example, with server sending individual message to specify client.Multi-Client Server chat application using java swing Android - Duration: 2:08. Mohammed Aboullaite 40,557 views. Examples. Simple Echo server and client. simpleclient.py - simple TCP client.echoclientssl.py - simple SSL client. AMP server client variants. ampserver.py - do math using AMP. 16 thoughts on Websocket Example: Server, Client and LoadTest.Conscrypting native SSL for Jetty. Testing JDK 9 with Dynamic Module Switching. Jetty ReactiveStreams HTTP Client. In HTTP, there are two different roles: server and client. In general, the client always initiates the conversation the server replies.For example: Another helpful way to familiarize yourself with HTTP is to use a dedicated client, such as cURL. Example: HTTP Client and Server in the Same Local Host. A network host is usually either a client or a server but it is possible for a host to be both. Lets see an example of this. The clientserver model is a distributed application structure that partitions tasks or workloads between the providers of a resource or service, called servers, and service requesters, called clients. Often clients and servers communicate over a computer network on separate hardware Our HTTP client (the Firefox browser) passes this text to our HTTP server written in Java. You can see that request type is GET and protocol used here is HTTP/1.1.Thats all about how to create HTTP server in Java. This is a good example to learn network programming in Java. Initially the paradigm about web was Client/Server model, in which clients job is to request data from a server, and aNow using AJAX it was easy to communicate with server but we still need more power when talk in term of real time applications. an simple example http request could be like bellow. Simple command line client. An example client is also available. Downloading the servers own source code from the serverRunning the example server and client with info level logging output: HTTP2LOGinfo node ./example/server.js.. Here is an example of how to extend a very simple client-server demo program into a fully functioning (but simple) Chat Client/Server package. There are five stages involved Is your apache server running on 80? As you attached the source code of server it seems your server running on 8000 port so try to communicate with your server using this port. This example demonstrates how to process HTTP responses using a response handler. This is the recommended way of executing HTTP requests and processing HTTP responses.Client authentication. Blog Java J2EE Java NIO (Non-blocking I/O) with Server-Client Example Same as EvictingQueue. Embedded Web Server Tutorial: How to Start Embedded HTTP Jersey server during Java Application Startup. The client-server API typically uses HTTP PUT to submit requests with a client-generated transaction identifier. This means that these requests are idempotent.Example request: GET /matrix/client/versions HTTP/1.1. Response For example, we often use an HTTP client library to retrieve information from a web server and to invoke a remote procedure call via web services. However, a general purpose protocol or its implementation sometimes does not scale very well.. HTTP Services Configuration Guide 4. HTTPS--HTTP Server and Client with SSL 3.0. Declaring a Certificate Authority Trustpoint. Step 5.(Optional) Configures the Device to obtain certificates from the CA through an HTTP proxy server. Example go get github.com/danil/go-client-server-example/cmd/server-example.You can also start the server in non-recursive mode. For example, for the root directory, as it can be too many files. server-example -h localhost -p 8080 -d /. Generate server and client code using the protocol buffer compiler.Use the Go gRPC API to write a simple client and server for your service.Why use gRPC? Our example is a simple route mapping application that lets clients get Both server and client should support this capability, but this should be absolutely transparent to your application.Consider following examples of SOAP servers: CGI: use SOAP::Transport:: HTTP In a previous example we learnt about the basics of socket programming in C. In this example we shall build a basic ECHO client and server. The server/client shown here use TCP sockets or SOCKSTREAM. Package http provides HTTP client and server implementations. Get, Head, Post, and PostForm make HTTP (or HTTPS) requestsHandler is typically nil, in which case the DefaultServeMux is used. A trivial example server is In this example I am writing directly to the client socket to keep things simple. The recommended way to write data to the HTTPS server is to use specialized clients like request or superagent.Node.js UDP Server and Client Example. TCP echo server using streams: import asyncio. async def handleecho(reader, writer): data await reader.read(100) message data.decode() addr writer.getextrainfo(peername) print("Received r from r" (message, addr)).HTTP client example. A detailed step-by-step tutorial on how to log the client and server HTTP headers using Spring-WS and Spring Boot.In this example, we will get access to the HTTP headers by using the writeTo() method of the WebServiceMessage interface. Instances of the http2.Http2Session class represent an active communications session between an HTTP/2 client and server.The following example creates an HTTP/2 server using the compatibility API This example implements a chat server and client.This example illustrates the use of asio in a simple single-threaded server implementation of HTTP 1.0. It demonstrates how to perform a clean shutdown by cancelling all outstanding asynchronous operations. print(content) Server example: from aiohttp import web async def handle(request): name request.matchinfo.get(name, "Anonymous") text "Hellofrom aiohttp.testutils import TestClient. with loopcontext() as loop: app create exampleapp(loop) client TestClient(app) root "http Once a client connects, the server receives data from the client and echoes (sends) the data received back to the client.If the client and server are executed on the sample computer, the client can be started as follows Example - Language Server. Language servers allow you to add your own validation logic to files open in VS Code.The above installs all dependencies and opens one VS Code instances containing both the client and server code. CloseableHttpClient.java:106) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:57) atExample itself explaining how to connect. Compile and execute. To access the local server, open a browser at. 50 thoughts on Example of Client-Server Program in C (Using Sockets and TCP). rahul joshi September 4, 2014 at 6:06 am. your program isot easy easy to understand also not executable . plz make some changes in program.
http://dfei8.ml/page6101-http-server-client-example.html
CC-MAIN-2018-22
refinedweb
1,790
59.8
Around 15 years ago, as a newish graduate student, I got access to a Pentium-based Linux machine. One of the coolest things about this machine was the new RDTSC instruction that measured the number of clock ticks since the processor had been reset. This could be used to directly observe cache misses, branch mispredictions, and other low-level performance phenomena; it was a little like looking through a microscope for the first time. I ended up using the timestamp counter for a lot of things during the next few years, including in my Hourglass tool. Lately my student Yang Chen has been using RDTSC to measure the execution times of function calls that take on the order of 10 to 1000 cycles to execute. Unfortunately, this activity is no longer nearly as straightforward as it once was. This post lists some things we learned. It’s somewhat specific to GCC and Linux. Enabling Basic Processor-Level Timing Stability In the BIOS, turn off hyperthreading and anything having to do with turbo mode and frequency scaling. Turn off all OS-level frequency scaling as well; this is of course specific to the OS. These instructions worked fine for us. Avoiding Scheduling and Multicore Problems The scheduler can mess up benchmarking in two main ways. First, it can simply take the processor away from the code being benchmarked. Second, it can migrate code to a different processor, slowing it down and also causing problems because the timestamp counters are typically not closely synchronized across CPUs. There seem to be three approaches to dealing with context switches messing up timing: - Ignore them. This is reasonable when timing events that are very short because context switches aren’t that fast; they’ll show up as massive outliers that are easy to discard. - Minimize their impact by raising the priority of running code using sched_setscheduler() and by pinning code to a single processor using the taskset command. Both of these are easy in Linux, although priority elevation requires root privileges. - Lock out the scheduler by disabling interrupts. This can be done from user-mode using the iopl(3) call, or can it be done by running code in a kernel module. Either way, root privileges are required. Incautious disabling of interrupts is a good way to necessitate hard reboots of a machine. Dealing with Out-of-Order Execution The RDTSC instruction is not serializing: it can be reordered significantly with respect to other in-flight instructions, causing serious (apparent) timing anomalies. Recently this fantastic white paper addressing this issue was released by Intel. It would have saved Yang and me a ton of time if it had existed six months earlier. The short answer is that if you’re running a newish processor in 64-bit mode, just use these functions to start and stop the timer: typedef unsigned long long ticks; static __inline__ ticks start (void) { unsigned cycles_low, cycles_high; asm volatile ("CPUID\n\t" "RDTSC\n\t" "mov %%edx, %0\n\t" "mov %%eax, %1\n\t": "=r" (cycles_high), "=r" (cycles_low):: "%rax", "%rbx", "%rcx", "%rdx"); return ((ticks)cycles_high << 32) | cycles_low; } static __inline__ ticks stop (void) { unsigned cycles_low, cycles_high; asm volatile("RDTSCP\n\t" "mov %%edx, %0\n\t" "mov %%eax, %1\n\t" "CPUID\n\t": "=r" (cycles_high), "=r" (cycles_low):: "%rax", "%rbx", "%rcx", "%rdx"); return ((ticks)cycles_high << 32) | cycles_low; } Why use RDTSC to start the timer and RDTSCP to stop it? The white paper explains this and contains a lot of other good details. Other Precautions - Code and data should be cache-line aligned when possible. - The machine under test should be quiescent. It could also be booted in single-user mode, but we don’t bother. - Turning off ASLR seems like a good idea, though we have not done the measurements to see how much it affects repeatability. - It used to be the case that paging would affect timing results, so we would use the mlockall() call to pin a process’s pages into RAM. Machines have so much memory these days that this hardly seems necessary. - It’s possible to boot a multicore with one or more processors disabled; this will reduce or eliminate TLB shootdowns, other cache invalidation traffic, and memory system contention. Again, we don’t bother. Analyzing Data The last important piece of the puzzle is to use robust statistical methods. Never take the average of a series of timing values: their distribution is almost always skewed by massive outliers. The minimum value may or may not be safe to use — there could be outliers on the low end due to migrations between unsynchronized processors. A good starting point would be to look at data points at the 25th, 50th, and 75th percentiles; if these are not very close together, something is probably amiss. Any time you get timing data from a real processor, it must be scrutinized carefully to see if it makes sense. A good understanding of modern processor architectures really helps. We’ve seen odd things happen such as a machine using frequency scaling when we thought it had been permanently disabled. Either a kernel upgrade or similar disturbed our configuration or we simply messed up. Summary Modern computers create a fairly hostile environment for accurate benchmarking of short-duration events. To do it right, you want to use a dedicated machine, carefully navigate the issues I’ve outlined (and whatever others I’ve missed), and develop a benchmarking procedure that includes plenty of sanity checks. Thank you for the great advice! Every modern architecture should have at the very least an ultra-low-power microsecond-accurate atomic clock that is powered independently of the processor, never turned off, and accessible–from user space–within 50 cycles or so. That’d be a start. A nanosecond-accurate clock with lower latency would be better of course, but apparently that’s way too much to ask for. It amazes me that they can make $10 watches that run for years on a single tiny battery and are accurate to within one second in a year, and yet PC clocks suck terribly and don’t have decent resolution. The Perl Advent Calendar offers a little bit of help for benchmarking: The FFTW project created a header file that gives access to cpu counters on a variety of architectures, if its helpful: Look for ‘cycle counters’ Thanks Jon, I hadn’t seen this. But their x86 and x86-64 functions are not good for measuring short-duration events, and shouldn’t be used for that purpose.
https://blog.regehr.org/archives/330
CC-MAIN-2021-43
refinedweb
1,088
59.84
Clang 3.4 Release Notes¶ - Introduction - What’s New in Clang 3.4? - Significant Known Problems - Additional Information Introduction¶ This document contains the release notes for the Clang C/C++/Objective-C frontend, part of the LLVM Compiler Infrastructure, release 3.4?¶ Some of the major new features and improvements to Clang are listed here. Generic improvements to Clang as a whole or to its underlying infrastructure are described first, followed by language-specific sections with improvements to Clang’s support for those languages. Last release which will build as C++98¶ This is expected to be the last release of Clang which compiles using a C++98 toolchain. We expect to start using some C++11 features in Clang Clang to have a heads up that the next release will involve a substantial change in the host toolchain requirements. Note that this change is part of a change for the entire LLVM project, not just Clang. Major New Features¶ Improvements to Clang’s diagnostics¶ Clang’s diagnostics are constantly being improved to catch more issues, explain them more clearly, and provide more accurate source information about them. The improvements since the 3.3 release include: -Wheader-guard warns on mismatches between the #ifndef and #define lines in a header guard. #ifndef multiple #define multi #endif returns warning: ‘multiple’ is used as a header guard here, followed by #define of a different macro [-Wheader-guard] -Wlogical-not-parentheses warns when a logical not (‘!’) only applies to the left-hand side of a comparison. This warning is part of -Wparentheses. int i1 = 0, i2 = 1; bool ret; ret = !i1 == i2; returns warning: logical not is only applied to the left hand side of this comparison [-Wlogical-not-parentheses] Boolean increment, a deprecated feature, has own warning flag -Wdeprecated-increment-bool, and is still part of -Wdeprecated. Clang errors on builtin enum increments and decrements in C++. enum A { A1, A2 }; void test() { A a; a++; } returns error: cannot increment expression of enum type ‘A’ -Wloop-analysis now warns on for-loops which have the same increment or decrement in the loop header as the last statement in the loop. void foo(char *a, char *b, unsigned c) { for (unsigned i = 0; i < c; ++i) { a[i] = b[i]; ++i; } } returns warning: variable ‘i’ is incremented both in the loop header and in the loop body [-Wloop-analysis] -Wuninitialized now performs checking across field initializers to detect when one field in used uninitialized in another field initialization. class A { int x; int y; A() : x(y) {} }; returns warning: field ‘y’ is uninitialized when used here [-Wuninitialized] Clang can detect initializer list use inside a macro and suggest parentheses if possible to fix. Many improvements to Clang’s typo correction facilities, such as: - Adding global namespace qualifiers so that corrections can refer to shadowed or otherwise ambiguous or unreachable namespaces. - Including accessible class members in the set of typo correction candidates, so that corrections requiring a class name in the name specifier are now possible. - Allowing typo corrections that involve removing a name specifier. - In some situations, correcting function names when a function was given the wrong number of arguments, including situations where the original function name was correct but was shadowed by a lexically closer function with the same name yet took a different number of arguments. - Offering typo suggestions for ‘using’ declarations. - Providing better diagnostics and fixit suggestions in more situations when a ‘->’ was used instead of ‘.’ or vice versa. - Providing more relevant suggestions for typos followed by ‘.’ or ‘=’. - Various performance improvements when searching for typo correction candidates. LeakSanitizer is an experimental memory leak detector which can be combined with AddressSanitizer. New Compiler Flags¶ - Clang no longer special cases -O4 to enable lto. Explicitly pass -flto to enable it. - Clang no longer fails on >= -O5. These flags are mapped to -O3 instead. - Command line “clang -O3 -flto a.c -c” and “clang -emit-llvm a.c -c” are no longer equivalent. - Clang now errors on unknown -m flags (-munknown-to-clang), unknown -f flags (-funknown-to-clang) and unknown options (-what-is-this). C Language Changes in Clang¶ - Added new checked arithmetic builtins for security critical applications. C++ Language Changes in Clang¶ - Fixed an ABI regression, introduced in Clang 3.2, which affected member offsets for classes inheriting from certain classes with tail padding. See PR16537. - Clang 3.4 supports the 2013-08-28 draft of the ISO WG21 SG10 feature test macro recommendations. These aim to provide a portable method to determine whether a compiler supports a language feature, much like Clang’s __has_feature macro. C++1y Feature Support¶ Clang 3.4 supports all the features in the current working draft of the upcoming C++ standard, provisionally named C++1y. Support for the following major new features has been added since Clang 3.3: - Generic lambdas and initialized lambda captures. - Deduced function return types (auto f() { return 0; }). - Generalized constexpr support (variable mutation and loops). - Variable templates and static data member templates. - Use of ' as a digit separator in numeric literals. - Support for sized ::operator delete functions. In addition, [[deprecated]] is now accepted as a synonym for Clang’s existing deprecated attribute. Use -std=c++1y to enable C++1y mode. OpenCL C Language Changes in Clang¶ - OpenCL C “long” now always has a size of 64 bit, and all OpenCL C types are aligned as specified in the OpenCL C standard. Also, “char” is now always signed. Internal API Changes¶ These are major API changes that have happened since the 3.3 release of Clang. If upgrading an external codebase that uses Clang as a library, this section should help get you past the largest hurdles of upgrading. Wide Character Types¶ The ASTContext class now keeps track of two different types for wide character types: WCharTy and WideCharTy. WCharTy represents the built-in wchar_t type available in C++. WideCharTy is the type used for wide character literals; in C++ it is the same as WCharTy, but in C99, where wchar_t is a typedef, it is an integer type. Static Analyzer¶ The static analyzer has been greatly improved. This impacts the overall analyzer quality and reduces a number of false positives. In particular, this release provides enhanced C++ support, reasoning about initializer lists, zeroing constructors, noreturn destructors and modeling of destructor calls on calls to delete. Clang Format¶ Clang now includes a new tool clang-format which can be used to automatically format C, C++ and Objective-C source code. clang-format automatically chooses linebreaks and indentation and can be easily integrated into editors, IDEs and version control systems. It supports several pre-defined styles as well as precise style control using a multitude of formatting options. clang-format itself is just a thin wrapper around a library which can also be used directly from code refactoring and code translation tools. More information can be found on Clang Format’s site. Windows Support¶ - clang-cl provides a new”. clang-cl targets the Microsoft ABI by default. Please note that this driver mode and compatibility with the MS ABI is highly experimental. Python Binding Changes¶ The following methods have been added: Additional Information¶ A wide variety of additional information is available on the Clang web page. The web page contains versions of the API documentation which are up-to-date with the Subversion revision of the source code. You can access versions of these documents specific to this release by going into the “clang/docs/” directory in the Clang tree. If you have any questions or comments about Clang, please feel free to contact us via the mailing list.
http://llvm.org/releases/3.4/tools/clang/docs/ReleaseNotes.html
CC-MAIN-2016-36
refinedweb
1,268
55.44
41644/double-click-in-selenium-using-python I am currently using Selenium with Python and I'm able to click on the page wherever I want, by using the code below. But I want it to double click. I'm not very good with the action chains and I know I need that for the double click. Can anyone help me with what I need to change the code? The snippet is: user = self.find_element_by_id("selUsers") for option in user.find_elements_by_tag_name("option"): if option.text == "Admin, Ascender": option.click() Hey there! As far as I know, the action chains are the only best option to this problem The code is something like this: from selenium.webdriver.common.action_chains import ActionChains driver=self.webdriver user = self.find_element_by_id("selUsers") for option in user.find_elements_by_tag_name("option"): if option.text == "Admin, Ascender": actionChains = ActionChains(driver) actionChains.double_click(option).perform() Hope this is helpful Try Actions class to perform this Actions action ...READ MORE Here, I give you working script which ...READ MORE Use this code, this will help you: from ...READ MORE This might work for you. It friend, getElementByClassName is not a method on ...READ MORE Hey there! You should be able to get ...READ MORE OR
https://www.edureka.co/community/41644/double-click-in-selenium-using-python
CC-MAIN-2019-30
refinedweb
204
63.66
Created on 2013-10-30 23:12 by gvanrossum, last changed 2014-01-28 05:48 by berker.peksag. This issue is now closed. (Bruce Leban, on python-ideas:) """ ntpath still gets drive-relative paths wrong on Windows: >>> ntpath.join(r'\\a\b\c\d', r'\e\f') '\\e\\f' # should be r'\\a\b\e\f' >>> ntpath.join(r'C:\a\b\c\d', r'\e\f') '\\e\\f' # should be r'C:\e\f' (same behavior in Python 2.7 and 3.3) """ (Let's also make sure PEP 428 / pathlib fixes this.) Looking at this some more, I think one of the reasons is that isabs() does not consider paths consisting of *just* a drive (either c: or \\host\share) to be absolute, but it considers a path without a drive but starting with a \ as absolute. So perhaps it's all internally inconsistent. I'm hoping Bruce has something to say to this. I'm willing to fix this. ntpath.join behaves weird in other situations too: >>> ntpath.join('C:/a/b', 'D:x/y') 'C:/a/b\\D:x/y' In fact, I don't know what the above should return. PEP 428 offers a reasonable view. Search for "anchored" and read on. Added a possible fix for ntpath.join. Didn't touch isabs yet. A non-UNC windows path consists of two parts: a drive and a conventional path. If the drive is left out, it's relative to the current drive. If the path part does not have a leading \ then it's relative to the current path on that drive. Note that Windows has a different working dir for every drive. x\y.txt # in dir x in current dir on current drive \x\y.txt # in dir x at root of current drive E:x\y.txt # in dir in current dir on drive E E:\x\y.txt # in dir x at root of drive E UNC paths are similar except \\server\share is used instead of X: and there are no relative paths, since the part after share always starts with a \. Thus when joining paths, if the second path specifies a drive, then the result should include that drive, otherwise the drive from the first path should be used. The path parts should be combined with the standard logic. Some additional test cases tester("ntpath.join(r'C:/a/b/c/d', '/e/f')", 'C:\e\f') tester("ntpath.join('//a/b/c/d', '/e/f')", '//a/b/e/f') tester("ntpath.join('C:x/y', r'z')", r'C:x/y/z') tester("ntpath.join('C:x/y', r'/z')", r'C:/z') Andrei notes that the following is wrong but wonders what the correct answer is: >>> ntpath.join('C:/a/b', 'D:x/y') 'C:/a/b\\D:x/y' The /a/b part of the path is an absolute path on drive C and isn't "transferable" to another drive. So a reasonable result is simply 'D:x/y'. This matches Windows behavior. If on Windows you did $ cd /D C:\a\b $ cat D:x\y it would ignore the current drive on C set by the first command and use the current drive on D. tester("ntpath.join('C:/a/b', 'D:x/y')", r'D:x/y') tester("ntpath.join('//c/a/b', 'D:x/y')", r'D:x/y') Do we even have a way to get the current directory for a given drive? (I guess this is only needed for C: style drives.) With previous patch: >>> ntpath.join('C:a/b', 'D:y/z') 'D:y/z\\y/z' Should be 'D:y/z'. Here is other patch which implements same algorithm as in pathlib (issue19908). Added new tests, removed duplicated tests. If there are no objections, I'll commit this patch tomorrow. I just discovered that perhaps ntpath.join should be even more clever. Windows supports current directories for every drive separately, so perhaps ntpath.join('c:/x', 'd:/y', 'c:z') should return 'c:/x\\z', not 'c:/z'. Could anyone please check it? Create directory x/z on drive c: and directory y on drive d:, then execute following commands: cd c:/x cd d:/y cd c:z What is resulting current working directory? Here is a patch which implements this algorithm. > so perhaps ntpath.join('c:/x', 'd:/y', 'c:z') should return 'c:/x\\z', not 'c:/z'. 'c:z' is consistent with what .NET's System.IO.Path.Combine does: via : import System.IO.Path; print System.IO.Path.Combine('c:/x', 'd:/y', 'c:z') returns 'c:z' > Could anyone please check it? Create directory x/z on drive c: and directory y on drive d:, then execute following commands: > cd c:/x > cd d:/y > cd c:z > > What is resulting current working directory? c:\>cd c:/x c:\x>cd e:\y c:\x>cd c:z Het systeem kan het opgegeven pad niet vinden. # file not found, in Dutch c:\x>cd c:\z Yes, there is a seperate current directory for each drive, but cd does not switch drives. (cd e:\f does not mean you actually go to e:\f - it just changes the current directory on the e:-drive). I don't think those semantics are sensible for joining paths... Sorry, I was a bit too quick - I forgot to create c:\x\z. Now this is the result: c:\x\z>cd c:/x c:\x>cd e:/y c:\x>cd c:z c:\x\z> However, the behavior does not work in, for example, a 'Save as...' window, where c:z will always return "illegal filename" Thank you Merlijn for your information. So which patch is more preferable? I'm not sure whether that question was aimed at me -- I think both options have their merits, but I'd suggest to adopt the .NET semantics. The semantics are also explicitly defined [1] and the behavior seems to be acceptable for the .NET world. [1] I think a python programmer is going to expect that join(a, b, c) == join(join(a, b), c) so the answer to Serhiy's example should be 'c:z'. New changeset 6b314f5c9404 by Serhiy Storchaka in branch '2.7': Issue #19456: ntpath.join() now joins relative paths correctly when a drive New changeset f4377699fd47 by Serhiy Storchaka in branch '3.3': Issue #19456: ntpath.join() now joins relative paths correctly when a drive New changeset 7ce464ba615a by Serhiy Storchaka in branch 'default': Issue #19456: ntpath.join() now joins relative paths correctly when a drive Committed first patch (with small change, ntpath.join('c:', 'C:') now returns 'C:'). There is yet one argument for first option: it is almost impossible (with current design) to implement second option in pathlib. Hi Serhiy, there are commented-out lines in the 2.7 version of the patch. Are they intentionally there?: + #tester("ntpath.join('//computer/share', 'x/y')", '//computer/share\\x/y') + #tester("ntpath.join('//computer/share/', 'x/y')", '//computer/share/x/y') + #tester("ntpath.join('//computer/share/a/b', 'x/y')", '//computer/share/a/b\\x/y') + #tester("ntpath.join('//computer/share', '/x/y')", '//computer/share/x/y') + #tester("ntpath.join('//computer/share/', '/x/y')", '//computer/share/x/y') + #tester("ntpath.join('//computer/share/a', '/x/y')", '//computer/share/x/y')
https://bugs.python.org/issue19456
CC-MAIN-2018-09
refinedweb
1,230
68.97
Profiles To make this correct, you need to configure your container. The base configuration is already on your system if you have used a regular distribution. You can further configure this with commands, but most people will use YAML files. The base usually looks like the one below. The file resides in /etc/lxc/default.conf. lxc.net.0.link = lxcbr0 lxc.net.0.flags = up lxc.net.0.hwaddr = 00:16:3e:xx:xx:xx Each container follows the settings according to the default profile and the file mentioned above. You can print the default file as per below. For more configuration, it is best to make new profiles. Each profile will contain some configuration detail, in our case networking. You can change any setting in your container with a profile, and this makes even more sense when you want to run it both locally and on a platform. description: Default LXD profile devices: eth0: name: eth0 network: lxdbr0 type: nic root: path: / pool: ros type: disk name: default used_by: - /1.0/instances/guiapps - /1.0/instances/ff The resulting output is a YAML file. All your profiles will be in the same format. With LXC itself, you can create, remove, and edit your profile. You can see in the file that the default uses the lxdbr0 network and type nic. Now, create a new profile using the following: Before any container is running, edit the profile: You use YAML format in the files that create these profiles. Note that the name “eth0” is the internal container name. The “parent” is what you have on your system, and you check it yourself using: The printout will vary depending on what you have had before. You should also know that you can do the bridging from outside of the container with the brctl tools. Using it in your container Once you have created a profile, you want to add it to your container. This is done with the same set of programs ‘lxc’. First, make sure you have a container, in this example, the container is named ‘ff’: The change takes effect when you restart networking in the container. The easiest and safest is to always add profiles only in stopped containers. Routed A bridged connection is one where your container receives a MAC address on the same Ethernet interface as your host. This is what you did earlier in this post. With a few more tricks, you can have your router assign a separate IP address to the container, and you can set this in your container. Although, when you use macvlan, you may run into trouble using Wi-Fi. WPA/WPA2 will not accept the two addresses, so your Wi-Fi will break, as your host will not use the Wi-Fi. The earlier example uses the brctl tools since lxc has created their own. This gets an address from the host, not the router. You can get the address from the router if you wish. Again, only if you use a wired connection or an insecure Wi-Fi. When you have made sure that you have a network connection on your host, you can connect that to your container. Change the word parent and set your nictype to macvlan. description: Setting for the network interface devices: eth0: name: eth0 nictype: macvlan parent: enp3s0 type: nic name: Route used_by: - /1.0/instances/guiapps - /1.0/instances/ff You will have to make sure the parent value matches your configuration, so make sure you create it dynamically. After this is done, you can start your container and find it in your router’s list of host destinations. Well, they are interfaces, to be technical about it. Figure 1: The container now shows up in your router Mobile Profiles An interesting part of the Linux containers is that you can grab your configurations and dump them into YAML files. To create the files for this, you run the show option in LXC, then pipe into a file. The output follows the YAML standard, and you can then use these files to configure them elsewhere. To use this for a new container, use the set values. Ordinarily, you would set a value at a time, but you already have a file for this. You can see that you must put the values into the namespace 'user.network.config'. This is important to know when you want to add other values unrelated to networking. Conclusion Networking with your containers has many options, which can be confusing, but with some research and testing on your own, you can get it to work the way you want. The best part is that you can try one thing at a time using profiles. You will never screw up your current container, just remove the one that did not work and add the old one. This technique works for everything in a container.
https://linuxhint.com/lxc-network-configuration/
CC-MAIN-2021-21
refinedweb
817
72.87
Paneque and borrows some behavior from "Wise Cleaner". VstudioCleaner is basically a file and directory search engine which presents the results for deletion. The search 'filters' can be changed. Groups of filter settings can be associated with 'bookmarks' for quick recall. My personal hang ups with other applications are the inverse of the following features I offer and guidelines I try to adhere to when creating software. a path or using the Path... button to browse and select a path. If you need to specify multiple paths, you cannot use the Path... button because it does not append, it only knows how to set the search path. Multiple directory (folder) paths are specified by separating them by semicolon, as in: c:\dir1;c:\dir2\subdir1;d;\dir3\subdir2;e:\ You set your filters by either 'checking' or 'unchecking' the built-in filters or by adding your own filters. Once the search "Path" and "Filters" are set, press the "Locate" button to build up a list of files and directories. The resulting list will appear in its own dialog. You can sort the various columns (why, directory, file, extension, size) and right-click to remove files from the list. The right-click remove action only removes the names from the list, it does not remove anything from your computer. Once you have your list of files pruned down to those you want to delete from your computer, you can press the "delete" button.. private void openRegistry_Click(object sender, EventArgs e) { string appName = Application.ProductName; // Preset last place RegEdit visited to our registry section RegistryKey regEditKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey (@"Software\Microsoft\Windows\CurrentVersion\Applets\Regedit"); regEditKey.SetValue ("LastKey", @"My Computer\HKEY_CURRENT_USER\Software\" + appName); regEditKey.Close(); // Launch RegEdit which will default at the last place it was (our stuff). System.Diagnostics.Process.Start("regedit.exe"); } The second trick "to scroll listview left" was required when a user is editing a row in a ListView. Depending on the size of the UI, it is possible that part of the row is not visible. Before a column is edited, I wanted it to be in view so I had to scroll. /// <summary> /// WildCompare supports simple '*' wildcard pattern. /// Returns true if pattern matches even if raw text has more characters. /// </summary> /// <returns> true for partial match</returns> private bool WildCompare(string wildStr, int wildOff, string rawStr, int rawOff) { while (wildOff != wildStr.Length) { if (rawOff == rawStr.Length) return (wildStr[wildOff] == '*'); if (wildStr[wildOff] == '*') { if (wildOff + 1 == wildStr.Length) return true; do { // Find match with char after '*' while (rawOff < rawStr.Length && char.ToLower(rawStr[rawOff]) != char.ToLower(wildStr[wildOff + 1])) rawOff++; if (rawOff < rawStr.Length && WildCompare(wildStr, wildOff + 1, rawStr, rawOff)) return true; ++rawOff; } while (rawOff < rawStr.Length); if (rawOff >= rawStr.Length) return (wildStr[wildOff + 1] == '*'); } else { if (char.ToLower(rawStr[rawOff]) != char.ToLower(wildStr[wildOff])) return false; if (wildStr.Length == wildOff) return true; ++rawOff; } ++wildOff; } return true; } Because the pattern matching is complex I added a popup help dialog, launched by pressing the "?" button. The original version used a RichTextBox. I found it painful to setup font size and colorization, so I switched in version v1.5 to HTML. I wanted to keep vstudti.
https://www.codeproject.com/Articles/39228/Visual-Studio-Cleaner-and-More?fid=1545740&select=4125201&tid=4110919
CC-MAIN-2017-34
refinedweb
529
50.73
I’m now working with mpu9250 for my master thesis, but I’m quite new to hardware device. My goal is to collect the data at the sample rate and postprocess these data via allan deviation. So I just want to get the data from 512 bytes fifo, but when I’m trying to read out the data, it always overflows which annoying me a lot. I know the method is to set the reading speed faster than the fifo writing speed, so I remove the time sleep in my loop, but it seems overflows sooner than before. I’m a little bit confused, because the reading speed depends on the writing speed. here are my code: #!/usr/bin/env python3 import os import time import sys import struct import csv from datetime import datetime from mpu9250_FIFO import MPU9250 from navio.leds import Led def main(): # Initialize MPU9250 mpu = MPU9250() # Set maximum SPI bus speed in Hz, default=10000000 # MPU8250 features: # -- 1MHz SPI serial interface for communicating with all registers # -- 20MHz SPI serial interface for reading sensor and interrupt registers mpu.bus_open(max_speed_hz=10000000) # Hz # Initialize sensors # samle_rate unit is Hz # low_pass_filter_gt is the low pass filter for gyroscope and temperature sensors. possible values are: # Gyroscope Sensor | Temperature Sensor | Bits # 250 Hz | 4000 Hz | 0x00 NO_DLPF # 184 Hz | 188 Hz | 0x01 # 92 Hz | 98 Hz | 0x02 # 41 Hz | 42 Hz | 0x03 # 20 Hz | 20 Hz | 0x04 # 10 Hz | 10 Hz | 0x05 # 5 Hz | 5 Hz | 0x06 # 3600 Hz | 4000 Hz | 0x07 NO_DLPF # low_pass_filter_accel is the low pass filter for accelerometer, possible values are: # Accelerometer Sensor | Bits # 218.1 Hz | 0x00 # 218.1 Hz | 0x01 # 99 Hz | 0x02 # 44.8 Hz | 0x03 # 21.2 Hz | 0x04 # 10.2 Hz | 0x05 # 5.05 Hz | 0x06 # 420 Hz | 0x07 NO_DLPF sampleRate = 50 sampleRateDiv = int(1000 / sampleRate - 1) mpu.initialize(sample_rate_div=sampleRateDiv, low_pass_filter_gt=0x01, low_pass_filter_a=0x01) # Set accelerometer scale, default is 16G # BITS_FS_2G = 0x00 # BITS_FS_4G = 0x08 # BITS_FS_8G = 0x10 # BITS_FS_16G = 0x18 mpu.set_acc_scale(0x08) # +/-4G # Set gyroscope scale, default is 2000DPS # BITS_FS_250DPS = 0x00 # BITS_FS_500DPS = 0x08 # BITS_FS_1000DPS = 0x10 # BITS_FS_2000DPS = 0x18 mpu.set_gyro_scale(0x08) # +/-500dps # Enable FIFO to collect data mpu.enableFIFO(True) # Test connection: if mpu.testConnection(): print("Connection working.") else: print("Connection to one of the sensors is faulty.") # find new filename # fileending = 1 # while True: # if os.path.isfile('/home/pi/Duan/Python/meas_data/mpufile_{}_IMU.txt'.format(fileending)) is True: # fileending += 1 # else: # break # # open('', '', 1) enables line buffering # with open('/home/pi/Duan/Python/meas_data/mpufile_{}_IMU.txt'.format(fileending), 'w', 1) as dat_imu: now = datetime.now().strftime('%d-%m-%Y_%H:%M:%S') fname = '/home/pi/Duan/Python/meas_data/mpu9250_data_' + now + r'.txt' with open(fname, 'w', 1) as data_imu: # write headers to file data_imu.write('Sample Rate: %d Hz\n' % sampleRate) data_imu.write('mpu_accel_1, mpu_accel_2, mpu_accel_3, mpu_gyro_1, mpu_gyro_2, mpu_gyro_3, temp\n') #print("----1----") # Main loop while True: mpudata_a, mpudata_g, mpudata_temp = mpu.getFIFOData() #print("----2----") data = mpudata_a + mpudata_g + mpudata_temp # print(data) data_imu.write(str(data).replace("[", "").replace("]", "") + "\n") if __name__ == "__main__": led = Led() led.setColor('Green') errfile = "/home/pi/Duan/Python/errorfile.txt" with open(errfile, 'w', 1) as efile: try: main() except KeyboardInterrupt: led.setColor('Yellow') except Exception as e: led.setColor('Red') efile.write("Some error occured:\n{}".format(e)) def getFIFOData(self): while True: mpu_int_status = self.getIntStatus() INT_FIFO_OFLOW_BIT = 0x10 # the 4th bit is set to 1 when FIFO buffer is overflowed fifoCount = self.getFIFOCount() #print("fifoCount:%d" % fifoCount) if fifoCount < 14: continue # check for overflow (this shouldn't happen) elif (mpu_int_status & 0x10 == 0x10) or fifoCount>=512: print("fifoCount is: %d" % fifoCount) print("FIFO is overflow!") # print("Reset FIFO...") # self.resetFIFO() break else: packet_count = int(fifoCount/14) # print("packet count:%d" % packet_count) for i in range(0, packet_count): response = self.ReadRegs(self.__MPUREG_FIFO_R_W, 14) # print(response) # Get Accelerometer values for i in range(0, 3): data = self.byte_to_float(response[i * 2:i * 2 + 2]) self.accelerometer_data[i] = self.G_SI * data / self.acc_divider # print(self.accelerometer_data) # Get temperature i = 3 temp = self.byte_to_float(response[i * 2:i * 2 + 2]) self.temperature[i - 3] = (temp / 333.87) + 21.0 # print(self.temperature) # Get gyroscope values for i in range(4, 7): data = self.byte_to_float(response[i * 2:i * 2 + 2]) self.gyroscope_data[i - 4] = (self.PI / 180) * data / self.gyro_divider # print(self.gyroscope_data) return self.accelerometer_data, self.gyroscope_data, self.temperature def getIntStatus(self): return self.ReadReg(self.__MPUREG_INT_STATUS) def getFIFOCount(self): response = self.ReadRegs(self.__MPUREG_FIFO_COUNTH, 2) fifoCount = self.byte_to_float(response) return fifoCount def resetFIFO(self): self.WriteReg(self.__MPUREG_USER_CTRL, 0x00) self.WriteReg(self.__MPUREG_USER_CTRL, 0x04) # reset fifo mode self.WriteReg(self.__MPUREG_USER_CTRL, 0x40) # FIFO_EN print('fifo is reset!') def enableFIFO(self, flag): self.WriteReg(self.__MPUREG_FIFO_EN, 0x00) if flag: self.resetFIFO() self.WriteReg(self.__MPUREG_FIFO_EN, 0xF8) print('fifo is enabled!')` [![enter image description here][1]][1] [1]: migrated from arduino.stackexchange.com yesterday This question came from our site for developers of open-source hardware and software that is compatible with Arduino. - Are you sure that this code runs on an Arduino UNO. I’m not an Arduino guru, but I don’t know any possibility to run python code on a Arduino UNO. And if you have a python question it would be better to ask on the python channel. From your code I would expect it runs on a raspberry pi. So the Raspi Channel would be a better choice to ask on. – Peter Paul Kiefer 2 days ago - yes,it runs on raspi – 段永旭 2 days ago - @段永旭, Ah let me see. If you don’t sleep, then you might be reading too fast. MPU9250 gyro max output data rate is only 8kHz. So it can’t follow and becomes crazy, buffer explodes, … 🙂 BTW, SPI 10MHz is too fast for testing. Try 1MHz and MPU9250 might like it. – tlfong01 yesterday - If you are attempting to read as fast as possible you should not be using Python. Are you sure Python can keep up with the data rate? – joan yesterday - @tlfong01, I’ve tried to set it to 1MHz, but it still overflows. And I check the time cost of my main loop, every time the reading is stucked due to some unknown reasons, and the time cost rises to 1or 2 seconds, and the fifo count is then over 512 and causes overflow. It’s quite annoying T_T – 段永旭 50 mins ago - @段永旭, Many thanks for reporting result on my suggestion. It seems obvious that the reading function is making all the trouble. But I think this problem seems not that difficult to solve. First thing first, my troubleshooting trick is to zoom the big picture into the problem area. I must confess I have not even skimmed through your frighteningly long code. But please confirm one thing: (1) Is it possible to REMOVE everything related to MPU9250? If yes, then write a short test WITHOUT this statement: “from mpu9250_FIFO import MPU9250”. I know I might be asking too much, but / continure, … – tlfong01 14 mins ago - Or (1) Just input the “from mpu9250_FIFO import MPU9250”, but do not feed real realtime input from MMPU9250. Instead DIY one, yes, just one fake test byte data into the buffer, and profile / time for one or repeat 10 times the time cost. So what I am suggest is 抽絲剝繭 to the very bottom layer, … Ah sorry, I need to go to meet a friend for dinner. So see you late this evening or tomorrow, or after weekend. Good luck and cheers. – tlfong01 6 mins ago - Similarly, when later using real data, there is no point mixing both gyro and accelero data. Remove either one to focus just one type of data. If you find the problem of gyro, of course you know accelero have the same cause. Similarly, when DIYing fake data, just use simple integer, not even floating point (OK, if you must use float point, then use int(float(123)), hopefully 水落 and 石出. Bye. – tlfong01 just now Edit Categories: Uncategorized
https://tlfong01.blog/2019/11/02/mpu-9250-buffer-problem/
CC-MAIN-2021-04
refinedweb
1,323
59.19
Hello! I am doing a task and wondered if someone could help me. Here is the task: Create a program that allows a user to enter 10 words. The program will prompt each user to show how far she has come, for example: "Enter the word number 6:" The program will then print all the words forwards, backwards and every other word. Program code should have high cohesion. It should therefore consist of three classes. Class names should be the start point, Dialog and Printing. One class will be responsible for being the entry point. The second class will be responsible for the dialogue with the user entering keywords, and to manage printing. The third class will be responsible for printing. Clarification: By "backwards" here means "in reverse" in relation to the order of the words were written in. My code: public class Startpunkt { public static void main(String[] args) { new Dialog(); } } import javahjelp.Konsoll; public class Dialog { public Dialog(){ String[] rekke = new String[10]; for (int i=0;i<10;i++) rekke[i] = Konsoll.readLine("Write a word "+i); int i; for (i=0;i<10;i++) new Print(); } } public class Print { System.out.println("You wrote " +rekke[i]) } The last class is my problem. How do i print something from class Dialog ? And print the other way I'm supposed to (watch task)? I need help
http://www.javaprogrammingforums.com/whats-wrong-my-code/32206-print-given-sentence-forwards-backwards-every-other-word.html
CC-MAIN-2015-27
refinedweb
228
75.91
Keras IoU implementation Are there any implementations of Intersection over Union metric in Keras 2.1.*? 2 votes Are there any implementations of Intersection over Union metric in Keras 2.1.*? def mean_iou(y_true, y_pred): y_pred = K.cast(K.greater(y_pred, .5), dtype='float32') # .5 is the threshold inter = K.sum(K.sum(K.squeeze(y_true * y_pred, axis=3), axis=2), axis=1) union = K.sum(K.sum(K.squeeze(y_true + y_pred, axis=3), axis=2), axis=1) - inter return K.mean((inter + K.epsilon()) / (union + K.epsilon())) Zoe, he knew cause he's smart It's not difficult. Remember we are talking about masks and y_true, y_pred are matrices with 0 or 1. The operations are pixelwise Intersection = y_true * y_pred // all pixel locations, which are 1 for both y_true and y_pred Union = y_true + y_pred - Intersection // combines all pixel locations from y_true and y_pred. If we just add y_true and y_pred we will calculate their common part twice, that's why we subtract their intersection. the sum function and axis arguments are just parameters and it's a way to understand the shapes of y_true and y_pred. How did you know this?
https://ai-pool.com/d/keras_iou_implementation
CC-MAIN-2022-40
refinedweb
192
67.55
This dissertation has been submitted by a student. This is not an example of the work written by our professional dissertation writers. Chapter 1 1.1 Introduction 1.1 Market Trend Before the early twentieth century, upholstered furniture was not common household furniture. In the later twentieth century, the household furniture started making headline. In upholstery, there are different types of fabrics and textiles, and there are varieties of product available. 1.2 The Upholstery Markets across the Globe The global market for upholstery furniture, sofa and bed market has gone through series of trends in terms of growth. In recent years, the rate of growth of this industry has been greatly affected by the spending of the consumers and the condition of the housing market. During the period 2000 – 2002, consumers have experienced a great deal of confidence in this market because of the easy access to housing mortgage. The wooden furniture trade was estimated at $45billions worldwide in 2000, and this was based on the selling price of the manufacturing. This is small when compared with the globe trade of woods that are primarily processed that was estimated at $240billions. Japan and USA are the two main countries where furniture market is substantial. These two countries account for 37% of the global trade. However, the Asia, Eastern Europe, and Latin American are very competitive in the domestic furniture market. Enhancing the industrial productivity is the principal economic goal of a nation. Therefore, a way of doing this is to increase the competitiveness by employing the resources in an efficient manner. The table below indicates the labour productivity figures in different countries in the furniture industry. It explains the value that is being added per employee is not as a result of the production input only, but also market and product ingenuity. In Asia, the value of value added attained is less compared to Italy, Germany, United States, and Taiwan. The cheaper production of raw materials and labour in Taiwan has made it cost sustainable as one of the leading export countries in the world. The main strength in this country is as a result of the structural difference in the manufacturing strategy. In Russia, the market for upholstered furniture is one of the most popular markets during the 2006-2007. The market tries to distinguish its market from other western world, and a main difference of this market from the rest is the fact that the manufacturers are required to think and develop. This makes them to develop and advance in the products they manufacture, and are able to produce varieties of upholstery product in a year and as a result, the sales go up. As a result of this, the number of furniture supermarket in Russia increased. However, the Russian market lacks the clarity. Its main concern is the companies’ revolution. The market lacks the authenticity of analysing information on manufacturer, as well as furniture realisation. Since the building boom in Russia in 2000, and in 2005, there was increase in the number of constructed apartment and as a result, the upholstery market experienced boom. The United Kingdom upholstery market has experienced series of growth over the years, and in 2004, the rate was estimated to be around 2%. Due to the import rate in some part of the sector, price competition is curbing the growth in both the bed and upholstery market. During the period 2000 – 2004, the market experiences a high consumer confidence as a result of the buoyant housing market. During the 2003, the market had experience an increase in growth, and 90% of it was from the domestic market while the rest of the 10% was from the hotel and leisure sector. Some parts of the sector are responsible for this growth. 1.3 Analysis of companies in the same industry It is important to analyse three other companies in the same industry as SCS Upholsteries. The companies identified are King Fisher Plc, Carpet Right Plc, and Home Retail Group. These three companies are also in the upholstery furnishing industry and their analysis will help as a bench mark for SCS Upholstery. Kingfisher plc is the leading home improvement retailer in Europe and Asia, and the third largest in the world. Carpet right plc is Europe’s leading specialist floor covering retailer. Since the first store was opened in 1988 the business has followed a controlled store expansion programme developing both organically and, in recent years, through acquisition within the UK and other European countries. Home Retail Group, the UK’s leading home and general merchandise retailer, which comprise both Argos and Home base in the annual report. Its first Annual Report for the financial period ended 3 March 2007. The financial period is shorter than a full year due to the change in year-end and it also includes certain financial impacts of GUS plc’s ownership of Home Retail Group up to the point of demerger on 10 October 2006. In 2006, there was a major step in transforming GUS, with significant disposal, acquisitions and organic investment. 1.4 About SCS Upholstery Plc SCS Upholstery Plc is a national retailer that has been in existence for more than 100 years and specialises on selling in lounge room sofas and chairs. They are positioned in the middle-market of the upholstery retail sector offering excellent value, choice and service to their customers. The increased the number of stores from 70 in 2005 to 95 stores nationwide in 2007, 91 of which are in prime out of town retail park locations with a high quality fit out and mezzanine floor. Their branches network has developed through regional clusters supported by 11 distribution centres, designed to deliver cost synergies in distribution and through effective use of national media. The company do not manufacture but source their products from 15-20 principal suppliers with whom they have developed good working relationship. The company employ the best people in whom they invest heavily in training with a focus on customer service. Remuneration packages, which contain significant incentives based upon sales and profits, provide the focus on maximising profits and managing costs and support the successful implementation of strategy. 1.5 Financial Review Financial overview for four years Revenue was £183.8 million for the ten months ended 28 July 2007 (twelve months ended 30 September 2006: £195.8 million), although there has been significant increase compared to 2004 and 2005. The drop in revenue in 2007 reflected the extremely tough trading conditions which prevailed. The balance sheet remained very strong with net assets of £36.1 million (2006: £37.6 million) and no borrowings. Comparing these two years to 2004-2005 net asset, there has been has increase of about 73% in net assets from 2004-2006, and 27% increase from 2005-2007. The increase in the net asset over the years is as a result of acquisition of property, land and equipment. The strong balance sheet and significant operating cash flow generation of the business enabled a continuous expansion strategy and the refurbishment programme whilst supporting the payment of dividends at appropriate levels, all of which is financed from the company’s resources. The Group had changed its accounting reference date from 30 September to the nearest Saturday to 31 July in order to alleviate the logistical issues created by annual supplier holidays falling during August and the change has taken effect from the current financial period. As a result the comparative figures in the Income Statement, Balance Sheet for 2007 is for ten months and will be assumed to be for twelve months. Summary Table The trend of the profit before tax and the earnings per share is shown is shown in the diagrams below. The balance sheet remained very strong with net assets of £36.1 million (2006: £37.6 million) and no borrowings. The financial statement select suitable accounting policies and then apply them consistently; make judgments and estimates that are reasonable and prudent; state whether applicable UK Accounting Standards have been followed, subject to any material departures disclosed and explained in the financial statements; and prepare the financial statements on the going concern. Business risk Revenue was £183.8 million for the ten months ended 28 July 2007 (twelve months ended 30 September 2006: £195.8 million). This reflected the extremely tough trading conditions which prevailed during the financial year. The trading profit has dropped for about 58% from 2006 to 2007. The corrective action taken included spare capacity in distribution, which has led increase in the distribution cost to take 5.6% of the 2007 revenue (2006: 4.7%). Also expansion (opening of new stores) and pre-opening and launch cost for the new stores, staff recruitment cost that been taking place has a negative impact on the company’s revenue. Chapter 2 2.1 Accounting Policies Basis of preparing the annual reports SCS Upholstery The SCS Upholstery financial statement has been prepared according to the IFRS as adopted for European Union use which applies to the group financial statements for the ten month 28 July 2007 and applied accordance with the provision of the company Act 1985. The full details of the accounting policies can be found on the company’s annual report on page 32-34. The following new standards and interpretations are not applied The following standards and interpretations have been issued by the IASB and IFRIC with an effective date after the date of these financial statements: International Accounting Standards (“IAS/IFRS”) IAS 1: Amendments to IAS 1: Presentation of Financial Statements: Capital Disclosures 1 January 2007 IFRS 7: Financial Instruments: Disclosures 1 January 2007 IFRS 8: Operating Segments 1 January 2009 IAS 23: Amendment to IAS 23: Borrowing Costs 1 January 2007 The Directors do not expect that the implementation of these standards and interpretations will have a material impact on the Group’s financial statements. Goodwill Goodwill represents the excess of the cost of acquisition of a business unit over the fair value of the identifiable net assets acquired at the date of acquisition Consolidated goodwill in respect of acquisitions made prior to 1 January 1998 was written off directly against reserves. Future goodwill will be shown as an asset (in accordance with FRS 10) and amortised over its useful economic life. Goodwill previously eliminated would be charged or credited to the profit and loss account on subsequent disposal of the business to which it related. Going concern Having made appropriate enquiries, the Directors have a reasonable expectation that the Company and the Group have adequate resources to continue in operational existence for the foreseeable future and for this reason they continue to adopt the going concern basis in preparing the financial statements. Taxation The taxation expense is calculated on the basis of the Director’s estimate of the tax rate (annual) which is added to profit for that period. The effective rate for the period is calculated to be 34.3%, and for 12 months till September 2006 is 31.5%. Operating leases the operating lease is in accordance with IAS 17.Rentals payable under operating leases are charged in the income statement on a straight line basis over the lease term. Carpet Right The company in the past was using the United Kingdom Generally Acceptable Standard (UK GAP). After the European Union issued directive in 2002, the group in July 2002 started preparing its consolidated financial statements in accordance with International Financial Reporting Standards (“IFRS”). In 2007 the financial statements have been prepared in accordance with International Financial Reporting Standards (IFRSs) and International Financial Reporting Interpretations Committee (IFRIC) interpretations endorsed by the European Union, together with those parts of the Companies Act 1985 applicable to companies reporting under IFRS. Financial statement of Carpet right represents 52 weeks ended 28 April 2007, and for 2006 was 52 weeks ended 29 April 2006. The financial statements have been prepared in accordance with International Financial Reporting Standards (IFRSs) and International Financial Reporting Interpretations Committee (IFRIC) interpretations endorsed by the European Union, together with those parts of the Companies Act 1985 applicable to companies reporting under IFRS. Exceptional items Transactions which are material by virtue of their size or incidence such as profits or losses on disposal of property, plant and equipment and investment property are disclosed as exceptional items. Goodwill Goodwill is capitalised based on the excess of the fair value of the consideration paid over the fair value of the separable net assets acquired. It is carried at cost less accumulated impairment losses. King fisher The consolidated financial statement in 2005-2006 is prepared according to the International Accounting Standard Boards (IFRS) as the European Union (EU) directed as well as the International Financial Reporting Standards issued by the International Accounting Standards Board (IASB), and with those parts of the Companies Act 1985 applicable to companies reporting under IFRS. The 2007 consolidated financial statement as also been prepared in accordance with EU standard, as well has IFRIC interpretations and those parts of the Companies Act 1985 applicable to companies reporting under IFRS. The consolidated financial statements have been prepared under the historical cost convention, as modified by the revaluation of certain financial instruments. Home Retail Group The Home Retail Group (then ARG) before prepares its financial statement for 12 months to 31 March except for the results of Home base Limited which were included for the 12 months to 28 or 29 February each year, with adjustments to reflect the balance sheet movements in cash to the end of March. This was done to facilitate comparability of the income statement by avoiding the distortions that would arise relating to changes in the timing of Easter. The accounting policies that are applied to prepare the financial statement are set below. These policies have been consistently applied to all the periods presented, unless otherwise stated, and are in line with the listing particulars. Home Retail Group separated from its parent company, GUS plc in 10 October 2006. Home Retail Group companies which were owned by GUS plc prior to demerger were transferredunder the new ultimate parent company, Home Retail Group plc, and prior to 11 October 2006. The introduction of this new ultimate holding company constitutes a group reconstruction and has been accounted for using merger accounting principles. Therefore, although the Group reorganisation did not become effective until 10 October 2006, these consolidated financial statements of. In the prospectus, funding balances between the Group and GUS plc which were interest bearing and had the characteristics of debt, were presented as debt in the balance sheet, with the interest taken to the income statement. Prior to demerger, the net funding balances were reduced by £240.0m by means of a capitalisation and the financial statements reflect this capitalisation as having taken place just prior to 31 March 2005. Changes in accounting standards A number of new standards, amendments and interpretations have been put in place at the short period ended 3 March 2007, but have had no material impact on the results of the Group. The impact of IFRIC 4 ‘Determining whether an arrangement contains a lease’ has been reflected through both the current period and prior year within Notes 8 and 31. At the balance sheet date a number of IFRSs and IFRIC interpretations were in issue but not yet effective. The Group has not early adopted IFRS 7 ‘Financial instruments: Disclosures’ and the ‘Capital disclosure amendment’ to IAS 1 ‘Presentation of financial statements’, which are applicable for accounting periods commencing on or after 1 January 2007. 2.2 Financial Ratios The financial ratio is a simple and better means of assessing the financial position of a firm. The use of ration is useful in comparing the financial position of different companies and also to the industry average. Ratio is grouped into different types, and each explains the financial performance of the company. 2.3 Profitability Ratio It measures the firm’s use of its assets and control of its expenses to generate an acceptable rate of return. They express profit made in relation to other key figures in the financial statement. Return on Capital Employed (ROCE): This is used as a measure of the returns that a company is realising from its capital employed. The company under review with its competitors have shown to have the ROCE above the industry average for the periods under consideration. For SCS Upholstery, there was a great decline in profit in 2007 and this had affected their returns by a total difference of 22.68%. This is due to the significant shortfall in sale being experienced in 2007. As sales reduce, and overall cost of sales increases, there will be a significant effect on the overall profit. The price at which the company is selling its product is not sufficiently covering its cost. Carpet right has had a stable ROCE for two year period (2006-2006), although there was a great decline of 27% in figure from 2005-2006. This is attributed to the decrease in the operating profit. Looking at King Fisher, the figures have not been stable over the periods especially during 2005 when there was 110% increase in the operating profit. Home Retail Group also experienced an upward trend. In comparing the ROCE figures with those of the peer companies, Carpet Right appears to main a stronger position, although all the companies including SCS Upholstery exceeded the industry average. Return on Equity: This ratio helps to match up the amount of profit available to the owner during the period under consideration. There has been decline in the ratio for all the companies in 2007. This is due to the fact that the companies have all issued more equity compared to the profit before tax they all made. ROE figures for the peer companies offer mixed results, which gives an industry average which is influenced by the good performance of Carpet Right. Both SCS Upholstery and Carpet Right have their figure for all the periods greater than the industry average except for the 2007 figure for SCS Upholstery that is below the industry average and this is as a result of the reduced profit caused by the capital expenditure incurred. Gross profit percentage: This measures the percentage of sales available to pay overhead expenses of the company. It is the amount of contribution to the business enterprise, after paying for direct-fixed and direct-variable unit cost, requires covering overheads and providing a buffer for unknown items. Observing the gross profit ratio, it is noted that Carpet Right like before outperforms the other companies including SCS Upholstery for all the periods. In 2007, the gross profit ratio of Carpet Right is 29% above that of SCS Upholstery. But SCS Upholstery seems in line with the industry average. Both King Fisher and Home Retail group have their ratios below the industry average. For SCS Upholstery, no substantial change in the ratio, but it can be seen that the gross profit was lower relative to sales revenue in 2007 than it had been in 2006. The reduction in gross margin reflected the impact of lower average order values. This is attributed to the logistic issue which resulted in a smooth delivery experience around March period. The cost of these actions and of the spare distribution capacity to protect against peak trading period is reflected in increase in distribution cost as a percentage of sales were. This strategy was rolled out across all warehouses over a period of time, to increase flexibility for delivery to customers and ensure success in realising economies of scale and increasing profitability. 2.4 Liquidity ratio This provides information about the firm’s ability to meet its short term financial obligations. They are of particular interest to those extending short-term credit to the firm. Current Ratio: This is one of the best known measures of financial strength. This is a financial ratio that measures whether or not a firm has enough resources to pay its debt over the period of time. This means that for every £1 the company owes, it has its equivalent current ratio in form of current assets. The summary of this is that for every £1 SCS Upholstery owe, it has £1.05 in 2007 (£1.21 -2005; £1.01 2006) available in current assets. This indicates that the firm holds most of its assets in non current form. The makes most of its sales in cash, and generates a lot of cash sales revenue. Comparing this ratio to its pairs and the industry average, the company has to find a way of increasing its current assets in relation to the current liabilities because the industry average figures are higher. The current ratio of Carpet Right has shown a very strong trend compared to its pairs and the industry average. Also Home Retail has maintained a good current ratio despite the fact that the gross profit, returns on capital ratios have not been impressive. King fisher current ratio is also seen to be below the industry average suggesting that it has more current liabilities in relation to current assets. It is likely that king fisher is facing liquidity issues. Acidic test ratio: This measures the ability of a company to use its near cash to immediately extinguish or retire its current liabilities. The Acid Test or Quick Assets Ratio provides a more prudent measure of short-term liquidity. Carpet Right has the highest ratio and it’s the only one that has its ratio above the industry average suggesting it is able to meet its short term liquidity. It can be seen that the liquid current assets of SCS Upholstery do not quite cover the current liabilities. There is a subsequent need to reduce the purchase of noncurrent assets (property, plant and equipment) and intangible assets as seen on the balance sheet in 2007 to have taken a huge sum. The company need to keep some of its asset in liquid form to meet any unforeseen obligations that may arise. Home Retail is not doing well in this ratio, but King Fisher having relative low ratio might be faced with liquidity problem. 2.5 Efficiency ratio This examines the ways in which various resources of the business are managed. It is also related to the liquidity ratio and gives an insight to the effectiveness to the company’s management of the components of working capital. Stock turnover: the stock turn often represent a significant investment for business. This ratio reveals how well inventory is being managed. It is important because the more times inventory can be turned in a given operating cycle, the greater the profit. The ratio analysis for the four companies shows that King Fisher has the highest number of stock turnover, followed by Home Retail. This explains why King Fisher has had very low profitability ratio compared to its pairs. Also Carpet Right has the lowest stock turnover suggesting that they sell their stocks sooner than the rest and this also reflects in their sales revenue. Looking back to the Acidic Ratio of SCS Upholstery, is can be finalised that problem might arise in future if this figure is not monitored. The firm is a retail market and order their products from their suppliers. They can afford not to invest so much in inventory (sofa) as this can be ordered from their suppliers. Debtor’s turnover: this indicates the percentage of the company’s assets that are provided via debt. The ratio indicates how well accounts receivables are being managed. Analysis of the debtor turnover shows that both Carpet Right and King Fisher have been managing its credit control with their figures below SCS Upholstery and Home Retail, as well as the industry average. SCS Upholstery figures for 2004 and 2005 were not impressive given the industry average and the stock turnover, but there was a turnaround in 2006-2007. This is done by doing more of cash sales than credit sales. In fact, it started doing most of its business in cash sales and this holds true for most retail stores. Creditor’s turnover: measures how long on the average, the business takes to pay its creditors. It can be understood from the analysis that of the 2 years that there is no significant change. While the company does a lot of cash sales, it tries to delay making payment to its suppliers. The ratio for the period under study has been consistent with the industry average. This is equivalent to taking out a free interest loan to finance working capital. The success has been attributed to the developing and maintaining effective, long term working relationship with suppliers and was able to negotiate exclusively on all product lines. They are able to negotiate and affect a good repayment plan with suppliers. Carpet Right has produced a large Creditor Turnover Ratio in all the years round. The ratios for 2006-2007 are higher than the industry average. The implication of this is that the company may lose its credibility, and the suppliers may decide not to supply credit goods unless cash is paid. Home Retail have its ratios for the three years below the industry average, this means that most of the goods are bought with cash. This is not a good strategy for the company as it may enjoy an interest free loan, and the fund can be employed for other purposes. Working capital This gives an indication of the length of time cash spends tied up in current assets. As said earlier that the company can generate cash more quickly because they make a lot of cash sales, then a negative working capital signifies that is company is being efficiently managed. They order goods from their suppliers making a deal that they will sell them in 58 days (55 days in 2006) and sold to customers before then. Since they do not have to pay the money right away, they can invest the money further, and even earn some interest on it, until payment day arrives. Also, some customers pay upfront and so rapidly, the business has no problems raising cash. In this company, products are delivered and sold to the customer before the company ever pays for them. The high negative figures for 2004 and 2005 stem from the high trade payable days. The Working Capital Cycle figures for King Fisher and Home Retail are positive compared to SCS Upholstery and Carpet Right. This explains that those companies with negative working capital have better cash flow than later. Lower ratio is beneficial to the financial health of the company. 2.6 Financial gearing This occurs when a business is financed, at least in part, by borrowing, instead of by finance provided by the owners (shareholders). A business level of gearing is an important factor in assessing risk. Where a business borrows heavily, it takes up a commitment to pay interest charges and also make capital repayment. This analysis will only focus on gearing ratio and leaves out the interest cover ratio because there is no borrowing that yielded interest. Gearing Ratio: measures the contribution of long-term lenders to the long-term capital structure of a business. The idea is that this relationship ought to be in balance, with the shareholders' funds being significantly larger than the long term liabilities. The gearing ratio of SCS Upholstery firm is the lowest compared to its pairs and the industry average. This indicate that there is less debt in relation to the equity issued by the company especially when compared with Home retail that has its gearing ratio even higher than the industry average. Although in 2006 the ratio is times three of 2005 and in 2007, it is almost times four. The reason for this in 2004 and 2005, the only form of liability used in the calculation is the amount due to creditor that is over a year compared to 2006 and 2007 that has more debt. The company only has 19.8% of shareholders funds in the business. In future, if the company is facing any liquidity problem, it can still raise more capital for the company. 2.7 Investment Ratio There are different types of ratios under the investment ratio, and they are analysed below. Dividend yield: this is a measure of the proportion of earning that is being paid out by a firm to its shareholders as dividend. The dividend yield for SCS Upholstery has increased by 79% from 2006 to 2007, and it is even higher than the industry average. It is generally believed that with high dividend yield, there is a danger of the future dividend not meeting the level paid in previous year and the dividend may outgrow the earnings. Carpet right ratio has been consistent over the years, and Home retail has the lowest compared to the to the industry average. Earnings per share This relates the generated earnings by a firm and the one paid to share holders to the number of share issue at a particular period in time. This is also used used to measure the performance of share. It is not really fundamental to comapre different company’s earnings per share because different company employ different capital structure. The earnings per share of SCS Upholstery is relatively higher than the industry average. Price-earnings ratio This relates the earnings per share to the market value of the share. It indicates the market confidence of the future earning power of the firm. Also the accounting policies of different company have an impact on this ratio. It shows that the capital value of SCS Upholstery share is 14 times higher than the present level of earnings. The company has the highest price earnings ratio when compared with its pairs and the industry average for the period under study. This indicates that investors will be more confident in the future earning power of carpet right. Dividend payout ratio It measures the amount of earning being paid out by a firm to its shareholders as dividend. The analysis shows that in 2007, SCS Upholstery has the ratio greater than the industry average. This reason for this is that the dividend paid in 2007 is higher than the earnings and this is the reason the same amount of dividend paid in 2006 is paid in 2007. Also this can be explained in terms of the cut in profit as the company embarked on capital project in order to expand its capital base. King fisher had a very high ratio in 2006 when compared to the industry average. Carpet right has had stable ratio over the time period, and only the 2005 ratio is higher than the industry average. 2.8 The capital Structure of SCS Upholstery Form of financing The capital structure will explain the equity financing in the operation of the company. There are two mainly types of firms raising funds, which are; debt and equity financing. Using debt to raise fund lowers the cost of capital, has an impact on increasing shareholders rate of return and also increases the risk of returns. Also, the risk of bankruptcy (firm’s asset fall short of debt value) will be introduced when gearing is employed relative to equity in financing. When debt is employed in capital structure, it is seen as splitting into two the risks and the earnings generated where one goes to the equity shareholders, and the other to the debt holders. However, if a firm is financed by equity, the shareholders stand the risk of bearing the loss of the company, and can only claim the net cash flow. If this should happen, the market value of the firm will depend on the nature of the cash flows. Although SCS Upholstery has no form of borrowing on their balance sheet, there is however trade credit that has been due for over a year. In order for me to analyse the capital structure (as an investor), the trade payable and amount due to creditors over a period of one year will be regarded to a debt. Capital structure theory Although gearing promises a higher expected rate of return, but it exposes the shareholders to higher risk. It is vital to consider the trade-off between risk and return before concluding if the use of debt is better or not. For the debt holders to have a lower risk exposure, the equity holders have to absorb more risk. It is imperative to note that manipulating capital structure of a firm cannot in any way increase the value of the firm. Modigliani and Miller The theory of capital structure was first introduced by Modigliani and Miller (1958), and they proposed that firm’s value is dependent on the risk and the level of earnings. Modigliani and Miller analysis of capital structure is based on the assumptions that the capital markets are perfectly competitive. These assumptions are as follows: - there are no taxes; - information is available and its is costless; - there are no transaction costs; - interest rate available for both the investors and the firms is the same; - Market participants are the price takers and posses no market power. Although in real life, the capital market is not competitive, but the formal model can be loosened up so that analysis can incorporate the real life situation. Therefore, employing gearing in the capital structure of a firm is cheaper the equity financing. Debt-equity ratio The use of debt equity ratio helps a firm to have an idea the amount of fund the company can borrow over a long period of time. This is done by looking the total debt which includes short and long term debt against the total equity of the firm. The table below shows the debt-equity ratio of SCS Upholstery and the other three firms and these are compared with the industry average to know how the debt-equity ratio has been over the years compared to the other firms and the industry average. The table shows that the debt-equity ratio of the firm has dropped dramatically over the years. This indicates that less debt has been incurred compared to equity from 2005-2007, and it is in line with the industry average. The reason for this change is for the fact that during 2006 and 2007, the company did not employ long term trade payable, unlike 2006. This indicates that the company is trying to have its debt equity ratio in line with other companies in the same industry as well as the industry average. 2.9 Capital structure and bankruptcy When a firm adopts more debt in relation to equity, threat of bankruptcy is likely to be faced by such firm especially when the firm's assets fall short of the debt value. A firm faced with threat of bankruptcy will have its assets allocated to the creditors and its equity owners bearing the loss (interest of equity holders is eliminated). In assessing the balance sheet of SCS Upholstery to know if there is threat of bankruptcy faced by the firm, the total assets will be assessed against the equity capital and the total liabilities. Looking at the 2007 balance sheet of SCS Upholstery firm, it can be seen that the company is not faced with any threat of bankruptcy even though financial trading is proving difficult for the financial year. If a firm is faced with bankruptcy, the equity holders suffer the loss and therefore on the balance sheet, the equity capital becomes zero. For the periods under consideration for SCS Upholstery balance sheets, it can be seen that each value of the non current asset or the noncurrent asset is sufficient to cover for the loss of equity capital. It can therefore be concluded that the firm is not faced with threat of bankruptcy. It is important to know that the SCS Upholstery has no interest payable for the period under consideration and there has not been any form of long term loan incurred. As a result, the company is not faced with any threat of bankruptcy. Business risk Revenue was £183.8 million for the ten months ended 28 July 2007 (twelve months ended 30 September 2006: £195.8 million). This reflected the extremely tough trading conditions which prevailed during the financial year compared to 2004-6. The trading profit has dropped for about 58% from 2006 to 2007. The corrective action taken included; spare capacity in distribution. This has led increase in the distribution cost to be 5.6% of the 2007 revenue (2006: 4.7%). Also expansion (opening of new stores) and pre-opening and launch cost for the new stores, staff recruitment cost that been taking place has a negative impact on the company’s revenue. 2.10 Dividend policy The Lintner 1956 dividend policy model The dividend model proposed by lintner in 1958 has helped to develop a better understanding of how the managers of a firm make their dividend decisions. Based on the interviews with some management of different firms suggested that the dividend to be paid in present year is compared in relation to the one paid in the previous year even if the earnings have fallen, and this dividend increases as earnings increase over time. Increase in dividend will be as a result of difference between the long run target and the dividend paid the last time. This suggests that even if the earnings reduce, the dividend paid may not necessarily reduce. The most important factors in the dividend change are the adjustment to the change in earnings and the payout ratio. Earnings per share/dividend After applying the lintner model to explain the dividend policy of SCS Upholstery for the period 2004-2005, the adjustment factor (s) is calculated to be a negative coefficient of (-0.055), and the long run target payout ratio (z) was is calculated to be a negative coefficient of (-0.81). This therefore means that the Lintner model will not be applicable to SCS Upholstery Plc. Looking at the trend of the earnings per share, dividend per share and the dividend as a percentage of earning, it can be inferred that dividend paid from 2004-2007 has been increasing although, the same for both 2006 and 2007. The earnings have not been stable over the years and this can be attributed to the logistic issues of capital expenditure that is carried out in 2006/2007. The company can be said to take into account the implication of reducing the dividend paid even with reduced earning, and in 2007 even though the earnings per share is significantly small compared to previous years, the company still maintained the same amount of dividend paid in the previous year, and this is paid from the retain earnings. Any reduction in dividend may suggest to the investors that the company is having some financial problems. Chapter 3 Valuation of the company 3.1 Dividend Valuation Model The dividend valuation model presumes the market of a company’s share is calculated using the discounted value of the dividend per share that shareholders are expecting to get. The cash flow is made up of the expected dividend for the period and the proceeds expected from share sale at the end of that period to determine the present cash flows, the discount rate is used. Where: represent the market value of a share; dividend expected to be paid in period t; price of the share expected at the end of period N; r is the discount rate and r; and is the number of years planned for the period. The firm share price will be undervalued if the current share price is less than the estimated value of the share, and therefore investors will see good prospects of buying the company’s share. As investors are seeking undervalued shares and will therefore take advantage of any market error that occur even if it is not for long. Applying the above first equation, it is necessary to find the anticipated share price at the end of the period N, the discount rate (r) and the growth rate (g). The first calculation is based on the growth rate which is expressed as; g = b * k Where b = retention ratio; and k = rate of return on equity (average for the four years) The retention ratio is calculated by subtracting the average payout ratio from one. The dividend per share for 2007 will not be employed in this analysis because the earnings per share for that period are higher. Therefore, the payout ratio will only be calculated for a three year period. The payout ratio which is calculated using the formula; Dividend for the periods Earnings per share The retention ratio is calculated as b = 1 – payout ratio; In calculating the growth rate using the formula, b = 1 – 0.48 = 0.52 Therefore, the growth rate gives; g = 0.52 * 0.306 = 0.159 Looking at the dividend per share paid in relation to the earnings per share for the period under study, the earnings per share in 2007 is relatively lower than the dividend paid. It explains why the same dividend paid in 2006 is paid in 2007. This implies that is company is having issues (even though it’s still paying the same dividend) with its level of earnings. This is however a matter of concern as to the financial position of the company. Therefore, in calculating the expected dividend, instead of using the calculated growth model (0.159), the average percentage change in dividend for the period is used calculated as (0.11). Year 1 = D1 = Do (1 + g) = 19 (1 + 0.11) = 21.09 Year 2 = D2 = 21.09 (1 + 0.11) = 23.41 Year 3 = D3 = 23.41 (1 + 0.11) = 25.99 Year 4 =D4 = 25.99 (1 + 0.11) = 28.85 The dividend growth rate has increased by 11% from year one to year two, and from year three to year four, there is an increase of 11%. The growth rate has been consistent and this can be explained with the fact that there has been drop in the earnings of the company in 2007. The cornerstone of modern finance is the Capital Asset Pricing Model, CAPM. Investor who wants to invest in the market portfolio must be prepared to earn some level of risk. Because of the investor’s risk adverse nature the portfolio is chosen in the manner that the risk is minimised to its barest minimum and maximise the expected return. To calculate the discount rate (r), the Capital Asset Pricing Model is adopted and the expected rate of return is expressed as; r = Rf + [E(Řm) – Rf]β (1) Where; Rf = risk free rate of interest at a given period; E(Řm) = return of the market portfolio return expected in a given period; and β = measurement of risk [E(Řm) – Rf] = historical risk premium in UK (0.042) The risk free of interest rate is calculated by finding the annual average of the risk free FT All-share in UK for the period January 1990-december 2008 which gives 0.0624. The beta β (3.66) that measure the risk is calculated by running a regression of the company’s excess return against the excess market return. The company’s excess return is calculated using the historical share prices for the period January 2003- June 2008. The UK FT All-share of the excess market return for the same period is used as the as the excess market return. Comparing the calculated beta to the one on yahoo finance which is 3.83 (with industry average of beta 0.63), then it is in line and I decided to use the beta that I regressed because of the time period considered for them market share price. The discount rate of return r is calculated as follows: r = Rf + [E(Řm) – Rf]β = 0.0624 + (0.042) * 3.66 = 0.21612 This high figure of the discount rate of return is as a result of high beta risk of the company. PO = 21.09 + 23.41 + [ 25.99 * 1 ] (1+0.21612) (1+0.21612)2 (0.21612-0.159) (1+0.21612)3 It is important to note that the number of periods employed is three years are used in the valuation. This is because it is assumed that investors may not believe in the long term prospects of the company due to its latest low earnings. Constant rate growth model Estimating the dividend indefinitely is not viable, it is therefore necessary to establish a regular dividend model. This model is not necessarily have to follow one period to the other, but at least start at some point. For dividend to be constant for a period of time, the equation for the valuation will be taken in form of perpetuity. However, the retained earning of a company’s is usually to finance some long term investment so far the dividends, assets, and earnings are expected to produce a constant growth rate referred to as (g). In the constant dividend growth model, the dividend paid in future is expressed in terms of the dividend that will be paid now, as well as the growth rate. In adopting the equation below, the discount rate must be greater than the growth rate of the company r>g, otherwise the equation gives a share price that is infinite. The model implies that dividends can be paid out from generated earnings without having any impact on the future earnings generating capacity of the firm’s assets. It means that in calculating the earnings, the amount charged to depreciation will be equal to the reinvestment that is needed to maintain the asset base of the company. The constant rate of growth model is represented as follows: P1 = Do( 1 + g) r – g PO = 19(1+ 0.11) (0.21612 – 0.159) PO = 385.52 P1 = Do r – g = 19/ (0.21612 – 0.159) = 332.63 Also, explaining in terms of the growth rate (g), that is: g = b * k With the assumption that dividends are not growing it is also possible to assume that the company will not be able to grow. Earnings are no longer retained and therefore there will be little prospects for growth. Also, as growth rate is a factor of retention ratio which is now zero, then it is safe to assume that the growth rate for the firm is zero: P1 = Do r = 19/0.21612 = 87.9 3.2 Earnings Valuation Model The earnings valuation model is important because investors/shareholders have the right to the company’s earning. This could either be in form of dividend or used in financing further investment. Since dividends are paid from earnings, the firm’s earning power determines the market value. In the share valuation of the company, the level of earnings and the investment play crucial role. The earnings model helps in differentiating between the contributions of firm future investment from its existing contribution of assets. The investment of the firm has to guarantee higher rate of return for the shareholders in order for the market value to go up. The net value of a company’s investment after deducting the cost associated is given by the net present value. Since the basis of this analysis is on the future contributions of the investments to the present share value, it is imperative to discount the expected net present value back to present which gives the present value of growth opportunities (PVGO). Earnings model does not depend on the constraint on the type of investment that is being undertaken by the company. It is not necessary to state the investment lives, and the cash flows may either be irregular or constant. This is because of the assumption that investments are in perpetuity form in order for earnings model to be comparable to the dividend model. The Gordon Model assumptions are as follows: - The investments of the company are financed from retention; - Retained earnings are the same; - The same amounts of dividends are paid out (1-b); - The earnings produced from the assets are constant in perpetuity; - Rate of return (k) is constant; and - A constant cash flow is produced by all investments in perpetuity. The earnings model valuation can be written and calculated as: Vo = E1 + PVGO r where: PVGO = present value growth opportunity Vo = E1 + E1[b(k/r – 1)] r r - g E1 = EPS (1+g) = 13.68 (1 + 0.11 = 15.185 Therefore: Vo = 15.185 + 15.185[0.52(0.306/0.21612) – 1)] 0.21612 (0.21612 – 0.159) = 127.75 The figure is low but it is understandable because of low 2007 earnings compared to the dividend paid. As noted earlier, the company does not really have any prospects for growth and hence it is also be assumed that the share value is a function of earnings and discount rate. Vo = E1 r = 15.185/0.21612 = 70.26 3.3 The valuation multiplier model The valuation multiplier is analysed in terms of the analyst’s appropriate price-earnings ratio for share. The valuation model is equivalent to the prevailing price-earnings ratio when the market is assumed to value share correctly. The valuation multiplier model is expressed as: = P/E * NET earnings Number of ordinary shares The price-earnings ratio used in this analysis is the 2007, and this is assuming that hence forth, there is no growth as the earnings in 2007 is lower than the dividend. Substituting into the equation, the value gives: = 14.26 * 4616 33753 = 1.95 If I also assume that there is growth rate in 2007 and after this period, the rate becomes the same. This means that (1+g) will be added to the analysis. = P/E * NET earnings (1+g) Number of ordinary shares = 14.26 * 4616 (1+0.11) 33753 = 2.17 3.4 The free cash flow valuation Another method of the valuation model is the free cash flow valuation, and it is the cash flow that is accessible to the equity share holders and the firm net of capital expenditure. Any firm can use the free cash flow model because it gives a better picture of the value of the firm beyond the constant growth model. A way of doing this is by discounting the free cash flow for the firm at the weighted cost of capital in order to get the firm’s value, after which the then-existing debt value is subtracted to get the equity value. The free cash flow of a company (FCFF) is given as: In the case of SCS Upholstery, there is no interest payment because the company did not incur any debt, so as a result, the weighted average cost of capital (WACC) cannot be determined so the return on equity will be used as the WACC. The table below shows the figures for net earnings, depreciation charge, capital expenditure and total property, plant and equipment PPE. The valuation of the cash flow involves calculating the net cash flow for the period under consideration. The net cash flow is summarized in the table below and the net cash flow is calculation using the formula: Net cash flow = net earnings + depreciation – capital expenditure It is necessary to forecast the earnings, the capital expenditure and the depreciation charge into the future. For the purpose of this analysis, a 5-year forecast is analysed. In order to forecast the net earnings into the future, the net earnings growth using the net earnings is used and the average is calculated. The average will be use to project the future forecast. For capital expenditure, it is necessary to relate the purchase of property plant and equipment for the year to the total property, plant and equipment (PPE) of the company. The analysis gives: Applying the same analysis to depreciation by relating the depreciation for the year to the total PPE, the percentage is used to forecast depreciation for the period of 5 years. It is also necessary to find average growth rate on property, plant and equipment PPE from 2004-2006. This average growth is used to forecast the capital expenditure and the depreciation for the next 5 years and it is analysed by relating the values of the total PPE from year to year. The 5-year forecast The 5-year forecast will be for the net earnings, capital expenditure, and the depreciation charges. This will therefore be from 2008-2012. Earnings forecast Recall that there has been a negative growth in the net earnings and therefore, for the purpose of forecasting the earnings, an assumption is made that after 3-year forecast (2008-2010), the company will start regaining its financial position back to what it was, so the same rate at which the earning has dropped (-12%) will be assumed to be the same rate it will pick up for the next 2 years (12%). As a result, the forecast gives: 2008 = -12% * 4616 = 4062 2009 = -12% * 4062 = 3575 2010 = -12% * 3575 = 3146 2011 = 12% * 3146 = 3523 2012 = 12% * 3523 = 3946 Looking at the previous earnings (2005-2006), there has been sustainable growth from 2004-2006, and a substantial decline in 2007. The graph below shows the rate of growth with the forecasted figures from 2008. It can be seen that the same rate at which the earnings decline from 2007 is the same rate at which it starts regaining its original position. PPE forecast In order to forecast the depreciation charge and capital expenditure, it is necessary to forecast what in the PPE will be in the next 5 year, and this is done using the average growth rate of PPE (20.6%) on the total PPE FOR 2007 (40,256). 2008 = 40256 (1+ 0.206) = 48549 2009 = 48549 (1 + 0.206) = 58550 2010 = 58550 (1 + 0.206) = 70611 2011 = 70611 (1 + 0.206) = 85157 2012 = 85157 (1 + 0.206) = 102700 Capital expenditure CAPX The forecast above can then be used to find the capital expenditure and the 2008 = 48549 * 0.266 = 12914 2009 = 58550 * 0.266 = 15574 2010 = 70611 * 0.266 = 18783 2011 = 85157 * 0.266 = 22652 2012 = 102700 * 0.266 = 27318 Depreciation To be able to forecast the depreciation rate into the future, the depreciation rate of 10.9% is multiplied with 2008 = 48549 * 0.109 = 5292 2009 = 58550 * 0.109 = 6382 2010 = 70611 * 0.109 = 7697 2011 = 85157 * 0.109 = 9282 2012 = 102700 * 0.109 = 11194 Net cash flow Net cash flow = net earnings + depreciation – capital expenditure 2008 = 4062 + 5292 – 12914 = -3560 2009 = 3575 + 6382 – 15574 = -5617 2010 = 3146 + 7697 – 18783 = -7940 2011 = 3523 + 9282 – 22652 = -9847 2012 = 3946 + 11194 – 27318 = -12178 The forecasted net cash flow gives negative figures, and this is as a result of the rate the huge amount of capital expenditure incurred during the 2006-2007. This has resulted in the negative forecast. Applying the capital expenditure to forecast the cash flow pose a big problem. Therefore, the percentage growth in the capital expenditure (from the cash flow statement) for 2006-2007 is applied. = 14356 – 8826 14356 = 0.3852 Rate = 1 – 0.3852 = 0.6148 = 61.4 % This rate is then used to multiply the capital expenditure for 2007 in order to forecast for 2008. I am also assuming that the company will not want to spend much on the CAPX in future, so the same rate is applied throughout for the cash flow forecast. This will enable me to have forecasted positive cash flow analysed below: 2008 = 61.4% * 8826 = 5419 New cash flow forecast 2008 = 4062 + 5292 – 5419 = 3935 2009 = 3575 + 6382 – 5419 = 4538 2010 = 3146 + 7697 – 5419 = 5424 2011 = 3523 + 9282 – 5419 = 7386 2012 = 3946 + 11194 – 5419 = 9721 The cash flow forecasted is then discounted to find the value of the company. V0 = CF1 + CF 2 + CF3 + CFn + Vn (1+r) (1+r)2 (1+r)3 (1+r)n (1+r)n V0 = CF1 + CF 2 + CF3 + CF4 + CF4 * 1 (1+r) (1+r)2 (1+r)3 (1+r)4 (r-g) (1+r)5 The weighted average cost of capital (WAAC) because no interest charge on the financial statement. This is due to the fact that the company did not incur any borrowing. Therefore, the average return on equity is (k=r) is used as WAAC. The value of the company is computed using the formula above: V0 = 28.052.61 To get the share price per share, the value of the company is divided by the number of outstanding shares in 2007. Share price/share = V0/N0 Share price/share = 28,052.61 33,753 = 0.8311 = 83.11 pence
https://www.ukessays.com/dissertation/examples/construction/upholstery-markets.php
CC-MAIN-2017-09
refinedweb
9,456
50.26
A highly specialized feature of SQL Server 2008, managed user-defined aggregates (UDAs) provide the capability to aggregate column data based on user-defined criteria built in to .NET code. You can now extend the (somewhat small) list of aggregate functions usable inside SQL Server to include those you custom-define. The implementation contract for a UDA requires the following: A static method called Init(), used to initialize any data fields in the struct, particularly the field that contains the aggregated value. A static method called Terminate(), used to return the aggregated value to the UDA’s caller. A static method called Aggregate(), used to add the value in the current row to the growing value. A static method called Merge(), used when SQL Server breaks an aggregation task into multiple threads of execution (SQL Server actually uses a thread abstraction called a task), each of which needs to merge the value stored in its instance of the UDA with the growing value. UDAs cannot do any data access, nor can they have any side-effects—meaning they cannot change the state of the database. They take only a single input parameter, of any type. You can also add public methods or properties other than those required by the contract (such as the IsPrime() method used in the following example). Like UDTs, UDAs are structs. They are decorated with the SqlUserDefinedAggregate attribute, which has the following parameters for its constructor: Format— Tells SQL Server how serialization (and its complement, deserialization) of the struct should be done. This has the same possible values and meaning as described earlier for SqlUserDefinedType. A named parameter list— This list contains the following: IsInvariantToDuplicates—Tells SQL Server whether the UDA behaves differently with respect to duplicate values passed in from multiple rows. IsInvariantToNulls—Tells SQL Server whether the UDA behaves differently when null values are passed to it. IsInvariantToOrder—Tells SQL Server whether the UDA cares about the order in which column values are fed to it. IsNullIfEmpty—Tells SQL Server that the UDA will return null if its aggregated value is empty (that is, if its value is 0, or the empty string "", and so on). Name—Tells the deployment routine what to call the UDA when it is created in the database. MaxByteSize—Tells SQL Server not to allow more than the specified number of bytes to be held in an instance of the UDA. You must specify this when using Format.UserDefined. For this example, you implement a very simple UDA that sums values in an integer column, but only if they are prime. Listing 8 shows the code to do this. using System;using System.Data;using System.Data.Sql;using System.Data.SqlTypes;using Microsoft.SqlServer.Server;[Serializable][Microsoft.SqlServer.Server.SqlUserDefinedAggregate( Format.Native, IsInvariantToDuplicates=false, IsInvariantToNulls=true, IsInvariantToOrder=true, IsNullIfEmpty=true)]public struct SumPrime{ SqlInt64 Sum; private bool IsPrime(SqlInt64 Number) { for (int i = 2; i < Number; i++) { if (Number % i == 0) { return false; } } return true; } public void Init() { Sum = 0; } public void Accumulate(SqlInt64 Value) { if (!Value.IsNull && IsPrime(Value) && Value > 1) Sum += Value; } public void Merge(SumPrime Prime) { Sum += Prime.Sum; } public SqlInt64 Terminate() { return Sum; }} In this code, SQL Server first calls Init(), initializing the private Sum data field to 0. For each column value passed to the aggregate, the Accumulate() method is called, wherein Sum is increased by the value of the column, if it is prime. When multiple threads converge, Merge() is called, adding the values stored in each instance (as the Prime parameter) to Sum. When the rowset has been completely parsed, SQL Server calls Terminate(), wherein the accumulated value Sum is returned. Following are the results of testing SumPrime on Production.Product (an existing AdventureWorks2008 table): SELECT TOP 10 dbo.SumPrime(p.ProductId) AS PrimeSum, p.NameFROM Production.Product pJOIN Production.WorkOrder o ONo.ProductId = p.ProductIdWHERE Name LIKE '%Frame%'GROUP BY p.ProductId, p.NameORDER BY PrimeSum DESCgoPrimeSum Name--------------------------------------------360355 HL Mountain Frame - Black, 42338462 HL Mountain Frame - Silver, 42266030 HL Road Frame - Red, 48214784 HL Road Frame - Black, 48133937 HL Touring Frame - Yellow, 4668338 LL Road Frame - Red, 5254221 LL Mountain Frame - Silver, 4815393 ML Road Frame - Red, 520 HL Mountain Frame - Black, 380 HL Road Frame - Black, 44(10 row(s) affected.) Following is the DDL syntax for this UDA: CREATE AGGREGATE SumPrime(@Number bigint)RETURNS bigintEXTERNAL NAME SQLCLR.SumPrime As with UDTs, with UDAs there is no ALTER AGGREGATE, but you can use DROP AGGREGATE to drop them.
http://mscerts.programming4.us/sql_server/sql%20server%202008%20%20%20developing%20custom%20managed%20database%20objects%20(part%205)%20-%20developing%20managed%20user-defined%20aggregates.aspx
CC-MAIN-2014-49
refinedweb
750
52.49
Introduction: Rose Heart Border Large heart shaped cut-out to overlay on a picture of your favorite person, or printout for card or picture mat supplies needed: template from .pdf file (or screen capture of image) copy paper for template colored or fancy paper fot the heart cutout stapler scissors Paint program - I used PhotoShop Elements optional: craft knife and cutting mat. electronic die cutter machine like the one given for the grand prize on the paper craft contest. Step 1: Step 1 For a cut out border: print out the enclosed .pdf file on light weight paper staple this template to paper you are going to use for the cut out. (staples keep the template from sliding) Use your craft knife and very carefully remove all the white areas from the template. when centers of flowers and leaves are cut, then use your scissors to remove center and outer areas. OR import .pdf (it is vector based -so it should import as a "cuttable".) into your die cutter's software, save and and send it to cut. For an easier multi color print out: import .pdf file into your favorite paint program 1. Use magic wand to select the art 2. use gradient file 3. add a bevel effect Step 2: Print your art out on colored paper cut out the center area place over your favorite sweethearts! Discussions
https://www.instructables.com/id/Rose-Heart-Border/
CC-MAIN-2018-39
refinedweb
230
71.85
Slashback: Bnetd, Salmon, Towers 295 All I'm certain of is my true love's hair. CompaniaHill writes: "As previously reported on /., first they though it was turquoise. Then they found an error in their early calculations, and announced it was really beige. But doubts lingered, and color experts pointed out that an objective color as viewed from the theoretical blackness of space would appear different when viewed on Earth in typical daylight. So adjustments were made, and calculations were revised and rechecked by color scientists Michael Brill of McClendon Automation Inc. and Mark Fairchild of the Munsell Color Science Laboratories. And now, at last, Ivan Baldry and Karl Glazebrook, astronomers at Johns Hopkins University, using spectral data from the 2dF Galaxy Redshift Survey, have announced the final result: The universe is decidedly salmon. Really." The milestones are getting closer together. Dare Obasanjo writes: "Xindice (), the Apache native XML database has finally reached version 1.0. Xindice used to be called dbXML and was mentioned in my article on XML and databases." Three From the Courts TheFrood writes: "It looks as though the battle between Blizzard and bnetd (as reported in previous stories here(1), here(2), and here(3))is heating up. Vivendi has sent another letter to the EFF, which has wasted no time responding." ElitusPrime writes with an update in the strange case of Ken Hamidi, the Intel employee whose mass-mail to Intel employees brought charges of trespassing. Now the California Supreme Court may take another look at the case. Says ElitusPrime: "If this guy is put in jail, I can think of more then a few other spammers that need to go up the creek with him..." In a very different case, pagan26 writes: "It seem that DMCA will have its day in court. With ElmcoSoft." Well, at least you can trust their word, right? Masem writes: "According to MSNBC, the developers of the spyware program WinWhatWhere will no longer have their install program trample the bits of anti-spyware programs, after word broke that this behavior was occurring. However, no word has been made by a similar spyware program developed by SpectreSoft that does similar damage." I will fork out to see this, happily. Pingsmoth writes "It looks like the faithful fans of Peter Jackson and Tolkien will be able to catch a glimpse of The Two Towers this Saturday. Lordoftherings.net is reporting, through a video of Peter Jackson, that a preview (read: not a trailer) of The Two Towers will be shown in theatres this Saturday, presumably attached to The Fellowship of the Ring. Maybe at the end? At any rate, it looks like I'll be seeing the film at least seven times now, and it's a good thing I got a morning shift tomorrow." For a more colorful description of this 4-minute tease, check out Ain't it Cool News' version. Color of the Universe (Score:2, Funny) I knew it all along! (Score:4, Funny) I knew it all along; God is a She! I Personally Recommend ML [monolinux.com] Re:I knew it all along! (Score:4, Funny) Re:I knew it all along! (Score:3, Funny) How about white, off-white, slightly yellowed or even clear. Re:I knew it all along! (Score:2) I think it's more likely that God outsourced the universe's design to one of these decorators and overpaid a bit. Re:I knew it all along! (Score:2) More often than not, the resulting room is an abomination that only a colorblind wombat would like. My award for worst that I've seen - cool downstairs den done in natural wood and various "guy" accents converted to lime green, red and black. They pained the dude's coffee table CHECKERBOARD. I'm surprised this show doesn't result in more fatalities... GTRacer - Slipcovers and gaudy colors should be used in moderation with apologies to Douglas Adams... (Score:5, Funny) So long, and thanks for all the fish! Re:with apologies to Douglas Adams... (Score:4, Insightful) Russ %-) Re:with apologies to Douglas Adams... (Score:2) The universe isn't beige? (Score:5, Funny) On the other hand, don't. I'd rather have beige everything than salmon. How did they determine it was salmon, anyway? Are they sure it isn't coral? Or sunset pink? Or... Someone find a box of crayons for these researchers. In the name of research, of course. Re:The universe isn't beige? (Score:4, Funny) until they change the color again ... and then I'll start fretting about Sept. 11th all over again ... Re:The universe isn't beige? (Score:2) Re:The universe isn't beige? (Score:2) If these multicolored pillows don't convince her, may I suggest a trip to this dictionary [m-w.com], which returns the following: One entry found for organdy. /'or-g&n-dE/ Main Entry: organdy Variant(s): also organdie Function: noun Inflected Form(s): plural -dies Etymology: French organdi Date: 1835 : a very fine transparent muslin with a stiff finish In fact even Emily Dickinson [darsie.net] seems to think it's a type of cloth. preview vs trailer (Score:4, Interesting) Trailers used to be shown after a film, thus the name trailers they trail the film. But as you've I'm sure noticed most people leave the theatre well before the credits reach the top of the screen. So theatres started to show "previews" the exact same thing only before the movie. This had the added bonus of keeping people entertained. And in resent years earning ticket sales to movies people wouldn't other wise be cought dead in (wing commander anyone???) I just had to point this out after the talk of a preview (not a trailer) but it would be after the movie. Re:preview vs trailer (Score:2, Informative) Trailers have always been shown before the film: Origins of the word trailer [uselessknowledge.com] says: "Preview" just refers to the fact that it is a "preview" of a forthcoming movie. Grammatically, this is more correct, or else the "preview of The Two Towers" would actually be the "preview of The F of R, which shows clips from TTT." Re:preview vs trailer (Score:2, Insightful) first you say Trailers have always been shown before the film then later you quote. So basically, trailers used to be at the end(but some people didn't realize it), and now they are at the beginning, which is what they parent post was saying. Re:preview vs trailer (Score:2) Since trailers were spliced to the end of the last reel, they spewed by while the current audience left and the next audience walked in. The hope being that the current audience left during credits and the next audience walked in afterwards to be greeted by the trailers. Re:preview vs trailer (Score:2) The whole preview vs trailer thing is not about when the footage is being shown, it's about the type of thing being shown. It's about four minutes long and is really just a collection of images from the The Two Towers. It doesn't have the cohesiveness that normal movie trailers have, and it's a fair bit longer. I expect there will be a "real" trailer appear in about 3 months time. Re:preview vs trailer (Score:2) Re:preview vs trailer (Score:2) Re:preview vs trailer (Score:2) Headers (Score:2) #include "tt.h" Ken Hamidi is not an ordinary spammer (Score:4, Insightful) Commercial speech deservces less protection than non-commercial speech. In addition, complaints about employment practices may come under protection by the ADA, FMLA, Title VII, and the NLRA [nlrb.gov]. But, this intersect with the rights of Intel to have control over their mail servers. Maybe the lawmakers should look at this case when drafting anti-spam statutes. Re:Ken Hamidi is not an ordinary spammer (Score:3, Interesting) Are we supposed to just let individuals repeatedly send one sided biased screeds to tens of thousands of employees at their old place of work and keep doing it without the company being able to do anything about it? It is abusing the company's email system in the worst way. protections (Score:2) Under Sumner v. US Postal (3rd or 9th circuit) an employee is protected in reasonable protests for their rights. In Payne v. McLemore picketing against racial discrimination was held to be protected. Is sending lots of email more intrusive than picketing? The Supreme Court in Robison v. Shell Oil considers that protections extend to ex-employees. My argument (and seems to be the AFL-CIO's) that this is a protected act, and did this cross the line or being overly intrusive. Though Intel argues that it is tens of thousands of emails, it is not that many per person and only 450 requested removal. You have a point (Score:2) but the laws are (or should be) decided upon actual code, rather than vague notions. Currently, the way Intel decides who they "allow" onto their system is determined by how they configure their mail servers. There are exceptions for cracking and some very weak (civil) penalties for unsolicited commercial email. That's it. But instead, they sued after the fact for "trespassing" -- when there's no law to suit your case, just make the crime fit the law. The fact that Intel might be able to get away with this is, in my opinion, more troubling than the actual emails which were sent out. Imagine if a company could sue for trespassing anyone who sent an email through it's servers, that management afterwards decided they didn't like. Can Taco sue the trolls around here, when they play games to bypass the lameness filter? If I get pissed off, and write an email to my working group, can I be sued for trespassing? What if I write an email and ask someone else to forward it -- will that party be trespassing? I think the whole approach is wrong. If Intel uses an intra-net that's firewalled off, and someone hacks into it to send an email -- well, fine that's trespassing. But for an internet and mail server connected to the net, trespassing is just ludicrous. Until some anti-spam laws are actually passed that do not restrict themselves to commercial email, they should have no case. And I hope you see the folly of passing any such law. teasers, previews, trailers (Score:3, Insightful) I would think that this is a way to get people to see movies repeatedly in the theater at the inflated price... your average geek can see LOTR on some pirated version by now, so all the replay value has to be added via these teasers n'previews. You are drooling because of a very short piece of film, and you are allowing yourself to be marketed to. The fansites could be very useful centers of discussion and analysis, if they weren't so breathlessly following announcements of a teaser of a trailer. Re:teasers, previews, trailers (Score:3, Interesting) I would think this would be so obvious as to hardly be worth noting. In economic terms, look at it this way: Every time you see LOTR (unless you are an addict), your marginal utility drops. Eventually it falls below the unit price, at which point you are no longer willing to spend the money to see the film. If prices could fluctuate, the ticket price might fall to entice you back in. But movie tickets are essentially fixed. So it seems like they could never make more money off this from you. But lo! They add some teaser material. Now, assuming you want to see the teaser, they've added marginal utility back to the experience. Your ticket, at say $8, buys more and, if they're right, this raises your satisfaction to the level where you're willing to shell it out. But that isn't to say that the new material need be worth $8. It might only be worth $0.40 to you. But if you value seeing LOTR again at $7.60 -- if that were the price you'd have been willing to pay to see it -- then, with the additional material, your utility is $8 and you're willing to go back. So that little bit of value, small in itself, might still justify the trip. Gotta love Econ 101. Great Band Name! (Score:3, Funny) Decidedly Salmon is a great band name. example of more DMCA uselessness (Score:5, Informative) The man in question, pleading guilty under both Copyright law and the DMCA for illegally copying video tapes, faces the following sentances: What was so lacking in the punishment for violating the copyright laws that the DMCA was needed? This and the Blizzard BNETD case show, IMHO, that the DMCA is nothing more than a legal weapon paid for the entertainment industry to chill any speech or action that they feel cuts into their profits. It does not impact the 'for-profit' pirates that actually cost the industry revenue, it tramples on the average consumer. Copying copyrighted video tapes was illegal before the DMCA. There is no need for an additional law like the DMCA to put "fear" into the pirates like this guy. They face stricter punishments for violating copyright laws than they do the DMCA. The DMCA just broadens the scope to include that so-called gray area that is the average consumer wanting to time-shift/space-shift their belongings, which happens to cut into the entertainment industries profits. Fuck the DMCA and Jack Valenti and Hillary Rosen. The correct url is here [usatoday.com]. salmon... (Score:2, Funny) LOTR (Score:2) After all, it's not only 8 bucks that is at stake, but 3+ hours of movie time (I'm not saying that the movie doesn't worth the time spent, but it's hard to justify it to the wife LOTR (Score:4, Interesting) With that in mind, I can't understand why people loved Peter Jackson's film so much. I tried to remain open minded, but I found it incredibly hard not to just walk out in anger. He completely ruined the spirit of the tale, and quite unecessarily at that. Most of his changes were totally not needed. Once he decided to remove Tom Bombadil/The Barrow Downs he easily had enough time to remain true to the story, and so many of his alterations took longer to correct later on in the story than he would have ever have saved if he'd just left it be. That is one of the main problems with making alterations to a story as deep as The Lord of the Rings, if you remove one thing, all the other parts of the story connected to it have to be altered, which cause more alterations later on. Plus since when has 4 Oscars been a "snub"? Re:LOTR (Score:5, Insightful) Plus, it's a good movie in its own right; millions who have never read the books saw it and enjoyed it as a movie. Obviously Peter Jackson is doing something right. Complaining about what was left out - especially Tom Bombadil or the Barrow Downs - is just plain silly. There is no way Jackson - or anyone - could have included that material without totally bogging the storyline down and ruining the movie. It had to go. Similarly, the other changes were necessary to make the story flow as a movie script. There is no way of avoiding these necessary changes. I suggest you do what I did: see the movie again. I enjoyed it the first time, but spent too much time obsessing over every little thing that was changed. By the second and third viewing I was simply enjoying the movie, and not worrying about the changes. Re:LOTR (Score:2) I agree with you - it's a good adaptation, but then again, I also like the Bakshi version, and in some ways find it more "faithful", and find that PJ did some direct lifting from that movie in his. Either way, I reread the books rather often as well, so I have become used to and tuned into deviations - which can be annoying, but oh well. As long as Moria is done well, I don't care who does it Re:LOTR (Score:2, Insightful) anyways... He hardly has time to remain 100% true to the story. Which is basically an unachievable goal. I can't think of any case where that has happened. It might be close but there are ALWAYS differences. That is notwithstanding poor casting, which IMO, did not happen in FOTR. Lord of the Rings is about half a million words. There is no conceivable way that even with selective edits and ellipsis that that big of a work can be compressed accurately into 9-10 hours of screenplay (for all three parts of the story). The BBC's radio version was very near 13 hours. Again other mitigating circumstances appear. While yourself, most of the people here, and I can vividly recall almost every scene and the order that each character is introduced the vast majority of the public cannot. In fact, this might be their introduction to it. Thus the story had to have more edits (other than those due to time constraints). With the fact that it could not replicate every detail or even attempt to... It was still superb. It was epic; it was fun; it was well acted... It did indeed capture the essence of the original work. If you looked closely you could see several details of exactly how well crafted it was. The broaches given to the company appeared after visiting Galadriel -- time constraints didn't allow that story to be told. But the items themselves WERE there. There are several similar circumstances were time would not allow everything to be told, but they still happened. Take it as it was offered - A standalone work that did well to represent the original and brought more people into the realm of Middle-Earth Re:LOTR (Score:2) Everything that was shown was accurate (in the details) - even down to the oars they used were right. The big stuff got moved around, but that was to cover the stuff cut. Even my second biggest complaint, the long battle scenes, were probably necessary. In the book, some of the scenes were 500 words - but you can quickly *say* "the battle raged on around them for hours", but to *show* that it was a long, tough battle takes time. (Incidently, I liked how they showed the wizards power were not on the "toss lightning" modern style, but more "control the weather and talk to animals"... which was horribly negated by the really dumb looking wizard battle. That would be my biggest complaint about the movie. Although I'd love to see a half hour, stand alone version of Tom Bombadil, complete with songs, included in the boxed set). -- Evan Re:LOTR (Score:2) As someone who's read LotR (and re-read many times), I found fault with nearly all of the script decisions that the movie made. However, the movie amazed me visually. Seeing Hobbiton, Rivendell, Moria and Orthanc come to life before my eyes made the movie well worth the price of admission (they did get Lorien wrong in my mind, but no one's perfect And Ian McKellan *is* Gandalf...if he doesn't win an Oscar for one of the movies, I'll be upset. Re:LOTR (Score:2) Anyway, all I am getting at is that the movie trilogy has not been fully revealed to us, so I'd save any critique about it (as in contrast to the book) until all three movies have been released. Also, LOTR::FOTR was interesting enough that I was compelled to read the whole book. Jackson must have gotten something right, because I have an urge to see the movie again. Now what I think would be pretty badass would be a movie-translation of the Silmarillion. No offense to those cute hobbits, but the creation of Arda thru the end of the Second Age are more interesting to me. It'd be pretty badass to witness the Music of Ainur, the beauty of the Undying Lands, the creation and loss of the Silmarils (and Morgoth getting his ass kicked but good), and the rise and fall of Numenor. After all, The Silmarillion sets the stage for Lord Of The Rings. Any fan of Middle-Earth that hasn't read The Silmarillion should do so. Now if I could just become fluent in the high-elven tongue... hehe Re:LOTR (Score:2) Just looking at how well LotRs is selling (the book, not the movie), and that, by itself, is a good enough reason for the movie. The fact that people are getting into the Silmarillion from the movie is icing. (And I second your notion - the creation being a Fantasia like opening on the front (a la the Pixar shorts), and then the events of the Second Age would truely kick azz). -- Evan Re:LOTR (Score:2) Everything in it felt incredibly rushed; it was nuts! It turns out that the BBC play took about 4 hours to do FoTR, including narration of visuals which were obviously missing. Still they left in a whole lot more dialogue. It was actually more interesting and exciting than the movie--and ten times deeper. PJ cut an hour off that time, but on film he had the luxury of conveying a lot more information per unit time, because he has both audio and video. So why does it feel like I got so much less? To be fair to him, I'm not sure I could pick out many parts that I thought were a waste of time. I do remember some distortions which I thought to be unnecessary because they saved no time at all, but perhaps they set us up for future distortions in the other two movies. Maybe the problem with LOTR is that it's not inherently filmable. Re:LOTR (Score:2) Or it could have gone off on some pervy hobbit fancying tangent. And Sam will kill him if he tries anything. "The universe is decidedly salmon. Really." (Score:2) LOTR: TTT preview / trailer on Fri., *NOT* Sat. (Score:5, Informative) That was close! I already have my tickets for my 5th screening tomorrow (Friday). Re:LOTR: TTT preview / trailer on Fri., *NOT* Sat. (Score:2) On a side note, when can we get a prop auction or something? The things they created for the films are just awesome. Blizzard doesn't have a leg to stand on. (Score:5, Informative) We have reviewed the arguments in your letter, and do not find them convincing. We continue to believe [that bnetd is] an infringement of VUG's copyrights. Those activities implicate a number of VUG's exclusive rights under copyright... etc etc. Their response is classic, and I love their lawyer. It would be more helpful in the future, however, if rather than summarily claiming that you believe that "the activities engaged in by" violate "a number" of your copyrights, you would state specifically what portions of the website and which particular files you believe are infringing, which of your copyrights you believe are infringed and how. We are also uncertain about the exact nature of the technological protection measure you believe has been circumvented... The CD-Key protection isn't really a "protection measure" per se. You can install the game without using a valid key, you can even play the single-player mode (well, there IS no SP mode in the beta, but you know what I mean) without a true key. Ergo, a circumvention has only occurred if I loaded a program that caused your official server to validate my fake key. Vivendi knows this, and that's why they're unclear about the "several copyrights" that were infringed. The copyrights were to the "for" method, the "if" statement, the "void" function type and the "main()" function, is the only thing I can see here... But I suppose I shouldn't joke about that, or we'll have some bright guy trying to patent them, eh? Bah. I find this highly amusing.... Re:Blizzard doesn't have a leg to stand on. (Score:2) Blizzard can't possibly claim that battle.net cd-key checking is a copy protection method: it doesn't stop the copies from being made, or even from working (they DO work) - just prevents copies (actually, 'certain reported CD-keys' - so it could actually be used to ban individual people for no reason, even though Blizzard hasn't done this - yet) from working with their servers. I have no idea why Blizzard is doing this, or why they haven't noticed that Vivendi's lawyers are monkeys (see my other post - that letter is real big crap, and they misinterpreted the USC 512 code they quoted). Vivendi's throwing money away, when Blizzard should be working with bnetd to try to fix this. If they really want to save money and stop piracy (rather than just charge for battle.net at a later time, which is what they REALLY want to do) they'd be doing that, which is what id software and every other game manufacturer in the world with online play has done. Re:Blizzard doesn't have a leg to stand on. (Score:2) Blizzard doesn't like that much, and I am pretty sure that this is just Vivendi's doing. Blizzard is probably just wanting to write a damned game. Re:Blizzard doesn't have a leg to stand on. (Score:3, Insightful) What I'd LIKE to point out to them is that there are several solutions (hello! math!) where they can guarantee that only legal copies are being used on battle.net, and provide an easy way for bnetd to prevent illegal copies there as well. (Someone correct me if I'm wrong. I'm aware hackers could work around this, but it would take a lot of effort, and they'd have to hack both bnetd and their own client, so then it's not so easy) You could easily give the CD-KEY to a blizzard keychecking server, which then not only figures out if the key is correct, but then generates a unique number, which, when hashed together with the original CD-KEY on the client, activates the product. Blizzard then forwards the result back to the bnetd server, and the bnetd server passes it back to the client. If it's incorrect, the client doesn't run (here's the key - the CLIENT doesn't run, not the server doesn't allow the client. The DMCA prevents you from bypassing something designed to prevent CLIENT copying, on the CLIENT). You could hack around this, by altering both the bnetd server, and hacking the client to do it as well, but that's complicated and then Blizzard could go after people who are distributing the hacks that do that, rather than bnetd, because THAT would be clearly illegal. This is better than a simple blind "accept/reject" system because it requires that any battle.net server has to communicate with Blizzard (or figure out the algorithm behind the Battle.net check/second key generation, which can be made quite difficult) and Blizzard guarantees that things are OK. Re:Blizzard doesn't have a leg to stand on. (Score:2, Insightful) First, it wouldn't be incredibly hard to develop a method by which one found a bunch of valid keys by spamming the keyserver. Second, if you're going to say that the server itself never knows that the key going through it is actually valid, you don't need to hack the bnetd server, just the client. If the bnetd server knows if it's correct or not, then (since this is an OSS product, it's made easier) one could make their server dump all keys that came up valid to a file, and thereby harvest many many keys. And third, as has already been pointed out, they don't care about piracy, they want to charge for b.net access. The piracy slant is a coverup. Re:Blizzard doesn't have a leg to stand on. (Score:2) You're right about not hacking the server, though - the clients could just communicate with a keyserver completely separate from the bnetd protocol completely - oh wait. That would be intelligent. Re:Blizzard doesn't have a leg to stand on. (Score:2) Yes, what I'm suggesting is kindof something like Windows Product Activation - I'm not suggesting this is a good thing. What I'm suggesting is that if they're this paranoid about piracy, they are much more stringent restrictions they can allow. Again, this is all a moot point, as they really only care about charging for battle.net. The funny thing is that even if they win against bnetd here (which they won't) as soon as they start charging, bnetd could start again, as battle.net servers are then a monetary resource, and Blizzard would be holding an illegal monopoly. Re:Blizzard doesn't have a leg to stand on. (Score:2) Then maybe you might actually want to go after the people who promulgate that hack, rather than after bnetd, which is completely legal. That said, it will completely suck if Blizzard doesn't provide remote access to the keyserver - then they're really just holding a monopoly (battle.net servers) and refusing to let anyone else play. If you want a good example of how life SHOULD be, take a look at what Bungie did with Myth II's server - they open sourced it when they decided to take it offline. I'm not saying that Blizzard wouldn't do the same - it's just looking very likely that they won't (they'll just remove WC2 support from the next battle.net setup, and poof, we're all out of luck...) Re:Blizzard doesn't have a leg to stand on. (Score:2) The trick is to start at the basics, and by the way Somebody beat you to it [theonion.com] Gheez.. (Score:2, Insightful) Nice movies (Score:2) Good stuff. Ice caps melting from beneath (Score:2) I just keep wondering (Score:5, Interesting) any politician that is not strongly in favor of alternate forms of energy is a dick. not because fossil fuels are inherently evil (ok, the corps behind them may be), but more importantly, they're never going to get us off this idiot-infested rock. oh, and they're not renewable. go nuclear! it's god's favorite power source. check out, oh, say, the rest of the universe if you're in doubt. hey, god can't be wrong. um, that's about it. Re:I just keep wondering (Score:2) to my point (Score:2) the problem is that humans have this pesky habit of building their civilizations right along the shoreline. it's not a good long-term plan when you're in the thawing cycle. building further north becomes problematic during the freezing cycle because glaciers tend to be fairly persistent and, oh, huge and unstoppable. humans have this other rather irksome habit of being, on the whole, fairly short-sighted. most civilizations aren't really planned. no where is it ingrained in our personalities to go out of our way to make sure our current agenda has any real positive bearing on future generations. and don't go thinking you're going to make a difference. the power is in the hands of the governments and megacorps. behold the USA, pinnacle of "Democracy" and "Freedom"! how much of the wrangling that occurs in Washington, DC every day has the enlightened future of humans in mind? bingo if you said, "zippo, zilch and nada". it's grubbing for money and power with the occasional kissing of babies and touching of cripples to please the electorate. and no where else is any better. oh, wait, it looks like florida is flooding. well, we just didn't see that coming. quick, who do we blame? who can I use this against? sorry, until we have a global change of consciousness and get past our basic animal instincts, it'll be slow and perilous going. Re:I just keep wondering (Score:2) I think the concern is this: first, that humans are changing their environment, and second, that we're doing it so fast (and the rate of change is accelerating?) that we won't be able to predict/deal with the consequences. In the broadest sense, that's pretty much what it boils down to. In the case of global warming, there's a lot of evidence and research which backs up that first point. This means that the second is a valid concern, especially since many people who know more about it than you or I think that we're going to have problems (specifically, that the rate of change in the temperature of the Earth is too high to be purely natural, and is getting faster, yet that we're not doing enough to either prevent it or deal with its consequences). After that it gets complicated. Discussing that second point at all requires making predictions, and prediction is an inexact science. Also, some of the issues related to global warming are extremely complex. For example, there are several reasons to want to move away from gasoline-burning automobiles, from concern over global warming to issues of long-term availability of fossil fuels, the health effects of automobile exhaust, city planning issues, and so on. Then there's convencience, habit, corporations trying to protect their profits, and other forces on the side of maintaining the status quo. This results in one dang complicated issue, which is why people spend a lot of time talking about it! Incidentally, last time a global warming story was posted on SlashDot, someone got modded way up for pointing out that we are in a cooling period, not a warming period. Another reason why there's so much discussion is the massive amount of misinformation out there. Plus there's the fact that the issue is way to big for a discussion to cover every aspect of it. On top of that, there's a tendancy for people to believe what they want to believe (a general tendancy - ask any tech support person!) The result: massive amounts of discussion. what the heck kind of letter was that??? (Score:4, Interesting) Vivendi didn't address ANY of their claims, specifically the point that 1201(c) and 1201(f) clearly ALLOW software such as bnetd (they might as well have specifically given this as an example of what the DMCA does NOT prevent) - just saying "no, you suck, go away." They also misinterpreted 17 U.S.C. it looks like, thinking that bnetd only had 10 business days to respond or they can't file a counter notification, whereas the statute is saying that the offending material can't be redistributed in less than 10 days after sending a counter notification. Vivendi's actions are going to look really bad from a court's perspective - they're being very aggressive and holding their cards all to their chest, so if they do sue, and try to pull some trick, a judge isn't going to be very lenient. I am very glad that the EFF is handling this, though - it would've been very difficult, if not impossible, for bnetd to handle it themselves. Tickle Me Elmco Soft? (Score:2) I can think of something else that's salmon (Score:2, Funny) XML based dbs? (Score:3, Interesting) Re:XML based dbs? (Score:2) Re:XML based dbs? (Score:2) Re:XML based dbs? (Score:2) Nevermind that it is text, the important point is that is is a tree structure. Standard databases are relational, and are great at storing simple attributes for an object. They are absolutely horrible at storing relationships between these objects and, more importantly, in managing those relationships. So, for example, if you have a grommet that can consist of multiple other grommets, each of couse consisting of grommets etc., then in XML you are laughing: In a standard relational database you end up with a grommet table and, perhaps, an attribute that is the parent grommet. To get the list I just suggested above, you need to do a self-join on the grommet table an unknown number of times, something SQL just can't do. Object-oriented databases are good at this (and much more), and it is funny that the old style of databases that preceeded the relational databases, were often hierachical, i.e. tree structures! So the scoop is this: the trees are back. Trespassing (Score:4, Insightful) Re:Trespassing (Score:2, Insightful) What makes these scientists brilliant... (Score:5, Funny) Johns Hopkins Administration: Okay, what are you guys working on now? Astronomers (quickly alt-tabbing from Return to Castle Wolfenstein to a spreadsheet): Uhhh... we're calculating... the... color of the universe! We'll need at least two weeks. JHA: Right then. Talk to you in two weeks. Astronomer 1: Whew. How're we gonna figure out the color of the universe? Astronomer 2: Who cares? It's turquoise. Now be quiet. I'm sniping. [two weeks later] Astronomer 1: Hey check it out! The Warcraft III beta is out! [JH Admin comes in] JHA: Hey guys, got your report on the universe being turquoise. Great work. Astronomer 2: Yeah, um, we've got a problem. We think it might be beige. We've got to do spectral graphalisys and whatnot. we'll need another two weeks. JHA: Okay. etc... Re:What makes these scientists brilliant... (Score:5, Funny) Salmon [slamonidaho.net] Correction: LoTR - Friday, not saturday (Score:2, Redundant) At the end, before the credits (Score:2) I saw a two towers preview last weekend (Score:2) looked pretty cool. Boycott Blizzard, and a petition (Score:3, Interesting) [boycottblizzard.org] I also have a link from there to a petition that I would appreciate signatures by anyone against the use of the DMCA by Blizzard (Vivendi Universal Games) in this case (even if you don't plan on boycotting). Re:Boycott Blizzard, and a petition (Score:2) Hah, I'm _still_ boycotting blizzard over their complete disregard for privacy and malware concerns over the starcraft name emailing debacle. The big deal there was not so much that they erred, or that they shipped such an egrious piece of software that would pass your personal registry items to blizarred if you miskeyed your registration code, but that they refused to admit that there was anything questionable about this or that there was any other angle from which to view the situation. A company that effectively implants spyware in their product and refuses to accept that this was an undesirable action is untrustworthy and is not a reasonable source of software products. At least, that's my view. DiabloII.Net Censors Bnetd Discussions (Score:5, Interesting) As of a few days ago, the fan website has been banned any discussion of the legality of bnetd in their chatroom, #diabloii on irc.wiregrass.com. Furthermore, when many of the regular members protested this action by included [censored] or [oppressed] in their nicknames, they were banned. The nickname modifications that resulted in being banned include: [bnetd], [censored], [oppressed], and [not_battle_net] (there may have been others). A posting to their forums [diabloii.net] mentioning the censorship was deleted, and the account of the poster (myself) is no longer allowed to post (not a big deal, I created the account specifically for that purpose). Don't petty tyrants surpress news of censorship, too? As it stands, discussing bnetd is forbidden in the chat room. Protesting the censorship in any way is forbidden. Discussing bnetd or the censorship in the forums is forbidden. Under a different account, I posted a rebuttal [diabloii.net] to their recent anti-bnetd article [diabloii.net]. I wonder if they will censor that as well? Re:DiabloII.Net Censors Bnetd Discussions (Score:2) I hope you never have to release closed source code and have to worry about someone reverse engineering some of the profitibility out of it. Breaking news! (Score:3, Funny) After the latest press conference some color experts were asking how it could possibly be yellow. The head astronomer explained that it was a red-shift effect. "My assistant Bob can explain it to you, he entered the red-shift adjustments..." Bob: "Me? I didn't enter them. You were supposed to do that" Head astronomer: "You didn't? Oh shit..." - Blizzard of Issues (Score:2) It summarizes a lot of how I feel about this issue. I'd also like to add that I think that the precedent that bnetd is trying to set is eerily dangerous while on the other hand I think Blizz's invocation of the DMCA is also not-a-good-thing. Music Companies != Blizzard (Score:3, Interesting) Every so often people talk about napster/kazaa/morpheus, and someone usually says, "It's not the government's responsibility to protect companies that depend on an obsolete business model." By this they mean that music is too expensive, artists get stiffed, there's no way to buy single tracks, etc., etc. I think we all feel stiffed by the music industry sometimes. Now Blizzard has a much better business model. They sell game boxes in the store, and then they let you spawn multiple copies to play it with your friends locally. (Real companies actually support fair use?) The best part is, when you start getting good and enjoying the game, all they ask is that you get your own copy so that you can play on the Internet. If you only like the game enough to play once in a while at your friends' house, you can go your own way. I mean, they'll even let you create your own account on your friend's machine, because they know sooner or later you'll want your own copy so you can play alongside your friends. This business model lets each customer decide for themselves the threshold at which they pay for the product. This is one of the best, most fair business models I've ever seen. The thing that saddens me is that if we try to take advantage of Blizzard, they (unlike the music companies) are talented and flexible enough to switch straight over to writing console games, and where will we be then? If Blizzard is forced to change their business model, we, the consumers, will lose out. We'll end up with games that can only be played on XBox via a proprietary network, and nobody will be able to spawn guest copies. I know code = free.speech; I know that some people whine about how battle.net can get slow; but wouldn't you rather have the EFF fight to defend open source licenses instead of fighting to help people crack into the Warcraft 3 beta? XML databases obsolete 30 years already (Score:2) An XML database amounts to a domain-specific technology – hierarchical databases, a special case of network (in the connecting conceptual nodes representing pieces of data sense, not the connecting physical computers over cables, protocols and radio sense) databases – that has been obsolete for 30 years now, since EF ‘Ted’ Codd published his ‘A Relational Model of Data for Large Shared Data Banks [acm.org]’ paper. There have long been the desire for a truly relational [dbdebunk.com.] DBMS that would solve not only hierarchical problems like XML and bills-of-materials cases, but also would provide a much saner OO database foundation than current OODBMSs or ORDBMSs. There’s even a proprietary beta implementation [alphora.com] that I’ve submitted twice to Slashdot, being twice ignored if we don’t pay attention this could give the Microsoft camp a real technology first and jumpstart over us – ‘ meaning both the free software and the open standards ’ for the first time, except the ease-of-use issue where they are still a step ahead. tell them you hate DMCA and why Re:Email the media! (Score:2) Better yet, tell jim Jesse Jackson supports it! That'll get his attention! #insert "drippingsarcasm.h" Re:Email the media! (Score:2) Were you trying to say something? Accuse me of something? Obviously it must have been important or you would have spewed vitriol like you did. Re:DMCA in action (Score:5, Insightful) You're either a troll, or someone incredibly ignorant. Did it occur to you that Vivendi might just be firing off BULLSHIT in their letters? Reading a legal document from the bad guy isn't going to give you an accurate profile of the entirety of the situation. Hence, your ignorance. Bnetd wasn't created to pirate Blizzard games any more than DeCSS was created to pirate DVDs. It was created so people playing Blizzard games could have multiplayer games on local LANs without having to rely on battle.net. Blizzard is just using the lack of CD key authentication as a reason to kill the project. Bnetd asked Blizzard to provide a means to authenticate CD keys, and Blizzard refused. So what happens? Bnetd functions happily without it. They tried to take their ball and run home, but they made their OWN ball. Boo hoo for Blizzard. Re:DMCA in action (Score:2) B: That's not a game server - that's connecting to play with friends. Blizzard provided a functionality for playing with a game server - they can't restrict it and say "uh, no, only ours." I could give reams of reasons why this is valid, but I only need to give one. It's fair use. Re:DMCA in action (Score:2, Interesting) Sorry, but IPX REALLY sucks. Network performance is terrible if you're on a local LAN and want to connect to someone across the Internet (with Kali, let's say), especially if that person is on a slow modem. Under IPX, everyone's performance is synced to the person with the slowest network connection. Battle.Net is also pretty bad -- laggy as hell, unstable, and filled with people where the average maturity seems to be that of a 12-year old. Setting up a bnetd server on my box was the best way for myself and a small circle of friends to connect together, have our own ladder games, and play in our own private environment. It probably wouldn't have been necessary if Starcraft came with a TCP/IP option, but it doesn't. (for that matter, why doesn't the TCP/IP option in Diablo2 accept hostnames instead of IP addresses?) Re:You are mistaken (Score:2) Sure. But I don't see purely LAN games too often myself. Often it's "people on a LAN... and a guy halfway across the country." That was the nice thing about Kali -- even though people might be scattered, from the game's perspective they were all on the local LAN. Some of Blizz's games are synchronous, like the starcraft you mentioned, so your friend with the modem is going to slow down everyone else, IPX vs. TCP/IP is irrelevant in this case. Actually with Starcraft, that is not the case. When you connect with Battle.Net, a slow modem user does not slow down the other users like he would if he were using IPX. If the net-connection is completely unresponsive, then the game freezes for everyone until the lagger is dropped or unlags, but that is the extent to which a slow modem user (aren't they all? ;) ) lags the game. The behavior is completely different for an IPX game. Nearly all of Blizz's games are peer-to-peer, again the starcraft you mention, so battle.net is not lagging your game. You're right, but the part I was refering to was the initial game setup which occurs on Battle.Net -- gathering in a channel, hosting a game, letting people join... then finally when the game starts it's out of Battle.Net's hands. I've had nights where I gathered a small handful of friends, and we weren't even able to start a game together. When Battle.Net lags, it will often incorrectly claim a game doesn't exist (I think a lot of famous misleading error message like "game doesn't exist" and "character not found" are generic catchall error responses). When I tracerouted uswest.battle.net, the trace was perfectly clean... until the very last hop, where the times spiked by at least half a second. Packet loss was pretty high as well. Fortunately that's not the norm, but it's very annoying when it happens. That night of frustration when we couldn't start a Starcraft game (Kali wouldn't work since one of my friends was on a modem) was the night I decided to compile and setup the bnetd server. We haven't looked back since. You are mistaken, Starcraft does have TCP/IP LAN play. It was added about the time the MacOS X version was released. Starcraft, as of the current version, only has local TCP/IP capabilities. DiabloII has true TCP/IP over the Internet, but Starcraft's UDP support is still limited to the local lan. (though I've yet to try this with Kali -- might be interesting to see if it doesn't lag anymore) Re:DMCA in action (Score:2) mmorpg games make a nice tidy sum from their player base, I pay for two different ones every month. Sony have had nearly £300 from me so far to play Everquest. Mark my words, battle.net will not remain free and I predict that it will change with the release of WC3. bnetd is a real threat to that and the piracy thing is just a smokescreen . Re:DMCA in action (Score:3, Interesting) My server, my resources, my decision about who I let on it, and how I verify them. The onus is on the player, imo, in a keygen situation. The player is the one infringing by using a keygen and infringing copyright - bnetd is simply reverse-engineering and providing a plug-compatible solution. (that's one point of view, in any case) Re:DMCA in action (Score:3, Interesting) Failure to include copyright controls in your own work is not the same as NOPing them out of someone elses software. Re:DMCA in action (Score:2) I'm really glad this started a thread. For the most part I was ignorant of the details of the bnetd/blizzard controversy. My post was not meant to be a troll. The question was answered. The existence of a single positive use (TCP LAN play) may be a good reason for its existence. The real problem that people are struggling with here is that ownership of information doesn't make sense. That is why everyone here is so hell bent against the DMCA, because, the way I see it, the DMCA puts teeth into that ownership. I don't really agree with the DMCA, but if you really belive in content ownership, I can see how the DMCA makes sense. People don't really believe (me included) that it really makes sense that you can own an idea. Before the last five years, before sharing big sets of ideas (digital content) was so easy -- it wasn't really a problem for the content owners. I see the DMCA, and recent legislation, as a symptom of a more fundamental problem -- most people instinctively don't believe that its OK to own ideas. It flys against a basic fundamental nature. It used to be that individuals survived through cooperation, sharing -- for hundred of thousands of years our species all shared to survive. Only in the last 6,000 years has the norm shifted to one of individuals competing to survive. Not sharing to survive. Welcome to business 101. see my site Re:DMCA in action (Score:5, Informative) How is what bnetd doing OK in any way? Perhaps you should read EFF's response, and possibly even Title 17, Chapter 12 [cornell.edu] where it says (as referenced by the EFF letter): 1201 (c) Other Rights, Etc., Not Affected. ... (3)1201 (f) Reverse Engineering ... (3) Nonsense. (Score:4, Insightful) Idiot. TheFrood Re:Hmm... (Score:2) What ever happened to this supposed posthumous release from Adams? Re:Hmm... (Score:2) Man, I still feel like crying when I think about it. Meghan Re:A New Sentence to Absolutely Hate. (Score:2) Ever heard of the idea that there might be ways to express disagreement without resorting to moderation? Like, y'know, engaging Mr Braincell before hitting that darn' Reply link? Yes, I think he had quite a valid point. Over here [UK] we had an article on the radio news about how it was "6 months on since Sept 11th" - like, erm, gee, let's just define a whole calendar around the incident. It's like after Princess Di died - Elton John was well reported as saying "she's gone, now let's get on with it". The world does not revolve around her, or the absence of the twin towers, or about some idiot moderator on
https://slashdot.org/story/02/03/27/179239/slashback-bnetd-salmon-towers
CC-MAIN-2018-13
refinedweb
8,975
71.65
Hi I have an assignment to do where I have to make a race between two cars (this assignment is a continuation of a previos 'mini' assignment where I had to do the 'race' with one car). The commands that I implemented for the cars is foward (increases distance travelled), reverse (decreases the distance travelled), left and right (left and right doesn't increase or decrease the distance). Now what I need to do is make a race between two cars where what is currently displayed needs to be accompanied by the commands of the other car. Console example of the layout. To make the two columns you can use \t. Car1. . . . . . . . . . . . . . . . .Car2 Forward 1km. (total). . . . . . Right. Left. . . . . . . . . . . . . . . . . Reverse -1km. (total) Forward 4km. (total). . . . . . Left. Reverse 3km. (total). . . . . . Forward 3km. (total) Oh and i'm using two classes because that is what was required by my lecturer. Simulator.java import java.util.Random; class Simulator{ public static void main(String args[]){ vehicleCMD car = new vehicleCMD(); Random rand = new Random(); int km, km_rev; int do_what; car.start(); while (car.cmd_start == true){ km = 1+rand.nextInt(3); km_rev = 1+rand.nextInt(1); do_what = rand.nextInt(4); switch(do_what) { case 0: km = car.forward(km); break; case 1: car.left(); break; case 2: car.right(); break; case 3: km_rev = car.reverse(km_rev); break; } if (car.total_km >= 70){ car.stop(); } } } } Methods class. public class vehicleCMD{ boolean cmd_start = false; boolean cmd_stop = false; boolean cmd_forward = false; boolean cmd_reverse = false; boolean cmd_right = false; boolean cmd_left = false; int total_km = 0; public void start(){ cmd_start = true; cmd_stop = false; System.out.println("Power ON."); } public void stop(){ cmd_stop = true; cmd_start = false; System.out.print("\n\nGas Tank empty. Car STALLED"); } public int forward(int km){ cmd_reverse = false; cmd_forward = true; total_km = total_km + km; System.out.println("Forward " +total_km+ "km. (total)"); return km; } public int reverse(int km_rev){ cmd_forward = false; cmd_reverse = true; total_km = total_km - km_rev; System.out.println("Reverse " +total_km+ "km. (total)"); return km_rev; } public void left(){ cmd_left = true; cmd_right = false; System.out.println("Left."); } public void right(){ cmd_right = true; cmd_left = false; System.out.println("Right."); } } The code is in working order and is totally open source.
https://www.daniweb.com/programming/software-development/threads/276696/need-help-with-assignment-car-race
CC-MAIN-2020-40
refinedweb
355
61.33
PDB Web Services Script Overview A short snippet of code utilizing the new PDB Web Services. Notes: - See PDB Web Services - You need SOAP for Python installed - The sequence of a chain fetched from the PDB does not always equal the sequence of a chain fetched from the PDB Web Services. I believe the PDB Web Services has the complete biological chain, not just what's in the structure. - The offset is a hack; it uses a trick in PyMOL and may not be robust at all. Use at your own caution. The Code import pymol from pymol import stored, cmd import SOAPpy # define a mapping from three letters to one # Thanks to whomever posted this on the PyMOLWiki: #'} # fetch some molecule; yes, 1foo exists in the PDB = ''.join( stored.pyMOLSeq ) server = SOAPpy.SOAPProxy("") # fetch the secondary structure assignment from the PDB & # split it up into an array of characters stored.ss = list( server.getKabschSander("1foo", "A") ) # get the sequence pdbSeq = server.getSequenceForStructureAndChain("1foo", "A") # danger: hackishly foolish, but worked for 1foo. offset = pdbSeq.find( stored.pyMOLSeq ) # make the assignment in PyMOL cmd.alter( "1foo and c. A and n. CA and i. " + str(offset) + "-", "ss=stored.ss.pop(0)" ) # show as cartoons cmd.as("cartoon")
https://pymolwiki.org/index.php/PDB_Web_Services_Script
CC-MAIN-2020-05
refinedweb
206
67.96
USBD_Callbacks_TypeDef Struct Reference USB Device stack callback structure. #include < em_usb.h> Callback functions used by the device stack to signal events or query status to/from the application. See USBD_Init_TypeDef. Assign members to NULL if your application don't need a specific callback. Field Documentation Called whenever the device stack needs to query if the device is currently self- or bus-powered. Applies to devices which can operate in both modes. Called on each setup request received from host. Called at each SOF interrupt. If NULL, the device stack will not enable the SOF interrupt. Called whenever USB reset signalling is detected on the USB port. Called whenever the device change state. The documentation for this struct was generated from the following file: em_usb.h
https://docs.silabs.com/thread/2.8/structUSBD-Callbacks-TypeDef
CC-MAIN-2019-13
refinedweb
125
51.95
I am working on an Angular 2 application in ASP.NET Core and I am trying to import oidc-client () into one of my Typescript files. The oidc-client files were installed via bower which placed them in the expected bower_components folder. The oidc-client.js file is copied to the lib folder under wwwroot via a gulp task on build. My directory structure looks like this (only relevent portions represented): wwwroot | --app | | | --shared | | | --auth | | | --token.service.ts --lib | | | --oidc-client | | | --oidc-client.js | --bower_components | | | --oidc-client | | | --dist | | | | | --oidc-client.js | --oidc-client.d.ts | --typings | --index.d.ts import { Oidc } from './lib/oidc-client/oidc-client'; As mentioned in a comment made above, using the NPM distribution of oidc-client would be the preferred option. However, the typings that are included in the oidc-client are a little strange. Usually, the typings .d.ts file sits side-by-side with the .js file. With oidc-client, they are in different directories and that's what's causing problems with your import statement. If you install the NPM module and add node_modules/oidc-client/oidc-client.d.ts to the files configuration of your tsconfig.json: { "files": [ "index.ts", "node_modules/oidc-client/oidc-client.d.ts" ] } You should be able to create an index.ts file that imports oidc-client: import { OidcClient } from "oidc-client"; If the .d.ts file and the .js file had been side-by-side, your import would have worked, but they are not, so it doesn't. If you do not want to use the NPM distribution, it is likely that the separation of the .d.ts and .js files is what's causing the problem with the Bower distribution, too.
https://codedump.io/share/qGPmwUtLwOD6/1/importing-bower-component-library-into-angular-2-application
CC-MAIN-2017-30
refinedweb
286
52.76
A. In my last article where I talked about my new project Gnocchi, I wrote about how I tested, hacked and then ditched whisper out. Here I'm going to explain part of my thought process and a few things that raised my eyebrows when hacking this code. Before I start, please don't get the spirit of this article wrong. It's in no way a personal attack to the authors and contributors (who I don't know). Furthermore, whisper is a piece of code that is in production in thousands of installation, storing metrics for years. While I can argue that I consider the code not to be following best practice, it definitely works well enough and is worthy to a lot of people. Tests The first thing that I noticed when trying to hack on whisper, is the lack of test. There's only one file containing tests, named test_whisper.py, and the coverage it provides is pretty low. One can check that using the coverage tool. $ coverage run test_whisper.py ........... ---------------------------------------------------------------------- Ran 11 tests in 0.014s OK $ coverage report Name Stmts Miss Cover ---------------------------------- test_whisper 134 4 97% whisper 584 227 61% ---------------------------------- TOTAL 718 231 67% While one would think that 61% is "not so bad", taking a quick peak at the actual test code shows that the tests are incomplete. Why I mean by incomplete is that they for example use the library to store values into a database, but they never check if the results can be fetched and if the fetched results are accurate. Here's a good reason one should never blindly trust the test cover percentage as a quality metric. When I tried to modify whisper, as the tests do not check the entire cycle of the values fed into the database, I ended up doing wrong changes but had the tests still pass. No PEP 8, no Python 3 The code doesn't respect PEP 8 . A run of flake8 + hacking shows 732 errors… While it does not impact the code itself, it's more painful to hack on it than it is on most Python projects. The hacking tool also shows that the code is not Python 3 ready as there is usage of Python 2 only syntax. A good way to fix that would be to set up tox and adds a few targets for PEP 8 checks and Python 3 tests. Even if the test suite is not complete, starting by having flake8 run without errors and the few unit tests working with Python 3 should put the project in a better light. Not using idiomatic Python A lot of the code could be simplified by using idiomatic Python. Let's take a simple example: def fetch(path,fromTime,untilTime=None,now=None): fh = None try: fh = open(path,'rb') return file_fetch(fh, fromTime, untilTime, now) finally: if fh: fh.close() That piece of code could be easily rewritten as: def fetch(path,fromTime,untilTime=None,now=None): with open(path, 'rb') as fh: return file_fetch(fh, fromTime, untilTime, now) This way, the function looks actually so simple that one can even wonder why it should exists – but why not. Usage of loops could also be made more Pythonic: for i,archive in enumerate(archiveList): if i == len(archiveList) - 1: break could be actually: for archive in itertools.islice(archiveList, len(archiveList) - 1): That reduce the code size and makes it easier to read through the code. Wrong abstraction level Also, one thing that I noticed in whisper, is that it abstracts its features at the wrong level. Take the create() function, it's pretty obvious: def create(path,archiveList,xFilesFactor=None,aggregationMethod=None,sparse=False,useFallocate=False): # Set default params if xFilesFactor is None: xFilesFactor = 0.5 if aggregationMethod is None: aggregationMethod = 'average' #Validate archive configurations... validateArchiveList(archiveList) #Looks good, now we create the file and write the header if os.path.exists(path): raise InvalidConfiguration("File %s already exists!" % path) fh = None try: fh = open(path,'wb') if LOCK: fcntl.flock( fh.fileno(), fcntl.LOCK_EX ) aggregationType = struct.pack( longFormat, aggregationMethodToType.get(aggregationMethod, 1) ) oldest = max([secondsPerPoint * points for secondsPerPoint,points in archiveList]) maxRetention = struct.pack( longFormat, oldest ) xFilesFactor = struct.pack( floatFormat, float(xFilesFactor) ) archiveCount = struct.pack(longFormat, len(archiveList)) packedMetadata = aggregationType + maxRetention + xFilesFactor + archiveCount fh.write(packedMetadata) headerSize = metadataSize + (archiveInfoSize * len(archiveList)) archiveOffsetPointer = headerSize for secondsPerPoint,points in archiveList: archiveInfo = struct.pack(archiveInfoFormat, archiveOffsetPointer, secondsPerPoint, points) fh.write(archiveInfo) archiveOffsetPointer += (points * pointSize) #If configured to use fallocate and capable of fallocate use that, else #attempt sparse if configure or zero pre-allocate if sparse isn't configured. if CAN_FALLOCATE and useFallocate: remaining = archiveOffsetPointer - headerSize fallocate(fh, headerSize, remaining) elif sparse: fh.seek(archiveOffsetPointer - 1) fh.write('\x00') else: remaining = archiveOffsetPointer - headerSize chunksize = 16384 zeroes = '\x00' * chunksize while remaining > chunksize: fh.write(zeroes) remaining -= chunksize fh.write(zeroes[:remaining]) if AUTOFLUSH: fh.flush() os.fsync(fh.fileno()) finally: if fh: fh.close() The function is doing everything: checking if the file doesn't exist already, opening it, building the structured data, writing this, building more structure, then writing that, etc. That means that the caller has to give a file path, even if it just wants a whipser data structure to store itself elsewhere. StringIO() could be used to fake a file handler, but it will fail if the call to fcntl.flock() is not disabled – and it is inefficient anyway. There's a lot of other functions in the code, such as for example setAggregationMethod(), that mixes the handling of the files – even doing things like os.fsync() – while manipulating structured data. This is definitely not a good design, especially for a library, as it turns out reusing the function in different context is near impossible. Race conditions There are race conditions, for example in create() (see added comment): if os.path.exists(path): raise InvalidConfiguration("File %s already exists!" % path) fh = None try: # TOO LATE I ALREADY CREATED THE FILE IN ANOTHER PROCESS YOU ARE GOING TO # FAIL WITHOUT GIVING ANY USEFUL INFORMATION TO THE CALLER :-( fh = open(path,'wb') That code should be: try: fh = os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL), 'wb') except OSError as e: if e.errno == errno.EEXIST: raise InvalidConfiguration("File %s already exists!" % path) to avoid any race condition. Unwanted optimization We saw earlier the fetch() function that is barely useful, so let's take a look at the file_fetch() function that it's calling. def file_fetch(fh, fromTime, untilTime, now = None): header = __readHeader(fh) [...] The first thing the function does is to read the header from the file handler. Let's take a look at that function: def __readHeader(fh): info = __headerCache.get(fh.name) if info: return info originalOffset = fh.tell() fh.seek(0) packedMetadata = fh.read(metadataSize) try: (aggregationType,maxRetention,xff,archiveCount) = struct.unpack(metadataFormat,packedMetadata) except: raise CorruptWhisperFile("Unable to read header", fh.name) [...] The first thing the function does is to look into a cache. Why is there a cache? It actually caches the header based with an index based on the file path ( fh.name). Except that if one for example decide not to use file and cheat using StringIO, then it does not have any name attribute. So this code path will raise an AttributeError. One has to set a fake name manually on the StringIO instance, and it must be unique so nobody messes with the cache import StringIO packedMetadata = <some source> fh = StringIO.StringIO(packedMetadata) fh.name = "myfakename" header = __readHeader(fh) The cache may actually be useful when accessing files, but it's definitely useless when not using files. But it's not necessarily true that the complexity (even if small) that the cache adds is worth it. I doubt most of whisper based tools are long run processes, so the cache that is really used when accessing the files is the one handled by the operating system kernel, and this one is going to be much more efficient anyway, and shared between processed. There's also no expiry of that cache, which could end up of tons of memory used and wasted. Docstrings None of the docstrings are written in a a parsable syntax like Sphinx. This means you cannot generate any documentation in a nice format that a developer using the library could read easily. The documentation is also not up to date: def fetch(path,fromTime,untilTime=None,now=None): """fetch(path,fromTime,untilTime=None) [...] """ def create(path,archiveList,xFilesFactor=None,aggregationMethod=None,sparse=False,useFallocate=False): """create(path,archiveList,xFilesFactor=0.5,aggregationMethod='average') [...] """ This is something that could be avoided if a proper format was picked to write the docstring. A tool cool be used to be noticed when there's a diversion between the actual function signature and the documented one, like missing an argument. Duplicated code Last but not least, there's a lot of code that is duplicated around in the scripts provided by whisper in its bin directory. Theses scripts should be very lightweight and be using the console_scripts facility of setuptools, but they actually contains a lot of (untested) code. Furthermore, some of that code is partially duplicated from the whisper.py library which is against DRY. Conclusion There are a few more things that made me stop considering whisper, but these are part of the whisper features, not necessarily code quality. One can also point out that the code is very condensed and hard to read, and that's a more general problem about how it is organized and abstracted. A lot of these defects are actually points that made me start writing The Hacker's Guide to Python a year ago. Running into this kind of code makes me think it was a really good idea to write a book on advice to write better Python code!
https://julien.danjou.info/python-bad-practice-concrete-case/
CC-MAIN-2018-39
refinedweb
1,643
55.34
Hello readers! In this article. we will be focusing on how we can normalize data in Python. So, let us get started. What is Normalization? Before diving into normalization, let us first understand the need of it!! Feature Scaling is an essential step in the data analysis and preparation of data for modeling. Wherein, we make the data scale-free for easy analysis. Normalization is one of the feature scaling techniques. We particularly apply normalization when the data is skewed on the either axis i.e. when the data does not follow the gaussian distribution. In normalization, we convert the data features of different scales to a common scale which further makes it easy for the data to be processed for modeling. Thus, all the data features(variables) tend to have a similar impact on the modeling portion. According to the below formula, we normalize each feature by subtracting the minimum data value from the data variable and then divide it by the range of the variable as shown– Thus, we transform the values to a range between [0,1]. Let us now try to implement the concept of Normalization in Python in the upcoming section. Steps to Normalize Data in Python There are various approaches in Python through which we can perform Normalization. Today, we will be using one of the most popular way– MinMaxScaler. Let us first have a look at the dataset which we would be scaling ahead. Dataset: Further, we will be using min and max scaling in sklearn to perform normalization. Example: import pandas as pd import os from sklearn.preprocessing import MinMaxScaler #Changing the working directory to the specified path-- os.chdir("D:/Normalize - Loan_Defaulter") data = pd.read_csv("bank-loan.csv") # dataset scaler = MinMaxScaler() loan=pd.DataFrame(scaler.fit_transform(data), columns=data.columns, index=data.index) print(loan) Here, we have created an object of MinMaxScaler() class. Further, we have used fit_transform() method to normalize the data values. Output: So, as clearly visible, we have transformed and normalized the data values in the range of 0 and 1. Summary Thus, from the above explanation, the following insights can be drawn– - Normalization is used when the data values are skewed and do not follow gaussian distribution. - The data values get converted between a range of 0 and 1. - Normalization makes the data scale free. Conclusion By this, we have come to the end of this article. Feel free to comment below in case you come across any question. Till then, Stay tuned @ Python with AskPython and Keep Learning!!
https://www.askpython.com/python/examples/normalize-data-in-python
CC-MAIN-2021-31
refinedweb
423
58.38
Attended: Alessandra, Andrew, Balazs, Steve, Stephan, Greg, Alexey, Julia Main topic of the discussion - CRR structure Main changes agreed: -Definition of the 'processor' in the CRR context - Adding definition of the wallclock work -Number of logical CPUs is changed by number of processors - Adding namespace for the site - Adding node_type optional attribute suggested by Balasz inspired by Amazon Instance Types: - Adding optional attribute hosting_site in the accesspoints section. In case the accesspoint is located in a site different from the one providing computing resources. If acesspoints are located at the same site which hosts computing resources, this attribute is omitted Julia told that CRIC could already digest CRR info. The only limitation is that CRIC misses the concept of computingresource or cluster, which is being currently implemented by Alexey. Balazs pointed out that it is possible that CRR would require authentication. Julia told that services which would consume this data could authenticate with service certificate, at least the CRIC can do. Steve shortly described his work on CRR validation. Validation aims to check that the document is well formed, conforms with the schema and satisfies referential integrity. This work is very useful, it would allow sites to validate their CRR and SRR in the future as well. Julia mentioned that there was already a request for SRR validation. Dimitrios was going to look into it, but most probably did not have time. Julia will point Dimitrios to the work of Steve. Steve will present more about his work at the next meeting. Julia will create the latest version of CRR following today decisions and will attach it to the twiki page.
https://indico.cern.ch/event/828655/?print=1
CC-MAIN-2021-25
refinedweb
271
51.78
Q:. For a hypothetical little date structure struct mystruct { int year, month, day; };the comparison function might look like [footnote] int mystructcmp(const void *p1, const void *p2) { const struct mystruct *sp1 = p1; const struct mystruct *sp2 = p2; if(sp1->year < sp2->year) return -1; else if(sp1->year > sp2->year) return 1; else if(sp1->month < sp2->month) return -1; else if(sp1->month > sp2->month) return 1; else if(sp1->day < sp2->day) return -1; else if(sp1->day > sp2->day) return 1; else return 0; }(The conversions from generic pointers to struct mystruct pointers happen in the initializations sp1 = p1 and sp2 = p2; the compiler performs the conversions implicitly since p1 and p2 are void pointers.) For this version of mystructcmp, the call to qsort might look like #include <stdlib.h> struct mystruct dates[NDATES]; int ndates; /* ndates cells of dates[] are to be sorted */ qsort(dates, ndates, sizeof(struct mystruct), mystructcmp); If, on the other hand, you're sorting pointers to structures, you'll need indirection, as in question 13.8; the head of the comparison function would look like int myptrstructcmp(const void *p1, const void *p2) { struct mystruct *sp1 = *(struct mystruct * const *)p1; struct mystruct *sp2 = *(struct mystruct * const *)p2;and the call would look like struct mystruct *dateptrs[NDATES]; qsort(dateptrs, ndates, sizeof(struct mystruct *), myptrstructcmp); To understand why the curious pointer conversions in a qsort comparison function are necessary (and why a cast of the function pointer when calling qsort can't help), it's useful to think about how qsort works. qsort doesn't know anything about the type or representation of the data being sorted: it just shuffles around little chunks of memory. (All it knows about the chunks is their size, which you specify in qsort's third argument.) To determine whether two chunks need swapping, qsort calls your comparison function. (To swap them, it uses the equivalent of memcpy.) Since qsort deals in a generic way with chunks of memory of unknown type, it uses generic pointers (void *) to refer to them. When qsort calls your comparison function, it passes as arguments two generic pointers to the chunks to be compared. Since it passes generic pointers, your comparison function must accept generic pointers, and convert the pointers back to their appropriate type before manipulating them (i.e. before performing the comparison). A void pointer is not the same type as a structure pointer, and on some machines it may have a different size or representation (which is why these casts are required for correctness). If you were sorting an array of structures, and had a comparison function accepting structure pointers: int mywrongstructcmp(struct mystruct *, struct mystruct *);and if you called qsort as qsort(dates, ndates, sizeof(struct mystruct), (int (*)(const void *, const void *))mywrongstructcmp); /* WRONG */the cast (int (*)(const void *, const void *)) would do nothing except perhaps silence the message from the compiler telling you that this comparison function may not work with qsort. The implications of any cast you use when calling qsort will have been forgotten by the time qsort gets around to calling your comparison function: it will call them with const void * arguments, so that is what your function must accept. No prototype mechanism exists which could operate down inside qsort to convert the void pointers to struct mystruct pointers just before calling mywrongstructcmp. In general, it is a bad idea to insert casts just to ``shut the compiler up.'' Compiler warnings are usually trying to tell you something, and unless you really know what you're doing, you ignore or muzzle them at your peril. See also question 4.9. Additional links References: ISO Sec. 7.10.5.2 H&S Sec. 20.5 p. 419 Hosted by
http://c-faq.com/lib/qsort2.html
crawl-002
refinedweb
625
53.24
TIMKEN 5356-3 Supplier|5356-3 bearing in Western Sahara timken 46369-3 bearing high quality in India | GRAND New SKF 6209 2ZJEM Bearing TIMKEN 46369-2 authorized dealers in interchange all bearing types, including TIMKEN 5356-3 McGill CAMROL Cam Followers fag nsk skf Top Timken Wheel Bearing | Timken-Wheel-Bearing.BEST-PRICE.com Compare prices online & save up to 75% on Timken Wheel Bearing now!Contact us TIMKEN 5356-3 | Leader Bearing Bearings>Roller Bearings>Tapered Roller Bearings>5356-3Cone, Bearing Class 3 Precision 1-3/4" Bore 1-3/4" WidLeader Singapore isContact us Timken Wheel Bearings - Search for Timken Wheel Bearings. The Best New and Used Autos, Parts & Accessories. Your Auto Search Engine.Contact us Timken 5356 Tapered Roller Bearing, Single Cone, Standard Timken 5356 Tapered Roller Bearing, Single Cone, Standard Tolerance, Straight Bore, Steel, Inch, 1.7500" ID, 1.7510" Width: Amazon.com: Industrial & ScientificContact us Timken Wheel Bearings - Search for Timken Wheel Bearings. The Best New and Used Autos, Parts & Accessories. Your Auto Search Engine.Contact us TIMKEN 5356/5335 bearings TIMKEN 5356/5335 Bearings Company information. TIMKEN 5356/5335 bearings Company enjoys a high reputation in bearing industry , the quality of the TIMKEN 5356/5335Contact us TIMKEN L879947-90012 | Leader Bearing TIMKEN 5356-3 Wheel Bearing and Hub Assembly dealers in interchange all bearing types, including TIMKEN L879947-90012 McGill CAMROL Cam FollowersContact us Timken Bearings and more at Summit Racing Find great, long-lasting Timken bearings and hub assemblies, and much more at Summit Racing, and order today for fast shipping and great service.Contact us Timken 5356 Tapered Roller Bearings | eBay Find great deals for Timken 5356 Tapered Roller Bearings. Shop with confidence on eBay!Contact us import timken 5356-2 bearing | Product import timken 5356-2 bearing High Quality And Low Price. import timken 5356-2 bearing are widely used in industrial drive, agriculture, compressors, motors andContact us Timken (Torrington) T-5356-B Cylindrical Roller Bearings INA ,TIMKEN, TORRINGTON FAG RP-5356 bearing; Require more details about IR-506032 TIMKEN bearing like dimension,weight or drawing of TIMKEN IR-506032 .Contact us Timken Engineered Bearings | The Timken Company Timken® engineered bearings deliver strong performance, consistently and reliably. Our products include tapered, spherical, cylindrical, thrust, ball, plainContact us _17<< Amazon.com: Timken 5356 Bearing: Automotive Buy Timken 5356 Bearing: Replacement Parts FREE DELIVERY possible on eligible purchasesContact us Find Top Products on eBay - Seriously, We have EVERYTHING Over 70% New & Buy It Now; THIS is the new eBay. Find Great Deals now!Contact us - FAG NU216E Factory|NU216E bearing in Mauritius - NTN 6892 Lubrication|6892 bearing in Doha - SKF 238/670 CAMA/W20 Importers|238/670 CAMA/W20 bearing in South Korea - NSK 6003-2RZ Cross Reference|6003-2RZ bearing in Liberia - IKO 5X29.8 Plant|5X29.8 bearing in Papua New Guinea - TIMKEN JL724348/JL724314 Outside Diameter|JL724348/JL724314 bearing in U.A.E
http://welcomehomewesley.org/?id=12862&bearing-type=TIMKEN-5356-3-Bearing
CC-MAIN-2018-47
refinedweb
484
53
REMOVE(3) Linux Programmer's Manual REMOVE(3) remove - remove a file or directory #include <stdio.h> int remove(const char *pathname);. On success, zero is returned. On error, -1 is returned, and errno is set appropriately. The errors that occur are those for unlink(2) and rmdremove() │ Thread safety │ MT-Safe │ └──────────┴───────────────┴─────────┘ POSIX.1-2001, POSIX.1-2008, C89, C99, 4.3BSD. 5.08 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. GNU 2017-09-15 REMOVE(3) Pages that refer to this page: unlink(2), unlinkat(2), stdio(3), symlink(7)
https://man7.org/linux/man-pages/man3/remove.3.html
CC-MAIN-2020-40
refinedweb
110
61.43
SEMCTL(2) BSD Programmer's Manual SEMCTL(2) semctl - semaphore control operations #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> int semctl(int semid, int semnum, int cmd, union semun arg); only be executed by the superuser,user or a process with an effective UID equal to the sem_perm.cuid or sem_perm.uid values in the data structure as- sociated with the semaphore can do this. The permission to read or change a message queue (see semop(2)) is deter- mined. semctl() will fail if: [EPERM] cmd is equal to IPC_SET or IPC_RMID and the caller is not the superuser, nor does the effective UID match either the sem_perm.uid or sem_perm.cuid fields of the data structure associated with the message queue. [EACCES] The caller has no operation permission for this semaphore. [EINVAL] semid is not a valid message semaphore identifier. cmd is not a valid command. [EFAULT] arg.buf specifies an invalid address. semget(2), semop(2) MirOS BSD #10-current August 17,.
http://www.mirbsd.org/htman/i386/man2/semctl.htm
CC-MAIN-2013-20
refinedweb
169
61.43
ThreadDetach(), ThreadDetach_r() Detach a thread from a process Synopsis: #include <sys/neutrino.h> int ThreadDetach( int tid ); int ThreadDetach_r( int tid ); Since: BlackBerry 10.0.0 Arguments: - tid - The ID of the thread that you want to detach, as returned by ThreadCreate(), or 0 to detach the current thread. Library: libc Use the -l c option to qcc to link against this library. This library is usually included automatically. Description:. Instead of using these kernel calls directly, consider calling pthread_detach(). Blocking states These calls don't block. Returns: The only difference between these functions is the way they indicate errors: Errors: - EINVAL - The thread is already detached. - ESRCH - The thread indicated by tid doesn't exist. Classification: Last modified: 2014-06-24 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/t/threaddetach.html
CC-MAIN-2015-32
refinedweb
138
52.05
I mentioned about the project here and here I've added script engine for the Java programming language. This engine uses Java Compiler API (JSR-199) to compile the "script" and then uses a memory ClassLoader to load the generated class(es). I find being able to "eval" Java code is kind of cool! If you also like it, you may want to checkout Java script engine from java.net and try out java.sh (or java.bat) in the bin directory (which is a wrapper over jrunscript) Sample code that uses Java script engine: import javax.script.\*; class Main { public static void main(String[] args) throws ScriptException { ScriptEngineManager m = new ScriptEngineManager(); ScriptEngine e = m.getEngineByName("java"); e.eval("class t { " + " public static void main(String[] args) { " + " System.out.println(\\" hello from eval\\"); " + " }" + "}"); } } jrunscript -cp java-engine.jar -l java -f Main.java
https://blogs.oracle.com/sundararajan/jsr-223-script-engine-for-the-java-language
CC-MAIN-2017-26
refinedweb
143
59.9
Yes, you're right. Use count. Suppose the total posts is 5 for $total_posts = count($posts);. You'll have to check your $counter for total - 1 as the array is $posts[0], $posts[1], $posts[2], $posts[3], $posts[4]. <?php if ( have_posts() ) : $counter = 0; $total_posts = count($posts) - 1; while ( have_posts() ) : the_post(); if( $counter == $total_posts ) { ?> <div class="container"><?php // CUSTOM CODE FOR LAST ARTICLE ?></div> <?php } else { ?> <div class="container"><?php // CUSTOM CODE FOR THE REST OF ARTICLES ?></div> <?php } $counter++; endwhile; endif; Note that you only need to open <?php've managed this with editing my data. I just copy the last status to a own property. But I think this might be the solution:" } } Ok, first I should tell you that this is a question that can have many many many correct answeres. You could instead of creating an array of strucutures studentInfo, create a tree and whenever you insert a new node into the tree keep the root node as the oldest among many other solutions. Anyway for your simple case, a simple solution could be as follows Step 0. You want to find studentInfo *oldest = records; Step 1. Iterate through the array studentInfo *traveler; for(traveler = records; i<recNum; i++, traveler++) Step 2. Compare the date from oldest and traveler. if(oldest->birthDate.year > traveler->birthDate.year && oldest->birthDate.month > traveler->birthDate.month && oldest->birthDate.day > traveler->birthDate.day) Step. On the MongoDB shell you can do: db.collectionName.find( { city: "London" } ).skip( 20 ).limit( 20 ); To show the results from document 21 to 40. Please look at limit and skip: I also strongly suggest you go over a tutorial: it should be plain and simple if I understood your question. say you have a model that uses mongoid class Model include Mongoid::Document #define fields here end then in controller @records = Model.all then you should get an array of records() Maybe this is more like it? exports.findItemsByUserId = function(req, res) { var userId = "51e101df2914931e7f000003"; //Just for testing var user = db.users.find({"_id": userId}); var items = db.items.find({'_id': {'$in' : user.useritems}}); res.send(items.toArray()); }; can definitely be used for your scenario. Look at, or Real-time statistics: MySQL(/Drizzle) or MongoDB? for more on this topic The collection will not be created until you add data, this is since collections and even databases in MongoDB are done lazily by default. If you wish to explicitly allocate a collection eagerly then use: In MongoDB when you go to a sharded system and you don't see any balancing it could one of several things. You may not have enough data to trigger balancing. That was definitely not your situation but some people may not realize that with default chunk size of 64MB it might take a while of inserting data before there is enough to split and balance some of it to other chunks. The balancer may not have been running - since your other collections were getting balanced that was unlikely in your case unless this collection was sharded last after the balancer was stopped for some reason. The chunks in your collection can't be moved. This can happen when the shard key is not granular enough to split the data into small enough chunks. As it turns out this was your case because your shard ke According to the mongo manual, use the $in operand: db.inventory.find( { qty: { $in: [ 5, 15 ] } } ). quote: Just because you set balancer state to "off" does not mean it's not still running, and finishing cleaning up from the last moveChunk that was performed. You should be able to see in the config DB in changelog collection when the last moveChunk.commit event was - that's when the moveChunk process committed to documents from some chunk being moved to the new (target) shard. But after that, asynchronously the old shard needs to delete the documents that no longer belong to it. Since the "count" is taken from meta data and does not actually query for how many documents there are "for real" it will double count documents "in flight" during balancing rounds (or any that are not properly cleaned up or from aborted balance attempts). Asya. In Mongoose, you can use a validator to check if a field has been set before you save it. As far as I know, there is no way of specifying on a Schema that a field is required, so it requires a little more boilerplate code. You did not say what you actually tried. To access a sub-document inside an array, you need to use dot notation with numeric indices. So to address the Name field in your example: Segments.Devices.0.Interfaces.0.Name Did you try that? Does it work? I don't think that the CSV format allows you to split up a single document as multiple documents, as this is something that you would need if you have nested documents. It would most definitely not create multiple fields for each sub-document as you are expecting. If you want to do that, then you can quite easily write your own CSV exporter which allows you a lot more flexibility anyway. Capped collections are preallocated when created and with ext3 that will block. Ext4 or XFS is preferred[1] because they implement posix_fallocate, which means MongoDB can allocate large files quickly. [1] This is the code you need: var update = Update.Set("Comments.$.Text", "new comment text"); var query = Query.And( Query<User>.EQ(u => u.Id, userId), Query<User>.ElemMatch(u => u.Comments, eq => eq.EQ(c => c.Id, commentId))); userCollection.Update(query, update); Of course you can do this in casbah - remember db.flags.distinct returns an iterable that should be converted implicitly to a list for use in $in. Heres a test example for you: import com.mongodb.casbah.Imports._ val db = MongoClient()("casbahTest") val customers = db("customers") val flags = db("flags") customers.drop() flags.drop() // Add some customers customers += MongoDBObject("_id" -> 1, "name" -> "foo") customers += MongoDBObject("_id" -> 2, "name" -> "bar") customers += MongoDBObject("_id" -> 3, "name" -> "baz") // Add some flags flags += MongoDBObject("cid" -> 1) flags += MongoDBObject("cid" -> 3) // Query // In JS: db.customers.find({id: {$in: db.flags.distinct("cid", {})}}) // Long hand: customers.find(MongoDBObject("_id" -> MongoDBObject("$in" The SERVER-7623 ticket that Mason referred to in his comment above will definitely support this, after it is implemented. For the time being, you will have to resort to the $where query operator, which takes a string of JavaScript code and allows you select documents where the expression would evaluate to true (the current document is available as this). There are examples in the documentation that cover your exact use case. Be aware of the performance caveats of $where (e.g. regarding indexes), which are also discussed there. You can use the "copyDB" database command, which is described at: In C#, you would run the following on the destination server: var command = new CommandDocument(new BsonElement("copydb", 1), new BsonElement("fromhost", mydbserver), new BsonElement("fromdb", sourcedb), new BsonElement("todb", targetdb)); var client = new MongoClient(mydbserver); var server = client.GetServer(); var db = server.GetDatabase("admin"); db.RunCommand(command);
http://www.w3hello.com/questions/Find-oldest-youngest-post-in-mongodb-collection
CC-MAIN-2018-17
refinedweb
1,196
64.51
FGETC(3P) POSIX Programmer's Manual FGETC(3P) This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux. fgetc — get a byte from a stream #include <stdio.h> int fgetc(FILE *stream); The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of POSIX.1‐2008 defers to the ISO C standard.. The fgetc() function shall fail if data needs to be read and: EAGAIN The O_NONBLOCK flag is set for the file descriptor underlying stream and the thread calling thread is blocking SIGTTIN or the process is ignoring SIGTTIN or the process group of the. None.. None. None. Section 2.5, Standard I/O Streams, feof(3p), ferror(3p), fgets(3p), fread(3p), fscanf(3p), getchar(3p), getc(3p), gets(3p), ungetcGETC(3P) Pages that refer to this page: stdio.h(0p), fgets(3p), fread(3p), fscanf(3p), getc(3p), getchar(3p), getdelim(3p), gets(3p)
http://man7.org/linux/man-pages/man3/fgetc.3p.html
CC-MAIN-2017-43
refinedweb
196
62.88
Console output from ui' Try replacing time.sleep(5)with ui.delay(None, 5)... I am not sure if it will do the right thing or not. If not, you could create a function called print_c()that does print('c')and then do ui.delay(print_c, 5).. The typical way you handle long running callbacks is to use the ui.in_background decorator. Remember, a button action needs to exit wuickly, or the ui appears frozen. However, that does not work with wait_modal -- not sure if that is a bug or a documentation quirk. Basically, wait_modal seems to use the same single background thread, so anything backgrounded gets run after the dialog is closed. The solution is to use ui.delay to launch another function containing your slow process. def button(sender): print 'b' def other(): time.sleep(5) # call to some time consuming task print 'c' ui.delay(other,0.01) #easy way to launch a new thread Another option would be to use this run_async decorator on you action, which actually runs the function a background thread, as opposed to queuing it up.. def run_async(func): from threading import Thread from functools import wraps @wraps(func) def async_func(*args, **kwargs): func_hl = Thread(target = func, args = args, kwargs = kwargs) func_hl.start() return func_hl return async_func @JonB gave better advise than I did... import ui def download(): print('download') print('a') ui.delay(download, 0.02) print('b') Thank you all for your help. After some fumbling around I decided to close the UI and then start the action. This was the easiest way without having to change much code :)
https://forum.omz-software.com/topic/2359/console-output-from-ui
CC-MAIN-2018-13
refinedweb
269
66.44
Opened 8 years ago Closed 23 months ago Last modified 22 months ago #8391 closed Bug (wontfix) slugify template filter poorly encodes non-English strings Description Going through the admin interface with a slug field, 'bøøøø' becomes 'boooo' (as expected) But running this code: from django.template.defaultfilters import slugify print slugify('bøøøø') print slugify(u'bøøøø') results in: 'b' 'ba-a-a-a' Results vary depending on which characters are used; I found this trying to inject a bunch of cyrillic and greek into a database, and most of the slug fields were empty. Entering them manually through the admin interface worked fine. Change History (39) comment:1 Changed 8 years ago by bjornkri - Needs documentation unset - Needs tests unset - Patch needs improvement unset comment:2 Changed 8 years ago by Daniel Pope <dan@…> For the first example, the expected results aren't well defined: Unicode characters can't be reliably represented in a bytestring. I think Django does smart_unicode on the input so it works for UTF-8 byte strings but that's just Django being flexible. For the second example, I suspect where you've typed u'bøøøø', Python has interpreted your unicode string literal as the wrong character set, equivalent to u'bøøøø'.encode('utf8').decode('iso-8859-1') Putting the same thing in a script with a PEP-263 header gives 'b' for the second example. comment:3 follow-up: ↓ 4 Changed 8 years ago by julien The reason why it doesn't give the same result in the admin and via the code above is that different algorithms are used. In the admin, it is done with some javascript, and odd characters are replaced by their latin 'equivalent', in particular: var LATIN_MAP = { ... 'ø': 'o', ... } In the template filter, odd characters that are not representable in ASCII are simply stripped out, see the 'ignore' below: value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore') Maybe the filter should replicate the javascript's algorithm, or vice versa, to make things homogeneous? comment:4 in reply to: ↑ 3 Changed 8 years ago by bjornkri Yep, I've been digging in and found the same. I absolutely think the two should work the same way, especially since it would make my like so much easier ;) var LATIN_MAP = { ... 'ø': 'o', ... } I'm trying to translate the javascript into Python, but python's handling of this is giving me a headache. In the javascript function, there's a regular expression that matches one or more characters not in, a sequence of characters in, the list of special characters. As an example, 'bjørn' becomes 'bj', 'ø' and 'rn'. It then tries to find these in the above map: LATIN_MAPbj? returns nothing so it's left unchanged, LATIN_MAPø? returns 'o', and LATIN_MAPrn? nothing again. The result is 'bjorn' Python, on the other hand, matches 'bj', '\xc3' and '\xb8rn'. There is no match for '\xc3' in LATIN_MAP, only in the regexp. Now I just need to find a way of splitting this correctly, any ideas? comment:5 Changed 8 years ago by bjornkri ... I really need to start using the 'Preview' function. Hope that's legible. comment:6 Changed 8 years ago by Jökull Sólberg Auðunsson <jokullsolberg@…> Maybe there should be a JSON file with the character map for DRY. comment:7 Changed 8 years ago by julien - Summary changed from Results of slugify in the admin interface differ from the one in shell. to Admin slugify function's results defer from those of slugify template filter There's another difference between the two algorithms. In the admin, small words are stripped out by the javascript. For example, "This is a sentence with small words" returns "sentence-small-words". Whereas the template filter gives "this-is-a-sentence-with-small-words". Ideally, this word replacement should be configurable per-language. Maybe it already is, I've never tried. Another remark. In the admin, the javascript function is called 'URLify', so that's maybe for a good reason... comment:8 Changed 8 years ago by anonymous - milestone set to 1.0 maybe comment:9 Changed 8 years ago by Daniel Pope <dan@…> - Summary changed from Admin slugify function's results defer from those of slugify template filter to Admin slugify function's results differ from those of slugify template filter Unfortunately, slugify isn't very well-defined outside of English. In German, for example, you would want to slugify 'Grüß' as 'gruess', but the same logic doesn't apply in other languages, where generally you can just omit accents at a pinch. We could build JSON transliteration character maps, but for i18n we would need several so that they can be selected based on locale. As an alternative, we could just do something with IRIs instead of trying to coerce Unicode to a "nice" ASCII string. comment:10 Changed 8 years ago by bjornkri Perhaps some sort of overriding mechanism could be implemented, say a dictionary in settings.py that is appended to and overrides the defaults? So by default 'ö' becomes 'o', but this behaviour could be changed by something like: CHARACTER_MAP = { 'ö': 'oe', 'ü': 'ue', ..... } But julien raises a good point, the javascript function is called URLify, not slugify, so perhaps the issue is not that slugify is 'wrong', but more that we need a python equivalent of URLify? comment:11 Changed 8 years ago by bjornkri My efforts at translating the javascript so far fall flat at the way python matches things: import re LATIN_MAP = { 'ö': 'o' } regex = re.compile('[ö]|[^ö]+') pieces = regex.findall('björn') downcoded = "" for piece in pieces: mapped = "" try: mapped = LATIN_MAP[piece] except: mapped = piece downcoded += mapped print pieces, downcoded # Expected: ['bj', 'ö', 'rn'] bjorn # Result: ['bj', '\xc3', '\xb6' 'rn'] björn I.e. LATIN_MAP['ö'] isn't looked up, but LATIN_MAP['\xc3'] and LATIN_MAP['\xb6'] are, separately. LATIN_MAP['\xc3\xb6'] would work, but how to make sure these 'stay together' is something that leaves me stumped. comment:12 Changed 8 years ago by Daniel Pope <dan@…> I think the template filter should accept an argument, so slugify:"de" might add in the German-specific rules, and so on; a settings.py option would just choose whether that was done by default. But it would be difficult to ensure those tables are comprehensive enough. I note that libiconv has rudimentary support for transliteration, so perhaps we could use their data. Slugs and URLs are the same thing, imho. If we can adequately provide IRIs, on the other hand, the slugify operation can be well-defined, eg. >>> slugify(u'Føø Bär Baß') u'føø-bär-baß' @bjornkri: You're still using UTF-8 encoded bytestrings. You must use unicode strings. comment:13 Changed 8 years ago by julien @Daniel Pope Using IRIs seems quite promising. I guess language specific rules could be stored in the local flavors. comment:14 Changed 8 years ago by julien Hmmmm... this ticket is looking less and less like a ticket, and more and more like an email discussion. Should it be brought to the dev-list? Volunteer? comment:15 Changed 8 years ago by julianb comment:16 Changed 8 years ago by mtredinnick - Resolution set to wontfix - Status changed from new to closed Okay, this is all a bit of a non-issue. The Javascript and Python versions are not intended to give the same results. There is much more functionality available at the Python level, for a start, in the form of codecs and unicode mapping data. Secondly, we're not interested in shipping more and more data over in the Javascript file. The Javascript version works reasonably well for a bunch of cases. It doesn't work at all in other cases (e.g. Japanese text. In other cases it gives some result and some people may prefer something else. The point is that it doesn't matter. It's just an aid. If you don't like what the aid gives you, you can happily edit the field in the admin, or always do it on the Python side, or create your own Javascript function to use. The Javascript function is not meant to be something that works perfectly for everybody because transliteration is a very ambiguous area. If it doesn't work for your purposes, don't use it. comment:17 Changed 8 years ago by Daniel Pope <dan@…> - Component changed from Uncategorized to Template system - milestone 1.0 maybe deleted - Resolution wontfix deleted - Status changed from closed to reopened - Summary changed from Admin slugify function's results differ from those of slugify template filter to slugify template filter poorly encodes non-English strings Sorry Malcolm, I may have subverted this ticket a little by talking about generalised handling of slugs, and thrown you off the scent. The original ticket was about a broken Python slugify filter, not a broken Javascript function. It was simply an observation on bjornkri's part that the admin javascript works better. The Python filter is not "just an aid". It should produce acceptably good results, which it has not done for the string u'bøøøø'. Reopening. comment:18 Changed 8 years ago by harkal I have created a function that downcodes a string in a way similar to what urlify does but in Python. This can be used in conjunction to slugify like this : slug = slugify(downcode(u'Γειά σου κόσμε!')) Or it can be called from within slugify if the developers agree to merge it in! Have fun! #!/usr/bin/python # -*- coding: utf-8 -*- # # (c) 2008 Harry Kalogirou <harkal@gmail.com> # # * Language maps taken from django's javascript urlify # import re LATIN_MAP = {'ß': 'ss','ÿ': 'y' } LATIN_SYMBOLS_MAP = { u'©':'(c)' } GREEK_MAP = {'ς':'s', u'ϊ':'i', u'ΰ':'y', u'ϋ':'y', u'ΐ':'i','Ϊ':'I', u'Ϋ':'Y' } TURKISH_MAP = { u'ş':'s', u'Ş':'S', u'ı':'i', u'İ':'I', u'ç':'c', u'Ç':'C', u'ü':'u', u'Ü':'U', u'ö':'o', u'Ö':'O', u'ğ':'g', u'Ğ':'G' } RUSSIAN_MAP = {KRAINIAN_MAP = { u'Є':'Ye', u'І':'I', u'Ї':'Yi', u'Ґ':'G', u'є':'ye', u'і':'i', u'ї':'yi', u'ґ':'g' } CZECH_MAP = { u'č':'c', u'ď':'d', u'ě':'e', u'ň':'n', u'ř':'r', u'š':'s', u'ť':'t', u'ů':'u', u'ž':'z', u'Č':'C', u'Ď':'D', u'Ě':'E', u'Ň':'N', u'Ř':'R', u'Š':'S', u'Ť':'T', u'Ů':'U', u'Ž':'Z' } POLISH_MAP = { u'ą':'a', u'ć':'c', u'ę':'e', u'ł':'l', u'ń':'n', u'ó':'o', u'ś':'s', u'ź':'z', u'ż':'z', u'Ą':'A', u'Ć':'C', u'Ę':'e', u'Ł':'L', u'Ń':'N', u'Ó':'o', u'Ś':'S', u'Ź':'Z', u'Ż':'Z' } LATVIAN_MAP = { u'ā':'a', u'č':'c', u'ē':'e', u'ģ':'g', u'ī':'i', u'ķ':'k', u'ļ':'l', u'ņ':'n', u'š':'s', u'ū':'u', u'ž':'z', u'Ā':'A', u'Č':'C', u'Ē':'E', u'Ģ':'G', u'Ī':'i', u'Ķ':'k', u'Ļ':'L', u'Ņ':'N', u'Š':'S', u'Ū':'u', u'Ž':'Z' } def _makeRegex(): ALL_DOWNCODE_MAPS = {} ALL_DOWNCODE_MAPS.update(LATIN_MAP) ALL_DOWNCODE_MAPS.update(LATIN_SYMBOLS_MAP) ALL_DOWNCODE_MAPS.update(GREEK_MAP) ALL_DOWNCODE_MAPS.update(TURKISH_MAP) ALL_DOWNCODE_MAPS.update(RUSSIAN_MAP) ALL_DOWNCODE_MAPS.update(UKRAINIAN_MAP) ALL_DOWNCODE_MAPS.update(CZECH_MAP) ALL_DOWNCODE_MAPS.update(POLISH_MAP) ALL_DOWNCODE_MAPS.update(LATVIAN_MAP) s = u"".join(ALL_DOWNCODE_MAPS.keys()) regex = re.compile(u"[%s]|[^%s]+" % (s,s)) return ALL_DOWNCODE_MAPS, regex _MAPINGS = None _regex = None def downcode(s): """ This function is 'downcode' the string pass in the parameter s. This is useful in cases we want the closest representation, of a multilingual string, in simple latin chars. The most probable use is before calling slugify. """ global _MAPINGS, _regex if not _regex: _MAPINGS, _regex = _makeRegex() downcoded = "" for piece in _regex.findall(s): if _MAPINGS.has_key(piece): downcoded += _MAPINGS[piece] else: downcoded += piece return downcoded if __name__ == "__main__": string = u'Καλημέρα Joe!' print 'Original :', string print 'Downcoded :', downcode(string) comment:19 Changed 7 years ago by jacob - Resolution set to wontfix - Status changed from reopened to closed Please don't reopen tickets closed by a committer. The correct way to revisit issues is to take it up on django-dev. comment:20 Changed 7 years ago by mtredinnick - Resolution wontfix deleted - Status changed from closed to reopened Jacob, I probably wontfixed in error, due to the confusion sown by Daniel. It's worth looking at this. comment:21 Changed 7 years ago by anonymous - Triage Stage changed from Unreviewed to Design decision needed comment:22 Changed 7 years ago by HM Another datapoint: In my language both 'å' and 'ø' are valid words in and of themselves... the standard slugify reduces both of these to . Oopsy. 'æææææææ' is a popular way to describe a scream, it also becomes... . I have my own slugify-function that turns the unicode-string into NFKD then slugifys that, then checks that the string isn't empty and if it is: adds a dummy string + the datetime + random string. This is independent of locale, which I consider a bonus. comment:23 Changed 7 years ago by HM And it seems trac can't handle those letters either =) comment:24 Changed 7 years ago by iElectric Why not use proper Unicode transliteration package like ? Transliteration is currently the best way to go Unicode->ASCII comment:25 Changed 7 years ago by Daniel Pope <dan@…> That package is too big to bundle and too trivial for Django to depend strongly upon. But it's a good starting place if you want to write your own slugify filter. comment:26 Changed 6 years ago by hejsan - Cc hr.bjarni+django@… added Hi, this ticket is way to old for a trivial feature (for non-English-speaking-country based programmers). When slugifying characters in my language, some of them are properly downgraded to ascii lookalikes but some of them get lost. That's pretty irritating for such a trivial feature. There seems to be a consensus in other web frameworks on slugifying international characters, and that is to have a map. Did you (core programmers) take a look at harkal's suggestion above? This is the way i.e. WordPress and others go about solving this problem. I also found this ready made function: slughify It is small, concise and it works. If you decide you don't want/need to fix/upgrade the slugify function, or if you think it will take a very long time before you decide, then I'd like to suggest that it be made into a setting as soon as possible: SLUGIFY_FUNCTION = myown_slugify with django.template.defaultfilters.slugify as the default But optimally the function provided by django should work for all languages in my opinion. Thanks comment:27 Changed 6 years ago by RaceCondition - Cc eallik+django@… added comment:28 Changed 5 years ago by kmike - Cc kmike84@… added comment:29 Changed 5 years ago by RaceCondition - Cc eallik+django@… removed comment:30 Changed 5 years ago by lukeplant - Severity set to Normal - Type set to Bug comment:31 Changed 5 years ago by mitar - Cc mmitar@… added - Easy pickings unset - UI/UX unset I have added made slugify2 function which first downcodes and then translates to slug. It behaves exactly the same as its JavaScript counterpart. So now it is possible to have both in Python and JavaScript same behavior. comment:32 Changed 5 years ago by ptone - Triage Stage changed from Design decision needed to Accepted comment:33 Changed 5 years ago by mitar You can take the above slugify2 function. comment:34 Changed 5 years ago by yasar11732@… Above slugify2 function won't fix #16853. # -*- coding: utf-8 -*- import sys import re from django.utils import encoding TURKISH_MAP = { u'ş':'s', u'Ş':'S', u'ı':'i', u'İ':'I', u'ç':'c', u'Ç':'C', u'ü':'u', u'Ü':'U', u'ö':'o', u'Ö':'O', u'ğ':'g', u'Ğ':'G' } ALL_DOWNCODE_MAPS = [ TURKISH_MAP, ] class Downcoder(object): map = {} regex = None def __init__(self): self.map = {} chars = u'' for lookup in ALL_DOWNCODE_MAPS: for c, l in lookup.items(): self.map[c] = l chars += encoding.force_unicode(c) self.regex = re.compile(ur'[' + chars + ']|[^' + chars + ']+', re.U) downcoder = Downcoder() def downcode(value): downcoded = u'' pieces = downcoder.regex.findall(value) if pieces: for p in pieces: mapped = downcoder.map.get(p) if mapped: downcoded += mapped else: downcoded += p else: downcoded = value return value def slugify2(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. """ import unicodedata value = downcode(value) value = unicodedata.normalize('NFD', value).encode('ascii', 'ignore') value = unicode(re.sub('[^\w\s-]', '', value).strip().lower()) return re.sub('[-\s]+', '-', value) print(slugify2(u"Işık ılık süt iç")) This prints "isk-lk-sut-ic", but expected value is, "isik-ilik-sut-ic". comment:35 Changed 5 years ago by mitar Ups. That was a bug. Fixed version of slugify2. comment:36 Changed 3 years ago by aaugustin - Status changed from reopened to new comment:37 Changed 2 years ago by claudep Note that slugify2 is now here: comment:38 Changed 23 months ago by aaugustin - Resolution set to wontfix - Status changed from new to closed There's obviously more than one way to achieve slugification, depending on your tastes and constraints. If we try to be smart, we'll get dozens and dozens of tickets from people who want to be smarter -- see the urlize filter for an example. Django's implementation has the advantage of being simple and relying only on the stdlib. Pretty good solutions are available externally. The drawbacks of implementing something more complicated outweigh the advantages at this stage. The code snippet again, for easy copying and pasting... results in: 'b' 'ba-a-a-a'
https://code.djangoproject.com/ticket/8391
CC-MAIN-2016-30
refinedweb
2,963
61.97
#include <stanza.h> #include <stanza.h> Inherited by IQ, Message, Presence, and Subscription. Inheritance diagram for Stanza: Definition at line 33 of file stanza.h. [virtual] Virtual destructor. Definition at line 42 of file stanza.cpp. [protected] Creates a new Stanza, taking from and to addresses from the given Tag. Definition at line 31 of file stanza.cpp. Creates a new Stanza object and initializes the receiver's JID. Definition at line 26 of file stanza.cpp. Use this function to add a StanzaExtension to this Stanza. Definition at line 52 of file stanza.cpp. A convenience function that returns the stanza error condition, if any. Definition at line 47 of file stanza.cpp. [inline] Returns the list of the Stanza's extensions. Definition at line 107 of file stanza.h. Finds a StanzaExtension of a particular type. Example: const MyExtension* c = presence.findExtension<MyExtension>( ExtMyExt ); Definition at line 98 of file stanza.h. Finds a StanzaExtension of a particular type. Definition at line 57 of file stanza.cpp. Returns the JID the stanza comes from. Definition at line 45 of file stanza.h. Returns the id of the stanza, if set. Definition at line 57 of file stanza.h. Removes (deletes) all the stanza's extensions. Definition at line 64 of file stanza.cpp. [pure virtual] Creates a Tag representation of the Stanza. The Tag is completely independent of the Stanza and will not be updated when the Stanza is modified. Implemented in IQ, Message, Presence, and Subscription. Returns the receiver of the stanza. Definition at line 51 of file stanza.h. Retrieves the value of the xml:lang attribute of this stanza. Default is 'en'. Definition at line 70 of file stanza.h.
http://camaya.net/api/gloox-trunk/classgloox_1_1Stanza.html
crawl-001
refinedweb
285
55.2
Overview This project generates the global header and footer code for the site. It also includes all of the global styles and variables needed for the styling of the site. Install This package is managed within the Mod Op organization namespace within NPM. When installing it's helpful to specify the exact version so that changes are immediately reflected upon install. npm install @modop/hpp-corp-global -S Local Development When modifications are needed to the global header and footer you will want to develop locally. To accomplish this you'll need to do the following steps. HPP Corp Global Project npm install npm link # this adds the project to the local repository so that it can be shared amongst other projects npm start Projects that are using the HPP Corp Global (HPP Corp, HPP Corp Static) # This command should be run within the project that you're working on npm link @modop/hpp-corp-global Usage There are three primary exports of the project. In order to use the project you must add the link command. This should not be done in this project, but the project that you're using this in. For example, within the Hudson Corporate site repository you will need to run the following. This will need to be run after every install command. import Global from 'hpp-corp-global'; // includes the header tag wrappers as well as the logo overlay const Header = Global.header; // includes the footer content const Footer = Global.footer; // includes only the navigation menu. Useful when using for mobile / sub-templates const Menu = Global.menu;
https://www.npmtrends.com/@modop/hpp-corp-global
CC-MAIN-2021-39
refinedweb
264
54.73
Sony Adopts Objective-C and GNUstep Frameworks samzenpus posted more than 3 years ago | from the new-way-of-doing-things dept. ." nice! (-1) Anonymous Coward | more than 3 years ago | (#34342250) fuck your mother! Re:nice! (2, Funny) MightyMartian (840721) | more than 3 years ago | (#34343292) I did, and then you came along. Re:nice! (-1, Troll) Anonymous Coward | more than 3 years ago | (#34343482) I did, and then you came along. You fucked your own mother? You are one sick MOFO. So you are the OP's father and half brother? WebKit? (1, Insightful) Anonymous Coward | more than 3 years ago | (#34342256) I wonder if this will finally give us GNUStep WebKit. That would be an interesting thing :) How compatitble (1) AnonymousClown (1788472) | more than 3 years ago | (#34342260) The GNUstep core libraries strictly adhere to the OpenStep standard and OPENSTEP implementation. From the submission: While Apple has continued to update their specification in the form of Cocoa and Mac OS X, ... So, I take it one would need two code bases? Re:How compatitble (5, Informative) TheRaven64 (641858) | more than 3 years ago | (#34342292) Re:How compatitble (2, Interesting) Daengbo (523424) | more than 3 years ago | (#34342416) I read this last night on Reddit, and have been chewing on it. I see this as a move to get mobile developers by piggy-backing on the Obj-C knowledge of iOS devs. Same language -- subset of API. Re:How compatitble (1, Interesting) Lucky75 (1265142) | more than 3 years ago | (#34343062) Re:How compatitble (1) Abcd1234 (188840) | more than 3 years ago | (#34343158) Give me good old C++ any day of the week. ROFL... yeah... nothing more to be said, really... Re:How compatitble (3, Insightful) kohaku (797652) | more than 3 years ago | (#34343262) Re:How compatitble (1) olau (314197) | more than 3 years ago | (#34343340):How compatitble (1) DrXym (126579) | more than 3 years ago | (#34343006) Re:How compatitble (2, Funny) WrongSizeGlass (838941) | more than 3 years ago | (#34342364) So, I take it one would need two code bases? Objective-C: All your code bases are belong to us Re:How compatitble (0) Anonymous Coward | more than 3 years ago | (#34342872) Could be worse. Just look at Java, which nowadays feels like you're working more with XML files than actual code. Re:How compatitble (1) MrHanky (141717) | more than 3 years ago | (#34342522) The summary is (surprise!) wrong. GNUstep has been following Cocoa for a while. So says this guy [blogspot.com] . Bizarre choice (0) Anonymous Coward | more than 3 years ago | (#34342288) Objective-C is kind of blah these days. It has the performance of a scripting language with the verbosity of a compiled language (I'm exaggerating but not much). No thanks. I guess they don't have much choice though, the most logical choice would be Qt (C++) but since that is owned by Nokia I imagine they don't like that idea very much. After that the next most logical would be Android or Windows, neither of which is that great (Windows is bloated and obviously controlled by Microsoft, Android is clunky, chunky and slow because of their moronic decision to use puketastic Java). Re:Bizarre choice (4, Insightful) sznupi (719324) | more than 3 years ago | (#34342336):Bizarre choice (0, Troll) Bobakitoo (1814374) | more than 3 years ago | (#34342452) The only way Qt could be use by many phone makers would require Nokia the drop the proprietary license and pass the right to some independent foundation(ala mozilla). No phone maker is going to lay at the mercy of Nokia. It is not truly open if some party has privileged access. Re:Bizarre choice (-1) Anonymous Coward | more than 3 years ago | (#34342428) Good points. As others have mentioned in the comments, Objective-C was one of Apple's poorer decisions (actually it wasn't "Apple" proper, more like Steve Jobs as he is the one that basically put GNUstep together before moving it all back to Apple). It's just obsolete and never worked that well to begin with and GNUstep is incredibly outdated these days, Sony would have done better to use the Amiga OS if they're going that route. Apple has been busy trying pull out all the Objective-C stuff for the last few years. And to the person above, Nokia does in fact own Qt. Licensing is a completely separate issue. All this says to me is that, as usual, Sony has a poor plan (you know, like all the other crap they have done: rootkits, alienating their user base, Playstation3, etc). Re:Bizarre choice (3, Insightful) K. S. Kyosuke (729550) | more than 3 years ago | (#34342474) As others have mentioned in the comments, Objective-C was one of Apple's poorer decisions I suppose you have a significantly better (simpler and more flexible) compiled OO language suitable for system-level programming up your sleeve, when you talk like that. Re:Bizarre choice (0) Coryoth (254751) | more than 3 years ago | (#34342710) I suppose you have a significantly better (simpler and more flexible) compiled OO language suitable for system-level programming up your sleeve, when you talk like that. I'm not sure "simpler and more flexible" are the only measures of "better", but if you want compiled OO languages suitable for systems level programming that are arguably better than Objective-C, you could try Certainly arguments for each of them as better options could be made. Re:Bizarre choice (2, Interesting) onionman (975962) | more than 3 years ago | (#343427. Err, why would you do system level programming... (1) Viol8 (599362) | more than 3 years ago | (#34342894) ... with a language that does run time binding? It sounds like the ideal enviroment for all sorts of trojans , viruses and obscure faults and failures. Re:Err, why would you do system level programming. (1) abigor (540274) | more than 3 years ago | (#34343338) Can you give some concrete, real-world examples where these have plagued Objective-C applications/systems? Re:Bizarre choice (3, Interesting) forsey (1136633) | more than 3 years ago | (#34343302) Re:Bizarre choice (5, Insightful) beelsebob (529313) | more than 3 years ago | (#34342482). Apple's response? (2, Interesting) symes (835608) | more than 3 years ago | (#34342290) Re:Apple's response? (0) Anonymous Coward | more than 3 years ago | (#34342304) The converse, however, is also true. If someone develops for a Sony gadget then it would be natural to port it over to Apple products which will increase their available apps. Developer eligibility (1) tepples (727027) | more than 3 years ago | (#34342356):Apple's response? (1) RedK (112790) | more than 3 years ago | (#34342338) Re:Apple's response? (2, Interesting) Bill_the_Engineer (772575) | more than 3 years ago | (#34342892) Re:Apple's response? (1) yabos (719499) | more than 3 years ago | (#34342340) Re:Apple's response? (-1) bomanbot (980297) | more than 3 years ago | (#34342424) But that was about a decade ago and Cocoa grew and changed a lot during this time. I have not dabbled in GNUstep, but I believe that although there may be some familiarities, nowadays using GNUstep and using Cocoa is a pretty different experience for developers. For this reason, I also think the summary is way too optimistic: There are already some big differences between developing for the Mac and developing for iOS and those two are at least developed side by side by the same company. The differences between GNUstep and iOS should even be bigger then, making the possible transition not nearly as smooth as the summary might suggest, especially since GNUstep might not even have many APIs for touchscreens and other mobile device-specific stuff yet. I think GNUstep is still pretty much desktop-only as of right now, which makes the Sony decision more than just What this Sony decision might do, however, is increase adoption of Objective-C as a language. Before now, Objective-C was pretty much confined to the Apple ecosystem, apart from some guys fiddling around GNUstep for fun, I think the language did not have any other commercial venue besides using it on a Mac or on iOS devices (which is a pretty big venue, though). Now, you can also use it to target some Sony stuff as well and maybe, if it proves successful, also gets adopted by some other manufacturers, too. In that sense, Apple might secretly even be pleased that Sony did this, as it promotes Objective-C and gives developers more incentive to learn the language, which might then spur more Mac or iOS development as well. Re:Apple's response? (0) Anonymous Coward | more than 3 years ago | (#34342870) "but I believe that although there may be some familiarities, nowadays using GNUstep and using Cocoa is a pretty different experience for developers". Cocoa is much more "OpenStep" than you might think. Furthermore, most of what they did were additions and then a myriad of Frameworks. Add to this that GNUstep tracked and implemented several new methods and classes. As a developer I can tell you that the similarities are so striking that you can port an application by just recompiling it from GNUstep to Cocoa (and, often, also vice-versa). The User interface has some differences, so an adjustment to the NIB and Gorm files is advisable, but the code can be really the same. Sure, GNustep has some extensions and Cocoa has many more, but the common subset is itself much bigger than what OpenStep was. Re:Apple's response? (0) Anonymous Coward | more than 3 years ago | (#34342460) If you don't think Apple would love a world where most software was written for their platforms first and then ported to others as an afterthought, then I think you seriously misunderstand "their nature". Re:Apple's response? (2, Insightful) DrXym (126579) | more than 3 years ago | (#34343212):Apple's response? (1) lurch_mojoff (867210) | more than 3 years ago | (#34342486) Re:Apple's response? (1) countertrolling (1585477) | more than 3 years ago | (#34343040) Combining efforts to write a better DRM.. If there was any conflict over assets, I'm sure an agreement of sorts has been, or soon will be reached Re:Apple's response? (1) tlhIngan (30335) | more than 3 years ago | (#34343298) Why should Apple be worried? It enhances both ecosystems. People who want to develop for Sony's platform exclusively still need Objective-C developers, and those developers can turn around and write MacOS X and iOS apps as well, enhancing Apple's platforms on the market. Apple knows they need developers, which is why they threw in the developer tools for free with every Mac. Sony also validates Obj-C as a useful language and that can easily bring in more developers, who after writing apps for the Sony device may decide to re-use their skills on MacOS X and iOS, enhance both ecosystems. In the short term it'll hurt a bit as Obj-C devs get poached by Sony but that'll just bring new entrants into the field. Right now, other than iOS and MacOS X, development with Obj-C is very minimal. But having two major players in it can entire others to use Obj-C, and hey, they too can develop for MacOS X or iOS. Provided Sony doesn't screw it up too badly. for the better? really? (0) Anonymous Coward | more than 3 years ago | (#34342316) "probably for the better"? You sir have obviously never tried to work with Objective-C.. Who does what? (4, Insightful) clickclickdrone (964164) | more than 3 years ago | (#34342322) Or more accurately, One foreign company adopts a compiler. For the better? (2, Insightful) Xest (935314) | more than 3 years ago | (#34342330) "The world continues to chase apple -- probably for the better." lol, did someone really just say that in the context of Objective-C? For all the things Apple has done right and does well, clinging on to Objective-C is not one of them. Re:For the better? (0) Anonymous Coward | more than 3 years ago | (#34342386) Yes, all those iOS apps sure are doing poorly because of Objective-C. Would you actually like to explain what is wrong with Objective-C? I'm assuming you've actually used it but I could be wrong. Re:For the better? (1, Funny) Anonymous Coward | more than 3 years ago | (#34342528) s/because of/in spite of/ Re:For the better? (2, Insightful) WrongSizeGlass (838941) | more than 3 years ago | (#34342400) Re:For the better? (1) CODiNE (27417) | more than 3 years ago | (#34342430)? (0, Troll) Anonymous Coward | more than 3 years ago | (#34342632) Yeah - it allows inconsistent dynamic runtime crashes thanks to the lack of compile time binding. Great, thanks Obj-C. Re:For the better? (3, Insightful) Xest (935314) | more than 3 years ago | (#34342742)? (2, Interesting) Viol8 (599362) | more than 3 years ago | (#34342772). Re:For the better? (5, Insightful) onefriedrice (1171917) | more than 3 years ago | (#34343464):For the better? (3, Insightful) teh kurisu (701097) | more than 3 years ago | (#34343044). Re:For the better? (1) Xest (935314) | more than 3 years ago | (#34343254)? (3, Insightful) Arker (91948) | more than 3 years ago | (#34343378):For the better? (3, Informative) muecksteiner (102093) | more than 3 years ago | (#34343448) You apparently do not really understand what Objective-C is about yet. Yeah, I know, "you don't know what you are talking about" is the classical ad hominem attack in any programming language flamewar. But in my opinion, it is hard to see how anyone who has actually taken the time to look at Objective-C closely could ever refer to it as being a "poor man's C++". Now calling it a "poor man's Smalltalk", well, you might have a point there. But C++? ObjC and C++ are both in some way descended from C, but that is where the conceptual similarities end. The ObjC runtime is dynamic, which is IMHO a blessing, compared to the strict typing and template system of C++. But I'll grant you any day that Obj-C could do with some modernisation, in particular w/r to namespaces. But even the other thing you mention, operator overloading... that is absent for a reason, simply because software design works differently in ObjC. You don't really need it in the same way that you do with C++. Same with multiple inheritance. You have protocols for that, amongst other things. So please give ObjC another, more in-depth look, some time. You might be surprised in a positive way, once you look past the admittedly rather weird syntax. A. Re:For the better? (1) hobbit (5915) | more than 3 years ago | (#34342770) It used to be a lightweight extension to C, but ObjC-2.0 rather spoiled that with dot syntax for properties :( Re:For the better? (5, Informative) Graff (532189) | more than 3 years ago | (#34342912) Also doesn't it's dynamic runtime stuff allow certain things that C++ doesn't? Yeah, like built-in introspection [wikipedia.org] and reflextion [wikipedia.org] . Stuff like RPC (remote procedure calls) [wikipedia.org] is simple and flexible under Objective-C but under C++ it has to be hard-coded in and can be very brittle. Re:For the better? (1) CODiNE (27417) | more than 3 years ago | (#34343140) Nice link on Reflection, every now and then I wish I could do that but didn't know I could. Re:For the better? (3, Informative) Graff (532189) | more than 3 years ago | (#34343442) Nice link on Reflection, every now and then I wish I could do that but didn't know I could. There's a lot more to it if you dig deeper: Objective-C Runtime Programming Guide [apple.com] You can do some pretty neat stuff like dynamically creating a class and adding methods to it. Some of it should only be used as a last resort but it's nice having the tools at hand if you really need them. This kind of stuff is either extremely difficult or outright impossible in C++. Yes, there are some performance penalties to a dynamic runtime but for most cases it is negligible. If you desire you can circumvent the dynamic aspect of Objective-C and "freeze" method calls in order to get around those penalties for performance-critical code. There's a great series of articles on this subject: The Optimizing Objective C Series [mulle-kybernetik.com] Re:For the better? (2, Insightful) dyfet (154716) | more than 3 years ago | (#34343018)? (1) t2t10 (1909766) | more than 3 years ago | (#34343070):For the better? (4, Interesting) thenextstevejobs (1586847) | more than 3 years ago | (#34342484)? (-1, Troll) Anonymous Coward | more than 3 years ago | (#34342538) How about no one uses it in business, military, banking, data processing et al, and the vast majority of its usage is in web-applet replacements for apple's toy platforms? Re:For the better? (4, Informative) lurch_mojoff (867210) | more than 3 years ago | (#34342574) Re:For the better? (2, Insightful) barzok (26681) | more than 3 years ago | (#34342586) Just because something is popular & widespread, doesn't mean it's high-quality. And just because something is not widespread, does not mean that it isn't high-quality. Re:For the better? (0, Flamebait) t2t10 (1909766) | more than 3 years ago | (#34343082) Yeah, but Objective-C just isn't high quality, it's obsolete. Re:For the better? (-1, Troll) Anonymous Coward | more than 3 years ago | (#34342572) Syntax and implementation. I willingly go the extra mile to avoid using Obj-C anywhere except for UI code. Not in my experience, eg: All the documentation presumes the developer is using IB when no serious developer I know will touch it. 100% with you here. XCode is such utter shit that it's not funny. There really should be a command line tool allowing developers to manage the project whilst maintaining a modicum of sanity. Re:For the better? (1) teh kurisu (701097) | more than 3 years ago | (#34342724) developer wouldn't touch IB? I find it to be quite a useful tool, much better than the equivalent in Qt Creator. Agreed. Xcode 4 is available as a developer preview and I'm hoping that it solves a lot of the issues I have with the current version, but I haven't had a chance to play with it properly yet. Re:For the better? (1, Interesting) Anonymous Coward | more than 3 years ago | (#34342956) The bits that aren't C. Load time of xib and the fact that for any non-trivial interface, you're going to end up hand-coding it anyway. I forget, is this one of those things I agreed to an NDA on? If so would Apple kill me for telling you that despite a cleaner UI; XCode4 is just as useless? Re:For the better? (1) beelsebob (529313) | more than 3 years ago | (#34342812):For the better? (0) Anonymous Coward | more than 3 years ago | (#34343486) So the first thing you ask every iOS developer is "do you use Interface Builder"? Granted there are plenty of developers who use it for the root view and hand code everything else. I say these folk aren't using it, merely tolerating it. Re:For the better? (2, Informative) nicholas22 (1945330) | more than 3 years ago | (#34342578) Re:For the better? (1) Maury Markowitz (452832) | more than 3 years ago | (#34343182) Or perhaps more accurately, not updating it. It still has some things I like, but there's many more things I like in other places now. Boxing for one... Summary is incorrect (4, Informative) zr-rifle (677585) | more than 3 years ago | (#34342332) Please read the definition [gnustep.org] Re:Summary is incorrect (1) thenextstevejobs (1586847) | more than 3 years ago | (#34342540) Less money for them for common functionality, more ability for me to see what's causing a bug. Re:Summary is incorrect (1) gnasher719 (869701) | more than 3 years ago | (#34342630):Summary is incorrect (2, Informative) rxmd (205533) | more than 3 years ago | (#34343324) Apple has always been one of the driving forces behind Unicode. For selected values of "always". Apple has supported Unicode well since OS X, that is since 2001 or so, or in other words, ten years after the Unicode standard was published. Even Windows was earlier - Unicode support in Windows NT 3.x was there on the API level, in NT 4 it would work well if your programmers had been halfway diligent, and in Windows 2000 it would work well out of the box. With Apple systems before 2001, it was a pain to get Unicode working properly on MacOS 9 - it was technically supported. Re:Summary is incorrect (1) beelsebob (529313) | more than 3 years ago | (#34342874) Apple do open source their implementation for things like strings... here it is: [apple.com] Global Competitors (-1, Troll) aelarne (1947374) | more than 3 years ago | (#34342376) Re:Global Competitors (1, Redundant) WrongSizeGlass (838941) | more than 3 years ago | (#34342412) Apple is so far ahead in competition compared to its competition. I nominate this for November's Yogi Berra award. Re:Global Competitors (0) Anonymous Coward | more than 3 years ago | (#34343362) O RLY??? (0) Anonymous Coward | more than 3 years ago | (#34342446) Does that mean Sony is exploring new avenues for their rootkits? closed. (-1, Flamebait) blackfrancis75 (911664) | more than 3 years ago | (#34342598) Re:closed. (1) lurch_mojoff (867210) | more than 3 years ago | (#34342718) Re:closed. (1) Verunks (1000826) | more than 3 years ago | (#343428:closed. (0) Anonymous Coward | more than 3 years ago | (#34343422) You = zero knowledge Discontinued (1, Insightful) Anonymous Coward | more than 3 years ago | (#34342610) Why is this pushed without mentioning that "SNAP Development is currently on hold" and the source code removed? C/C++/Objective-C OOP (2, Interesting) mrnick (108356) | more than 3 years ago | (#34342700):C/C++/Objective-C OOP (1, Informative) t2t10 (1909766) | more than 3 years ago | (#34343126) Why not learn something decent instead, like Ruby or Python? Re:C/C++/Objective-C OOP (0) Anonymous Coward | more than 3 years ago | (#34343290) show me the native compiler for those Re:C/C++/Objective-C OOP (1) H0p313ss (811249) | more than 3 years ago | (#34343322) Why not learn something decent instead, like Ruby or Python? That's funny, you should get that on T-shirts. You could make a bundle from project managers. Re:C/C++/Objective-C OOP (1) abigor (540274) | more than 3 years ago | (#34343444) Because he wants to write commercial software that runs on millions of devices? I love Python, but it's not the language one chooses for that sort of thing. Re:C/C++/Objective-C OOP (1) asvravi (1236558) | more than 3 years ago | (#34343358) [quote] I thought I new OOP but it was learning Objective-C that really let it sink in. [/quote] So I take it you didn't no OOP? The world continues to chase apple? (3, Interesting) Assmasher (456699) | more than 3 years ago | (#34342776)... Why not Cocotron? (1) hobbit (5915) | more than 3 years ago | (#34342844) As far as I understand it, Cocotron is more concerned with implementing Cocoa rather than OpenStep (i.e. it would be more attractive to iOS developers), and I'd have thought its license (MIT) would be easier for Sony to ensure compliance with than the GPL. Re:Why not Cocotron? (1) hobbit (5915) | more than 3 years ago | (#34342888) I guess I should have searched before I posted, as I see that there's recently been a blog post on the former matter: [blogspot.com] But the latter? Looks like SNAP just shut down (1) halfdan the black (638018) | more than 3 years ago | (#34342978) it says SNAP development is currently on hold Now, when I was checking out the site last night, it was all still there, now for some reason, some CEO type decides axe the project. Wonder if Microsoft got wind of this and forced them to shut it down and re-write in visual basic. Perhaps Microsoft threatened Sony by raising their OEM costs or something? "The world continues to chase apple -- probably fo (3, Insightful) Charliemopps (1157495) | more than 3 years ago | (#34343076) When did Slashdot become a forum for apple fanboys? Re:"The world continues to chase apple -- probably (3, Insightful) hrimhari (1241292) | more than 3 years ago | (#34343430). GNUstep on Android? (1) korpenkraxar (1731280) | more than 3 years ago | (#34343172) mod 30wn (-1, Troll) Anonymous Coward | more than 3 years ago | (#34343174)
http://beta.slashdot.org/story/144208
CC-MAIN-2014-41
refinedweb
4,091
70.84
are four related but completely independent issues: The RDF model: statements are triples; use graphs not trees The RDF/XML serialization: a popular syntax for expressing individual RDF documents RDF tool support: RDFlib for Python, Drive for .NET, etc. The Semantic Web And here are four related but completely independent counterarguments:.. Why do I bring this up? Because, as it happens, the Atom project is creating a new format for syndicating content and an API for a new web service. For the past week and a half it has been completely engulfed in an all-out flame war over whether it should use RDF. The discussion has been almost entirely unproductive: this question is really four questions, corresponding to the four issues: My answers? Yes, no, it depends, and I don't care. I sat in on an IRC chat with Sam Ruby, Shelley Powers, Sean Palmer, Joe Gregorio, and others who have contributed heavily to Atom over the past few months. About half of these people are traditionally considered pro-RDF, half anti-RDF; but as you've seen, these simplistic labels are really just another a source of confusion, so I won't tell you which person is which. The focus of the chat was to come up with an RDF serialization of Atom by taking the examples from the Atom 0.2 snapshot (which are straight XML) and creating an XSLT transformation into RDF. During the course of this chat, all of the four issues (model, syntax, tools, vision) came up. As you might imagine, some were more constructive than others. The model was really the most constructive, in that it taught us two key things: Cardinality is vitally important to figure out up front, and the RDF model forces you to figure it out up front. This is a good thing. For example, an Atom <feed> can contain one or more <entry> elements. If you had a feed with one element, it would look like this in XML: <feed> <entry> <feed version="0.2" xmlns=""> <!-- some feed-level metadata omitted for brevity --> <entry> <title>Atom 0.2 snapshot</title> <link></link> <id>tag:diveintomark.org,2003:3.2397</id> <issued>2003-08-05T08:29:29-04:00</issued> <modified>2003-08-05T18:30:02Z</modified> <summary>The Atom 0.2 snapshot is out. Here are some sample feeds.</summary> </entry> </feed> Now suppose you wanted to add a second entry. You just add a second <entry> element: <feed version="0.2" xmlns=""> <!-- ... --> <entry> <title>Atom 0.2 snapshot</title> <link></link> <!-- ... --> </entry> <entry> <title>Atom API primer</title> <!-- ... --> </entry> </feed> In other words, straight XML doesn't force you to think about cardinality until it's too late. If you looked at the first example (with only one entry) and said "Aha! A feed has an entry in it!" and went off to write code based on that assumption, you'd be borked when your code hit the second example (with two entries). But in RDF, collections of things are always explicit, so a feed with one entry would look like this: <rdf:RDF xmlns:rdf="" xmlns:atom="" xmlns:dc="" xmlns: <atom:Feed rdf: <!-- ... --> <atom:entries rdf: <atom:Entry rdf: <dc:title>Atom 0.2 snapshot</dc:title> <atom:link rdf: <dcterms:issued>2003-08-05T08:29:29-04:00</dcterms:issued> <dcterms:modified>2003-08-05T18:30:02Z</dcterms:modified> <dcterms:created>2003-08-05T12:29:29Z</dcterms:created> <dc:description>The Atom 0.2 snapshot is out. Here are some sample feeds.</dc:description> </atom:Entry> </atom:entries> </atom:Feed> </rdf:RDF> See the difference? Entries are always wrapped in an <entries rdf: container element. If there's one entry, you get a collection of one; if there are two entries, you get a collection of two. But you know up front that it's a collection. <entries rdf: <modified> However, RDF forces it to be a concern because there are different container types for ordered and unordered lists. Once again the rigorous RDF model forced us to consider this up front, exposing an ambiguity in our current specification. The process of converting Atom-XML into Atom-RDF forced us to clarify these issues in our conceptual model. So is the RDF model a good thing? I think that it is; considering it made our format better, regardless of the syntax. However, as you can see from the above snippets and the full final Atom-RDF prototype, the RDF/XML syntax is far more complex than the equivalent just-XML version. (Depending on your browser, you may need to view the source of either or both of those examples.) Part of the problem stems from the very thing that RDF is supposed to be good at, namely, reusing and combining ontologies in a single document. You see, we kind of cheated when we created Atom-XML. The specification defines a number of elements (such as <title>) in terms of Dublin Core, but when you look at the actual Atom-XML document, you can see that we really redefined them in the Atom namespace. As a result, the XML version looks simpler as first glance because all the elements are in a single namespace which is defined as the default namespace. <title> In theory, you could cheat in this same way in RDF and put everything in a single namespace. But then you've pretty much negated one of the main benefits of RDF because you've redefined parts of existing ontologies and made it harder for people to integrate your RDF documents with other RDF data. Now they'll need to transform or map all your redefined elements back to their original ontologies. Since we were creating an XSLT transformation and could make the RDF look like whatever we wanted, we all agreed that we should do the right thing and reuse existing ontologies as much as possible. (This was actually the bulk of the discussion time, bickering about which ontologies to use.) This highlights the crux of the perennial flame wars about RDF/XML: it can almost be as simple as pure XML. In fact with a few DTD tricks to default the parseType attributes, it can look virtually identical, but only if you cheat and redefine everything in your own ontology and force everyone else to map it back to other ontologies later. Or you can do the right thing and reuse existing ontologies from the beginning and then the syntax gets hellishly complex. There's always an additional cost; you can put it wherever you want, but you can't get rid of it. parseType So should Atom use the RDF/XML syntax directly? I vote "NO". RDF (the model) is a good thing; RDF (the syntax) is a bad thing. "But," I hear you cry, "I don't care about the syntax because I have good RDF tools!". Here it is, the result of a 4-hour IRC chat. We should include it in the specification, maintain it as the format changes, and mandate that it is the One True Way to use Atom syndicated feeds as RDF. Is this more work for the RDF folk? Sure. Now they need an XSLT parser as well as their favorite RDF tool. But. I don't care about the Semantic Web. Next question? © , O’Reilly Media, Inc. (707) 827-7019 (800) 889-8969 All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
http://www.xml.com/pub/a/2003/08/20/dive.html
CC-MAIN-2013-20
refinedweb
1,247
64.1
2.6.33-stable review patch. If anyone has any objections, please let us know.------------------From: Russell King <rmk@arm.linux.org.uk>[ Upstream commit c3be57b6f35ef96a980ce84e59d6a5a8ca6184ad ]On Sun, Jan 03, 2010 at 12:23:14AM +0000, Russell King wrote:> - with IDE> - locks the interrupt line, and makes the machine extremely painful -> about an hour to get to the point of being able to unload the> pdc202xx_old module.Having manually bisected kernel versions, I've narrowed it down to somechange between 2.6.30 and 2.6.31. There's not much which has changedbetween the two kernels, but one change stands out like a sore thumb:+static int pdc202xx_test_irq(ide_hwif_t *hwif)+{+ struct pci_dev *dev = to_pci_dev(hwif->dev);+ unsigned long high_16 = pci_resource_start(dev, 4);+ u8 sc1d = inb(high_16 + 0x1d);++ if (hwif->channel) {+ /*+ * bit 7: error, bit 6: interrupting,+ * bit 5: FIFO full, bit 4: FIFO empty+ */+ return ((sc1d & 0x50) == 0x40) ? 1 : 0;+ } else {+ /*+ * bit 3: error, bit 2: interrupting,+ * bit 1: FIFO full, bit 0: FIFO empty+ */+ return ((sc1d & 0x05) == 0x04) ? 1 : 0;+ }+}Reading the (documented as a 32-bit) system control register when theinterface is idle gives: 0x01da110cSo, the byte at 0x1d is 0x11, which is documented as meaning that theprimary and secondary FIFOs are empty.The code above, which is trying to see whether an IRQ is pending, checksfor the IRQ bit to be one, and the FIFO bit to be zero - or in English,to be non-empty.Since during a BM-DMA read, the FIFOs will naturally be drained to thePCI bus, the chance of us getting to the interface before this happensare extremely small - and if we don't, it means we decide not to servicethe interrupt. Hence, the screaming interrupt problem with drivers/ide.Fix this by only indicating an interrupt is ready if both the interruptand FIFO empty bits are at '1'.This bug only affects PDC20246/PDC20247 (Promise Ultra33) based cards,and has been tested on 2.6.31 and 2.6.33-rc2.Signed-off-by: Russell King <rmk+kernel@arm.linux.org.uk>Tested-by: Russell King <rmk+kernel@arm.linux.org.uk>Signed-off-by: David S. Miller <davem@davemloft.net>Signed-off-by: Greg Kroah-Hartman <gregkh@suse.de>--- drivers/ide/pdc202xx_old.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)--- a/drivers/ide/pdc202xx_old.c+++ b/drivers/ide/pdc202xx_old.c@@ -100,13 +100,13 @@ static int pdc202xx_test_irq(ide_hwif_t * bit 7: error, bit 6: interrupting, * bit 5: FIFO full, bit 4: FIFO empty */- return ((sc1d & 0x50) == 0x40) ? 1 : 0;+ return ((sc1d & 0x50) == 0x50) ? 1 : 0; } else { /* * bit 3: error, bit 2: interrupting, * bit 1: FIFO full, bit 0: FIFO empty */- return ((sc1d & 0x05) == 0x04) ? 1 : 0;+ return ((sc1d & 0x05) == 0x05) ? 1 : 0; } }
https://lkml.org/lkml/2010/3/30/484
CC-MAIN-2018-39
refinedweb
453
64.2
0 HI please can you run the code as attachement..i m trying to test the guess number ..if it is greater than the random number or smaller but when it is equal the function will return -1 i have error that i cannot understand as i m new in java the function is in number 108 or the name of the function is "public static int checkGuess(int guess)" any help will be appreciated thanks package exercices; import java.util.Scanner; public class RandomGuess { //) { String var1,var2; if(guess == randomNumber) { return -1; } else if (guess > randomNumber){ var1="Greater than the guess"; int num = Integer.parseInt(var1); return num; } else if (guess < randomNumber){ var2="smaller than the guess"; int num1 = Integer.parseInt(var2); return num1; } else{ return guess; // Must return a value of type int } } }
https://www.daniweb.com/programming/software-development/threads/474470/return-string-in-int-public-function
CC-MAIN-2017-34
refinedweb
135
59.13
In various places sqlite3.c carefully allocates heap blocks that are power-of-two sized, to avoid the heap allocator rounding up the requested size. One example (note the 1024): static int growOpArray(Vdbe *p){ VdbeOp *pNew; int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op))); pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op)); Another example: ** The size chosen is a little less than a power of two. That way, ** the FileChunk object will have a size that almost exactly fills ** a power-of-two allocation. This mimimizes wasted space in power-of-two ** memory allocators. */ #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*))) struct FileChunk { FileChunk *pNext; /* Next chunk in the journal */ u8 zChunk[JOURNAL_CHUNKSIZE]; /* Content of this chunk */ }; ROWSET_ENTRY_PER_CHUNK is another case like this. Unfortunately, sqlite3.c adds 8 bytes to every allocation request before it gets sent to the heap allocator, in order to store the request size: /* ** Like malloc(), but remember the size of the allocation ** so that we can find it later using sqlite3MemSize(). */ static void *sqlite3MemMalloc(int nByte){ sqlite3_int64 *p; assert( nByte>0 ); nByte = ROUND8(nByte); p = malloc( nByte+8 ); if( p ){ p[0] = nByte; p++; }else{ testcase( sqlite3GlobalConfig.xLog!=0 ); sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte); } return (void *)p; } So those carefully computed sizes of 1024 become 1032 and subsequently get rounded up by jemalloc to 2048. And ironically enough, this renders sqlite3MemSize (which uses the stored size) completely inaccurate -- it underestimates these botched allocations by almost 2x. Argh! This accounts for at least 1.3MB of waste in the cumulative allocations that occur when I start up Firefox and load Gmail. I don't have numbers on how many of those allocations are live at once. What would be ideal would be to change sqlite3MemSize to just use malloc_usable_size. That would avoid this rounding botch, and also save 8 bytes per allocation. Can we change sqlite3.c? no, we can't touch sqlite3.c, we can contact sqlite team and suggest upstream fixes though. I don't think we should be afraid to patch sqlite in our tree, but we should definitely make the changes upstream too and pick them up when they trickle back. we are not afraid, we cannot afaict. (In reply to comment #3) > we are not afraid, we cannot afaict. Why is this? We patch almost every other library we import... Background information: SQLite uses a start-time pluggable memory allocator. (Details at) The default memory allocator is standard library malloc() though SQLite also comes with a memory allocator that allocates from a large static buffer using a power-of-two first-fit algorithm. Or, applications can plug in a different memory allocator of their own choosing. (Note that the test harnesses for SQLite plug in their own custom memory allocators to facilitate testing of out-of-memory (OOM) errors.) The memory allocator used by SQLite must have four routines. There is the traditional malloc(), realloc(), and free(). And there is a fourth routine (call it size()) which returns the size of an outstanding allocation.. If that approach is not going to work for you, we can add a cpp macro SQLITE_MALLOC_OVERHEAD that defaults to 0, but which you can set to 8 at compile-time, and arrange for those power-of-two memory allocations you identify to request SQLITE_MALLOC_OVERHEAD bytes fewer than a power of two. The optimal solution in terms of performance and efficient memory utilization will be the first one. But that solution is also more work for FF devs. The SQLITE_MALLOC_OVERHEAD approach is simpler for FF devs, but it not quite as efficient. We (the SQLite devs) will go ahead and start working on the SQLITE_MALLOC_OVERHEAD approach, which you (the FF devs) can use or not use as you see fit. Let us know if you want further advice on how to plug jemalloc directly into SQLite, bypassing the standard library malloc wrapper. (In reply to comment #5) >. jemalloc supports size() (as malloc_usable_size()), so we should do this. Thanks for the explanation. I'll see if I can get this to work. But be aware that on Linux at least we can't assume that jemalloc is active even when it is built. This is because libxul is sometimes delay loaded, so it really depends on whether the initial binary is linked against jemalloc. I plan to add some instrumentation code to break down the memory allocated by SQLite in Firefox into three parts: ). Richard: maybe you should default SQLITE_MALLOC_OVERHEAD to 8, since that seems to be the common case. I wonder how many other SQLite users are wasting memory due to this same issue. Created attachment 550588 [details] [diff] [review] sqlite instrumentation patch > ). The attached patch add instrumentation for this. Note that the new memory reporters overlap with the old explicit/storage/sqlite one, but that doesn't matter for throw-away instrumentation code like this, and it allowed the new ones to be compared easily to the old ones. Here's the relevant about:memory output when I start the browser with a moderately-used profile: ├───3,528,848 B (08.60%) -- my-sqlite │ ├──3,014,152 B (07.34%) -- useful │ ├────492,488 B (01.20%) -- excess │ └─────22,208 B (00.05%) -- accounting ├───3,014,152 B (07.34%) -- storage │ └──3,014,152 B (07.34%) -- sqlite Here's after I open a bunch of tabs: ├────9,761,664 B (01.90%) -- my-sqlite │ ├──8,494,136 B (01.65%) -- useful │ ├──1,235,200 B (00.24%) -- excess │ └─────32,328 B (00.01%) -- accounting ├────8,494,136 B (01.65%) -- storage │ └──8,494,136 B (01.65%) -- sqlite Things to note: - The "my-sqlite/useful" numbers match the "storage/sqlite" numbers exactly, which is good evidence that my patch is correct. - SQLite under-reports its memory usage by ~1.15--1.20x. Not terrible, but definitely worth fixing. - The "my-sqlite/accounting" number ((2) above) is tiny, which is good, as it means that the simpler SQLITE_MALLOC_OVERHEAD approach will get us almost as much benefit as registering jemalloc would. - This will put a small dent (0.5--1.0%, maybe?) in heap-unclassified. Richard: BTW, SQLite currently doesn't include the 8-bytes-per-allocation in its memory accounting. IMO it should. Richard: do you have a link to the SQLite bug tracker? (In reply to Kyle Huey [:khuey] (khuey@mozilla.com) from comment #2) > I don't think we should be afraid to patch sqlite in our tree, but we should > definitely make the changes upstream too and pick them up when they trickle > back. Yes, we should. It makes upgrading hard. We used to have changes, and it made updating incredibly difficult. We will always be better off getting the changes upstreamed into SQLite proper and then taking an update. We have a support contract with SQLite for a reason. We should use it instead of going through the pain ourselves. Can anyone estimate the timelines involved here? By that I mean: - How long the SQLITE_MALLOC_OVERHEAD change will take to make it into an SQLite release. - How long it will take to update the SQLite version in Firefox. I did some more investigation. The 1024-sized power-of-two botches mentioned in comment 0 only account for a small fraction of the wasted memory in this case. I found four cases that accounted for most of the wasted memory: Request Request+8 actual slop percentage ------- --------- ------ ---- ---------- 1024 1032 2048 1016 4.5% 2048 2056 4096 2040 12.1% 32768 32776 36864 4088 9.7% 33016 33024 36864 3840 55.3% The "percentage" columns says how much of the live slop each size accounted for when I had a few tabs open. Clearly the 1024-sized ones aren't that important, it's the 33016-size ones that matter most. Still, let's go through them all: - 1024: This is a power-of-two botch due to the extra 8-byte size field. growOpArray and JOURNAL_CHUNKSIZE (both mentioned in comment 0) account for most (all?) of the cases. - 2048: Another power-of-two botch due to the 8-byte size field. pcache1ResizeHash calls |sqlite3_malloc(sizeof(PgHdr1 *)*nNew);| and nNew is usually a power-of-two. - 32768: Ditto. These ones all go through sqlite3PageMalloc. I think this is because our Makefile passes in -DSQLITE_DEFAULT_PAGE_SIZE=32768. - 33016: This is the most important one, and is a bit different. It always goes through pcache1AllocPage which allocates |sizeof(PgHdr1) + pCache->szPage|. |sizeof(PgHdr1)| is 5 words, so 40 bytes on 64-bit platforms. pCache->szPage is 32976. I found the following comment that seems to explain why it's this not-very-round number: ** SQLite will typically create one cache instance for each open database file, ** though this is not guaranteed. ^The ** first parameter, szPage, is the size in bytes of the pages that must ** be allocated by the cache. ^szPage will. Looks like the R value on my machine is 32976 - 32768 = 208. So, conclusions: - The SQLITE_MALLOC_OVERHEAD fix will have to include the 2048 and 32768 cases. Once they're done, this will avoid ~25% of the slop. - Can the 33016 case be changed so it's 32768 bytes instead? That one looks harder to fix, but would avoid more than 50% of the slop. FWIW, I just tried a different, older profile, and saw this: ├───32,620,912 B (05.20%) -- my-sqlite │ ├──28,938,232 B (04.61%) -- useful │ ├───3,640,552 B (00.58%) -- excess │ └──────42,128 B (00.01%) -- accounting In my earlier measurements it was more like 7MB. In this 32MB measurement the 33016 case is now accounting for 84% of the slop. I guess in the limit scenario the 33016 case will dominate. With 33016 of useful data, 8 bytes of size and 3840 bytes of slop, SQLite's total slop percentage will be 10.5%. (In reply to Nicholas Nethercote [:njn] from comment #14) > - How long the SQLITE_MALLOC_OVERHEAD change will take to make it into an > SQLite release. We can request a special release of SQLite if needed. I tend to avoid that because nothing we need fixed is ever super critical. > - How long it will take to update the SQLite version in Firefox. It's very easy to upgrade SQLite (mostly because we don't take changes to the library): I filed Bug 678977 for comment 6. The 33016-byte allocations will need to be fixed upstream, I think. (In reply to Benjamin Smedberg [:bsmedberg] from comment #8) > But be aware that on Linux at least we can't assume that jemalloc is active > even when it is built. This is because libxul is sometimes delay loaded, so > it really depends on whether the initial binary is linked against jemalloc. Can you explain more about this? I thought that if MOZ_MEMORY was defined, we can assume jemalloc exists and is used. I'm a little terrified by the thought that this might not be the case... Richard: With bug 678977 progressing well, your proposed SQLITE_MALLOC_OVERHEAD workaround looks less pressing now. The matter of the 200-odd bytes in the "R" increment is still the biggest problem. Is it possible that the "R" increment could be stored separately from its page when in memory? If sqlite will make use of the roundup space caused by rounding the 32K + R allocations up to 36 K I think we can resolve completely on our side. . (In case it's not clear) ... because jemalloc rounds 32K + epsilon up to 36K. . I did some investigation to answer this. With the patch from bug 678977 applied, for all 32K+R allocations I wrote some canary values in the final page when the memory was allocated, and then checked if they were modified when the allocation was freed. They were *not* modified, so I conclude that the slop space is *not* used. However, from looking at the memory accounting code, AFAICT the storage/sqlite reporter *is* counting the slop bytes for the 32K+R allocations (with the patch from bug 678977 applied). So we're wasting memory but at least we're being honest in about:memory about it. > So we're wasting memory but at least we're being honest in about:memory about it. So this is no longer a darkmatter blocker, right? (In reply to Justin Lebar [:jlebar] from comment #25) > > So we're wasting memory but at least we're being honest in about:memory about it. > > So this is no longer a darkmatter blocker, right? Once the patch from bug 678977 lands. The patch from bug 678977 just landed. I've spun off bug 699708 for the remaining issue, and I'll close this bug.
https://bugzilla.mozilla.org/show_bug.cgi?id=676189
CC-MAIN-2016-30
refinedweb
2,111
74.69
docs/project/cage_cleaners_guide.pod - Cage Cleaner Guide. From docs/project/roles_responsibilities.pod: Fixes failing tests, makes sure coding standards are implemented, reviews documentation and examples. A class of tickets in the tracking system (Trac) has been created for use by this group. This is an entry level position, and viewed as a good way to get familiar with parrot internals. To be really really sure you're not breaking anything after doing code cleaning or attending to the newspaper at the bottom of our Parrot's cage here are is the process I (ptc) go through before committing a new change: make realclean > make_realclean.out 2>&1 perl Configure.pl > perl_configure.out 2>&1 make buildtools_tests > buildtools_tests.out 2>&1 make test > make_test.out 2>&1 Then I diff the *.out files with copies of the *.out files I made on a previous test run. If the diffs show nothing nasty is happening, you can be more sure that you've not broken anything and can commit the change. Then rename the *.out files to something like *.out.old so that you maintain reasonably up to date references for the diffs. This process should be put into a script and stored somewhere... The more platforms we have, the more likely we are to find portability problems. Parrot has to be the most portable thing we've created. More platforms also means more compilers. Maybe your DEC compiler is more picky than gcc, and spews more warnings. Good! More opportunities for cleaning! icc is the Intel C/C++ Compiler and is available for free for non-commercial use. To use icc to build parrot, use the following arguments to Configure.pl: perl Configure.pl --cc=icc --ld=icc (courtesy of Steve Peters, steve at fisharerojo dot org). Use as many compiler warnings as we possibly can. The more warnings we enable, the less likely something will pass the watchful eye of the compiler. Note that warnings may not just be -W flags. Some warnings in gcc only show up when optimization is enabled. Splint () is a very very picky lint tool, and setup and configuration is a pain. Andy has tried to get Perl 5 running under it nicely, but has met with limited success. Maybe the Parrot will be nicer. Sun has made its dev tools freely available at. Its lint is the best one out there, except from Gimpel's FlexeLint () which costs many dollars. The docs in filename here explains what our code should look like. Write something that automatically validates it in a .t file. constchecking Declaring variables as const wherever possible lets the compiler do lots of checking that wouldn't normally be possible. Walk the source code adding the const qualifier wherever possible. The biggest bang is always in passing pointers into functions. In Perl, we have the use constant pragma to define unchanging values. The Readonly module extends this to allow arrays and hashes to be non-modifiable as well. In C, we have const numbers and pointers, and using them wherever possible lets us put safety checks in our code, and the compiler will watch over our shoulders. constnumbers The easiest way to use the const qualifier is by flagging numbers that are set at the top of a block. For example: int max_elements; max_elements = nusers * ELEMENTS_PER_USER; ... array[max_elements++] = n; /* but you really meant array[max_elements] = n++; */ Adding a const qualifier means you can't accidentally modify max_elements. const int max_elements = nusers * ELEMENTS_PER_USER; constpointers If a pointer is qualified as const, then its contents cannot be modified. This lets the compiler protect you from doing naughty things to yourself. Here are two examples for functions you're familiar with: int strlen( const char *str ); void memset( char *ptr, char value, int length ); In the case of strlen, the caller is guaranteed that any string passed in won't be modified. How terrible it would be if it was possible for strlen to modify what gets passed in! The const on strlen's parameter also lets the compiler know that strlen can't be initializing what's passed in. For example: char buffer[ MAX_LEN ]; int n = strlen( buffer ); The compiler knows that buffer hasn't been initialized, and that strlen can't be initializing it, so the call to strlen is on an uninitialized value. Without the const, the compiler assumes that the contents of any pointer are getting initialized or modified. constarrays Consting arrays makes all the values in the array non-modifiable. const int days_per_month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; You don't want to be able to do days_per_month[1] = 4;, right? (We'll ignore that about 25% of the time you want days_per_month[1] to be 29.) consts Combining consts on a pointer and its contents can get confusing. It's important to know on which side of the asterisk that the const lies. To the left of the asterisk, the characters are constant. To the right of the asterisk, the pointer is constant. Note the difference between a pointer to constant characters: /* Pointer to constant characters */ const char *str = "Don't change me."; str++; /* legal, now points at "o" */ *str = "x"; /* not legal */ and a constant pointer to characters: /* Constant pointer to characters */ char * const str = buffer; str++; /* not legal */ *str = 'x'; /* buffer[0] is now 'x' */ Note the difference between which side of the asterisk that the const is on. You can also combine the two, with a constant pointer to constant characters: const char * const str = "Don't change me"; or even an array of constant pointers to constant characters: const char * const days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; If you see a declaration you don't understand, use cdecl. It's standard in many C compiler suites, and is freely available around the net. $ cdecl Type `help' or `?' for help cdecl> explain const char * str; declare str as pointer to const char cdecl> explain char * const str; declare str as const pointer to char PMD () has been used on C code, even though it's a Java tool. It looks for repeated strings of tokens that are candidates for either functions or macros. General usage: pmd [directory] [report format] [ruleset file] To generate html output of unused code within parrot use: pmd . html rulesets/unusedcode.xml > unused_code.html Also distributed with PMD is the CPD (Copy/Paste Detector) which finds duplicate code. An easy way to get started with this tool is to use the gui (cpdgui). Set the root source directory to your parrot working directory, and choose the by extension... option of the Language: menu. Then put .c in the Extension: box and click Go. Perl5 has a lot of good source management techniques that we can use. A macro for declaring the interpreter argument, and maybe a macro for passing it BTW, our Perl experience teaches us that somebody is going to want to make the interpreter a C++ object for Windows environments, and it wouldn't hurt to make that possible, or at least work in that direction, as long as clarity doesn't suffer. Automated processing that would make a macro to let us write somefunc(interp,a,b,c) while the linkage is Parrot_somefunc(interp,a,b,c) for namespace cleanup. This is straight out of embed.fnc and proto.h in Perl5. This has started significantly with the headerizer.pl program. Right now, it extracts the function headers correctly, but now I have to have it create the .h files. Most of Andy's work right now is with GCC 4.2 on Linux. We need many more. Valgrind () is a profiler/debugger most notable for the way it magically monitors memory accesses and management. To run parrot under Valgrind, the following argument set should be helpful: valgrind --num-callers=500 \ --leak-check=full --leak-resolution=high --show-reachable=yes \ parrot --leak-test (adapted from a post to parrot-porters by chromatic). See also the tools/dev/vgp and tools/dev/parrot.supp files. vgp is a wrapper around running parrot with valgrind and uses a custom set of "valgrind suppressions". From #parrot: vsoni: there seems to be some dead code/feature....I had a chat with leo and I am going to send and email to p6i for deprecation of certain old features From chip's comment at. The api.yaml file lists features that are deprecated but not yet removed, as well as experimental features. A Trac ticket will document how this deprecated feature is to be replaced. Help prepare for the actual removal of the feature by replacing its usage. Parrot has too many skipped tests. Pick a test file with a skipped test, disable the skip() line, then make it pass. The Parrot code may not compile, or you may have to modify it to bring it up to date. The test may not even be useful anymore; we won't know until you try. If you can make it pass, great! If you can make it run, great! Make it a TODO test instead. If neither, please report your findings so that everyone can decide what to do. Add this to your .vimrc: set list set listchars=trail:-,tab:\.\ NOTE: there is a space character after the last backslash. It is very important! Contributed by Jerry Gay <jerry dot gay at gmail dot com>. Add this to your .emacs: (setq-default show-trailing-whitespace t) Emacs 22 users can highlight tabs like this: (global-hi-lock-mode 1) (highlight-regexp "\t") Contributed by Eric Hanchrow <offby1 at blarg dot net>. Paul Cochrane a.k.a. ptc; original document by Andy Lester docs/project/roles_responsibilities.pod, RESPONSIBLE_PARTIES and the list of Cage items in github.
http://search.cpan.org/dist/Rakudo-Star/rakudo-star/parrot/docs/project/cage_cleaners_guide.pod
CC-MAIN-2013-48
refinedweb
1,629
65.83
#include <Local_Tokens.h> Inheritance diagram for ACE_Local_WLock: This class implements the writer interface to canonical readers/writer locks. Multiple readers can hold the lock simultaneously when no writers have the lock. Alternatively, when a writer holds the lock, no other participants (readers or writers) may hold the lock. This class is a more general-purpose synchronization mechanism than SunOS 5.x WLock. For example, it implements "recursive WLock" semantics, where a thread that owns the token can reacquire it without deadlocking. In addition, threads that are blocked awaiting the token are serviced in strict FIFO order as other threads release the token (SunOS 5.x WLocks don't strictly enforce an acquisition order). The interfaces for acquire, tryacquire, renew, release, etc. are defined in ACE_Token_Proxy. The semantics for ACE_Local_WLock are that of a readers/writers lock. Acquire for this class implies a writer acquisition. That is, only one client may hold the lock for writing.
http://www.theaceorb.com/1.4a/doxygen/ace/classACE__Local__WLock.html
CC-MAIN-2017-51
refinedweb
155
50.53
I have the one excel file which contains the below values I need to compare a_id value with all the value of b_id and if it matches i have to update the value of a_flag to 1 otherwise 0. For example take the first value in a_tag ie; 123 then compare all the values of b_id(113,211,222,123) . When it reaches to 123 in b_id we can see it matches. So we will update the value of a_flag as 1. Just like that take all the values of a_id and compare with all the values of b_id. So after everything done we will have value either 1 or 0 in a_flag column. Once its done we will take the first value of b_id then compare with all the value in a_id column and update b_flag column accordingly. Finally i will have the below data. I need to this using pandas because i am dealing with large collection of data. Below is my findings but it compare only with the first value of b_id. For example it compares 123( a_id first value) with 113 only ( b_id first value). import pandas as pd df1 = pd.read_excel('system_data.xlsx') df1['a_flag'] = (df3['a_id'] == df3['b_id']).astype(int) Use Series.isin for test membership: df1['a_flag'] = df3['a_id'].isin(df3['b_id']).astype(int) df1['b_flag'] = df3['b_id'].isin(df3['a_id']).astype(int) Tags: excelexcel, pandas
https://exceptionshub.com/excel-compare-one-column-value-with-all-the-values-of-other-column-using-pandas.html
CC-MAIN-2020-45
refinedweb
233
76.11
This ‘renderable’ sets can be added to the partition. Sets can be added and removed from a partition by using the -addSet or -removeSet flags. Note:If a set is already selected, and the partition command is executed, the set will be added to the created partition. Derived from mel command maya.cmds.partition Example: import pymel.core as pm # To create a partition calls p1 which contains set1 and set2 ... pm.partition( 'set1', 'set2', n='p1' ) # To create an empty render partition ... pm.partition( render=True ) # To add/remove sets from partition p1 ... pm.partition( 'set3', add='p1' ) pm.partition( 'set1', rm='p1' ) # To get a list of all sets in a partition ... pm.partition( 'p1', q=True ) # To check if the partition is a render partition pm.partition( 'p1', q=True, re=True )
http://www.luma-pictures.com/tools/pymel/docs/1.0/generated/functions/pymel.core.general/pymel.core.general.partition.html#pymel.core.general.partition
crawl-003
refinedweb
135
61.53
Are you sure? This . . . .11 Glossary . . . . .8 More encapsulation . . . . . 6. . . . .7 Logical operators . . . .3 Alternative execution . . . . . . . . . . . . . . 4. . . .3 The while statement . . . . . . . .12 One more example . . . . . . . . 5. . . . . . . . . . . . . . . . . . . . . . . . .1 Return values . . 28 29 30 30 31 31 31 32 33 33 34 34 36 36 37 39 39 41 43 44 45 45 46 46 47 48 50 51 51 53 53 54 54 56 58 58 59 60 60 61 63 4 Conditionals and recursion 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10 More generalization . . . . . . . . . . . . . . 6. . . . .11 3. . . . . . . . . . . .12 Parameters and variables are local . . . . 5 Fruitful functions 5. . . . . 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Iteration 6. . .7 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 The modulus operator . . . . . . . . . . . . . . . .11 Leap of faith . . . . . . . . . . . . . . . . . . . . . . . . . .4 Chained conditionals . . . . . .3 Composition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5. . . . . . . . . . . . . . . . . . . . . . . .ii CONTENTS 3. . . . . . . . . . 5. . 5. . . . .1 Multiple assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 Iteration . . . .8 Bool functions . . . . 5. 6. . . . . 5.7 Recursion . . . . . . . . . . . . . . . . . . . . 5. .6 Encapsulation and generalization 6. . . 4. . . . . . . . . . . . . . . . . . . . . . . . .9 Stack diagrams for recursive 4. . . . . . . .4 Tables . . . . . . . . . . . . . . . . Glossary . 4. . . . . . . . . . . . . . . . . . 6. . . .2 Program development 5. . 6. . . . . . . . 6. . . . . . 5. . . . . . . . . . . . . . . . . . . . . . 5. . . . . . . . . . . . . . . . . . . . . . . . . . 4. . .10 Glossary . . . . .9 Local variables . . . . . . . . . .13 Glossary . . . . . . . . . . . . . 6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5. . . . . . . . . . . .9 3. . . . . . . . . . 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9 Returning from main . .4 Overloading . . . . . . . . . 6. . . . . . .5 Boolean values . . . . . . . . .10 More recursion . . . . . . . . . . . .5 Nested conditionals . . . . . . . . . . . . . functions . . . . . . . .2 Conditional execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8 Infinite recursion . . . . . . . . Functions with results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6. . . . . . . . . . 5. . . . . . . . . . . . . . .10 3. . . .6 Boolean variables . . .6 The return statement . . . . . . . . . . . . . Functions with multiple parameters . . . . . . . . . . . . 4. . . .5 Two-dimensional tables . . . 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7. . . . . . 8. . . . . . . . . . . . . . . 7. . .1 Containers for strings . . . . . .13 apstrings are comparable . 8. 9. . . . . . . . . 65 65 66 66 67 67 68 68 69 69 70 71 72 72 73 73 74 75 75 75 76 77 78 78 79 80 82 82 83 85 87 87 88 88 88 90 90 91 92 92 93 94 95 . . . .8 Which is best? .2 apstring variables . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Time . 7. . . . . . .10 Generalization . . . . . . . . . . . . . . . . . . . . . . 9. 9. . . . . . . . . . . 8. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.3 Accessing instance variables . . . . . . . . . . . . . . . . . .3 Functions for objects . . 8 Structures 8. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12 apstrings are mutable . . .7 Fill-in functions . . . . . . . . . . . . . . . 8. . . . . . . . . . . . . .5 Structures as parameters . . . . . . . . . . . .4 Operations on structures . . . 7. . . . . .10 Increment and decrement operators 7. . . . . . . . . . . . . . .15 Other apstring functions .1 Compound values . . . . . . . . . . . . . . . . . . . . .9 Incremental development versus 9. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7. . . . . . . . . . . . . . . . . . . . . . . . 8. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 Extracting characters from a string 7. . . . . . . .7 The find function . . . . . . . . . . . . . . . . . . . 9. . . . . . . . .9 Looping and counting . . . . 9.10 Passing other types by reference 8. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7. . . . . . . . . . . . . .14 Character classification . . . . . . . . . . . . . . . . . . . . . . . . . .11 Getting user input . . . . . . .9 Structures as return types . . . . . . . . . . . . . . . . . . .8 Rectangles . . . . . . . . . . . . . . . . . . . . . .6 A run-time error . . . . . . .4 Pure functions .11 Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . 8. . . . . . . . . . . . . . . .11 String concatenation . . . . .2 Point objects . . . . . . . . 9. . . . . . . . . . . . . . . . . . . . . .2 printTime . . 7. . . . . . . . . . . . . 8. . . . . . . . . . . 8. . 9.16 Glossary . . . . . . . . . .12 Glossary . . . . . . . . . . 7.5 Traversal . . . . . . . . 9. . . . . . . . . . . 9. . .6 Call by value . . . . . . . . . . . . . . . . . . . 8. . . 9 More structures 9. . . . 8. .7 Call by reference . .CONTENTS iii 7 Strings and things 7. . . . . . . . . . . .5 const parameters . . . . . . . . . . . . .4 Length . . . . . . . . . . . . . . . . . . . . . . . . . 7. . . . . . . . .12 Glossary . . . . . . . . . . . . . . . . . planning . . . . . . . . . . . . . . . . . . . . . . 7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8 Our own version of find . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6 Modifiers . . . . 7. . . . . . . . . . . . 7. . . . . . . . . . . . . 11. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 Another constructor . . .2 Copying vectors . . . . . .4 Another example . . . 10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 Decks . . . . . . . . . . . . . .1 Objects and functions . . . .6 A more complicated example 11. . . . . . . . . . . . . . . . . . . . . .11Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10. . . . . . . .3 for loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12Random seeds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13. . . . . . . . . . . . . . . . . . . . . . . . . . 10. .13Glossary . . . . . . . . . . . . . . . . . . . . .5 Random numbers . . . . . . . . . . . . . . . . . . 11. . . . . . . . . . 10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 Yet another example . . . . . . . . . . . . . 11. . . . . . . . . 10. . . . . 12. . . . . . . 11. . . . . . . . . . . . . . . . . . . 12. . . . . 13 Objects of Vectors 13. . . . . . . . . . . . .3 The printCard function 12. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12. . . . . 12. . .10Header files . . . . . 11. . . . . . . . . . . . .2 print . .4 Vector length . . . . . . . . . . . . . . . . . . . . 12 Vectors of Objects 12. . . . . 11. . . . . . . . . . . . . . .2 Card objects . . . . 13. . . . . . . . . . . . . . . . . . 10. . . . . 10. . . . . . . . . . .9 One last example .10Decks and subdecks . . . . . . . . . . . . . .5 The isGreater function 12. . . . . . . . . . . . . . . . . . . .8 Counting . . . . . . .7 Constructors . . . . . . . . . . . . . . . . 13. . . . . . . . .11A single-pass solution . .7 Vector of random numbers 10. . . . . . . . . . 11. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11. . . . . . .1 Accessing elements .iv CONTENTS 10 Vectors 10. . . . . . . . . . . . . . . . . . . . . . . . .6 Statistics . . . . . . . . 97 98 99 99 100 100 102 102 103 104 105 105 106 106 109 109 110 111 112 113 113 114 115 115 116 119 121 121 121 123 125 126 127 129 129 130 133 133 135 135 136 138 139 11 Member functions 11.11Glossary . . . . 10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 Implicit variable access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 switch statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11. . . . . . .8 Initialize or construct? . . . . . . . . . . . . . . . . . . . .8 Searching . . 12. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12. . . . . . . . . . . . . . .4 The equals function . . .1 Composition . . . 10. . . . 10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10A histogram . . . . . . . . . . . . . . . . . . . . . . 12. . .9 Checking the other values 10. . . . . . . . . . . . . . . . . . .1 Enumerated types . . . . . . . .7 The printDeck function 12. . . . . . . . . . . .9 Bisection search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6 Vectors of cards . . . . . . . . . . . . . . . . .2 File input . . . . . . . . . . . 15. . . . . . . . . . . . . . . . . . . 14. . . . . . . . . . . . . . . . 15. . . . . . . 13. . 14. . . . . . .9 Shuffling and dealing . . . . . . . . . . . .5 Output . . . . . . . . . . . . . . . . . . . . . . . . . 14. . . . . . . . . . . . . . . . . .3 File output . . . . . . . . . . . 15. . . . . . . . .3 Complex numbers . . . . . . . 174 . . . . . . . .5 Deck member functions 13. . 15. 173 . . . . . .2 apvector . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Private data and classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15. . . . . . . . . . . . . . . . . . .8 A distance matrix . . . . . . . . . . 15. . . . . . . . .5 Parsing numbers . . . . .10Mergesort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 Parsing input . . . . . . . . . . . . . . . . . . . . . .10Glossary . . . . . . . . . . . . . . . . . 13. .6 A function on Complex numbers . . . . . . . . . . 15. .6 Shuffling . . . . . . .4 Accessor functions . . . . .1 Streams . . . . . . . . . . . . . . . . . . . . A Quick reference for AP A. . . . . . . . . . . . . . . . . . . . . . . . . . . .11Glossary . . . .7 Another function on Complex numbers 14. . . . . . . . . . . . . . . .9 Preconditions . . . . . . . . 175 . . . . . . . . . . . . . . .1 apstring . . . . . . . . 13. . . . . . . 14. . . . . . . . . . . . . . . . . . . . . . . . . . . . . A. . . . . .7 apmatrix . . . 14. . . . . . . . . . . . . . . 14. . classes 173 . . . A. . . . 15. . . . . . . . . . . .8 Subdecks . . . . . . . . . . . . . . . . . . . . . . . . . 15 File Input/Output and apmatrixes 15. . . . . . . 13. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 apmatrix . . . . . . . .10Private functions . . . . . . . . . . . . . . . . . . . .2 What is a class? . . . . . . . . . . . . . . .6 The Set data structure . . . . . . . . . . . . . . . .8 Invariants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7 Sorting . . . . . . . . . . . . . . . . . . . . . .9 A proper distance matrix . . . . 13. . . . . . . . . . . . . . . . . .CONTENTS v 13. . . . . . . .11Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14. . . . . . . . . . . . . . . . . . . . . 15. . . . . . 139 141 141 142 143 143 145 147 147 148 149 151 152 153 153 154 155 157 158 159 159 160 161 161 163 164 167 168 169 171 14 Classes and invariants 14. . 14. . vi CONTENTS . which is a 1 . though. By that I mean the ability to formulate problems. Before that. think creatively about solutions. programs written in a high-level language have to be translated before they can run. and Natural Science.1 What is a programming language? The programming language you will be learning is C++. assembling components into systems and evaluating tradeoffs among alternatives. you will have all the tools you need to do well on the exam. On the other hand. form hypotheses. C and FORTRAN. if you understand the concepts in this book. they design things. Like mathematicians. 1.” there are also low-level languages. We may not take the most direct approach to that goal. Like scientists. as of 1998. That’s why this chapter is called “The way of the program. Loosely-speaking. Thus. As you might infer from the name “high-level language. along with the details of programming in C++. the other goal of this book is to prepare you for the Computer Science AP Exam. and express a solution clearly and accurately. As it turns out. there are not many exercises in this book that are similar to the AP questions. Both C++ and Pascal are high-level languages. I like the way computer scientists think because they combine some of the best features of Mathematics. the process of learning to program is an excellent opportunity to practice problem-solving skills.” Of course. computer scientists use formal languages to denote ideas (specifically computations). Like engineers. This translation takes some time. Engineering. For example. computers can only execute programs written in low-level languages. sometimes referred to as machine language or assembly language.Chapter 1 The way of the program The goal of this book is to teach you to think like a computer scientist. they observe the behavior of complex systems. the exam used Pascal. other high-level languages you might have heard of are Java. and test predictions. The single most important skill for a computer scientist is problem-solving. because that is the language the AP exam is based on. First. and then execute the compiled code later. source code interpreter The interpreter reads the source code.cpp. you might save it in a file named program. where “program” is an arbitrary name you make up. depending on what your programming environment is like. high-level languages are portable. Secondly. meaning that they can run on different kinds of computers with few or no modifications.o to contain the object code. and the result appears on the screen. Due to these advantages.. it’s shorter and easier to read. suppose you write a program in C++. Low-level programs can only run on one kind of computer. An interpreter is a program that reads a high-level program and does what it says. In this case. . There are two ways to translate a program. the high-level program is called the source code. As an example. The compiler would read your source code. almost all programs are written in high-level languages.. before executing any of the commands.exe to contain the executable. Low-level languages are only used for a few special applications.. . and have to be rewritten to run on another. A compiler is a program that reads a high-level program and translates it all at once.2 CHAPTER 1. and the suffix . and create a new file named program. Then. In effect. You might use a text editor to write the program (a text editor is a simple word processor). it is much easier to program in a high-level language. When the program is finished. it translates the program line-by-line. interpreting or compiling. by “easier” I mean that the program takes less time to write. translate it.. and it’s more likely to be correct. But the advantages are enormous.cpp is a convention that indicates that the file contains C++ source code. you might leave the text editor and run the compiler. or program. THE WAY OF THE PROGRAM small disadvantage of high-level languages. and the translated program is called the object code or the executable. alternately reading lines and carrying out commands. Often you compile the program as a separate step. Every program you’ve ever used. one way to describe programming is the process of breaking a large. but there are a few basic functions that appear in just about every language: input: Get data from the keyboard. math: Perform basic mathematical operations like addition and multiplication. You execute the program (one way or another). or some other device.. Believe it or not. no matter how complicated. usually with some variation. like searching and replacing text in a document or (strangely enough) compiling a program. The instructions (or commands.. On the other hand. complex task up into smaller and smaller subtasks until eventually the subtasks are simple enough to be performed with one of these simple functions. like solving a system of equations or finding the roots of a polynomial. so that if something goes wrong you can figure out what it is. The computation might be something mathematical. WHAT IS A PROGRAM? 3 source code compiler object code executor The compiler reads the source code. . it is useful to know what the steps are that are happening in the background. which requires some kind of executor. Thus. these steps are automated for you. but it can also be a symbolic computation. The next step is to run the program.. that’s pretty much all there is to it. is made up of functions that look more or less like these. 1. or statements) look different in different programming languages.. repetition: Perform some action repeatedly. the good news is that in most programming environments (sometimes called development environments). and generates object code...1. . testing: Check for certain conditions and execute the appropriate sequence of statements. and the result appears on the screen. or a file. . output: Display data on the screen or send data to a file or other device..2 What is a program? A program is a sequence of instructions that specifies how to perform a computation.2.. Usually you will only have to write a program and type a single command to compile and run it. The role of the executor is to load the program (copy it from disk into memory) and make the computer start executing the program. Although this process may seem complicated. 1. the compiler will print an error message and quit. and since it is done by human beings.3 What is debugging? Programming is a complex process. Syntax refers to the structure of your program and the rules about that structure. it will compile and run successfully. 1. so it might be a little while before you encounter one. . The meaning of the program (its semantics) is wrong. It will do something else.4 CHAPTER 1.3. but it will not do the right thing. and you will not be able to run your program. and the error messages you get from the compiler are often not very helpful. a few syntax errors are not a significant problem. There are a few different kinds of errors that can occur in a program. 1.3 Logic errors and semantics The third type of error is the logical or semantic error.1 Compile-time errors The compiler can only translate a program if the program is syntactically correct. THE WAY OF THE PROGRAM 1. programming errors are called bugs and the process of tracking them down and correcting them is called debugging. so-called because the error does not appear until you run the program. a sentence must begin with a capital letter and end with a period. If there is a logical error in your program. there are more syntax rules in C++ than there are in English. this sentence contains a syntax error. If there is a single syntax error anywhere in your program. you will make fewer errors and find them faster.3. it often leads to errors. Identifying logical errors can be tricky. it will do what you told it to do. and it is useful to distinguish between them in order to track them down more quickly. Specifically. the compilation fails and you will not be able to run your program. otherwise.3. you will probably spend a lot of time tracking down syntax errors. in English. As you gain experience. though. For whimsical reasons. During the first few weeks of your programming career. which is why we can read the poetry of e e cummings without spewing error messages. Compilers are not so forgiving. in the sense that the computer will not generate any error messages. For the simple sorts of programs we will be writing for the next few weeks. For example. So does this one For most readers. since it requires you to work backwards by looking at the output of the program and trying to figure out what it is doing.2 Run-time errors The second type of error is a run-time error. run-time errors are rare. To make matters worse. The problem is that the program you wrote is not the program you wanted to write. “One of Linus’s earlier projects was a program that would switch between printing AAAA and BBBB. And most importantly: Programming languages are formal languages that have been designed to express computations. Also. whatever remains. For example. but it started out as a simple program Linus Torvalds used to explore the Intel 80386 chip. Linux is an operating system that contains thousands of lines of code. In later chapters I will make more suggestions about debugging and other programming practices. As I mentioned before. so that you always have a working program. If your hypothesis was correct. debugging is one of the most intellectually rich. Once you have an idea what is going wrong. must be the truth.4 Experimental debugging One of the most important skills you should acquire from working with this book is debugging. As Sherlock Holmes pointed out. but 2 Zz is not. H2 O is a syntactically correct chemical name. Spanish. The idea is that you should always start with a working program that does something. they evolved naturally. and make small modifications. For some people.4. In some ways debugging is like detective work. “When you have eliminated the impossible. you have to come up with a new one. formal languages tend to have strict rules about syntax. Formal languages are languages that are designed by people for specific applications. and interesting parts of programming. you modify your program and try again. Debugging is also like an experimental science.4 Formal and natural languages Natural languages are the languages that people speak. Conan Doyle’s The Sign of Four). and you take a step closer to a working program. like English.1. 3+3 = 6 is a syntactically correct mathematical statement. programming is the process of gradually debugging a program until it does what you want. programming and debugging are the same thing. debugging them as you go. According to Larry Greenfield. and French. .3. FORMAL AND NATURAL LANGUAGES 5 1. Although it can be frustrating. That is. 1. This later evolved to Linux” (from The Linux Users’ Guide Beta Version 1). then you can predict the result of the modification. They were not designed by people (although people try to impose some order on them). however improbable. For example. challenging. For example. If your hypothesis was wrong.” (from A. but 3 = +6$ is not. Chemists use a formal language to represent the chemical structure of molecules. You are confronted with clues and you have to infer the processes and events that lead to the results you see. the notation that mathematicians use is a formal language that is particularly good at denoting relationships among numbers and symbols. which means that any statement has exactly one meaning. The statement 3=+6$ is structurally illegal. Tokens are the basic elements of the language. If I say. Although formal and natural languages have many features in common— tokens. People who grow up speaking a natural language (everyone) often have a hard time adjusting to formal languages. Prose: The literal meaning of words is more important and the structure contributes more meaning. When you read a sentence in English or a statement in a formal language. but more so: Poetry: Words are used for their sounds as well as for their meaning. In some ways the difference between formal and natural language is like the difference between poetry and prose. the way the tokens are arranged. because you can’t have a plus sign immediately after an equals sign. Once you have parsed a sentence. syntax and semantics—there are many differences. One of the problems with 3=+6$ is that $ is not a legal token in mathematics (at least as far as I know). and what it means to fall. Prose is more amenable to analysis than poetry. you will understand the general implication of this sentence. which people deal with by using contextual clues and other information. THE WAY OF THE PROGRAM Syntax rules come in two flavors. that is. the semantics of the sentence. “The other shoe fell. . For example. The second type of syntax error pertains to the structure of a statement. ambiguity: Natural languages are full of ambiguity. like words and numbers and chemical elements. “The other shoe fell. Formal languages are designed to be nearly or completely unambiguous. natural languages employ lots of redundancy. This process is called parsing. Similarly.6 CHAPTER 1. they are often verbose. Assuming that you know what a shoe is. and the whole poem together creates an effect or emotional response. structure. Formal languages are less redundant and more concise. Similarly. redundancy: In order to make up for ambiguity and reduce misunderstandings. you have to figure out what the structure of the sentence is (although in a natural language you do this unconsciously). 2 Zz is not legal because there is no element with the abbreviation Zz. molecular formulas have to have subscripts after the element name.” there is probably no shoe and nothing falling.” you understand that “the other shoe” is the subject and “fell” is the verb. when you hear the sentence. As a result. Ambiguity is not only common but often deliberate. pertaining to tokens and structure. but still often ambiguous. regardless of context. Formal languages mean exactly what they say. and can be understood entirely by analysis of the tokens and structure. literalness: Natural languages are full of idiom and metaphor. Programs: The meaning of a computer program is unambiguous and literal. not before. that is. you can figure out what it means. . When the compiler sees a //. so it is usually not a good idea to read from top to bottom. World. Also. meaning that it outputs or displays a message on the screen. For now. THE FIRST PROGRAM 7 Here are some suggestions for reading programs (and other formal languages). return 0 } Some people judge the quality of a programming language by the simplicity of the “Hello. so it takes longer to read them. this simple program contains several features that are hard to explain to beginning programmers.5. There is no limit to the number of statements that can be in main. identifying the tokens and interpreting the structure. we will ignore some of them.1. Little things like spelling errors and bad punctuation.h> // main: generate some simple output void main () { cout << "Hello." << endl. which indicates that it is a comment. in order. Finally. cout is a special object provided by the system to allow you to send output to the screen. In the third line. remember that formal languages are much more dense than natural languages. C++ does reasonably well. main is a special name that indicates the place in the program where execution begins. left to right. you can ignore the word void for now. and then it quits. 1. but notice the word main. but the example contains only one. Even so. By this standard. learn to parse the program in your head. which you can get away with in natural languages. can make a big difference in a formal language. The symbol << is an operator that you apply to cout and a string.” program. World. The second line begins with //. World.5 The first program Traditionally the first program people write in a new language is called “Hello. until it gets to the last statement. it ignores everything from there until the end of the line. A comment is a bit of English text that you can put in the middle of a program.” In C++. When the program runs. It is a basic output statement. this program looks like this: #include <iostream. world. Instead. like the first line. usually to explain what the program does. it starts by executing the first statement in main and it continues.” because all it does is print the words “Hello. First. and that causes the string to be displayed. remember that the details matter. the structure is very important. cpp:1: oistream.cpp). First. so if you see it again in the future you will know what it means. the output statement ends with a semi-colon (. high-level language: A programming language like C++ that is designed to be easy for humans to read and write. notice that the statement is indented. THE WAY OF THE PROGRAM endl is a special symbol that represents the end of a line. and in most cases the error message you get will be only a hint about what is wrong. modify it in various ways and see what happens. the compiler can be a useful tool for learning the syntax rules of a language. Starting with a working program (like hello. which helps to show visually which lines are inside the definition. but I did find something named iostream. Also. A more friendly compiler might say something like: “On line 1 of the source code file named hello. As I mentioned. but from now on in this book I will assume that you know how to do it. few compilers are so accomodating. Nevertheless.cpp.). I didn’t find anything with that name.6 Glossary problem-solving: The process of formulating a problem. For example. . but it is presented in a dense format that is not easy to interpret.8 CHAPTER 1. Like all statements. It will take some time to gain facility at interpreting compiler messages. If you make any errors when you type in the program. the C++ compiler is a real stickler for syntax. If you get an error message. There are a few other things you should notice about the syntax of this program. At this point it would be a good idea to sit down in front of a computer and compile and run this program.h: No such file or directory There is a lot of information on this line. you might get an error message like the following: hello. finding a solution. C++ uses squiggly-braces ({ and }) to group things together. the output statement is enclosed in squiggly-braces. The next time you output something. Is that what you meant. the new text appears on the next line. it causes the cursor to move to the next line of the display. chances are that it will not compile successfully. try to remember what the message says and what caused it. you tried to include a header file named oistream. When you send an endl to cout. The compiler is not really very smart. 1. by any chance?” Unfortunately. indicating that it is inside the definition of main.h. if you misspell iostream. In this case. The details of how to do that depend on your programming environment. and expressing the solution.h. semantics: The meaning of a program. object code: The output of the compiler. formal language: Any of the languages people have designed for specific purposes. syntax error: An error in a program that makes it impossible to parse (and therefore impossible to compile). all at once. like representing mathematical ideas or computer programs. algorithm: A general process for solving a category of problems. interpret: To execute a program in a high-level language by translating it one line at a time. before being compiled. logical error: An error in a program that makes it do something other than what the programmer intended. executable: Another name for object code that is ready to be executed. bug: An error in a program. natural language: Any of the languages people speak that have evolved naturally.6. after translating the program. parse: To examine a program and analyze the syntactic structure.” portability: A property of a program that can run on more than one kind of computer. in preparation for later execution. source code: A program in a high-level language. . compile: To translate a program in a high-level language into a low-level language. Also called “machine language” or “assembly language. All programming languages are formal languages. debugging: The process of finding and removing any of the three kinds of errors. syntax: The structure of a program. run-time error: An error in a program that makes it fail at run-time. GLOSSARY 9 low-level language: A programming language that is designed to be easy for a computer to execute.1. 10 CHAPTER 1. THE WAY OF THE PROGRAM . Chapter 2 Variables and types 2.” and the second 11 . as well as on a line by themselves. punctuation marks. The phrases that appear in quotation marks are called strings. cruel world!. For example. because they are made up of a sequence (string) of letters. cout << "cruel world!" << endl. and other special characters." << endl. Actually. Often it is useful to display the output from multiple output statements all on one line.h> // main: generate some simple output void main () { cout << "Hello. world. numbers. ". to output more than one line: #include <iostream.1 More output As I mentioned in the last chapter. You can do this by leaving out the first endl: void main () { cout << "Goodbye. } In this case the output appears on a single line as Goodbye. } // output one line // output another As you can see. you can put as many statements as you want in main. strings can contain any combination of letters. cout << "How are you?" << endl. Notice that there is a space between the word “Goodbye. it is legal to put comments at the end of a line. ". it should be clear that the first is a string. although you have probably noticed that the program is getting harder and harder to read. but if you pay attention to the punctuation. This example outputs a single close squiggly-brace on a line by itself. including integers and characters. making it easier to read the program and locate syntax errors. A character value is a letter or digit or punctuation mark enclosed in single quotes. VARIABLES AND TYPES quotation mark. Newlines and spaces are useful for organizing your program visually. This space appears in the output. ". so I could have written: void main(){cout<<"Goodbye. like "5". It is easy to confuse different types of values.} That would work. so it affects the behavior of the program. like ’a’ or ’5’. .12 CHAPTER 2. ’5’ and 5. } This program would compile and run just as well as the original. For example. You can output integer values the same way you output strings: cout << 17 << endl. like "Hello. The reason this distinction is important should become clear soon. An integer is a whole number like 1 or 17.cout<<"cruel world!"<<endl. You (and the compiler) can identify string values because they are enclosed in quotation marks. The breaks at the ends of lines (newlines) do not affect the program’s behavior either. I could have written: void main () { cout<<"Goodbye. the second is a character and the third is an integer. The only values we have manipulated so far are the string values we have been outputting. 2. ". You can output character values the same way: cout << ’}’ << endl.2 Values A value is one of the fundamental things—like a letter or a number—that a program manipulates. Spaces that appear outside of quotation marks generally do not affect the behavior of the program. world. too. cout<<"cruel world!"<<endl. There are other kinds of values. The type of a variable determines what kind of values it can store. We do that with an assignment statement. In general. and the comments show three different ways people sometimes talk about assignment statements. minute.3. you could probably make a good guess at what values would be stored in them. For example.2. For example. and it should come as no surprise that int variables can store integers. but the idea is straightforward: • When you declare a variable. the character type in C++ is called char.). where bob is the arbitrary name you made up for the variable. you create a named storage location. the syntax is int bob. . This kind of statement is called a declaration. etc. The following statement creates a new variable named fred that has type char. 2.3 Variables One of the most powerful features of a programming language is the ability to manipulate variables. but we are going to skip that for now (see Chapter 7). character. // give firstLetter the value ’a’ // assign the value 11 to hour // set minute to 59 This example shows three assignments. we would like to store values in them. there are different types of variables. There are several types in C++ that can store string values. To create an integer variable. A variable is a named location that stores a value. firstLetter = ’a’.4 Assignment Now that we have created some variables. A char variable can contain characters. int hour. When you create a new variable. you will want to make up variable names that indicate what you plan to do with the variable. minute = 59. if you saw these variable declarations: char firstLetter. you have to declare what type it is. char lastLetter. hour = 11. The vocabulary can be confusing here. VARIABLES 13 2. This example also demonstrates the syntax for declaring multiple variables with the same type: hour and minute are both integers (int type). char fred. Just as there are different types of values (integer. minute. because there are many ways that you can convert values from one type to another. but they are not. int hour. is not the same thing as the number 123. which is made up of the characters 1. This kind of figure is called a state diagram because is shows what state each of the variables is in (you can think of it as the variable’s “state of mind”). A common way to represent variables on paper is to draw a box with the name of the variable on the outside and the value of the variable on the inside. // WRONG! 2.5 Outputting variables You can output the value of a variable using the same commands we used to output simple values. This assignment is illegal: minute = "59". cout << "The current time is ". you give it a value. The following statement generates a compiler error. These shapes should help remind you that one of the rules in C++ is that a variable has to have the same type as the value you assign it. you cannot store a string in an int variable. Another source of confusion is that some strings look like integers. For example. int hour.". and we’ll talk about special cases later. . and C++ sometimes converts things automatically. 2 and 3. the string "123". minute = 59. // WRONG !! This rule is sometimes a source of confusion. hour = "Hello. But for now you should remember that as a general rule variables and values have the same type. char colon.14 CHAPTER 2. hour = 11. VARIABLES AND TYPES • When you make an assignment to a variable. This diagram shows the effect of the three assignment statements: firstLetter hour minute ’a’ 11 59 I sometimes use different shapes to indicate different variable types. For example. colon = ’:’. different parts of your program should appear in different colors. If you type a variable name and it turns blue. which is the official language definition adopted by the the International Organization for Standardization (ISO) on September 1.” we mean outputting the value of the variable. char colon.org/ Rather than memorize the list. Very impressive! 2. To output the name of a variable. you can include more than one value in a single output statement. The complete list of keywords is included in the C++ Standard. keywords might be blue. a character. I said that you can make up any name you want for your variables. colon = ’:’. It assigns appropriate values to each of the variables and then uses a series of output statements to generate the following: The current time is 11:59 When we talk about “outputting a variable. and the special value endl. and a character variable named colon. cout << "The current time is " << hour << colon << minute << endl. hour = 11. . As we have seen before. which can make the previous program more concise: int hour. These words. I would suggest that you take advantage of a feature provided in many development environments: code highlighting. This program creates two integer variables named hour and minute. For example: cout << "hour". On one line. but that’s not quite true. There are certain words that are reserved in C++ because they are used by the compiler to parse the structure of your program. void. and other code black. minute. minute. and if you use them as variable names. colon. KEYWORDS 15 cout cout cout cout << << << << hour.6 Keywords A few sections ago. watch out! You might get some strange behavior from the compiler. this program outputs a string. endl. include int. called keywords. strings red.ansi. minute = 59.6. As you type.2. 1998. endl and many more. You can download a copy electronically from. it will get confused. For example. char. two integers. you have to put it in quotes. In each case the name of the variable is replaced with its value before the computation is performed. but the second line is odd.16 CHAPTER 2. even in cases like this where the next integer is so close. Addition. . We’ll get to that in the next chapter. the result must also be an integer. but at least now the answer is approximately correct. the operator for adding two integers is +. the following program: int hour. not 0. In order to get an even more accurate answer. subtraction and multiplication all do what you expect. For example. would generate the following output: Number of minutes since midnight: 719 Fraction of the hour that has passed: 0 The first line is what we expected. The following are all legal C++ expressions whose meaning is more or less obvious: 1+1 hour-1 hour*60 + minute minute/60 Expressions can contain both variables names and integer values. minute = 59. cout << minute/60 << endl.7 Operators Operators are special symbols that are used to represent simple computations like addition and multiplication. minute. cout << "Fraction of the hour that has passed: ". The reason for the discrepancy is that C++ is performing integer division. VARIABLES AND TYPES 2. A possible alternative in this case is to calculate a percentage rather than a fraction: cout << "Percentage of the hour that has passed: ". called floating-point. but you might be surprised by division. For example. and 59 divided by 60 is 0. The value of the variable minute is 59. that is capable of storing fractional values. cout << minute*100/60 << endl. When both of the operands are integers (operands are the things operators operate on). we could use a different type of variable. Most of the operators in C++ do exactly what you would expect them to do. and by definition integer division always rounds down. cout << hour*60 + minute << endl. cout << "Number of minutes since midnight: ".98333. because they are common mathematical symbols. hour = 11. The result is: Percentage of the hour that has passed: 98 Again the result is rounded down. and only convert from one to the other if there is a good reason. Automatic type conversion is an example of a common problem in designing a programming language. yielding 5900/60. but just to get you started: • Multiplication and division happen before addition and subtraction. So in the expression minute*100/60. • If the operators have the same precedence they are evaluated from left to right. even though it doesn’t change the result. So 2*3-1 yields 5. which is wrong.8. However.9 Operators for characters Interestingly. not 4. not 1 (remember that in integer division 2/3 is 0). The result is 97. int number. . number = ’a’. it is generally a good idea to treat characters as characters. but that is not completely true. letter = ’a’ + 1. and integers as integers. which in turn yields 98. You can also use parentheses to make an expression easier to read. which is the number that is used internally by C++ to represent the letter ’a’. outputs the letter b.8 Order of operations When more than one operator appears in an expression the order of evaluation depends on the rules of precedence. and 2/3-1 yields -1. In some cases. A complete explanation of precedence can get complicated. the multiplication happens first. cout << number << endl. ORDER OF OPERATIONS 17 2. it is almost never useful to do it. char letter. If the operations had gone from right to left. the result would be 59*1 which is 59. the following is legal. Expressions in parentheses are evaluated first. Earlier I said that you can only assign integer values to integer variables and character values to character variables. so 2 * (3-1) is 4. cout << letter << endl. For example. Although it is syntactically legal to multiply characters. 2. the same mathematical operations that work on integers also work on characters.2. For example. C++ converts automatically between types. which is that there is a conflict between formalism. as in (minute * 100) / 60. • Any time you want to override the rules of precedence (or you are not sure what they are) you can use parentheses. who are spared from rigorous but unwieldy formalism. convenience wins. For example. We’ve already seen one example: cout << hour*60 + minute << endl. most notably. You can also put arbitrary expressions on the right-hand side of an assignment statement: int percentage. and convenience. Actually. only values. without talking about how to combine them. WARNING: There are limits on where you can use certain expressions. but the point is that any expression.11 Glossary variable: A named storage location for values.10 Composition So far we have looked at the elements of a programming language—variables. it turns out we can do both at the same time: cout << 17 * 3. 2. In this book I have tried to simplify things by emphasizing the rules and omitting many of the exceptions. who are often baffled by the complexity of the rules and the number of exceptions. More often than not. which is usually good for expert programmers.” since in reality the multiplication has to happen before the output. All variables have a type. can be used inside an output statement. and variables. we know how to multiply integers and we know how to output values. . This ability may not seem so impressive now. the left-hand side of an assignment statement has to be a variable name. expressions. but we will see other examples where composition makes it possible to express complex computations neatly and concisely. I shouldn’t say “at the same time. which determines which values it can store. characters.. One of the most useful features of programming languages is their ability to take small building blocks and compose them. That’s because the left side indicates the storage location where the result will go. Expressions do not represent storage locations. which is the requirement that programming languages be easy to use in practice. and statements—in isolation. percentage = (minute * 100) / 60. So the following is illegal: minute+1 = hour. not an expression. VARIABLES AND TYPES which is the requirement that formal languages should have simple rules with few exceptions. 2. involving numbers. but bad for beginning programmers.18 CHAPTER 2. So far. operand: One of the values on which an operator operates. expression: A combination of variables. assignments. Examples we have seen include int. declaration: A statement that creates a new variable and determines its type. statement: A line of code that represents a command or action. and output statements.2. keyword: A reserved word that is used by the compiler to parse programs. operator: A special symbol that represents a simple computation like addition or multiplication. The types we have seen are integers (int in C++) and characters (char in C++). void and endl. operators and values that represents a single result value. assignment: A statement that assigns a value to a variable. or other thing that can be stored in a variable. composition: The ability to combine simple expressions and statements into compound statements and expressions in order to represent complex computations concisely. type: A set of values.11. . or number. Expressions also have types. GLOSSARY 19 value: A letter. precedence: The order in which operations are evaluated. the statements we have seen are declarations. as determined by their operators and operands. VARIABLES AND TYPES .20 CHAPTER 2. Chapter 3 Function 3. For example. double pi = 3. even though they seem to be the same number. 21 . which can represent fractions as well as integers. the following is illegal int x = 1. We worked around the problem by measuring percentages instead of fractions. It is also legal to declare a variable and assign a value to it at the same time: int x = 1. a floatingpoint number. and strictly speaking. You can create floating-point variables and assign values to them using the same syntax we used for the other types.0. you are not allowed to make assignments between types. For example: double pi.14159. they are often a source of confusion because there seems to be an overlap between integers and floating-point numbers. is that an integer. In C++. but a more general solution is to use floating-point numbers. there are two floating-point types. this syntax is quite common. In fact.1. A combined declaration and assignment is sometimes called an initialization. if you have the value 1. Although floating-point numbers are useful. They belong to different types. pi = 3. or both? Strictly speaking.14159. called float and double. String empty = "". In this book we will use doubles exclusively. For example. C++ distinguishes the integer value 1 from the floatingpoint value 1.1 Floating-point In the last chapter we had some problems dealing with numbers that were not integers. The simplest way to convert a floating-point value to an integer is to use a typecast. This leniency is convenient. so x gets the value 3.0.14159. but in fact it will get the value 0. . because no information is lost in the translation. The syntax for typecasting is like the syntax for a function call. are aware of the loss of the fractional part of the number. All the operations we have seen—addition. C++ converts ints to doubles automatically if necessary. 3. int x = int (pi). should technically not be legal.99999999. In fact. but C++ allows it by converting the int to a double automatically. For example: double pi = 3.333333. not throwing). but it can cause problems.0. One way to solve this problem (once you figure out what it is) is to make the right-hand side a floating-point expression: double y = 1. FUNCTION because the variable on the left is an int and the value on the right is a double. But it is easy to forget this rule. the result is 0.0 / 3. for example: double y = 1 / 3. which is a legal floating-point value. most processors have special hardware just for performing floating-point operations. subtraction. in order to make sure that you. so C++ does integer division.22 CHAPTER 3. Typecasting is so called because it allows you to take a value that belongs to one type and “cast” it into another type (in the sense of molding or reforming. although you might be interested to know that the underlying mechanism is completely different. as expected. The int function returns an integer.333333. You might expect the variable y to be given the value 0. This sets y to 0. The reason is that the expression on the right appears to be the ratio of two integers. C++ doesn’t perform this operation automatically. For example. and division—work on floating-point values. multiplication. Converted to floating-point. even if the fraction part is 0. going from a double to an int requires rounding off. there is a corresponding function that typecasts its argument to the appropriate type. which yields the integer value 0. On the other hand. For every type in C++. Converting to an integer always rounds down.2 Converting from double to int As I mentioned. as the programmer. especially because there are places where C++ automatically converts from one type to another. double y = 1.0. h> . Similarly. C++ provides a set of built-in functions that includes most of the mathematical operations you can think of. world!” program we included a header file named iostream. MATH FUNCTIONS 23 3. The first example sets log to the logarithm of 17. double pi = acos(-1. If you don’t happen to know π to 15 digits. To convert from degrees to radians. double angle = degrees * 2 * pi / 360.3. and 1/x is 0. π/2 is approximately 1. Then you can evaluate the function itself. you can divide by 360 and multiply by 2π. Before you can use any of the math functions. C++ assumes that the values you use with sin and the other trigonometric functions (cos.h: #include <math. You can include it at the beginning of your program along with iostream. First.0). you have probably seen functions like sin and log. The math functions are invoked using a syntax that is similar to mathematical notation: double log = log (17.5. This process can be applied repeatedly to evaluate more complicated expressions like log(1/ sin(π/2)). you evaluate the expression in parentheses. The sin of 1. The arccosine (or inverse cosine) of -1 is π. There is also a function called log10 that takes logarithms base 10. then evaluate the function. including the object named cout. base e. Header files contain information the compiler needs about functions that are defined outside your program. you can calculate it using the acos function.1 (if x happens to be 10).3. you have to include the math header file.571. because the cosine of π is -1. either by looking it up in a table or by performing various computations. For example. and the log of 0. which is called the argument of the function. in the “Hello. and so on. The second example finds the sine of the value of the variable angle.h using an include statement: #include <iostream.3 Math functions In mathematics. For example. the math header file contains information about the math functions.0).1 is -1 (assuming that log indicates the logarithm base 10).571 is 1.h contains information about input and output (I/O) streams.0.h> iostream. tan) are in radians. double angle = 1. First we evaluate the argument of the innermost function. and you have learned to evaluate expressions like sin(π/2) and log(1/x). double height = sin (angle). double degrees = 90. 0)). The first couple of functions we are going to write also have no parameters. it contains only a single statement. but it is also possible to add new functions. main doesn’t take any parameters. as indicated by the empty parentheses () in it’s definition. The sum is then passed as an argument to the cos function.5 Adding new functions So far we have only been using the functions that are built into C++. 3.4 Composition Just as with mathematical functions. if any. In main we can call this new function using syntax that is similar to the way we call the built-in C++ commands: . but the syntax for main is the same as for any other function definition: void NAME ( LIST OF PARAMETERS ) { STATEMENTS } You can make up any name you want for your function. This statement takes the value of pi. you have to provide in order to use (or call) the new function. Actually.24 CHAPTER 3. The result gets assigned to x. we have already seen one function definition: main. C++ functions can be composed. This statement finds the log base e of 10 and then raises e to that power. so the syntax looks like this: void newLine () { cout << endl. divides it by two and adds the result to the value of angle. You can also take the result of one function and pass it as an argument to another: double x = exp (log (10. FUNCTION 3. The function named main is special because it indicates where the execution of the program begins. meaning that you use one expression as part of another. you can use any expression as an argument to a function: double x = cos (angle + pi/2). The list of parameters specifies what information. For example. which outputs a newline character. } This function is named newLine. represented by the special value endl. I hope you know what it is. except that you can’t call it main or any other C++ keyword. cout << "Second Line. Or we could write a new function. (). } You should notice a few things about this program: • You can call the same procedure repeatedly. What if we wanted more space between the lines? We could call the same function repeatedly: void main { cout << newLine newLine newLine cout << } () "First Line." << endl. . main calls threeLine and threeLine calls newLine. ().3." << endl. it is quite common and useful to do so. (). • You can have one function call another function. void main () { cout << "First Line." << endl. Notice the extra space between the two lines. (). that prints three new lines: void threeLine () { newLine (). "Second Line." << endl. Second line. named threeLine." << endl. ADDING NEW FUNCTIONS 25 void main { cout << newLine cout << } () "First Line. } newLine (). newLine (). threeLine (). Again. The output of this program is First line. In this case." << endl. In fact.5. "Second Line. this is common and useful. newLine ().6 Definitions and uses Pulling together all the code fragments from the previous section. FUNCTION • In threeLine I wrote three statements all on the same line. newLine or cout << endl? 2. but this example only demonstrates two: 1. I sometimes break that rule in this book to save space. and main. Creating a new function gives you an opportunity to give a name to a group of statements. So far. cout << "Second Line. } This program contains three function definitions: newLine. How would you print 27 new lines? 3. to make your program easy to read." << endl. the whole program looks like this: #include <iostream." << endl. threeLine. Creating a new function can make a program smaller by eliminating repetitive code. threeLine (). there are a lot of reasons. . which is syntactically legal (remember that spaces and new lines usually don’t change the meaning of a program). } void threeLine () { newLine (). On the other hand. it may not be clear why it is worth the trouble to create all these new functions. a short way to print nine consecutive new lines is to call threeLine three times. Functions can simplify a program by hiding a complex computation behind a single command. void main () { cout << "First Line. and by using English words in place of arcane code.26 CHAPTER 3. Which is clearer.h> void newLine () { cout << endl. } newLine (). For example. Actually. it is usually a better idea to put each statement on a line by itself. Some functions take more than one parameter. if you want to find the sine of a number. which are values that you provide to let the function do its job. C++ is adept at keeping track of where it is. don’t read from top to bottom. Fortunately.7. the base and the exponent. For example. That sounds simple enough. PROGRAMS WITH MULTIPLE FUNCTIONS 27 Inside the definition of main. execute all the statements there.8 Parameters and arguments Some of the built-in functions we have used have parameters. you have to indicate what the number is.3. Execution always begins at the first statement of main. You should try compiling this program with the functions in a different order and see what error messages you get. while we are in the middle of main. What’s the moral of this sordid tale? When you read a program. For example: void printTwice (char phil) { cout << phil << phil << endl. Similarly. there is a statement that uses or calls threeLine.7 Programs with multiple functions When you look at a class definition that contains several functions. Thus. the definition of a function must appear before (above) the first use of the function. threeLine calls newLine three times. which takes two doubles. Notice that the definition of each function appears above the place where it is used. 3. But while we are executing threeLine. Instead. the parameter list indicates the type of each parameter. and eventually gets back to main so the program can terminate. sin takes a double value as a parameter. we might have to go off and execute the statements in threeLine. Function calls are like a detour in the flow of execution. but that is likely to be confusing. Notice that in each of these cases we have to specify not only how many parameters there are. So it shouldn’t surprise you that when you write a class definition. it is tempting to read it from top to bottom. so each time newLine completes. follow the flow of execution. but also what type they are. we get interrupted three times to go off and execute newLine. This is necessary in C++. regardless of where it is in the program (often it is at the bottom). until you reach a function call. because that is not the order of execution of the program. Thus. the program picks up where it left off in threeLine. Instead of going to the next statement. 3. Statements are executed one at a time. in order. except that you have to remember that one function can call another. } . and then come back and pick up again where you left off. like pow. you go to the first line of the called function. This rule is important. Like state diagrams. it is useful to draw a stack diagram. The value you provide as an argument must have the same type as the parameter of the function you call. but it is important to realize that they are not the same thing. and we say that the argument is passed to the function. except that they happen to have the same value (in this case the character ’b’). and we will deal with exceptions later. Whatever that parameter is (and at this point we have no idea what it is). named phil. For example. it gets printed twice.9 Parameters and variables are local Parameters and variables only exist inside their own functions.28 CHAPTER 3. followed by a newline. printTwice (argument). if we had a char variable. Let me say that again: The name of the variable we pass as an argument has nothing to do with the name of the parameter. If you try to use it. They can be the same or they can be different. . Within the confines of main. that has type char. In this case the value ’a’ is passed as an argument to printTwice where it will get printed twice. we have to provide a char. Similarly. there is no such thing as phil. FUNCTION This function takes a single parameter. For now you should learn the general rule. In order to keep track of parameters and local variables. } Notice something very important here: the name of the variable we pass as an argument (argument) has nothing to do with the name of the parameter (phil). the compiler will complain. we might have a main function like this: void main () { printTwice (’a’). inside printTwice there is no such thing as argument. 3. I chose the name phil to suggest that the name you give a parameter is up to you. we could use it as an argument instead: void main () { char argument = ’b’. In order to call this function. Alternatively. but in general you want to choose something more illustrative than phil. but it is sometimes confusing because C++ sometimes converts arguments from one type to another automatically. } The char value you provide is called an argument. Variables like this are said to be local. } It might be tempting to write (int hour. but the variables are contained in larger boxes that indicate which function they belong to. For example void printTime (int hour.3. For example. remember that you have to declare the type of every parameter. In the example. In the diagram an instance of a function is represented by a box with the name of the function on the outside and the variables and parameters inside. and no parameters.10 Functions with multiple parameters The syntax for declaring and invoking functions with multiple parameters is a common source of errors. main has one local variable. Each instance of a function contains the parameters and local variables for that function. int minute). cout << minute. int minute) { cout << hour. named phil. printTime (int hour. the state diagram for printTwice looks like this: argument main ’b’ phil printTwice ’b’ Whenever a function is called. not for parameters. The following is wrong! int hour = 11. int minute = 59. argument. 3. FUNCTIONS WITH MULTIPLE PARAMETERS 29 stack diagrams show the value of each variable. minute). // WRONG! . it creates a new instance of that function. Another common source of confusion is that you do not have to declare the types of arguments. First. but that format is only legal for variable declarations. cout << ":". printTwice has no local variables and one parameter.10. argument: A value that you provide when you call a function. FUNCTION In this case. the compiler can tell the type of hour and minute by looking at their declarations. function: A named sequence of statements that performs some useful function.30 CHAPTER 3.” and we’ll do it in a couple of chapters.12 Glossary floating-point: A type of variable (or value) that can contain fractions as well as integers. Parameters are like variables in the sense that they contain values and have types. Other functions. I will leave it up to you to answer the other two questions by trying them out. a good way to find out is to ask the compiler. The correct syntax is printTime (hour. Functions may or may not take parameters. It is unnecessary and illegal to include the type when you pass them as arguments. minute). 3. . yield results. This value must have the same type as the corresponding parameter. initialization: A statement that declares a new variable and assigns a value to it at the same time.e.11 Functions with results You might have noticed by now that some of the functions we are using. or are we stuck with things like newLine and printTwice? The answer to the third question is “yes. call: Cause a function to be executed. you don’t assign it to a variable or use it as part of a larger expression)? • What happens if you use a function without a result as part of an expression. parameter: A piece of information you provide in order to call a function. 3. There are a few floating-point types in C++. Any time you have a question about what is legal or illegal in C++. perform an action but don’t return a value. and may or may not produce a result. like newLine. like the math functions. That raises some questions: • What happens if you call a function and you don’t do anything with the result (i. the one we use in this book is double. you can write functions that return values. like newLine() + 7? • Can we write functions that yield results. Also. you can check whether one number is divisible by another: if x % y is zero. integer division. %. int remainder = 7 % 3.1 The modulus operator The modulus operator works on integers (and integer expressions) and yields the remainder when the first operand is divided by the second. nothing happens. For example. 4. then x is divisible by y. you can use the modulus operator to extract the rightmost digit or digits from a number. Conditional statements give us this ability. } The expression in parentheses is called the condition. The simplest form is the if statement: if (x > 0) { cout << "x is positive" << endl. Thus. The first operator. The syntax is exactly the same as for other operators: int quotient = 7 / 3. yields 2. In C++. If the condition is not true. we almost always need the ability to check certain conditions and change the behavior of the program accordingly. If it is true. the modulus operator is a percent sign. The modulus operator turns out to be surprisingly useful. For example. x % 10 yields the rightmost digit of x (in base 10).2 Conditional execution In order to write useful programs. 7 divided by 3 is 2 with 1 left over. then the statements in brackets get executed.Chapter 4 Conditionals and recursion 4. The second operator yields 1. 31 . Similarly x % 100 yields the last two digits. } } . The two sides of a condition operator have to be the same type. the second set of statements is executed. as follows: void printParity (int x) { if (x%2 == 0) { cout << "x is even" << endl. Remember that = is the assignment operator. Unfortunately. exactly one of the alternatives will be executed. and == is a comparison operator. If the condition is false. A common error is to use a single = instead of a double ==. Since the condition must be true or false. in which there are two possibilities. if you think you might want to check the parity (evenness or oddness) of numbers often. and the condition determines which one gets executed. then we know that x is even. and this code displays a message to that effect. the syntax C++ uses is a little different from mathematical symbols like =. = and ≤. at this point you can’t compare Strings at all! There is a way to compare Strings. 4. } else { cout << "x is odd" << endl. The syntax looks like: if (x%2 == 0) { cout << "x is even" << endl. but we won’t get to it for a couple of chapters. there is no such thing as =< or =>. you might want to “wrap” this code up in a function.32 CHAPTER 4.3 Alternative execution A second form of conditional execution is alternative execution. } If the remainder when x is divided by 2 is zero. Also. You can only compare ints to ints and doubles to doubles. As an aside. } else { cout << "x is odd" << endl.. These chains can be as long as you want.5 Nested conditionals In addition to chaining. You should resist the temptation to write things like: int number = 17. One way to do this is by chaining a series of ifs and elses: if (x > 0) { cout << "x } else if (x cout << "x } else { cout << "x } is positive" << endl. } else { if (x > 0) { cout << "x is positive" << endl. as demonstrated in these examples. you can also nest one conditional within another.4 Chained conditionals Sometimes you want to check for a number of related conditions and choose one of several actions. In main you would call this function as follows: printParity (17). } else { cout << "x is negative" << endl. is zero" << endl. you are less likely to make syntax errors and you can find them more quickly if you do. you do not have to declare the types of the arguments you provide. We could have written the previous example as: if (x == 0) { cout << "x is zero" << endl. CHAINED CONDITIONALS 33 Now you have a function named printParity that will display an appropriate message for any integer you care to provide.4.4. 4. C++ can figure out what type they are. } } . If you keep all the statements and squiggly-braces lined up. printParity (int number). // WRONG!!! 4. although they can be difficult to read if they get out of hand. One way to make them easier to read is to use standard indentation. < 0) { is negative" << endl. Always remember that when you call a function. I neglected to mention that it is also legal for a function to call itself. Remember that any time you want to use one a function from the math library. cout << "The log of x is " << result). this kind of nested structure is common. } This defines a function named printLogarithm that takes a double named x as a parameter. Notice again that indentation helps make the structure apparent. it is a good idea to avoid them when you can. It may not be obvious why that is a good thing. nested conditionals get difficult to read very quickly. CONDITIONALS AND RECURSION There is now an outer conditional that contains two branches. so you better get used to it. I used a floating-point value on the right side of the condition because there is a floating-point variable on the left.h> void printLogarithm (double x) { if (x <= 0. and we will see it again.34 CHAPTER 4. but it turns out to be one of the most magical and interesting things a program can do. One reason to use it is if you detect an error condition: #include <math. which has two branches of its own. those two branches are both output statements. . return. and we have seen several examples of that. The flow of execution immediately returns to the caller and the remaining lines of the function are not executed. } double result = log (x). Fortunately. The first branch contains a simple output statement.7 Recursion I mentioned in the last chapter that it is legal for one function to call another.0) { cout << "Positive numbers only." << endl. but nevertheless.6 The return statement The return statement allows you to terminate the execution of a function before you reach the end. but the second branch contains another if statement. although they could have been conditional statements as well. please. On the other hand. 4. you have to include the header file math.h. The first thing it does is check whether x is less than or equal to zero. in which case it displays an error message and then uses return to exit the function. 4. In general. ” Otherwise. The execution of countdown begins with n=2. The execution of countdown begins with n=0. and since n is not zero. The countdown that got n=1 returns.. } The execution of countdown begins with n=3. What happens if we call this function like this: void main () { countdown (3). } else { cout << n << endl. it outputs the word “Blastoff!” and then returns. The execution of countdown begins with n=1. } } The name of the function is countdown and it takes a single integer as a parameter... So the total output looks like: 3 2 1 Blastoff! As a second example. and since n is not zero. The countdown that got n=2 returns. . RECURSION 35 For example. and then calls itself. it outputs the value 1. it outputs the word “Blastoff. If the parameter is zero. and since n is zero. countdown (n-1). and then calls itself.. let’s look again at the functions newLine and threeLine.7.4. And then you’re back in main (what a trip). it outputs the value 3.. and since n is not zero. it outputs the parameter and then calls a function named countdown—itself— passing n-1 as an argument. it outputs the value 2.. The countdown that got n=3 returns. look at the following function: void countdown (int n) { if (n == 0) { cout << "Blastoff!" << endl. and then calls itself. If a recursion never reaches a base case. } } This program is similar to countdown. Eventually. This case—when the function completes without making a recursive call—is called the base case. which usually comes out to roughly n. so eventually it gets to zero. and it is generally not considered a good idea. as long as n is greater than zero. newLine ().36 CHAPTER 4. Although these work. something will break and the program will report an error. they would not be much help if I wanted to output 2 newlines. 4. and such functions are said to be recursive.9 Stack diagrams for recursive functions In the previous chapter we used a stack diagram to represent the state of a program during a function call. it outputs one newline. a program with an infinite recursion will not really run forever. } newLine (). In most programming environments. the function returns immediately. notice that each time the functions get called recursively. Thus. The same kind of diagram can make it easier . or 106. The process of a function calling itself is called recursion. This is known as infinite recursion. the total number of newlines is 1 + (n-1).8 Infinite recursion In the examples in the previous section. CONDITIONALS AND RECURSION void newLine () { cout << endl. the argument gets smaller by one. nLines (n-1). } void threeLine () { newLine (). without making any recursive calls. This is the first example we have seen of a run-time error (an error that does not appear until you run the program). When the argument is zero. 4. and then calls itself to output n-1 additional newlines. A better alternative would be void nLines (int n) { if (n > 0) { cout << endl. it will go on making recursive calls forever and the program will never terminate. You should write a small program that recurses forever and run it to see what happens. recursion: The process of calling the same function you are currently executing.10 Glossary modulus: An operator that works on integers and yields the remainder when one number is divided by another. called with n = 3: main n: n: n: n: 3 2 1 0 countdown countdown countdown countdown There is one instance of main and four instances of countdown. 4. It does not make a recursive call. so there are no more instances of countdown. The instance of main is empty because main does not have any parameters or local variables.4. Eventually an infinite recursion will cause a run-time error. As an exercise. Remember that every time a function gets called it creates a new instance that contains the function’s local variables and parameters. chaining: A way of joining several conditional statements in sequence. each with a different value for the parameter n.10. The bottom of the stack. . draw a stack diagram for nLines. In C++ it is denoted with a percent sign (%). conditional: A block of statements that may or may not be executed depending on some condition. infinite recursion: A function that calls itself recursively without every reaching the base case. invoked with the parameter n=4. GLOSSARY 37 to interpret a recursive function. This figure shows a stack diagram for countdown. countdown with n=0 is the base case. nesting: Putting a conditional statement inside one or both branches of another conditional statement. 38 CHAPTER 4. CONDITIONALS AND RECURSION . which indicates that the return value from this function will have type double. for want of a better name. return area. the effect of calling the function is to generate a new value. we are going to write functions that return things. That is. But so far all the functions we have written have been void functions.0). that is. have produced results. In this chapter. like the math functions.Chapter 5 Fruitful functions 5. which indicates a void function. double area = pi * radius * radius. } The first thing you should notice is that the beginning of the function definition is different. which takes a double as a parameter. which I will refer to as fruitful functions. Instead of void. 39 .0). countdown (n-1). double height = radius * sin (angle). which we usually assign to a variable or use as part of an expression. and returns the area of a circle with the given radius: double area (double radius) { double pi = acos (-1. functions that return no value. For example: double e = exp (1. with no assignment: nLines (3). it is typically on a line by itself. When you call a void function. we see double.1 Return values Some of the built-in functions we have used. The first example is area. Sometimes it is useful to have multiple return statements. the type of the expression in the return statement must match the return type of the function. If you put return statements inside a conditional. the compiler will take you to task. } On the other hand. Although it is legal to have more than one return statement in a function. only one will be executed. temporary variables like area often make debugging easier. In other words. } else if (x > 0) { return x. In either case. one in each branch of a conditional: double absoluteValue (double x) { if (x < 0) { return -x. or any place else where it can never be executed. notice that the last line is an alternate form of the return statement that includes a return value. then you have to guarantee that every possible path through the program hits a return statement. } } Since these returns statements are in an alternative conditional. FRUITFUL FUNCTIONS Also. Code that appears after a return statement. “return immediately from this function and use the following expression as a return value.40 CHAPTER 5. is called dead code. } else { return x. This statement means. For example: double absoluteValue (double x) { if (x < 0) { return -x. so we could have written this function more concisely: double area (double radius) { return acos(-1. the function terminates without executing any subsequent statements. Some compilers warn you if part of your code is dead. or an expression with the wrong type.0) * radius * radius. when you declare that the return type is double.” The expression you provide can be arbitrarily complicated. you are making a promise that this function will eventually produce a double. you should keep in mind that as soon as one is executed. } // WRONG!! } . If you try to return with no expression. Unfortunately. You should turn this option on all the time. what are the inputs (parameters) and what is the output (return value). even though it is not the right answer. As a result. Then you give your program to someone else and they run it in another environment. Already we can write an outline of the function: double distance (double x1. In other words. distance = (x2 − x1 )2 + (y2 − y1 )2 (5. 5. you should know that there is a function in the math library called fabs that calculates the absolute value of a double—correctly. The return value is the distance. By the usual definition.0. It fails in some mysterious way. At this stage the . but the return value when x==0 could be anything. the program may compile and run. you will realize that the only thing worse than getting a compiler error is not getting a compiler error when your program is wrong. you should not blame the compiler. As an aside. you should thank the compiler for finding your error and sparing you days of debugging. double y1.1) The first step is to consider what a distance function should look like in C++. imagine you want to find the distance between two points. As an example. which will have type double. given by the coordinates (x1 . PROGRAM DEVELOPMENT 41 This program is not correct because if x happens to be 0. I am going to suggest one technique that I call incremental development. many C++ compilers do not catch this error. In this case. and it takes days of debugging to discover that the problem is an incorrect implementation of absoluteValue. if the compiler points out an error in your program. double y2) { return 0. By now you are probably sick of seeing compiler errors. But it may not be clear yet how to go about writing them. Rather. y1 ) and (x2 .5. Here’s the kind of thing that’s likely to happen: you test absoluteValue with several values of x and it seems to work correctly. the two points are the parameters. If only the compiler had warned you! From now on.2 Program development At this point you should be able to look at complete C++ functions and tell what they do. Some compilers have an option that tells them to be extra strict and report all the errors they can find. } The return statement is a placekeeper so that the function will compile and return something. and will probably be different in different environments.2. y2 ). and it is natural to represent them using four doubles. double x2. but as you gain more experience. then neither condition will be true and the function will end without hitting a return statement. we have to call it with sample values. Code like that is called scaffolding. double distance (double x1. FRUITFUL FUNCTIONS function doesn’t do anything useful. double x2. When the function is finished I will remove the output statements. we can start adding lines of code one at a time. we recompile and run the program. but it is not part of the final product. cout << "dy is " << dy << endl. We could use the pow function. we can use the sqrt function to compute and return the result. double y1. double x2. cout << "dx is " << dx << endl.0 and 4.0). double y2) { double dx = x2 . double dsquared = dx*dx + dy*dy. return 0. just in case you need it later. cout << dist << endl. Once we have checked the syntax of the function definition. The next step in the computation is to find the differences x2 −x1 and y2 −y1 . When you are testing a function. The next step in the development is to square dx and dy. double dy = y2 . 6. but comment it out. After each incremental change. at any point we know exactly where the error must be—in the last line we added.x1. I would compile and run the program at this stage and check the intermediate value (which should be 25. Sometimes it is a good idea to keep the scaffolding around. because it is helpful for building the program.0. return 0. I chose these values so that the horizontal distance is 3 and the vertical distance is 4. double distance (double x1.0.42 CHAPTER 5. Somewhere in main I would add: double dist = distance (1. but it is simpler and faster to just multiply each term by itself. it is useful to know the right answer. In order to test the new function.x1.y1.0). That way. 2.0. Finally. double y2) { double dx = x2 . that way. the result will be 5 (the hypotenuse of a 3-4-5 triangle). I will store those values in temporary variables named dx and dy.0. } I added output statements that will let me check the intermediate values before proceeding. double y1. . As I mentioned.y1. 4. double dy = y2 . } Again. but it is worthwhile to try compiling it so we can identify any syntax errors before we make it more complicated.0.0. I already know that they should be 3. cout << "dsquared is " << dsquared. Nevertheless. At any point. yp). distance. • Use temporary variables to hold intermediate values so you can output and check them. 5.3. that does that. double yp) { double radius = distance (xc. double radius = distance (xc. you can use it as part of an expression. } . xp. The second step is to find the area of a circle with that radius. the center of the circle and a point on the perimeter. double result = area (radius).y1. double yc. yp). if there is an error. The first step is to find the radius of the circle. we should output and check the value of the result. double dsquared = dx*dx + dy*dy. double y1.5. we get: double fred (double xc. Fortunately. double result = area (radius). what if someone gave you two points. which is the distance between the two points. return result. yc. double result = sqrt (dsquared). and you can build new functions using existing functions. COMPOSITION 43 double distance (double x1. yc. and asked for the area of the circle? Let’s say the center point is stored in the variables xc and yc. incremental changes.x1. you might want to remove some of the scaffolding or consolidate multiple statements into compound expressions. As you gain more experience programming. return result. you will know exactly where it is. once you define a new function. return result. you might find yourself writing and debugging more than one line at a time. we have a function. • Once the program is working. For example. but only if it does not make the program difficult to read. double dy = y2 . and the perimeter point is in xp and yp. double x2. this incremental development process can save you a lot of debugging time.3 Composition As you should expect by now. double y2) { double dx = x2 . double xp. and return it. xp. The key aspects of the process are: • Start with a working program and make small. Wrapping that all up in a function. } Then in main. double yc.0. FRUITFUL FUNCTIONS The name of this function is fred. If two functions do the same thing. I will explain why in the next section.0. } This looks like a recursive function. Many of the built-in C++ commands are overloaded. yc.44 CHAPTER 5. In other words. 4. Actually. double yp) { return area (distance (xc. C++ goes looking for a function named area that takes a double as an argument. double yc. which is called overloading. it would make more sense if fred were called area.0). for fred we provide two points.. but it is not. it should be used with caution. } 5. If you write: double x = area (3. You might get yourself nicely confused if you are trying to debug one version of a function while accidently calling a different one. we have to provide the radius. it is natural to give them the same name. double yp) { return area (distance (xc.0. xp. and so it uses the first version. yp)). this version of area is calling the other version.4 Overloading In the previous section you might have noticed that fred and area perform similar functions—finding the area of a circle—but take different parameters. double xp. C++ uses the second version of area. 2. Actually. yp)). When you call an overloaded function. yc. If you write double x = area (1. and seeing the same thing every time . For area. which may seem odd. meaning that there are different versions that accept different numbers or types of parameters. Having more than one function with the same name. but once the program is working we can make it more concise by composing the function calls: double fred (double xc.0). The temporary variables radius and area are useful for development and debugging. So we can go ahead and rename fred: double area (double xc. is legal in C++ as long as each version takes different parameters. C++ knows which version you want by looking at the arguments that you provide. double xp. xp. Also. for every type of value. the second line is an assignment. In C++ the boolean type is called bool. while (true) { // loop forever } is a standard idiom for a loop that should run forever (or until it reaches a return or break statement). 5. fred = true. For example: if (x == 5) { // do something } The operator == compares two integers and produces a boolean value. so you can store it in a bool variable . The first line is a simple variable declaration. and even more floating-point numbers. To check. There are a lot of integers in the world. there is another type in C++ that is even smaller. Well. bool testResult = false. It is called boolean.5 Boolean values The types we have seen so far are pretty big. As I mentioned.5. Boolean variables work just like the other types: bool fred. and the third line is a combination of a declaration and as assignment. The values true and false are keywords in C++. we have been using boolean values for the last couple of chapters. and can be used anywhere a boolean expression is called for. and the only values in it are true and false. the set of characters is pretty small.5. By comparison. Without thinking about it. BOOLEAN VALUES 45 you run it. stick in an output statement (it doesn’t matter what it says) and make sure the behavior of the program changes accordingly. the result of a comparison operator is a boolean. The condition inside an if statement or a while statement is a boolean expression.6 Boolean variables As usual. 5. there is a corresponding type of variable. For example. called an initialization. the result of a comparison operator is a boolean value. This is a warning sign that for one reason or another you are not running the version of the program you think you are. OR and NOT." << endl. since it flags the presence or absence of some condition. } } . Logical operators often provide a way to simplify nested conditional statements. FRUITFUL FUNCTIONS bool evenFlag = (n%2 == 0). how would you write the following code using a single conditional? if (x > 0) { if (x < 10) { cout << "x is a positive single digit. evenFlag || n%3 == 0 is true if either of the conditions is true. which are denoted by the symbols &&. 5. For example x > 0 && x < 10 is true only if x is greater than zero AND less than 10. if evenFlag is true OR the number is divisible by 3. that is. // true if n is even // true if x is positive and then use it as part of a conditional statement later if (evenFlag) { cout << "n was even when I checked it" << endl. || and !. if the number is odd.8 Bool functions Functions can return bool values just like any other type. The semantics (meaning) of these operators is similar to their meaning in English. } } 5. For example: bool isSingleDigit (int x) { if (x >= 0 && x < 10) { return true. so !evenFlag is true if evenFlag is false. bool positiveFlag = (x > 0). For example. } else { return false.46 CHAPTER 5. which is often convenient for hiding complicated tests inside functions. the NOT operator has the effect of negating or inverting a bool expression.7 Logical operators There are three logical operators in C++: AND. Finally. } A variable used in this way is called a flag. that is. It is common to give boolean functions names that sound like yes/no questions. bool bigFlag = !isSingleDigit (17). The return type is bool. which means that every return statement has to provide a bool expression. } The usual return value from main is 0. or some other value that indicates what kind of error occurred. it does not display the words true and false. 1 There is a way to fix that using the boolalpha flag. The first line outputs the value true because 2 is a single-digit number. Remember that the expression x >= 0 && x < 10 has type bool. } else { cout << "x is big" << endl. main is not really supposed to be a void function. so there is nothing wrong with returning it directly. although it is a bit longer than it needs to be.9. and avoiding the if statement altogether: bool isSingleDigit (int x) { return (x >= 0 && x < 10). It’s supposed to return an integer: int main () { return 0. The code itself is straightforward. when C++ outputs bools. . but it is too hideous to mention.5. } In main you can call this function in the usual ways: cout << isSingleDigit (2) << endl.9 Returning from main Now that we have functions that return values. } 5. which indicates that the program succeeded at whatever it was supposed to to. RETURNING FROM MAIN 47 The name of this function is isSingleDigit.1 The second line assigns the value true to bigFlag only if 17 is not a singledigit number. it is common to return -1. Unfortunately. but rather the integers 1 and 0. I can let you in on a secret. If something goes wrong. The most common use of bool functions is inside conditional statements if (isSingleDigit (x)) { cout << "x is little" << endl. which is 2 times 1!. On the other hand. you should conclude that factorial takes an integer as a parameter and returns an integer: . which is 6. A truly circular definition is typically not very useful: frabjuous: an adjective used to describe something that is frabjuous. you might be annoyed.48 CHAPTER 5. FRUITFUL FUNCTIONS Of course. we get 3! equal to 3 times 2 times 1 times 1. So 3! is 3 times 2!. If you take a course on the Theory of Computation. Putting it all together. but a lot of the early computer scientists started as mathematicians). which is not to be confused with the C++ logical operator ! which means NOT. It turns out that when the system executes a program. in the sense that the definition contains a reference to the thing being defined. Accordingly. you can usually write a C++ program to evaluate it. if you looked up the definition of the mathematical function factorial. If you can write a recursive definition of something. you will have a chance to see the proof. and what the return type is. but that’s all). we’ll evaluate a few recursively-defined mathematical functions.. you might wonder who this value gets returned to. it starts by calling main in pretty much the same way it calls all the other functions. disks. 5. n. is n multiplied by the factorial of n − 1. but we are not going to deal with them for a little while. To give you an idea of what you can do with the tools we have learned so far. Any program ever written could be rewritten using only the language features we have used so far (actually. With a little thought. and the factorial of any other value. etc. since we never call main ourselves. one of the first computer scientists (well. mouse. you might get something like: 0! = 1 n! = n · (n − 1)! (Factorial is usually denoted with the symbol !. some would argue that he was a mathematician. There are even some parameters that are passed to main by the system. The first step is to decide what the parameters are for this function. which is 1 times 0!.) This definition says that the factorial of 0 is 1. If you saw that definition in the dictionary. Proving that claim is a non-trivial exercise first accomplished by Alan Turing. but you might be interested to know that this subset is now a complete programming language.10 More recursion So far we have only learned a small subset of C++. by which I mean that anything that can be computed can be expressed in this language. we would need a few commands to control devices like the keyboard. it is known as the Turing thesis. A recursive definition is similar to a circular definition. . and the result is returned. MORE RECURSION 49 int factorial (int n) { } If the argument happens to be zero. The return value (1) gets multiplied by n. all we have to do is return 1: int factorial (int n) { if (n == 0) { return 1.. return result.5. it is similar to nLines from the previous chapter... } } If we look at the flow of execution for this program. and this is the interesting part. and then multiply it by n. The return value (1) gets multiplied by n. } } Otherwise.. and the result is returned. which is 1. If we call factorial with the value 3: Since 3 is not zero. we take the first branch and return the value 1 immediately without making any more recursive calls. Since 0 is zero.10. we have to make a recursive call to find the factorial of n − 1. which is 2. we take the second branch and calculate the factorial of n − 1.. Since 1 is not zero. int factorial (int n) { if (n == 0) { return 1. Since 2 is not zero. . } else { int recurse = factorial (n-1). we take the second branch and calculate the factorial of n − 1. int result = n * recurse. we take the second branch and calculate the factorial of n − 1. You just assume that they work. For example.50 CHAPTER 5. you don’t examine the implementations of those functions. When you call cos or exp. FRUITFUL FUNCTIONS The return value (2) gets multiplied by n. because the people who wrote the built-in libraries were good programmers. 5. The same is true of recursive programs. which is 3. and then ask yourself. the local variables recurse and result do not exist because when n=0 the branch that creates them does not execute.” When you come to a function call. Once we have convinced ourselves that this function is correct—by testing and examination of the code—we can use the function without ever looking at the code again. Of course. 6. you are already practicing this leap of faith when you use built-in functions. can I compute the factorial of n?” In this case. instead of following the flow of execution..11 Leap of faith Following the flow of execution is one way to read programs. Well. and the result. you should assume that the recursive call works (yields the correct result). by multiplying by n. An alternative is what I call the “leap of faith.8 we wrote a function called isSingleDigit that determines whether a number is between 0 and 9. In fact. it is a bit strange to assume that the function works correctly . is returned to main. but as you saw in the previous section. it is clear that you can. it can quickly become labarynthine. or whoever called factorial (3). in Section 5. you assume that the function works correctly and returns the appropriate value. instead of following the flow of execution. When you get to the recursive call. the same is true when you call one of your own functions. Notice that in the last instance of factorial. “Assuming that I can find the factorial of n − 1. 12 One more example In the previous example I used temporary variables to spell out the steps. which has the following definition: f ibonacci(0) = 1 f ibonacci(1) = 1 f ibonacci(n) = f ibonacci(n − 1) + f ibonacci(n − 2). 5. ONE MORE EXAMPLE 51 when you have not even finished writing it. But according to the leap of faith. and to make the code easier to debug. Translated into C++.13 Glossary return type: The type of value a function returns. this is int fibonacci (int n) { if (n == 0 || n == 1) { return 1. } else { return fibonacci (n-1) + fibonacci (n-2). even for fairly small values of n. your head explodes. } } From now on I will tend to use the more concise version. the classic example of a recursively-defined mathematical function is fibonacci.5. but I could have saved a few lines: int factorial (int n) { if (n == 0) { return 1. if we assume that the two recursive calls (yes. you can tighten it up. if you are feeling inspired. . you can make two recursive calls) work correctly.12. } } If you try to follow the flow of execution here. then it is clear that we get the right result by adding them together. } else { return n * factorial (n-1). When you have it working. After factorial. but I recommend that you use the more explicit version while you are developing code. but that’s why it’s called a leap of faith! 5. boolean values can be stored in a variable type called bool. often because it appears after a return statement.52 CHAPTER 5. C++ knows which version to use by looking at the arguments you provide. . scaffolding: Code that is used during program development but is not part of the final version. overloading: Having more than one function with the same name but different parameters. In C++. dead code: Part of a program that can never be executed. often called true and f alse. logical operator: An operator that combines boolean values in order to test compound conditions. flag: A variable (usually type bool) that records a condition or status information. that is. comparison operator: An operator that compares two values and produces a boolean that indicates the relationship between the operands. boolean: A value or variable that can take on one of two states. When you call an overloaded function. void: A special return type that indicates a void function. one that does not return a value. FRUITFUL FUNCTIONS return value: The value provided as the result of a function call. is not. int fred = 5. equality is commutative. Because C++ uses the = symbol for assignment. is legal. in mathematics if a = 7 then 7 = a.Chapter 6 Iteration 6. it is especially important to distinguish between an assignment statement and a statement of equality. but it is legal in C++ to make more than one assignment to the same variable. It is not! First of all. and 7 = a. The output of this program is 57. When you assign a value to a variable. fred 5 5 7 When there are multiple assignments to a variable. cout << fred. and the second time his value is 7. For example. 53 . it is tempting to interpret a statement like a = b as a statement of equality.1 Multiple assignment I haven’t said much about it. and assignment is not. fred fred = 7. But in C++ the statement a = 7. fred = 7. you change the contents of the container. This kind of multiple assignment is the reason I described variables as a container for values. because the first time we print fred his value is 5. The effect of the second assignment is to replace the old value of the variable with a new value. as shown in the figure: int fred = 5. cout << fred. Although multiple assignment is frequently useful. output the word ‘Blastoff!”’ More formally. and so they are no longer equal. such as <.54 CHAPTER 6. 6. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly. What this means is. 6.2 Iteration One of the things computers are often used for is the automation of repetitive tasks. // a and b are now equal // a and b are no longer equal The third line changes the value of a but it does not change the value of b. If the values of variables are changing constantly in different parts of the program. you should use it with caution. We have seen programs that use recursion to perform repetition. but they don’t have to stay that way! int a = 5. In many programming languages an alternate symbol is used for assignment. in mathematics. it can make the code difficult to read and debug. the flow of execution for a while statement is as follows: 1. } cout << "Blastoff!" << endl. In C++.or :=. } You can almost read a while statement as if it were English. then a will always equal b. Evaluate the condition in parentheses. When you get to zero. yielding true or false. int b = a.3 The while statement Using a while statement. This type of repetition is called iteration. such as nLines and countdown. and C++ provides several language features that make it easier to write iterative programs. The two features we are going to look at are the while statement and the for statement. an assignment statement can make two variables equal. a statement of equality is true for all time. n = n-1. ITERATION Furthermore. in order to avoid confusion. a = 3. we can rewrite countdown: void countdown (int n) { while (n > 0) { cout << n << endl. continue displaying the value of n and then reducing the value of n by 1. . “While n is greater than zero. If a = b now. the value of n is divided by two. At each iteration. 4. For example. Particular values aside. Notice that if the condition is false the first time through the loop. we can prove that the loop will terminate because we know that the value of n is finite. 5. Otherwise the loop will repeat forever. then the value of n will be even every time through the loop. execute each of the statements between the squiggly-braces. so eventually we have to get to zero. 8. An endless source of amusement for computer scientists is the observation that the directions on shampoo. rinse. which is called an infinite loop. 3. the statements inside the loop are never executed. no one has been able to prove it or disprove it! . eventually. “Lather. the condition becomes false and the loop terminates. If it is odd. In other cases it is not so easy to tell: void sequence (int n) { while (n != 1) { cout << n << endl. so the loop will continue until n is 1. until we get to 1. 16. exit the while statement and continue execution at the next statement. the interesting question is whether we can prove that this program terminates for all values of n. if the starting value (the argument passed to sequence) is 3. the program outputs the value of n and then checks whether it is even or odd. If it is even. The previous example ends with such a sequence. This type of flow is called a loop because the third step loops back around to the top. } } } // n is even // n is odd The condition for this loop is n != 1. or that the program will terminate. 2.6. For example. which will make the condition false. and we can see that the value of n gets smaller each time through the loop (each iteration). In the case of countdown. 10.” are an infinite loop. the resulting sequence is 3. THE WHILE STATEMENT 55 2. The body of the loop should change the value of one or more variables so that. 1. repeat. If the condition is true. For some particular values of n. Since n sometimes increases and sometimes decreases. } else { n = n*3 + 1. So far. The statements inside the loop are called the body of the loop. the value is replaced by 3n + 1. and then go back to step 1. we can prove termination. if (n%2 == 0) { n = n / 2. there is no obvious proof that n will ever reach 1. If the condition is false.3. starting with 16. if the starting value is a power of two. Well.693147 1. The following program outputs a sequence of values in the left column and their logarithms in the right column: double x = 1. The sequence \n represents a newline character. but shortsighted. it causes the cursor to move on to the next line. The output of this program is 1 2 3 4 5 6 7 8 0 0. tabs are useful for making columns of text line up. For example. A tab character causes the cursor to shift to the right until it reaches one of the tab stops.79176 1. which are normally every eight characters. almost. while (x < 10. and other common mathematical functions by hand.0) { cout << x << "\t" << log(x) << "\n". “This is great! We can use the computers to generate the tables. and then perform computations to improve the approximation. it still makes a good example of iteration.0. computers use tables of values to get an approximate answer.” That turned out to be true (mostly). I use \n. so there will be no errors. sines and cosines.07944 . although in these examples the sequence is the whole string. To make that easier. before computers were readily available.94591 2. I use endl. most famously in the table the original Intel Pentium used to perform floating-point division. Usually if a newline character appears by itself.60944 1. } The sequence \t represents a tab character. Creating these tables was slow and boring. When computers appeared on the scene. It turns out that for some operations. These sequences can be included anywhere in a string.09861 1. Soon thereafter computers and calculators were so pervasive that the tables became obsolete. In some cases. ITERATION 6.0. there have been errors in the underlying tables. As we will see in a minute.4 Tables One of the things loops are good for is generating tabular data. there were books containing long tables where you could find the values of various functions. but if it appears as part of a string. people had to calculate logarithms. one of the initial reactions was. Although a “log table” is not as useful as it once was. and the result tended to be full of errors. x = x + 1. A newline character has exactly the same effect as endl.38629 1.56 CHAPTER 6. Log tables may not be useful any more. The result is: 1 2 4 8 16 32 64 0 1 2 3 4 5 6 Because we are using tab characters between the columns. we often want to find logarithms with respect to base 2.0) << endl. which yields an arithmetic sequence.58496 2 2. 4 and 8 are powers of two. Since powers of two are so important in computer science. we could modify the program like this: double x = 1. If we wanted to find the logarithms of other powers of two. Print it out and memorize it.6.19722 If these values seem odd.0) { cout << x << "\t" << log(x) / log(2. modify this program so that it outputs the powers of two up to 65536 (that’s 216 ).0. knowing the powers of two is! As an exercise. .0. x = x * 2.32193 2. remember that the log function uses base e. while (x < 100. yields 1 2 3 4 5 6 7 8 9 0 1 1. but for computer scientists.58496 2. To do that. because their logarithms base 2 are round numbers. } Now instead of adding something to x each time through the loop.80735 3 3. the position of the second column does not depend on the number of digits in the first column.16993 loge x loge 2 We can see that 1.4. 2. we can use the following formula: log2 x = Changing the output statement to cout << x << "\t" << log(x) / log(2. yielding a geometric sequence.0) << endl. we multiply x by something. TABLES 57 9 2. we print the value 2*i followed by three spaces. or loop variable. As the loop executes. A multiplication table is a good example. A good way to start is to write a simple loop that prints the multiples of 2. ITERATION 6. We have seen two examples of encapsulation.58 CHAPTER 6. Let’s say you wanted to print a multiplication table for the values from 1 to 6. we get all the output on a single line.8.5 Two-dimensional tables A two-dimensional table is a table where you choose a row and a column and read the value at the intersection. Here’s a function that encapsulates the loop from the previous section and generalizes it to print multiples of n. while (i <= 6) { cout << n*i << " ". ". like printing the multiples of any integer. allowing you to take advantage of all the things functions are good for. all on one line. void printMultiples (int n) { int i = 1. Generalization means taking something specific. } . By omitting the endl from the first output statement. so good. } cout << endl. The output of this program is: 2 4 6 8 10 12 So far. when we wrote printParity in Section 4. i = i + 1. and making it more general. like printing multiples of 2. int i = 1. the loop terminates. 6.3 and isSingleDigit in Section 5. The first line initializes a variable named i. } cout << endl. the value of i increases from 1 to 6. while (i <= 6) { cout << 2*i << " i = i + 1. which is going to act as a counter. and then when i is 7.6 Encapsulation and generalization Encapsulation usually means taking a piece of code and wrapping it up in a function. Each time through the loop. The next step is to encapsulate and generalize. body: The statements inside the loop. tab: A special character. 6. Local variables cannot be accessed from outside their home function. local variable: A variable that is declared inside a function and that exists only within that function. infinite loop: A loop whose condition is always true. Generalization makes code more versatile. GLOSSARY 63 1 2 3 4 5 6 7 4 6 8 10 12 14 9 12 15 18 21 16 20 24 28 25 30 35 36 42 49 I’ll leave it up to you to figure out how it works. specific things. generalize: To replace something unnecessarily specific (like a constant value) with something appropriately general (like a variable or parameter).11. by using local variables). written as \t in C++.11 Glossary loop: A statement that executes repeatedly while a condition is true or until some condition is satisfied. I demonstrated a style of development based on developing code to do simple. In this chapter. development plan: A process for developing a program.6. and do not interfere with any other functions. encapsulate: To divide a large complex program into components (like functions) and isolate the components from each other (for example. more likely to be reused. and sometimes even easier to write. that causes the cursor to move to the next tab stop on the current line. iteration: One pass through (execution of) the body of the loop. including the evaluation of the condition. and then encapsulating and generalizing. . 64 CHAPTER 6. ITERATION . The apstring class contains all the functions that apply to apstrings.” You might be wondering what they mean by class. It will be a few more chapters before I can give a complete definition.Chapter 7 Strings and things 7. The versions of the C++ classes defined for use in the AP Computer Science courses included in this textbook were accurate as of 20 July 1999. Educational Testing service. and using them requires some concepts we have not covered yet. so for the most part we are going to avoid them.1 Unfortunately. it is not possible to avoid C strings altogether. int and double. In a few places in this chapter I will warn you about some problems you might run into using apstrings instead of C strings. which is a type created specifically for the Computer Science AP Exam.” The syntax for C strings is a bit ugly. floating-point numbers and strings—but only four types of variables—bool. Revisions to the classes may have been made since that time. In fact. or the AP Computer Science Development Committee. char. I have to include the following text: “Inclusion of the C++ classes defined for use in the Advanced Placement Computer Science courses does not constitute endorsement of the other material in this textbook by the College Board. characters. 65 . sometimes called “a native C string. So far we have no way to store a string in a variable or perform operations on strings. there are several kinds of variables in C++ that can store strings. 1 In order for me to talk about AP classes in this book. One is a basic type that is part of the C++ language. but for now a class is a collection of functions that defines the operations we can perform on some type. integers. The string type we are going to use is called apstring.1 Containers for strings We have seen five types of values—booleans. of characters. Before proceeding." The third line is a combined declaration and assignment. Normally when string values like "Hello.66 CHAPTER 7.2 apstring variables You can create a variable with type apstring in the usual ways: apstring first." appear. The second line assigns it the string value "Hello.3 Extracting characters from a string Strings are called “strings” because they are made up of a sequence. When I output the value of letter. 7. If you want the the zereoth letter of a string. The first operation we are going to perform on a string is to extract one of the characters. or string. The first line creates an apstring without giving it a value. computer scientists always start counting from zero. ". when we assign them to an apstring variable. you should type in the program above and make sure you can compile and run it. and you will have to add the file apstring. also called an initialization. you will have to include the header file for the apstring class. " or "world. char letter = fruit[1]. Unless you are a computer scientist. The expression fruit[1] indicates that I want character number 1 from the string named fruit. I get a surprise: a a is not the first letter of "banana".". apstring second = "world. For 0th 2th the . In this case. cout << letter << endl. first = "Hello. perverse reasons. they are converted automatically to apstring values. The letter (“zeroeth”) of "banana" is b.cpp to the list of files you want to compile. In order to compile this code. The result is stored in a char named letter. C++ uses square brackets ([ and ]) for this operation: apstring fruit = "banana". STRINGS AND THINGS 7. you have to put zero in square brackets: char letter = fruit[0]. The 1th letter (“oneth”) is a and the (“twoeth”) letter is n. The details of how to do this depend on your programming environment. We can output strings in the usual way: cout << first << second << endl. they are treated as C strings. in this case 6. you might be tempted to try something like int length = fruit. do something to it. } This loop traverses the string and outputs each letter on a line by itself. while (index < fruit. int length = fruit.7. LENGTH 67 7. // WRONG!! That won’t work. fruit. This vocabulary may seem strange. The reason is that there is no 6th letter in "banana". select each character in turn. char last = fruit[length].length().4 Length To find the length of a string (number of characters). This pattern of processing is called a traversal. the condition is false and the body of the . index = index + 1. as indicated by the empty parentheses (). but we will see many more examples where we invoke a function on an object. The return value is an integer. To find the last letter of a string. you have to subtract 1 from length. The syntax for calling this function is a little different from what we’ve seen before: int length. which means that when index is equal to the length of the string. length takes no arguments. the 6 letters are numbered from 0 to 5. cout << letter << endl. Notice that the condition is index < fruit. The syntax for function invocation is called “dot notation.length()) { char letter = fruit[index]. Since we started counting at 0. char last = fruit[length-1]. we would say that we are invoking the length function on the string named fruit. from the name of the function.5 Traversal A common thing to do with a string is start at the beginning.” because the dot (period) separates the name of the object. and continue until the end. length. length = fruit. 7. Notice that it is legal to have a variable with the same name as a function.4.length().length().length(). To get the last character. A natural way to encode a traversal is with a while statement: int index = 0. To describe this function call. we can use the length function. 3. string: banana Try it in your development environment and see how it looks. The name of the loop variable is index.2 I talked about run-time errors. According to the documentation. apstring fruit = "banana". it returns the index of the first appearance. For example. int index = fruit. there is a version of find that takes another apstring as an argument and that finds the index where the substring appears in the string.6 A run-time error Way back in Section 1. The set has to be ordered so that each letter has an index and each index refers to a single character. find returns -1. The find function is like the opposite the [] operator. the letter appears three times. you will get a run-time error and a message something like this: index out of range: 6. .find("nan").7 The find function The apstring class provides several other functions that you can invoke on strings. STRINGS AND THINGS loop is not executed. The index indicates (hence the name) which one you want. This example finds the index of the letter ’a’ in the string. Instead of taking an index and extracting the character at that index. As an exercise.68 CHAPTER 7. Well. all on one line. In this case. write a function that takes an apstring as an argument and that outputs the letters backwards. now we are. So far. If the given letter does not appear in the string. so it is not obvious what find should do.find(’a’). If you use the [] operator and you provide an index that is negative or greater than length-1. int index = fruit. in this case the set of characters in the string. you probably haven’t seen many run-time errors. The last character we access is the one with the index fruit. because we haven’t been doing many things that can cause one. An index is a variable or value used to specify one member of an ordered set. which are errors that don’t appear until a program has started running. 7. 7. find takes a character and finds the index where that character appears. In addition. so the result is 1. apstring fruit = "banana".length()-1. int i) { while (i<s. In this case.8.7. One way to generalize the find function is to write a version that takes an additional parameter—the index where we should start looking. int length = fruit. } cout << count << endl. The variable count is initialized to zero and then incremented each time we find an ’a’. } Instead of invoking this function on an apstring.length()) { if (s[i] == c) return i. int find (apstring s. i = i + 1.9 Looping and counting The following program counts the number of times the letter ’a’ appears in a string: apstring fruit = "banana". OUR OWN VERSION OF FIND 69 This example returns the value 2. } index = index + 1. called a counter. C++ knows which version of find to invoke by looking at the type of the argument we provide. char c. int count = 0. we may not want to start at the beginning of the string. int index = 0.4 that there can be more than one function with the same name. while (index < length) { if (fruit[index] == ’a’) { count = count + 1. as long as they take a different number of parameters or different types.length(). (To . } return -1. we have to pass the apstring as the first argument. 7.8 Our own version of find If we are looking for a letter in an apstring. This program demonstrates a common idiom. You should remember from Section 5. The other arguments are the character we are looking for and the index where we should start. Here is an implementation of this function. 7. like the first version of find. As a second exercise. or you can write index++. As an exercise. you might see something like: cout << i++ << endl. // WRONG!! Unfortunately. Technically. I would discourage you from using them.) When we exit the loop. so the compiler will not warn you. STRINGS AND THINGS increment is to increase by one. and -. char or double.. we can rewrite the letter-counter: int index = 0. it is not clear whether the increment will take effect before or after the value is displayed. For example.subtracts one. but you shouldn’t mix them. you can try it. count contains the result: the total number of a’s. it uses the version of find we wrote in the previous section. . this is syntactically legal. while (index < length) { if (fruit[index] == ’a’) { count++. it is the opposite of decrement. Looking at this.70 CHAPTER 7.10 Increment and decrement operators Incrementing and decrementing are such common operations that C++ provides special operators for them. Because expressions like this tend to be confusing. encapsulate this code in a function named countLetters.. If you really want to know. } It is a common error to write something like index = index++. 7. This is often a difficult bug to track down. and generalize it so that it accepts the string and the letter as arguments. it is legal to increment a variable and use it in an expression at the same time. I’m not going to tell you what the result is. Neither operator works on apstrings. rewrite this function so that instead of traversing the string. and neither should be used on bools. In fact. Using the increment operators. Remember. which is a noun. you can write index = index +1. and unrelated to excrement. to discourage you even more. The effect of this statement is to leave the value of index unchanged. The ++ operator adds one to the current value of an int. } index++. char letter = ’J’. Mack. Here is a loop that outputs these names in order: apstring suffix = "ack". while (letter <= ’Q’) { cout << letter + suffix << endl. the + operator can be used on strings.11 String concatenation Interestingly. For example. letter++. the + operator does not work on native C strings. Ouack. Unfortunately. Kack. To concatenate means to join the two operands end to end. though. C++ will automatically convert the other. the names of the ducklings are Jack. Nack. For example: apstring fruit = "banana". STRING CONCATENATION 71 7. } The output of this program is: Jack Kack Lack Mack Nack Oack Pack Qack . As long as one of the operands is an apstring. cout << dessert << endl.11. so you cannot write something like apstring dessert = "banana" + " nut bread". it performs string concatenation. because both operands are C strings. in Robert McCloskey’s book Make Way for Ducklings. It is also possible to concatenate a character onto the beginning or end of an apstring. “Abecedarian” refers to a series or list in which the elements appear in alphabetical order. apstring dessert = fruit + bakedGood. Lack. The output of this program is banana nut bread. Pack and Quack.7. apstring bakedGood = " nut bread". we will use concatenation and character arithmetic to output an abecedarian series. In the following example. 12 apstrings are mutable You can change the letters in an apstring one at a time using the [] operator on the left side of an assignment. For example. apstring greeting = "Hello. Unfortunately. } The other comparison operations are useful for putting words in alphabetical order. For example. like all lower-case. that the apstring class does not handle upper and lower case letters the same way that people do." << endl. although it produces a very strange result. STRINGS AND THINGS Of course. modify the program to correct this error. A common way to address this problem is to convert strings to a standard format.” As an exercise. at least in my development environment. if you want to know if two strings are equal: if (word == "banana") { cout << "Yes. comes before banana. } else { cout << "Yes. we have no bananas!" << endl. Your word. Again. As a result. comes before banana. The next sections explains how. All the upper case letters come before all the lower case letters. I will not address the more difficult problem. comes after banana. world!. Zebra. before performing the comparison. cout << greeting << endl.72 CHAPTER 7. we have no bananas!" << endl. that’s not quite right because I’ve misspelled “Ouack” and “Quack. greeting[0] = ’J’. } else if (word > "banana") { cout << "Your word. 7. be careful to use string concatenation only with apstrings and not with native C strings. 7. which is making the program realize that zebras are not fruit. . world!". though." << endl. " << word << ".13 apstrings are comparable All the comparison operators that work on ints and doubles also work on apstrings. produces the output Jello. if (word < "banana") { cout << "Your word. " << word << ". } You should be aware. an expression like letter + "ack" is syntactically legal in C++. 15 Other apstring functions This chapter does not cover all the apstring functions. Technically. which distinguish upper and lower case letters. and isspace. As an exercise.2 and Section 15. . Nevertheless. as shown in the example. This oddity is not as inconvenient as it seems. The output of this code is A. including spaces. which identifies the digits 0 through 9. C++ provides a library of functions that perform this kind of character classification. the C++ habit of converting automatically between types can be useful. There are also isupper and islower.14 Character classification It is often useful to examine a character and test whether it is upper or lower case. 7. and all non-zero values are treated as true.4. if (isalpha(letter)) { cout << "The character " << letter << " is a letter. this sort of thing should not be allowed—integers are not the same thing as boolean values. In order to use these functions. are covered in Section 15. and a few others. but for reasons I don’t even want to think about. you have to include the header file ctype.14. } You might expect the return value from isalpha to be a bool. Other character classification functions include isdigit. Finally. The value 0 is treated as false. c str and substr. The return type should be void. and some non-zero value if it is. newlines.h.7. tabs. cout << letter << endl. Two additional ones. and that modify the string by converting all the letters to upper or lower case. letter = toupper (letter). which identifies all kinds of “white” space. or whether it is a character or a digit." << endl. char letter = ’a’. it is actually an integer that is 0 if the argument is not a letter. because it is legal to use this kind of integer in a conditional. Both take a single character as a parameter and return a (possibly converted) character. there are two functions that convert letters from one case to the other. use the character classification and conversion library to write functions named apstringToUpper and apstringToLower that take a single apstring as a parameter. CHARACTER CLASSIFICATION 73 7. char letter = ’a’. called toupper and tolower. like a character from a string. usually initialized to zero and then incremented. In fact. The decrement operator in C++ is --. STRINGS AND THINGS 7. The increment operator in C++ is ++. .74 CHAPTER 7. concatenate: To join two operands end-to-end. and apstrings. counter: A variable used to count something. that’s why C++ is called C++. traverse: To iterate through all the elements of a set performing a similar operation on each. index: A variable or value used to select one of the members of an ordered set. The objects we have used so far are the cout object provided by the system.16 Glossary object: A collection of related data that comes with a set of functions that operate on it. increment: Increase the value of a variable by one. decrement: Decrease the value of a variable by one. because it is meant to be one better than C. or we may want to access its parts (or instance variables).2 Point objects As a simple example of a compound structure. We will start out with structures and get to classes in Chapter 14 (there is not much difference between them). then. a boolean value. C++ provides two mechanisms for doing that: structures and classes. In mathematical notation.Chapter 8 Structures 8.1 Compound values Most of the data types we have been working with represent a single value—an integer. At one level. apstrings are an example of a compound type. or structure. Depending on what we are doing. 75 . The question. The answer is a struct definition: struct Point { double x. points are often written in parentheses. we may want to treat a compound type as a single thing (or object). is how to group these two values into a compound object. y) indicates the point x units to the right and y units up from the origin. }. a point is two numbers (coordinates) that we treat collectively as a single object. For example. (0. A natural way to represent a point in C++ is with two doubles. 8. with a comma separating the coordinates. It is also useful to be able to create your own compound values. Thus. This ambiguity is useful. and (x. y. 0) indicates the origin. consider the concept of a mathematical point. the characters. a floating-point number. apstrings are different in the sense that they are made up of smaller pieces. length(). Of course.3 Accessing instance variables You can read the values of an instance variable using the same syntax we used to write them: int x = blank.” In this case we assign that value to a local variable named x. you can create variables with that type: Point blank. In this case. STRUCTURES struct definitions appear outside of any function definition. This definition indicates that there are two elements in this structure. It is a common error to leave off the semi-colon at the end of a structure definition. . The first line is a conventional variable declaration: blank has type Point. The expression blank.y = 4. It might seem odd to put a semi-colon after a squiggly-brace. The next two lines initialize the instance variables of the structure. as in fruit. for reasons I will explain a little later. named x and y. but you’ll get used to it.x.76 CHAPTER 8. Notice that there is no conflict between the local variable named x and the instance variable named x. blank. The purpose of dot notation is to identify which variable you are referring to unambiguously. usually at the beginning of the program (after the include statements). that value is a compound object with two named instance variables. even if it is empty. blank.0. Once you have defined the new structure.x = 3. The result of these assignments is shown in the following state diagram: blank x: y: 3 4 As usual.0. 8.x means “go to the object named blank and get the value of x. the name of the variable blank appears outside the box and its value appears inside the box. one difference is that function names are always followed by an argument list. These elements are called instance variables. The “dot notation” used here is similar to the syntax for invoking a function on an object. OPERATIONS ON STRUCTURES 77 You can use dot notation as part of any C++ expression. 4. An initialization looks like this: Point blank = { 3. It can be used in two ways: to initialize the instance variables of a structure or to copy the instance variables from one structure to another.y. double distance = blank. blank = { 3. " << p2.x << ".).4.x * blank. I’m not sure. the second line calculates the value 25. etc. this syntax can be used only in an initialization. It is legal to assign one structure to another. etc. %. The first line outputs 3. but I think the problem is that the compiler doesn’t know what type the right hand side should be. x gets the first value and y gets the second. 4. like mathematical operators ( +. cout << blank.0. 4. The values in squiggly braces get assigned to the instance variables of the structure one by one. the assignment operator does work for structures. cout << p2. it is possible to define the meaning of these operators for the new type.y << endl. Unfortunately. 4. in order.8. If you add a typecast: Point blank.4 Operations on structures Most of the operators we have been using on other types.x << ". not in an assignment statement. . 4. // WRONG !! You might wonder why this perfectly reasonable statement should be illegal.y * blank.) and comparison operators (==.0 }. blank = (Point){ 3. do not work on structures. 4. 8. Actually. For example: Point p1 = { 3.0 }. So the following is illegal. That works.y << endl. On the other hand. >. So in this case.x + blank.0. The output of this program is 3.0. Point p2 = p1. " << blank. so the following are legal. but we won’t do that in this book. Point blank.0 }.0 }.0. 6 Call by value When you pass a structure as an argument. the stack diagram looks like this: main blank x: y: 3 4 printPoint p x: y: 3 4 .x .x << ". we can rewrite the distance function from Section 5. it will output (3. void printPoint (Point p) { cout << "(" << p. " << p. return sqrt (dx*dx + dy*dy). double dy = p2. If you call printPoint (blank). STRUCTURES 8. 4).2 so that it takes two Points as parameters instead of four doubles. Point p2) { double dx = p2.x. double distance (Point p1. there are two variables (one in the caller and one in the callee) that have the same value. } 8.p1. For example. remember that the argument and the parameter are not the same variable.y . when we call printPoint. at least initially. As a second example. Instead.p1.5 Structures as parameters You can pass structures as parameters in the usual way. For example.78 CHAPTER 8.y << ")" << endl. } printPoint takes a point as an argument and outputs it in the standard format.y. reflect (blank). The output of this program is as expected: (3. 4) (4. we have to specify that we want to pass the parameter by reference. p. because the changes we make in reflect will have no effect on the caller. } // WRONG !! But this won’t work. 8. For example. so this isolation between the two functions is appropriate. it would have no effect on blank. CALL BY REFERENCE 79 If printPoint happened to change one of the instance variables of p.y. The most obvious (but incorrect) way to write a reflect function is something like this: void reflect (Point p) { double temp = p.7 Call by reference An alternative parameter-passing mechanism that is available in C++ is called “pass by reference. 3) . Of course.8.7. Instead. We do that by adding an ampersand (&) to the parameter declaration: void reflect (Point& p) { double temp = p. p. p. printPoint (blank). This kind of parameter-passing is called “pass by value” because it is the value of the structure (or other type) that gets passed to the function.” This mechanism makes it possible to pass a structure to a procedure and modify it. you can reflect a point around the 45-degree line by swapping the two coordinates.x.y = temp.x = p.y.y = temp.x.x = p. } Now we can call the function in the usual way: printPoint (blank). there is no reason for printPoint to modify its parameter. p. never at an angle. There are a few possibilities: I could specify the center of the rectangle (two coordinates) and its size (width and height). in C++ programs. In this book I will follow that convention. The usual representation for a reference is a dot with an arrow that points to whatever the reference refers to. Passing structures by reference is more versatile than passing by value. since it is harder to keep track of what gets modified where. Nevertheless. }. The most common choice in existing programs is to specify the upper left corner of the rectangle and the size. The important thing to see in this diagram is that any changes that reflect makes in p will also affect blank. STRUCTURES Here’s how we would draw a stack diagram for this program: main blank x: y: 3 4 4 3 reflect p The parameter p is a reference to the structure named blank.8 Rectangles Now let’s say that we want to create a structure to represent a rectangle.80 CHAPTER 8. The question is. because the callee can modify the structure. To do that in C++. . it is less safe. height. 8. double width. On the other hand. It is also faster. struct Rectangle { Point corner. almost all structures are passed by reference almost all the time. or I could specify one of the corners and the size. because the system does not have to copy the whole structure. or I could specify two opposing corners. what information do I have to provide in order to specify a rectangle? To keep things simple let’s assume that the rectangle will be oriented vertically or horizontally. we will define a structure that contains a Point and two doubles. . This code creates a new Rectangle structure and initializes the instance variables. we can compose the two statements: double x = box.height << endl. This statement is an example of nested structure. cout << box.0. 100.x.0 }.x. I should point out that you can.8. and assign it to the local variable x.0. RECTANGLES 81 Notice that one structure can contain another.8. box corner: x: y: 0 0 100 200 width: height: We can access the width and height in the usual way: box.0. In fact. Rectangle box = { corner. Of course. double x = temp. this sort of thing is quite common. we can use a temporary variable: Point temp = box. together they make up the first of the three values that go into the new Rectangle.0. 0. Alternatively. 200. 100. in fact. 0.corner.0 }. The figure shows the effect of this assignment.” While we are on the subject of composition. 200. In order to access the instance variables of corner. It makes the most sense to read this statement from right to left: “Extract x from the corner of the box.0 }.width += 50.corner. this means that in order to create a Rectangle. create the Point and the Rectangle at the same time: Rectangle box = { { 0. we have to create a Point first: Point corner = { 0. The innermost squiggly braces are the coordinates of the corner point.0.0 }. width/2. double y = box. All the other types we’ve seen can. For example.0. 0.height/2. we could write something like: void swap (int& x.corner.y + box.9 Structures as return types You can write functions that return structures. 8. For example. It would modify x and y and have no effect on i and j. STRUCTURES 8. If the parameters x and y were declared as regular parameters (without the &s). x = y. swap (i.0}. The output of this program is (50. y = temp. 100.corner. int& y) { int temp = x. The output of this program is 97. int j = 9. 200 }. findCenter takes a Rectangle as an argument and returns a Point that contains the coordinates of the center of the Rectangle: Point findCenter (Rectangle& box) { double x = box. we have to pass a box as an argument (notice that it is being passed by reference). Point center = findCenter (box). return result. Point result = {x. too. and assign the return value to a Point variable: Rectangle box = { {0. } We would call this function in the usual way: int i = 7.82 CHAPTER 8. to swap two integers. } To call this function. printPoint (center).10 Passing other types by reference It’s not just structures that can be passed by reference. cout << i << j << endl. j). swap would not work. Draw a stack diagram for this program to convince yourself this is true. For example: . 100). they often try to use an expression as a reference argument.x + box. y}. When people start passing things like integers by reference. though.11. Thus. We can invoke the good function on cin to check what is called the stream state. If not. .11 Getting user input The programs we have written so far are pretty predictable. then the last input statement succeeded. 8. j+1). GETTING USER INPUT 83 int i = 7. It is a little tricky to figure out exactly what kinds of expressions can be passed by reference. int j = 9. Instead. There are many ways to get input. If the user types a valid integer. they do the same thing every time they run. C++ doesn’t report an error. it puts some meaningless value in x and continues. there is a way to check and see if an input statement succeeds. // get input cin >> x. The >> operator causes the program to stop executing and wait for the user to type something. Most of the time.8. To get an integer value from the user: int x. good returns a bool: if true. Fortunately. // prompt the user for input cout << "Enter an integer: ". getting input from the user might look like this: int main () { int x. cin >> x. as well as more exotic mechanisms like voice control and retinal scanning. In the header file iostream. C++ defines an object named cin that handles input in much the same way that cout handles output. including keyboard input. or anything sensible like that. the program converts it into an integer value and stores it in x.h. For now a good rule of thumb is that reference arguments have to be variables. In this text we will consider only keyboard input. and also that the next operation will fail. we want programs that take input from the user and respond accordingly. If the user types something other than an integer. // WRONG!! This is not legal because the expression j+1 is not a variable—it does not occupy a location that the reference can refer to. we know that some previous operation failed. swap (i. mouse movements and button clicks. If not. So. The first argument to getline is cin. which is where the input is coming from. return -1. cout << "What is your name? ". STRUCTURES // check and see if the input statement succeeded if (cin. I avoid using the >> operator altogether. if you wanted the user to type an integer. getline is generally useful for getting input of any kind. This is useful for inputting strings that contain spaces. return 0.h. } // print the value we got from the user cout << x << endl. For example. getline (cin. this statement only takes the first word of input. you can print an error message and ask the user to try again. To convert a string to an integer you can use the atoi function defined in the header file stdlib. cout << name << endl. Because of these problems (inability to handle errors and funny behavior).good() == false) { cout << "That was not an integer. you can convert it to an integer value. We will get to that in Section 15." << endl. Instead. if you run this program and type your full name. } cin can also be used to input an apstring: apstring name. cout << "What is your name? ".4. . name).84 CHAPTER 8. and leaves the rest for the next input statement. Unfortunately. The second argument is the name of the apstring where you want the result to be stored. If so. cout << name << endl. you could input a string and then check to see if it is a valid integer. cin >> name. unless I am reading data from a source that is known to be error-free. apstring name. it will only output your first name. I use a function in the apstring called getline. getline reads the entire line until the user hits Return or Enter. In fact. GLOSSARY 85 8. instance variable: One of the named pieces of data that make up a structure.12 Glossary structure: A collection of data grouped together and treated as a single object. pass by reference: A method of parameter-passing in which the parameter is a reference to the argument variable. reference: A value that indicates or refers to a variable or structure. a reference appears as an arrow. pass by value: A method of parameter-passing in which the value provided as an argument is copied into the corresponding parameter.12. Changes to the parameter also affect the argument variable. but the parameter and the argument occupy distinct locations. . In a state diagram.8. STRUCTURES .86 CHAPTER 8. }. let’s make second a double.14159 }. It seems clear that hour and minute should be integers. so we can record fractions of a second.Chapter 9 More structures 9.14159 87 . The various pieces of information that form a time are the hour. double second. Here’s what the structure definition looks like: struct Time { int hour.1 Time As a second example of a user-defined structure. minute and second. Just to keep things interesting. 59. The first step is to decide what type each instance variable should be. We can create a Time object in the usual way: Time time = { 11. which is used to record the time of day. The state diagram for this object looks like this: time hour: minute: second: 11 59 3. 3. we will define a type called Time. so these will be the instance variables of the structure. minute. 3 Functions for objects In the next few sections.second << endl.hour > time2. For example: void printTime (Time& t) { cout << t. The only result of calling a pure function is the return value. fill-in function: One of the parameters is an “empty” object that gets filled in by the function. For some operations. and it has no side effects like modifying an argument or outputting something. 9. Often returns void.88 CHAPTER 9. } The output of this function. modifier: Takes objects as parameters and modifies some or all of them. 9. 9. The reason that instance variables are so-named is that every instance of a type has a copy of the instance variables for that type.4 Pure functions A function is considered a pure function if the result depends only on the arguments. if we pass time an argument. because every object is an instance (or example) of some type. The return value is either a basic type or a new object created inside the function. Time& time2) { if (time1.hour << ":" << t.hour < time2.hour) return false. is 11:59:3. you will have a choice of several possible interfaces. One example is after. Technically. MORE STRUCTURES The word “instance” is sometimes used when we talk about objects.2 printTime When we define a new type it is a good idea to write function that displays the instance variables in a human-readable form.hour) return true. so you should consider the pros and cons of each of these: pure function: Takes objects and/or basic types as arguments but does not modify the objects.minute << ":" << t. which compares two Times and returns a bool that indicates whether the first operand comes after the second: bool after (Time& time1. I will demonstrate several possible interfaces for functions that operate on objects. if (time1.14159. . this is a type of modifier. On the other hand. Here is a rough draft of this function that is not quite right: Time addTime (Time& t1.0 }.minute = t1. there are cases where the result is not correct. Time& t2) { Time sum. or extra minutes into the hours column.second (Time& t1. 14. sum.second. sum. Time& t2) { t1. When that happens we have to “carry” the extra seconds into the minutes column.hour = sum.second > time2.hour = t1. Time currentTime = { 9. if it is 9:14:30. PURE FUNCTIONS 89 if (time1.second) return true.hour. printTime (doneTime). The output of this program is 12:49:30. you could use addTime to figure out when the bread will be done. sum. breadTime).hour + t2. return false. sum. Time doneTime = addTime (currentTime.minute sum. would you mention that case specifically? A second example is addTime. If currentTime contains the current time and breadTime contains the amount of time it takes for your breadmaker to make bread.9.minute + t2.minute. = t1. } Here is an example of how to use this function. 30. 0. Can you think of one? The problem is that this function does not deal with cases where the number of seconds or minutes adds up to more than 60. For example.minute > time2.hour + t2. Time addTime Time sum. } What is the result of this function if the two times are equal? Does that seem like the appropriate result for this function? If you were writing the documentation for this function. 35.second + t2.minute < time2. if (time1. which calculates the sum of two times. Time breadTime = { 3. .minute) return false.0 }.4. corrected version of this function. = t1. which is correct.second = t1. Here’s a second.second + t2. if (time1.hour.minute. and your breadmaker takes 3 hours and 35 minutes.minute + t2. return sum.second.minute) return true. then you could use addTime to figure out when the bread will be done. sum. except by affecting the return value. These operators provide a concise way to increment and decrement variables. the statement sum. passing by reference usually is more efficient. 9. The advantage of passing by value is that the calling function and the callee are appropriately encapsulated—it is not possible for a change in one to affect the other. MORE STRUCTURES if (sum. it’s starting to get big. The syntax looks like this: void printTime (const Time& time) .second = sum. sometimes you want to modify one of the arguments. Later.0. or at least a warning. } return sum. += and -=.5 const parameters You might have noticed that the parameters for after and addTime are being passed by reference. Time addTime (const Time& t1. so I could just as well have passed them by value. you can declare that it is a constant reference parameter. This code demonstrates two operators we have not seen before.second >= 60. called const.0.minute >= 60) { sum.. . that can make reference parameters just as safe as value parameters.6 Modifiers Of course.second -= 60.0) { sum. you should get a compiler error. it can help remind you. Since these are pure functions.minute += 1. 9.second -= 60.minute -= 60..second .60.. I will suggest an alternate approach to this problem that will be much shorter. If you are writing a function and you do not intend to modify a parameter.hour += 1. is equivalent to sum. Functions that do are called modifiers. there is a nice feature in C++. I’ve included only the first line of the functions. If you tell the compiler that you don’t intend to change a parameter. const Time& t2) . If you try to change one. sum. For example. Furthermore..90 CHAPTER 9. they do not modify the parameters they receive. } if (sum. On the other hand. because it avoids copying the argument. } Although it’s correct. 0.hour += 1. consider increment.minute += 1.second += secs.minute -= 60. time. we have to keep doing it until second is below 60.second -= 60. time. if (time. Compare the following with the previous version: .0) { time. double secs) { time. double secs) { time. which adds a given number of seconds to a Time object. Is this function correct? What happens if the argument secs is much greater than 60? In that case. we could require the caller to provide an “empty” object where addTime can store the result.second += secs. We can do that by replacing the if statements with while statements: void increment (Time& time.0. time.minute >= 60) { time. while (time.second >= 60. Can you think of a solution that does not require iteration? 9. Again. but not very efficient. } while (time.0) { time.second -= 60.7 Fill-in functions Occasionally you will see functions like addTime written with a different interface (different arguments and return values). } if (time.hour += 1.second >= 60. the remainder deals with the special cases we saw before. a rough draft of this function looks like: void increment (Time& time.7. } } This solution is correct. } } The first line performs the basic operation. it is not enough to subtract 60 once. time. FILL-IN FUNCTIONS 91 As an example of a modifier. Instead of creating a new object every time addTime is called.9.minute -= 60.minute += 1.minute >= 60) { time. hour += 1.minute. that only allow pure functions.hour = t1. MORE STRUCTURES void addTimeFill (const Time& t1.8 Which is best? Anything that can be done with modifiers and fill-in functions can also be done with pure functions.minute = t1. called functional programming languages. sum. Notice that the first two parameters can be declared const.minute + t2. I wrote a rough draft (or prototype) that performed the basic calculation. Nevertheless. if (sum.hour. although it can be confusing enough to cause subtle errors. This approach might be called a functional programming style.second = t1. 9. there are programming languages. and cases where functional programs are less efficient. it is worth a spending a little run time to avoid a lot of debugging time. and then tested it on a few cases.minute += 1. sum. Some programmers believe that programs that use pure functions are faster to develop and less error-prone than programs that use modifiers.second + t2. } } One advantage of this approach is that the caller has the option of reusing the same object repeatedly to perform a series of additions. there are times when modifiers are convenient.9 Incremental development versus planning In this chapter I have demonstrated an approach to program development I refer to as rapid prototyping with iterative improvement.second. } if (sum. 9. Time& sum) { sum. .92 CHAPTER 9. I recommend that you write pure functions whenever it is reasonable to do so. In general. and resort to modifiers only if there is a compelling advantage. sum. This can be slightly more efficient. correcting flaws as I found them.minute >= 60) { sum. Although this approach can be effective. it can lead to code that is unnecessarily complicated—since it deals with many special cases—and unreliable— since it is hard to know if you have found all the errors.minute -= 60.0. In fact. but the third cannot.second -= 60. In each case. sum.hour + t2. For the vast majority of programming.second >= 60. const Time& t2.0) { sum. Here is a function that converts a Time into a double: double convertToSeconds (const Time& t) { int minutes = t. that the functions it calls are correct). } Now all we need is a way to convert from a double to a Time object: Time makeTime (double secs) { Time time. as usual.” the minute is the “60’s column”.second.minute * 60. return makeTime (seconds). return time.” When we wrote addTime and increment. Assuming you are convinced. in which a little insight into the problem can make the programming much easier.hour * 60 + t. In this case the insight is that a Time is really a three-digit number in base 60! The second is the “ones column. and the hour is the “3600’s column. secs -= time.0. secs -= time. Thus an alternate approach to the whole problem is to convert Times into doubles and take advantage of the fact that the computer already knows how to do arithmetic with doubles. which is why we had to “carry” from one column to the next. 9. time. we were effectively doing addition in base 60.10. we can use these functions to rewrite addTime: Time addTime (const Time& t1.minute.hour = int (secs / 3600. } You might have to think a bit to convince yourself that the technique I am using to convert from one base to another is correct. return seconds.9.10 Generalization In some ways converting from base 60 to base 10 and back is harder than just dealing with times. our intuition for dealing with times is better.second = secs. Base conversion is more abstract. double seconds = minutes * 60 + t. GENERALIZATION 93 An alternative is high-level planning. As an exercise.0). . and it is much easier to demonstrate that it is correct (assuming. time. const Time& t2) { double seconds = convertToSeconds (t1) + convertToSeconds (t2). time.hour * 3600.minute = int (secs / 60. } This is much shorter than the original version. rewrite increment the same way.0). That’s an algorithm! Similarly. to find the product of n and 9. It is also easier to add more features later. Ironically. subtraction with borrowing. but did not define it carefully. and useful algorithms computer science has produced. Some of the things that people do naturally. and make the investment of writing the conversion functions (convertToSeconds and makeTime). This trick is a general solution for multiplying any single-digit number by 9. If you take the next class in the Computer Science sequence. without difficulty or conscious thought. First. sometimes making a problem harder (more general) makes is easier (fewer special cases. In my opinion. consider something that is not an algorithm. But if you were “lazy. as opposed to a specific solution to a single problem. you will see some of the most interesting. They are mechanical processes in which each step follows from the last according to a simple set of rules. you have written an algorithm. the techniques you learned for addition with carrying. so I will try a couple of approaches. MORE STRUCTURES But if we have the insight to treat times as base 60 numbers. clever. On the other hand. you can write n − 1 as the first digit and 10 − n as the second digit. and more reliable. intellectually challenging. Later in this book. you memorized 100 specific solutions.” you probably cheated by learning a few tricks.11 Algorithms When you write a general solution for a class of problems. and a central part of what we call programming. quite literally. at least not in the form of an algorithm. Using the conversion functions would be easier and more likely to be correct. require no intelligence. fewer opportunities for error). it is embarrassing that humans spend so much time in school learning to execute algorithms that. I mentioned this word in Chapter 1. For example. For example. 9. you will have the opportunity to design simple algorithms for a variety of problems. we get a program that is shorter. are the most difficult to express algorithmically. Understanding natural language is a good example. the process of designing algorithms is interesting. but so far no one has been able to explain how we do it. One of the characteristics of algorithms is that they do not require any intelligence to carry out. imagine subtracting two Times to find the duration between them. and long division are all algorithms. easier to read and debug. It is not easy to define. In effect. We all do it.94 CHAPTER 9. you probably memorized the multiplication table. The naive approach would be to implement subtraction with borrowing. That kind of knowledge is not really algorithmic. When you learned to multiply single-digit numbers. . Data Structures. and usually returns void.. pure function: A function whose result depends only on its parameters. .12. algorithm: A set of instructions for solving a class of problems by a mechanical. functional programming style: A style of program design in which the majority of functions are pure. My cat is an instance of the category “feline things.” Every object is an instance of some type. GLOSSARY 95 9.12 Glossary instance: An example from a category.9. Each structure has its own copy of the instance variables for its type. constant reference parameter: A parameter that is passed by reference but that cannot be modified. and that has so effects other than returning a value. unintelligent process. instance variable: One of the named data items that make up an structure. 96 CHAPTER 9. MORE STRUCTURES . A constructor is a special function that creates new objects and initializes their instance variables. The nice thing about vectors is that they can be made up of any type of element. the second creates a vector of doubles. the constructor takes a single argument. the details of how to do that depend on your programming environment. again. You can create a vector the same way you create other variable types: apvector<int> count. it looks like a combination of a variable declarations and a function call. In fact. It is more common to specify the length of the vector in parentheses: apvector<int> count (4). An apstring is similar to a vector. The type that makes up the vector appears in angle brackets (< and >). and user-defined types like Point and Time. since it is made up of an indexed set of characters. The following figure shows how vectors are represented in state diagrams: 97 . apvector<double> doubleVector. The first line creates a vector of integers named count. including basic types like ints and doubles. which is the size of the new vector. In this case. you have to include the header file apvector. The vector type that appears on the AP exam is called apvector.h. they are not very useful because they create vectors that have no elements (their length is zero). The function we are invoking is an apvector constructor. that’s exactly what it is. Although these statements are legal. In order to use it. The syntax here is a little odd.Chapter 10 Vectors A vector is a set of values where each value is identified by a number (called an index). the elements are not initialized. the indices start at zero. 0). This statement creates a vector of four elements and initializes all of them to zero. 10.98 CHAPTER 10. As with apstrings. The small numbers outside the boxes are the indices used to identify each box. Here is the effect of this code fragment: count 0 1 2 3 7 14 1 -60 . When you allocate a new vector. VECTORS count 0 1 2 3 0 0 0 0 The large numbers inside the boxes are the elements of the vector. count[1] = count[0] * 2.1 Accessing elements The [] operator reads and writes the elements of a vector in much the same way it accesses the characters in an apstring. so count[0] refers to the “zeroeth” element of the vector. count[2]++. count[3] -= 60. All of these are legal assignment statements. apvector<int> count (4. the second is a “fill value. You can use the [] operator anywhere in an expression: count[0] = 7. and count[1] refers to the “oneth” element.” the value that will be assigned to each of the elements. There is another constructor for apvectors that takes two parameters. They could contain any values. which causes a run-time error. Vectors and loops go together like fava beans and a nice Chianti. INCREMENTOR) { BODY } . that depends on that variable. This type of loop is so common that there is an alternate loop statement. outputting the ith element. Each time through the loop we use i as an index into the vector.2. This type of vector traversal is very common. the body of the loop is only executed when i is 0. } This while loop counts from 0 to 4.2 Copying vectors There is one more constructor for apvectors. and inside the loop they do something to that variable. The = operator works on apvectors in pretty much the way you would expect. One of the most common ways to index a vector is with a loop variable. It is a common error to go beyond the bounds of a vector. which is called a copy constructor because it takes one apvector as an argument and creates a new vector that is the same size. the condition fails and the loop terminates. with the same elements. there is no element with the index 4. 2 and 3. and then quits. The program outputs an error message like “Illegal vector index”. when the loop variable i is 4. For example: int i = 0. it is almost never used for apvectors because there is a better alternative: apvector<int> copy = count. like increment it. that expresses it more concisely.3 for loops The loops we have written so far have a number of elements in common. All of them start by initializing a variable. COPYING VECTORS 99 Since elements of this vector are numbered from 0 to 3. The general syntax looks like this: for (INITIALIZER. while (i < 4) { cout << count[i] << endl. called for. 10. Although this syntax is legal. apvector<int> copy (count). You can use any expression as an index. or condition. 10. as long as it has type int.10. they have a test. Thus. i++. CONDITION. 1. It is a good idea to use this value as the upper bound of a loop.4 Vector length There are only a couple of functions you can invoke on an apvector. i++) { cout << count[i] << endl. which is the index of the last element. so they are said to be deterministic. } The last time the body of the loop gets executed. the condition fails and the body is not executed. it is easier to read. When i is equal to count.100 CHAPTER 10. rather than a constant. while (CONDITION) { BODY INCREMENTOR } except that it is more concise and. since it puts all the loop-related statements in one place. i < count. if the size of the vector changes. since it would cause a run-time error. VECTORS This statement is exactly equivalent to INITIALIZER. they will work correctly for any size vector. } 10. determinism is a good thing. One of them is very useful. for (int i = 0. which is a good thing. though: length. it returns the length of the vector (the number of elements). } is equivalent to int i = 0. since . while (i < 4) { cout << count[i] << endl. i++) { cout << count[i] << endl. Usually. the value of i is count. i < 4. you won’t have to go through the program changing all the loops. Not surprisingly.1.5 Random numbers Most computer programs do the same thing every time they are executed. For example: for (int i = 0. 10. That way.length().length() .length(). i++. double y = double(x) / RAND_MAX. cout << x << endl. Making a program truly nondeterministic turns out to be not so easy. which contains a variety of “standard library” functions. A simple way to do that is with the modulus operator. that y will never be equal to upperBound. For some applications.1. As an exercise. The return value from random is an integer between 0 and RAND MAX. we don’t always want to work with gigantic integers.h.0 and 200. though. Games are an obvious example. though. RANDOM NUMBERS 101 we expect the same calculation to yield the same result. on yours. Keep in mind.0 and 1.10. A common way to do that is by dividing by RAND MAX. More often we want to generate integers between 0 and some upper bound. including both end points. we would like the computer to be unpredictable. To see a sample.0. i < 4. One of them is to generate pseudorandom numbers and use them to determine the outcome of the program. between 100. For example: int x = random ().5. they will do. . For example: int x = random (). It is also frequently useful to generate random floating-point values. Of course. Pseudorandom numbers are not truly random in the mathematical sense.0. but for our purposes. It is declared in the header file stdlib. C++ provides a function called random that generates pseudorandom numbers. for example. int y = x % upperBound. This code sets y to a random value between 0. you might want to think about how to generate a random floating-point value in a given range. but different. } On my machine I got the following output: 1804289383 846930886 1681692777 1714636915 You will probably get something similar. including both end points. the only possible values for y are between 0 and upperBound . Since y is the remainder when x is divided by upperBound. but there are ways to make it at least seem nondeterministic. i++) { int x = random (). run this loop: for (int i = 0. Each time you call random you get a different randomly-generated number. where RAND MAX is a large number (about 2 billion on my computer) also defined in the header file. hence the name. The following code generates a vector and outputs it: int numValues = 20. i++) { vec[i] = random () % upperBound. } return vec. That means that each value in the range should be equally likely. provided that we generate a large number of values. . To test this function.” of course. we declare the parameter const. i++) { cout << vec[i] << " ". It’s always a good idea to start with a manageable number. and then increase it later. i<vec. apvector<int> randomVector (int n. for (int i = 0. In the next few sections. By “large number. printVector (vector). i<vec. I mean 20.6 Statistics The numbers generated by random are supposed to be distributed uniformly. since it makes it unnecessary to copy the vector. and fills it with random values between 0 and upperBound-1.102 CHAPTER 10. The following function takes a single argument.length(). int upperBound = 10. } The return type is apvector<int>. to help with debugging. we will write programs that generate a sequence of random numbers and check whether this property holds true. it should be roughly the same for all values. 10. the size of the vector.length(). VECTORS 10. It allocates a new vector of ints. apvector<int> vector = randomVector (numValues. upperBound). int upperBound) { apvector<int> vec (n). Since printVector does not modify the vector. If we count the number of times each value appears. } } Notice that it is legal to pass apvectors by reference.7 Vector of random numbers The first step is to generate a large number of random values and store them in a vector. which means that this function returns a vector of integers. In fact it is quite common. void printVector (const apvector<int>& vec) { for (int i = 0. it is convenient to have a function that outputs the contents of a vector. but as you gain experience you will have a better idea. With so few values. • A counter that keeps track of how many elements pass the test. and the numbers 4 and 8 never appear at all. This approach is sometimes called bottom-up design. it is not always obvious what sort of things are easy to write. for (int i=0. we expect each digit to appear the same number of times—twice each.length().8. COUNTING 103 On my machine the output is 3 6 7 5 3 5 6 2 9 1 2 7 0 9 3 6 0 6 2 6 which is pretty random-looking. Of course. I have a function in mind called howMany that counts the number of elements in a vector that equal a given value. Do these results mean the values are not really uniform? It’s hard to tell. int value) { int count = 0. int howMany (const apvector<int>& vec. If these numbers are really random. To test this theory. You can think of this program as an example of a pattern called “traverse and count. i< vec. } . The parameters are the vector and the integer value we are looking for. but a good approach is to look for subproblems that fit a pattern you have seen before. • A test that you can apply to each element in the container. we’ll write some programs that count the number of times each value appears.” The elements of this pattern are: • A set or container that can be traversed. The return value is the number of times the value appears. Also. In fact. Your results may differ. } return count. and then see what happens when we increase numValues. like a string or a vector. Then you can combine them into a solution. 10. the number 6 appears five times.10. and that might turn out to be useful. the chances are slim that we would get exactly what we expect. Back in Section 7. the outcome should be more predictable.9 we looked at a loop that traversed a string and counted the number of times a given letter appeared. it is not easy to know ahead of time which functions are likely to be useful. But as the number of values increases.8 Counting A good approach to problems like this is to think of simple functions that are easy to write. i++) { if (vec[i] == value) count++. In this case. i) << endl.104 CHAPTER 10.000 we get the following: value 0 1 2 3 4 5 6 7 howMany 10130 10072 9990 9842 10174 9930 10059 9954 . apvector<int> vector = randomVector (numValues. upperBound). for (int i = 0. but you should be aware that a variable declared inside a loop only exists inside the loop. it is hard to tell if the digits are really appearing equally often. in order. If we increase numValues to 100. and we are interested in seeing how many times each value appears. If you try to refer to i later. cout << "value\thowMany". The result is: value 0 1 2 3 4 5 6 7 8 9 howMany 2 1 3 3 0 2 5 2 0 2 Again.9 Checking the other values howMany only counts the occurrences of a particular value. We can solve that problem with a loop: int numValues = 20. you will get a compiler error. } Notice that it is legal to declare a variable inside a for statement. This syntax is sometimes convenient. This code uses the loop variable as an argument to howMany. i<upperBound. int upperBound = 10. in order to check each value between 0 and 9. VECTORS 10. i++) { cout << i << ’\t’ << howMany (vector. apvector<int> vector = randomVector (numValues. for (int i = 0. But that would require a lot of typing. 10. Every time it calls howMany. we can use the value from the vector as an index into the histogram. We could create 10 integer variables with names like howManyOnes. .10 A histogram It is often useful to take the data from the previous tables and store them for later access.10. specifying which location I should store the result in. 0). 10. and it would be a real pain later if we decided to change the range of values. it is an argument to howMany.10. For each value in the vector we could find the corresponding counter and increment it. rather than ten different names. i++) { int count = howMany (vector. the number of appearances is within about 1% of the expected value (10.11 A single-pass solution Although this code works. What we need is a way to store 10 integers. rather than just print them. That way we can create all ten storage locations at once and we can access them using indices. it is not as efficient as it could be. histogram[i] = count. int upperBound = 10. Here’s what that looks like: apvector<int> histogram (upperBound. upperBound). so we conclude that the random numbers are probably uniform. apvector<int> histogram (upperBound). } I called the vector histogram because that’s a statistical term for a vector of numbers that counts the number of appearances of a range of values. The tricky thing here is that I am using the loop variable in two different ways. In other words. A HISTOGRAM 105 8 9 9891 9958 In each case. i<upperBound. A better solution is to use a vector with length 10. First. etc.000). In this example we have to traverse the vector ten times! It would be better to make a single pass through the vector. howManyTwos. it traverses the entire vector. Here’s how: int numValues = 100000. specifying which value I am interested in. i). it is an index into the histogram. Second. 10. it is often helpful to see the same sequence over and over. when you make a change to the program you can compare the output before and after the change. The [] operator selects elements of a vector. While you are debugging. A common way to do that is to use a library function like gettimeofday to generate something reasonably unpredictable and unrepeatable. element: One of the values in a vector. index: An integer variable or value used to indicate an element of a vector. VECTORS for (int i = 0. like the number of milliseconds since the last second tick. when we use the increment operator (++) inside the loop. i<numValues. by default. you want to see a different random sequence every time the program runs. histogram[index]++.13 Glossary vector: A named collection of values. like games. The starting place is called a seed. It takes a single argument. The details of how to do that depend on your development environment. i++) { int index = vector[i].106 CHAPTER 10. } The first line initializes the elements of the histogram to zeroes. . 10. you can use the srand function. we know we are starting from zero. C++ uses the same seed every time you run the program. That way. and use that number as a seed. That way. Forgetting to initialize counters is a common error.12 Random seeds If you have run the code in this chapter a few times. As an exercise. encapsulate this code in a function called histogram that takes a vector and the range of values in the vector (in this case 0 through 10). That’s not very random! One of the properties of pseudorandom number generators is that if they start from the same place they will generate the same sequence of values. which is an integer between 0 and RAND MAX. where all the values have the same type. you might have noticed that you are getting the same “random” values every time. and that returns a histogram of the values in the vector. If you want to choose a different seed for the random number generator. For many applications. and each value is identified by an index. . histogram: A vector of integers where each integer counts the number of values that fall into a certain range. seed: A value used to initialize a random number sequence. pseudorandom: A sequence of numbers that appear to be random. deterministic: A program that does the same thing every time it is run. bottom-up design: A method of program development that starts by writing small. useful functions and then assembling them into larger solutions. GLOSSARY 107 constructor: A special function that creates a new object and initializes its instance variables. but which are actually the product of a deterministic computation. Using the same seed should yield the same sequence of values.13.10. VECTORS .108 CHAPTER 10. the Point and Rectangle structures correspond to the mathematical concept of a point and a rectangle. So far. and the operations we defined correspond to the sorts of things people do with recorded times. the Time structure we defined in Chapter 9 obviously corresponds to the way people record the time of day. With some examination. Each structure definition corresponds to some object or concept in the real world. For example. these features are not necessary. Member function differ from the other functions we have written in two ways: 109 . where most of the functions operate on specific kinds of structures (or objecs). but we have already seen some features of it: 1. For example. This observation is the motivation for member functions. Strictly speaking. It’s not easy to define object-oriented programming. though. For the most part they provide an alternate syntax for doing things we have already done. Similarly. in the Time program. there is no obvious connection between the structure definition and the function definitions that follow. it is apparent that every function takes at least one Time structure as a parameter. we have not taken advantage of the features C++ provides to support object-oriented programming. which means that it provides features that support object-oriented programming. and the functions that operate on that structure correspond to the ways real-world objects interact. 2. but in many cases the alternate syntax is more concise and more accurately conveys the structure of the program.Chapter 11 Member functions 11. Programs are made up of a collection of structure definitions and function definitions.1 Objects and functions C++ is generally considered an object-oriented programming language. One thing that makes life a little difficult is that this is actually a pointer to a structure. we no longer have a parameter named time.minute << ":" << time. in other words. double second. Time currentTime = { 9. If you are comfortable converting from one form to another. We can refer to the current object using the C++ keyword this. MEMBER FUNCTIONS 1.” or “sending a message to an object. To make printTime into a member function. Instead of passing an object as an argument. As a result. The next step is to eliminate the parameter. in order to make the relationship between the structure and the function explicit. we have a current object. 30. anything that can be done with a member function can also be done with a nonmember function (sometimes called a free-standing function).110 CHAPTER 11. you will be able to choose the best form for whatever you are doing. we invoke it on an object. Instead. 11. together they indicate that this is a function named print that can be invoked on a Time structure. we will take the functions from Chapter 9 and transform them into member functions. we had to pass a Time object as a parameter. the first step is to change the name of the function from printTime to Time::print. .hour << ":" << time. 14. inside the function.0 }. In the next few sections. } To call this function. But sometimes there is an advantage to one over the other. People sometimes describe this process as “performing an operation on an object.2 print In Chapter 9 we defined a structure named Time and wrote a function named printTime struct Time { int hour. The :: operator separates the name of the structure from the name of the function. minute. The function is declared inside the struct definition. you can do it just by following a sequence of steps. rather than just call it. A pointer is similar to a reference. printTime (currentTime). which is the object the function is invoked on. One thing you should realize is that this transformation is purely mechanical. we are going to invoke the function on an object. rather than a structure itself. void printTime (const Time& time) { cout << time. }.second << endl. As I said. When we call the function.” 2. C++ knows that it must be referring to the current object. but notice that the output statement itself did not change at all.hour << ":" << time.3 Implicit variable access Actually. This definition is sometimes called the implementation of the function. In order to invoke the new version of print. IMPLICIT VARIABLE ACCESS 111 but I don’t want to go into the details of using pointers yet. The declaration describes the interface of the function. you are making a promise to the compiler that you will. We don’t really need to create a local variable in order to refer to the instance variables of the current object. and the type of the return value. we have to invoke it on a Time object: Time currentTime = { 9. which converts a structure pointer into a structure. A function declaration looks just like the first line of the function definition. provide a definition for the function. since it contains the details of how the function works. the number and types of the arguments. at some point later on in the program. 11. }.second << endl. that is. 14.print (). In the following function. the new version of Time::print is more complicated than it needs to be. If the function refers to hour. 30.minute << ":" << time. except that it has a semi-colon at the end. void Time::print (). cout << time. } The first two lines of this function changed quite a bit as we transformed it into a member function. currentTime. The only pointer operation we need for now is the * operator. all by themselves with no dot notation. double second. When you declare a function. minute. minute. or provide a definition that has an interface different from what you promised.3. we use it to assign the value of this to a local variable named time: void Time::print () { Time time = *this.11. If you omit the definition. or second. The last step of the transformation process is that we have to declare the new function inside the structure definition: struct Time { int hour. So we could have written: .0 }. the compiler will complain. 0) { second -= 60. we have to invoke it on a Time object: Time currentTime = { 9. hour += 1. The output of this program is 9:22:50. we are going to transform one of the parameters into the implicit parameter called this. 11. } } By the way.0). If you didn’t do it back in Chapter 9. Then we can go through the function and make all the variable accesses implicit. } This kind of variable access is called “implicit” because the name of the object does not appear explicitly. And again. currentTime. remember that this is not the most efficient implementation of this function.4 Another example Let’s convert increment to a member function. . void Time::increment (double secs) { second += secs. 14. 30. } while (minute >= 60) { minute -= 60.0 }. }.increment (500. MEMBER FUNCTIONS void Time::print () { cout << hour << ":" << minute << ":" << second << endl. void Time::increment (double secs). Again. we can just copy the first line into the structure definition: struct Time { int hour. To declare the function. void Time::print (). to call it. minute += 1.print (). Features like this are one reason member functions are often more concise than nonmember functions.0. currentTime. minute. double second. you should write a more efficient version now. while (second >= 60.0.112 CHAPTER 11. } It is straightforward to convert this to a member function: double Time::convertToSeconds () const { int minutes = hour * 60 + minute. The answer. Instead. For example.second.minute) return false. return seconds. Inside the function.5. double seconds = minutes * 60 + second. and we can’t make both of them implicit. } To invoke this function: . YET ANOTHER EXAMPLE 113 11. there are some oddities. if (second > time2. if (hour < time2. not just one. return seconds. if (minute < time2.hour) return true. double seconds = minutes * 60 + time. bool Time::after (const Time& time2) const { if (hour > time2. 11. The print function in the previous section should also declare that the implicit parameter is const. after operates on two Time structures. if (minute > time2.5 Yet another example The original version of convertToSeconds looked like this: double convertToSeconds (const Time& time) { int minutes = time.second) return true. is after the parameter list (which is empty in this case). } The interesting thing here is that the implicit parameter should be declared const.minute) return true.hour) return false. we have to invoke the function on one of them and pass the other as an argument. we can refer to one of the them implicitly. since we don’t modify it in this function.11. but to access the instance variables of the other we continue to use dot notation.minute. But it is not obvious where we should put information about a parameter that doesn’t exist.6 A more complicated example Although the process of transforming functions into member functions is mechanical.hour * 60 + time. return false. as you can see in the example. secs -= minute * 60. and we don’t have to return anything.0. second = secs.0. minute = int (secs / 60.. } Of course. return time. MEMBER FUNCTIONS if (doneTime.after (currentTime)) { cout << "The bread will be done after it starts. } You can almost read the invocation like English: “If the done-time is after the current-time.0). secs -= time. notice that we don’t have to create a new time object.0. The arguments haven’t changed.hour * 3600. We can refer to the new object—the one we are constructing—using the keyword this.second = secs. } First.0).0). notice that the constructor has the same name as the class. To invoke the constructor. time. These functions are called constructors and the syntax looks like this: Time::Time (double secs) { hour = int (secs / 3600. time..0. then. secs -= hour * 3600. you use syntax that is a cross between a variable declaration and a function call: Time time (seconds). functions like makeTime are so common that there is a special function syntax for them." << endl. secs -= time. In fact. we need to be able to create new objects.0). or implicitly as shown here. time. and no return type.hour = int (secs / 3600.7 Constructors Another function we wrote in Chapter 9 was makeTime: Time makeTime (double secs) { Time time. minute and second.114 CHAPTER 11. though.minute = int (secs / 60. . When we write values to hour. the compiler knows we are referring to the instance variables of the new object. Both of these steps are handled automatically. for every new type. Second.” 11.minute * 60. we use the same funny syntax as before. The result is assigned to the variable time. and not both in the same program.9 One last example The final example we’ll look at is addTime: . then you have to use the constructor to initialize all new structures of that type. } To invoke this constructor.11.8 Initialize or construct? Earlier we declared and initialized some Time structures using squiggly-braces: Time currentTime = { 9. Fortunately. Then.” as long as they take different parameters. For example. minute = m. using constructors. 30. and that assigns the values of the parameters to the instance variables: Time::Time (int h. 0. the C++ compiler requires that you use one or the other. Time breadTime = { 3.0 }. when we initialize a new object the compiler will try to find a constructor that takes the appropriate parameters. double s) { hour = h. it is common to have a constructor that takes one parameter for each instance variable. we have a different way to declare and initialize: Time time (seconds). 11. These two functions represent different programming styles. it is legal to overload constructors in the same way we overloaded functions. 11. passing the value of seconds as an argument. second = s. Now. Maybe for that reason. int m. 30. 14.8. In other words. 14. 35. except that the arguments have to be two integers and a double: Time currentTime (9. The system allocates space for the new object and the constructor initializes its instance variables. and different points in the history of C++.0). The alternate syntax using squiggly-braces is no longer allowed.0 }. INITIALIZE OR CONSTRUCT? 115 This statement declares that the variable time has type Time. there can be more than one constructor with the same “name. If you define a constructor for a structure. and it invokes the constructor we just wrote. 116 CHAPTER 11.cpp. Change the name from addTime to Time::add. you have to change it in two places. 3. and it contains the following: struct Time { // instance variables int hour. Header files usually have the same name as the implementation file. Here’s the result: Time Time::add (const Time& t2) const { double seconds = convertToSeconds () + t2. Any time you change the interface to a function. return time. the compiler assumes that we want to invoke the function on the current object. There is a reason for the hassle. even if it is a small change like declaring one of the parameters const. the second invocation acts on t2. const Time& t2) { double seconds = convertToSeconds (t1) + convertToSeconds (t2). Replace the first parameter with an implicit parameter. the first invocation acts on this. which is that it is now possible to separate the structure definition and the functions into two files: the header file. though.h.10 Header files It might seem like a nuisance to declare functions inside the structure definition and then define the functions later. return makeTime (seconds). MEMBER FUNCTIONS Time addTime2 (const Time& t1. 11. double second. minute. which contains the structure definition.convertToSeconds (). including: 1. 2. } The first time we invoke convertToSeconds. which contains the functions.h instead of . Thus. Time time (seconds). } We have to make several changes to this function. The next line of the function invokes the constructor that takes a single double as a parameter. which should be declared const. . Replace the use of makeTime with a constructor invocation. the header file is called Time. For the example we have been looking at. but with the suffix . there is no apparent object! Inside a member function. and the implementation file. the last line returns the resulting object. cpp appear in the same order as the declarations in Time.h" Time::Time (int h.. Time Time::add (const Time& t2) const ... int min. Finally. double convertToSeconds () const. although it is not necessary. // modifiers void increment (double secs). double secs). int m. Time. That way. .h. Time (double secs).. // functions void print () const. In this case the definitions in Time. it is necessary to include the header file using an include statement.cpp contains the function main along with any functions we want that are not members of the Time structure (in this case there are none): #include <iostream.11.h> . The compiler knows that we are declaring functions that are members of the Time structure. }. On the other hand.. it knows enough about the structure to check the code and catch errors.. double s) Time::Time (double secs) . HEADER FILES 117 // constructors Time (int hour. Time add (const Time& t2) const. double Time::convertToSeconds () const .. while the compiler is reading the function definitions.cpp contains the definitions of the member functions (I have elided the function bodies to save space): #include <iostream.... void Time::print () const . Notice that in the structure definition I don’t really have to include the prefix Time:: at the beginning of every function name. main.h> #include "Time.. void Time::increment (double secs) .. bool after (const Time& time2) const... bool Time::after (const Time& time2) const .10. the number of interactions between components grows and quickly becomes unmanageable. When you compile your program. By separating the definition of Time from main. In fact.h> iostream. 0.0).increment (500.0). Time breadTime (3. For small programs like the ones in this book. main.cpp has to include the header file. currentTime. The details of how to do this depend on your programming environment.print (). It may not be obvious why it is useful to break such a small program into three pieces. especially since it explains one of the statements that appeared in the first program we wrote: #include <iostream.add (breadTime).0). } } Again. It is often useful to minimize these interactions by separating modules like Time. Time doneTime = currentTime. separate compilation can save a lot of time. you make is easy to include the Time structure in another program. doneTime.print ()." << endl. Managing interactions: As systems become large. most of the advantages come when we are working with larger programs: Reuse: Once you have written a structure like Time.118 CHAPTER 11. .after (currentTime)) { cout << "The bread will be done after it starts. 30. there is no great advantage to splitting up programs. you might find it useful in more than one program. currentTime.cpp from the programs that use them. 35. since you usually need to compile only a few files at a time. if (doneTime. 14. As the program gets large. MEMBER FUNCTIONS #include "Time. But it is good for you to know about this feature. you need the information in that header file.cpp. Separate compilation: Separate files can be compiled separately and then linked into a single program later.h" void main () { Time currentTime (9.h is the header file that contains declarations for cin and cout and the functions that operate on them. since we do not cover pointers in this book. GLOSSARY 119 The implementations of those functions are stored in a library. including the number and types of the parameters and the type of the return value.11. Declarations of member functions appear inside structure definitions even if the definitions appear outside. Also called a “free-standing” function. 11. so there is no reason to recompile it. Inside the member function. or the details of how a function works. invoke: To call a function “on” an object. current object: The object on which a member function is invoked. function declaration: A statement that declares the interface to a function without providing the body. nonmember function: A function that is not a member of any structure definition.11 Glossary member function: A function that operates on an object that is passed as an implicit parameter named this. which makes it difficult to use. sometimes called the “Standard Library” that gets linked to your program automatically. in order to pass the object as an implicit parameter. we can refer to the current object implicitly. For the most part the library doesn’t change. The nice thing is that you don’t have to recompile the library every time you compile a program. or by using the keyword this. constructor: A special function that initializes the instance variables of a newly-created object. interface: A description of how a function is used. implementation: The body of a function.11. this is a pointer. this: A keyword that refers to the current object. . 120 CHAPTER 11. MEMBER FUNCTIONS . containing things like "Spade" for suits and "Queen" for ranks. One possibility is apstrings. now would be a good time to get a deck. and having learned about vectors and objects. you should not be surprised to learn that you can have vectors of objects. you can have vectors that contain vectors. 8. 4.Chapter 12 Vectors of Objects 12. 121 . 10. or within another if statement. the rank of the Ace may be higher than King or lower than 2. In fact. 6. etc. 7. Hearts. each of which belongs to one of four suits and one of 13 ranks. 2. and so on. 5.1 Composition By now we have seen several examples of composition (the ability to combine language features in a variety of arrangements). Jack. 3. There are 52 cards in a deck. Diamonds and Clubs (in descending order in Bridge). It is not as obvious what type the instance variables should be. you can have objects that contain objects. The suits are Spades. you can also have objects that contain vectors (as instance variables). Another example is the nested structure of statements: you can put an if statement within a while loop. Depending on what game you are playing.2 Card objects If you are not familiar with common playing cards. using Card objects as a case study. or else this chapter might not make much sense. it is pretty obvious what the instance variables should be: rank and suit. Queen and King. In the next two chapters we will look at some examples of these combinations. 12. The ranks are Ace. If we want to define a new object to represent a playing card. 9. Having seen this pattern. One of the first examples we saw was using a function invocation as part of an expression. One problem with this implementation is that it would not be easy to compare cards to see which had higher rank or suit. What a computer scientist means by “encode” is something like “define a mapping between a sequence of numbers and the things I want to represent. the suit and rank of the card. They are part of the program design.” For example. or translate into a secret code. The class definition for the Card type looks like this: struct Card { int suit. It takes two parameters. rank = r. Card::Card () { suit = 0. } Card::Card (int s. By “encode. Spades Hearts Diamonds Clubs → → → → 3 2 1 0 The symbol → is mathematical notation for “maps to.122 CHAPTER 12. which is to encrypt. The first constructor takes no arguments and initializes the instance variables to a useless value (the zero of clubs). and for face cards: Jack Queen King → → → 11 12 13 The reason I am using mathematical notation for these mappings is that they are not part of the C++ program. each of the numerical ranks maps to the corresponding integer. The mapping for ranks is fairly obvious. The second constructor is more useful. but they never appear explicitly in the code. rank. }. rank = 0. . } There are two constructors for Cards. so we can compare suits by comparing integers. VECTORS OF OBJECTS An alternative is to use integers to encode the ranks and suits.” The obvious feature of this mapping is that the suits map to integers in order. Card (). int r). int r) { suit = s. Card (int s.” I do not mean what some people think. You can tell that they are constructors because they have no return type and their name is the same as the name of the structure. 12.cpp contains a template that allows the compiler to create vectors of various kinds. you are likely to get a long stream of error messages.3 The printCard function When you create a new type. "Spades". 12. A state diagram for this vector looks like this: 1 apvectors are a little different from apstrings in this regard. suits[0] suits[1] suits[2] suits[3] = = = = "Clubs". 0 represents the suit Clubs. You can create a vector of apstrings the same way you create an vector of other types: apvector<apstring> suits (4). To initialize the elements of the vector. naturally. "Diamonds". If you use a vector of apstrings. THE PRINTCARD FUNCTION 123 The following code creates an object named threeOfClubs that represents the 3 of Clubs: Card threeOfClubs (0. “human-readable” means that we have to map the internal representation of the rank and suit onto words. you will have to include the header files for both1 . In the case of Card objects. we can use a series of assignment statements. As a result. in order to use apvectors and apstrings. The file apvector. The second step is often to write a function that prints the object in human-readable form. the first step is usually to declare the instance variables and write constructors. I hope this footnote helps you avoid an unpleasant surprise. but the details in your development environment may differ. you do not have to compile apvector. the second. Of course. represents the rank 3. "Hearts". . A natural way to do that is with a vector of apstrings. if you do. the compiler generates code to support that kind of vector.h. 3). The first argument. The first time you use a vector of integers.cpp at all! Unfortunately.3. the compiler generates different code to handle that kind of vector. it is usually sufficient to include the header file apvector. ranks[6] = "6". suits[2] = "Hearts". ranks[12] = "Queen". ranks[10] = "10". ranks[11] = "Jack". VECTORS OF OBJECTS suits "Clubs" "Diamonds" "Hearts" "Spades" We can build a similar vector to decode the ranks. ranks[9] = "9". Finally. ranks[1] = "Ace". } The expression suits[suit] means “use the instance variable suit from the current object as an index into the vector named suits. ranks[7] = "7". cout << ranks[rank] << " of " << suits[suit] << endl. ranks[4] = "4". suits[1] = "Diamonds". suits[0] = "Clubs". ranks[2] = "2".124 CHAPTER 12. Then we can select the appropriate elements using the suit and rank as indices. ranks[3] = "3".” . apvector<apstring> ranks (14). ranks[13] = "King". we can write a function called print that outputs the card on which it is invoked: void Card::print () const { apvector<apstring> suits (4). ranks[8] = "8". and select the appropriate string. ranks[5] = "5". suits[3] = "Spades". From the point of view of the user. it looks like this: bool Card::equals (const Card& c2) const { return (rank == c2. It is also clear that there have to be two Cards as parameters. if (card1. We’ll call it equals. Unfortunately.4 The equals function In order for two cards to be equal. The output of this code Card card (1. But we have one more choice: should equals be a member function or a free-standing function? As a member function. } This method of invocation always seems strange to me when the function is something like equals. By leaving an unused element at the beginning of the vector.rank && suit == c2.12. Card card2 (1. we get an encoding where 2 maps to “2”. 11). it is often helpful for the programmer if the mappings are easy to remember.print ()." << endl. 12. card. etc. On the other hand. } To use this function. it doesn’t matter what the encoding is. is Jack of Diamonds. That’s because the only valid ranks are 1–13. THE EQUALS FUNCTION 125 Because print is a Card member function. It is clear that the return value from equals should be a boolean that indicates whether the cards are the same. 11). in which the two arguments are symmetric. You might notice that we are not using the zeroeth element of the ranks vector. 11). we have to invoke it on one of the cards and pass the other as an argument: Card card1 (1.equals(card2)) { cout << "Yup. 3 maps to “3”.suit). but we will not cover that in this book. they have to have the same rank and the same suit. that’s the same card. the == operator does not work for user-defined types like Card. since all input and output uses human-readable formats.4. What I . so we have to write a function that compares two cards. It is also possible to write a new definition for the == operator. it can refer to the instance variables of the current object implicitly (without having to use dot notation to specify the object). Just as we did for the == operator. which is why we cannot compare apples and oranges. For example. As another example. which means that you can compare any two elements and tell which is bigger. if (equals (card1. the bool type is unordered.rank == c2.rank && c1.suit == c2.126 CHAPTER 12. } When we call this version of the function.5 The isGreater function For basic types like int and double. it comes sorted with all the Clubs together. rank or suit.suit)." << endl. but the other has a higher suit. there are comparison operators that compare values and determine when one is greater or less than another. we have to decide which is more important. I think it looks better to rewrite equals as a nonmember function: bool equals (const Card& c1. the integers and the floatingpoint numbers are totally ordered. For example. I know that the 3 of Clubs is higher than the 2 of Clubs because it has higher rank. the arguments appear side-by-side in a way that makes more logical sense. this is a matter of taste. const Card& c2) { return (c1. . I will say that suit is more important. } Of course. 12. the choice is completely arbitrary. VECTORS OF OBJECTS mean by symmetric is that it does not matter whether I ask “Is A equal to B?” or “Is B equal to A?” In this case. we will use this function to sort a deck of cards. For the sake of choosing. that’s the same card. To be honest. and so on. and the 3 of Diamonds is higher than the 3 of Clubs because it has higher suit. But which is better. card2)) { cout << "Yup. Later. which means that there is no meaningful way to say that one element is bigger than another. so that you can choose the interface that works best depending on the circumstance. the fruits are unordered. the 3 of Clubs or the 2 of Diamonds? One has a higher rank. Some sets are unordered. Some sets are totally ordered. followed by all the Diamonds. For example. to me at least. which means that sometimes we can compare cards and sometimes not. These operators (< and > and the others) don’t work for user-defined types. My point here is that you should be comfortable writing both member and nonmember functions. The set of playing cards is partially ordered. we will write a comparison function that plays the role of the > operator. we cannot say that true is greater than false. because when you buy a new deck of cards. In order to make cards comparable. print (). (suit < c2. 12.. if (card1. the arguments are not symmetric. aces are less than deuces (2s). it is obvious from the syntax which of the two possible questions we are asking: Card card1 (2.print (). as they are in most card games.isGreater (card2)) { card1.suit) return true.rank) return true. fix it so that aces are ranked higher than Kings. Card card2 (1.6 Vectors of cards The reason I chose Cards as the objects for this chapter is that there is an obvious use for a vector of cards—a deck. Here is some code that creates a new deck of 52 cards: . } Then when we invoke it. // if the ranks are also equal. 11).12.suit) return false. // if the suits are equal. 11). Again.. } You can almost read it like English: “If card1 isGreater card2 .” The output of this program is Jack of Hearts is greater than Jack of Diamonds According to isGreater. and again we have to choose between a member function and a nonmember function..rank) return false. we can write isGreater. check the ranks if (rank > c2. card2. if (rank < c2. return false return false. This time. the arguments (two Cards) and the return type (boolean) are obvious. As an exercise. cout << "is greater than" << endl. VECTORS OF CARDS 127 With that decided.6. Since the outer loop iterates 4 times. Of course. the total number of times the body is executed is 52 (13 times 4). but in others they could contain any possible value. as shown in the figure. it makes more sense to build a deck with 52 different cards in it. In some environments. suit <= 3. for (int suit = 0. One way to initialize them would be to pass a Card as a second argument to the constructor: Card aceOfSpades (3. apvector<Card> deck (52. The expression deck[i].suit means “the suit of the ith card in the deck”. like a special deck for a magic trick. deck[i]. This code builds a deck with 52 identical cards. aceOfSpades). } } I used the variable i to keep track of where in the deck the next card should go. Here is the state diagram for this object: deck 0 suit: rank: 1 2 51 0 0 suit: rank: 0 0 suit: rank: 0 0 suit: rank: 0 0 The three dots represent the 48 cards I didn’t feel like drawing. suit++) { for (int rank = 1. int i = 0. they will get initialized to zero. The outer loop enumerates the suits. from 1 to 13. Keep in mind that we haven’t initialized the instance variables of the cards yet. . Notice that we can compose the syntax for selecting an element from an array (the [] operator) with the syntax for selecting an instance variable from an object (the dot operator). and the inner loop iterates 13 times. rank <= 13. To do that we use a nested loop.suit = suit. For each suit. VECTORS OF OBJECTS apvector<Card> deck (52). i++. rank++) { deck[i]. from 0 to 3. 1). the inner loop enumerates the ranks.rank = rank.128 CHAPTER 12. print (). it involves traversing the deck and comparing each card to the one we are looking for. so the following function should be familiar: void printDeck (const apvector<Card>& deck) { for (int i = 0.7 The printDeck function Whenever you are working with vectors. 12. We have seen the pattern for traversing a vector several times. It may not be obvious why this function would be useful. a linear search and a bisection search. int find (const Card& card. i < deck.length(). The function returns as soon as it discovers the card.7. Inside the loop. . which saved me from having to write and debug it twice.12. which searches through a vector of Cards to see whether it contains a certain card. we return -1. we compare each element of the deck to card. 12. const apvector<Card>& deck) { for (int i = 0.length(). If it is not in the deck. card)) return i. i++) { deck[i]. i < deck. } } By now it should come as no surprise that we can compose the syntax for vector access with the syntax for invoking a function. encapsulate this deck-building code in a function called buildDeck that takes no parameters and that returns a fully-populated vector of Cards. If we find it we return the index where the card appears. If the loop terminates without finding the card. } return -1. In fact. which means that we do not have to traverse the entire deck if we find the card we are looking for. we know the card is not in the deck and return -1.8 Searching The next function I want to write is find. Since deck has type apvector<Card>. } The loop here is exactly the same as the loop in printDeck. it is legal to invoke print on deck[i]. Linear search is the more obvious of the two. THE PRINTDECK FUNCTION 129 As an exercise. I copied it. when I wrote the program. i++) { if (equals (deck[i]. but it gives me a chance to demonstrate two ways to go searching for things. Therefore. an element of deck has type Card. it is convenient to have a function that prints the contents of the vector. 5. The output of this code is I found the card at index = 17 12. since otherwise there is no way to be certain the card we want is not there. 1. and call it mid. flip to somewhere earlier in the dictionary and go to step 2. . int index = card.130 CHAPTER 12. cout << "I found the card at index = " << index << endl. If you ever get to the point where there are two adjacent words on the page and your word comes between them. The trick is to write a function called findBisect that takes two indices as parameters.find (deck[17]). but that contradicts our assumption that the words are in alphabetical order. Choose a word on the page and compare it to the word you are looking for. you don’t search linearly through every word. 3. In the case of a deck of cards. We have to look at every card. 4. If the word you are looking for comes after the word on the page. there is no way to search that is faster than the linear search. you can conclude that your word is not in the dictionary. Start in the middle somewhere. stop. I wrote the following: apvector<Card> deck = buildDeck (). To search the vector. flip to somewhere later in the dictionary and go to step 2. VECTORS OF OBJECTS To test this function. choose an index between low and high. if we know that the cards are in order. If you found the word you are looking for. indicating the segment of the vector that should be searched (including both low and high). If the word you are looking for comes before the word on the page.9 Bisection search If the cards in the deck are not in order. As a result. The only alternative is that your word has been misfiled somewhere. you probably use an algorithm that is similar to a bisection search: 1. low and high. we can write a version of find that is much faster. Compare the card at mid to the card you are looking for. The best way to write a bisection search is with a recursive function. That’s because bisection is naturally recursive. But when you look for a word in a dictionary. The reason is that the words are in alphabetical order. 2. Well. With that line added. const apvector<Card>& deck. which is the case if high is less than low. . Steps 3 and 4 look suspiciously like recursive invocations. If the card at mid is higher than your card. it is still missing a piece. the function works correctly: int findBisect (const Card& card. We need a way to detect this condition and deal with it properly (by returning -1). high).isGreater (card)) { // search the first half of the deck return findBisect (card. if (high < low) return -1. If the card at mid is lower than your card.9.12. search in the range from mid+1 to high. there are still cards in the deck. int low. 3. deck. it will recurse forever. int mid = (high + low) / 2. " << high << endl. Here’s what this all looks like translated into C++: int findBisect (const Card& card. search in the range from low to mid-1. // otherwise. BISECTION SEARCH 131 2. int low. of course. const apvector<Card>& deck. card)) return mid. } } Although this code contains the kernel of a bisection search. low. // if we found the card. The easiest way to tell that your card is not in the deck is if there are no cards in the deck. mid+1. stop. mid-1). but what I mean is that there are no cards in the segment of the deck indicated by low and high. return its index if (equals (deck[mid]. 4. if the card is not in the deck. } else { // search the second half of the deck return findBisect (card. compare the card to the middle card if (deck[mid]. If you found it. int high) { int mid = (high + low) / 2. int high) { cout << low << ". As it is currently written. deck. 24 13. 51)). The number of recursive calls is fairly small. deck. 0. On the other hand. mid+1.isGreater (card)) { return findBisect (card. you might be able to convince yourself. I got the following: 0. 14 13. 24 I found the card at index = 23 Then I made up a card that is not in the deck (the 15 of Diamonds). } } I added an output statement at the beginning so I could watch the sequence of recursive calls and convince myself that it would eventually reach the base case. Two common errors in recursive programs are forgetting to include a base case and writing the recursive call so that the base case is never reached. 51 0. I tried out the following code: cout << findBisect (deck. deck[23]. 51 0. no amount of testing can prove that a program is correct. compared to up to 52 times if we did a linear search. 24 13. especially for large vectors. 24 22. by looking at a few cases and examining the code. mid-1). if (deck[mid].132 CHAPTER 12. That means we only had to call equals and isGreater 6 or 7 times. low. high). bisection is much faster than a linear search. deck. And got the following output: 0. VECTORS OF OBJECTS if (equals (deck[mid]. . } else { return findBisect (card. in which case C++ will (eventually) generate a run-time error. and tried to find it. card)) return mid. Either error will cause an infinite recursion. typically 6 or 7. 24 19. In general. 12 I found the card at index = -1 These tests don’t prove that this program is correct. 24 13. 17 13. In fact. it makes sense to think of such a variable as “empty. So there is no such thing as an empty object. When you create them. as a single parameter that specifies a subdeck. For example. the word “abstract” gets used so often and in so many contexts that it is hard to interpret. low and high. What I mean by “abstract. DECKS AND SUBDECKS 133 12. but which describes the function of the program at a higher level. by constructing a mapping between them. they are given default values. But if the program guarantees that the current value of a variable is never read before it is written.3. int high) { it might make sense to treat three of the parameters. you are really sending the whole deck. in which a program comes to take on meaning beyond what is literally encoded. is a very important part of thinking like a computer scientist. when you call a function and pass a vector and the bounds low and high. deck.10. This kind of thing is quite common.12. Nevertheless. abstract parameter: A set of parameters that act together as a single parameter. abstraction is a central idea in computer science (as well as many other fields). there is nothing that prevents the called function from accessing parts of the vector that are out of bounds. Abstractly.” is something that is not literally part of the program text. abstractly. There is one other example of this kind of abstraction that you might have noticed in Section 9.” This kind of thinking. All variables have values all the time. const apvector<Card>& deck.11 Glossary encode: To represent one set of values using another set of values. A more general definition of “abstraction” is “The process of modeling a complex system with a simplified description in order to suppress unnecessary details while capturing relevant behavior. But as long as the recipient plays by the rules. . when I referred to an “empty” data structure. then the current value is irrelevant. and I sometimes think of it as an abstract parameter. The reason I put “empty” in quotation marks was to suggest that it is not literally accurate. it makes sense to think of it. Sometimes. int low.” 12. as a subdeck.10 Decks and subdecks Looking at the interface to findBisect int findBisect (const Card& card. So you are not literally sending a subset of the deck. 134 CHAPTER 12. VECTORS OF OBJECTS . the instance variables rank and suit are can be declared with type Rank and Suit: struct Card { Rank rank. Although we created a mapping between ranks and integers.Chapter 13 Objects of Vectors 13. JACK. FIVE. FOUR. DIAMONDS. Within the Suit type. and between suits and integers. and internal representations like integers and strings. TEN. C++ provides a feature called and enumerated type that makes it possible to (1) include a mapping as part of the program. and (2) define the set of values that make up the mapping. SIX. For example. enum Rank { ACE=1. THREE. the first value in the enumerated type maps to 0. the value CLUBS is represented by the integer 0. For example. TWO. The definition of Rank overrides the default mapping and specifies that ACE should be represented by the integer 1. HEARTS. EIGHT. KING }. The other values follow in the usual way. Once we have defined these types. QUEEN. we can use them anywhere. here is the definition of the enumerated types Suit and Rank: enum Suit { CLUBS. DIAMONDS is represented by 1. the second to 1. I pointed out that the mapping itself does not appear as part of the program.1 Enumerated types In the previous chapter I talked about mappings between real-world values like rank and suit. and so on. SPADES }. By default. etc. SEVEN. NINE. Suit suit. 135 . Actually. rank = Rank(rank+1)) { deck[index]. suit <= SPADES. Now. in the expression suit+1. C++ automatically converts the enumerated type to integer. we can use the values from the enumerated type as arguments: Card card (DIAMONDS. Strictly speaking. A switch statement is an alternative to a chained conditional that is syntactically prettier and often more efficient. That the types of the parameters for the constructor have changed. Then we can take the result and typecast it back to the enumerated type: suit = Suit(suit+1). to create a card. suit = Suit(suit+1)) { for (Rank rank = ACE. we are not allowed to do arithmetic with enumerated types. too. We have to make some changes in buildDeck. On the other hand. } } In some ways.suit = suit. Because we know that the values in the enumerated types are represented as integers. 11). Actually.2 switch statement It’s hard to mention enumerated types without mentioning switch statements. though: int index = 0. index++. rank <= KING. OBJECTS OF VECTORS Card (Suit s. for (Suit suit = CLUBS. but there is one complication. This code is much clearer than the alternative using integers: Card card (1. there is a better way to do this—we can define the ++ operator for enumerated types—but that is beyond the scope of this book. By convention. It looks like this: . because they often go hand in hand. deck[index].rank = rank. we can use them as indices for a vector. so suit++ is not legal. the values in enumerated types have names with all capital letters. Rank r). using enumerated types makes this code more readable. Therefore the old print function will work without modification.136 CHAPTER 13. }. JACK). rank = Rank(rank+1). 13. } The break statements are necessary in each branch in a switch statement because otherwise the flow of execution “falls through” to the next case. } else if (symbol == ’*’) { perform_multiplication ().2. "Spades". In this case we don’t need break statements because the return statements cause the flow of execution to return to the caller instead of falling through to the next case. } else { cout << "I only know how to perform addition and multiplication" << endl. In general it is good style to include a default case in every switch statement. SWITCH STATEMENT 137 switch (symbol) { case ’+’: perform_addition (). Without the break statements. "Not a valid suit". } This switch statement is equivalent to the following chained conditional: if (symbol == ’+’) { perform_addition (). to handle errors or unexpected values. break. and then print the error message. switch statements work with integers. For example. "Hearts". break. characters. Occasionally this feature is useful.13. break. to convert a Suit to the corresponding string. default: cout << "I only know how to perform addition and multiplication" << endl. case ’*’: perform_multiplication (). the symbol + would make the program perform addition. . we could use something like: switch (suit) { case CLUBS: case DIAMONDS: case HEARTS: case SPADES: default: } return return return return return "Clubs". "Diamonds". but most of the time it is a source of errors when people forget the break statements. and enumerated types. and then perform multiplication. cards = temp. To access the cards in a deck we have to compose . For now there is only one constructor. passing the size as a parameter. but I also mentioned that it is possible to have an object that contains a vector as an instance variable. Here is a state diagram showing what a Deck object looks like: deck cards: 0 suit: rank: 1 2 51 0 0 suit: rank: 0 0 suit: rank: 0 0 suit: rank: 0 0 The object named deck has a single instance variable named cards. that contains a vector of Cards. which is a vector of Card objects.138 CHAPTER 13. called a Deck. } The name of the instance variable is cards to help distinguish the Deck object from the vector of Cards that it contains. Then it copies the vector from temp into the instance variable cards. Now we can create a deck of cards like this: Deck deck (52). Deck (int n). which it initializes by invoking the constructor for the apvector class. OBJECTS OF VECTORS 13. Deck::Deck (int size) { apvector<Card> temp (size). In this chapter I am going to create a new object.3 Decks In the previous chapter. It creates a local variable named temp. we worked with a vector of objects. }. The structure definition looks like this struct Deck { apvector<Card> cards. i++. the expression deck. For example. i<52. cards[i].4 Another constructor Now that we have a Deck object. rewritten as a Deck member function: void Deck::print () const { for (int i = 0. and deck.length(). cards = temp. Deck::Deck () { apvector<Card> temp (52). rank = Rank(rank+1)) { cards[i]. From the previous chapter we have a function called buildDeck that we could use (with a few adaptations). i < cards. } } } Notice how similar this function is to buildDeck.cards[i].5 Deck member functions Now that we have a Deck object. but it might be more natural to write a second Deck constructor. 13.13.print(). for (Suit suit = CLUBS. it makes sense to put all the functions that pertain to Decks in the Deck structure definition. rank <= KING. } demonstrates how to traverse the deck and output each card.suit is its suit.suit = suit. one obvious candidate is printDeck (Section 12. . The following loop for (int i = 0.print (). i++) { deck. ANOTHER CONSTRUCTOR 139 the syntax for accessing an instance variable and the syntax for selecting an element from an array. suit <= SPADES. except that we had to change the syntax to make it a constructor.7). suit = Suit(suit+1)) { for (Rank rank = ACE.4. Here’s how it looks. Looking at the functions we have written so far. Now we can create a standard 52-card deck with the simple declaration Deck deck. 13.cards[i].cards[i] is the ith card in the deck. i++) { cards[i].rank = rank. int i = 0. it would be useful to initialize the cards in it. rewrite find as a Deck member function that takes a Card as a parameter. Card (int s. *this)) return i.cards. One solution is to declare Deck before Card and then define Deck afterwards: // declare that Deck is a structure. or nonmember functions that take Cards and Decks as parameters.cards[i]. int find (const Deck& deck) const. For some of the other functions. OBJECTS OF VECTORS } } As usual. } The first trick is that we have to use the keyword this to refer to the Card the function is invoked on. int r). it doesn’t know about the second one yet. it is not obvious whether they should be member functions of Card. but you could reasonably make it a member function of either type. For example. The second trick is that C++ does not make it easy to write structure definitions that refer to each other. As an exercise. Card (). The problem is that when the compiler is reading the first structure definition. the version of find in the previous chapter takes a Card and a Deck as arguments. member functions of Deck. void print () const. Here’s my version: int Card::find (const Deck& deck) const { for (int i = 0. // that way we can refer to it in the definition of Card struct Card { int suit. rank. i < deck. we can refer to the instance variables of the current object without using dot notation. // and then later we provide the definition of Deck struct Deck { apvector<Card> cards. } return -1. i++) { if (equals (deck. }.140 CHAPTER 13.length(). Writing find as a Card member function is a little tricky. bool isGreater (const Card& c2) const. without defining it struct Deck. . and at each iteration choose two cards and swap them. One possibility is to model the way humans shuffle. I am using a combination of C++ statements and English words that is sometimes called pseudocode: for (int i=0. You can probably figure out how to write randomInt by looking at Section 10. after about 7 iterations the order of the deck is pretty well randomized. we need something like randomInt. we need a way to put it back in order. which is usually by dividing the deck in two and then reassembling the deck by choosing alternately from each deck. but it is not obvious how to use them to shuffle a deck.6.5 we saw how to generate random numbers. }. i<cards. void print () const. Ironically.5. although you will have to be careful about possibly generating indices that are out of range.” A better shuffling algorithm is to traverse the deck one card at a time. which is not really very random. 13. put the cards in a random order. For a discussion of that claim. In this case. To sketch the program. you would find the deck back in the same order you started in. see. that is.7 Sorting Now that we have messed up the deck.com/marilyn/craig. You can also figure out swapCards yourself. Here is an outline of how this algorithm works.length() // swap the ith card and the randomly-chosen card } The nice thing about using pseudocode is that it often makes it clear what functions you are going to need. there is an algorithm for sorting that is very similar to the algorithm .html or do a web search with the keywords “perfect shuffle. Deck (int n). and swapCards which takes two indices and switches the cards at the indicated positions. In fact. after 8 perfect shuffles.wiskit. I will leave the remaining implementation of these functions as an exercise to the reader. Since humans usually don’t shuffle perfectly. which chooses a random integer between the parameters low and high.length(). i++) { // choose a random number between i and cards. 13.6 Shuffling For most card games you need to be able to shuffle the deck. In Section 10. int find (const Card& card) const. SHUFFLING 141 Deck (). But a computer program would have the annoying property of doing a perfect shuffle every time.13. length().cards[i] = cards[low+i]. i<sub. that takes a vector of cards and a range of indices.142 CHAPTER 13. the pseudocode helps with the design of the helper functions. Which version is more errorprone? Which version do you think is more efficient? . 13. we are going to find the lowest card remaining in the deck. using pseudocode to figure out what helper functions are needed.8. i<cards. called findLowestCard. write a version of findBisect that takes a subdeck as an argument.cards. In this case we can use swapCards again. for (int i=0. The cards get initialized when they are copied from the original deck. } To create the local variable named subdeck we are using the Deck constructor that takes the size of the deck as an argument and that does not initialize the cards. As an exercise. we are going to traverse the deck and at each location choose another card and swap. that takes a vector of cards and an index where it should start looking. for (int i = 0. This process. subdeck. Once again. This sort of computation can be confusing. We might want a function. The only difference is that this time instead of choosing the other card at random. Drawing a picture is usually the best way to avoid them.8 Subdecks How should we represent a hand or some other subset of a full deck? One easy choice is to make a Deck object that has fewer than 52 cards. The length of the subdeck is high-low+1 because both the low card and high card are included. is sometimes called top-down design. int high) const { Deck sub (high-low+1). i++) { sub. in contrast to the bottom-up design I discussed in Section 10. OBJECTS OF VECTORS for shuffling. By “remaining in the deck. and that returns a new vector of cards that contains the specified subset of the deck: Deck Deck::subdeck (int low.length(). I am going to leave the implementation up to the reader. so we only need one new one. and lead to “off-by-one” errors. i++) { // find the lowest card at or to the right of i // swap the ith card and the lowest card } Again.” I mean cards that are at or to the right of the index i. Again. rather than a deck and an index range. } return sub.. there are many possible representations for a Card. including two integers. the most common way to enforce data encapsulation is to prevent client programs from accessing the instance variables of an object.1 Private data and classes I have used the word “encapsulation” in this book to refer to the process of wrapping up a sequence of instructions in a function. two strings and two enumerated types. In C++. As another example.” which is the topic of this chapter.Chapter 14 Classes and invariants 14. and prevent unrestricted access to the internal representation. in order to separate the function’s interface (how to use it) from its implementation (how it does what it does). rank. This kind of encapsulation might be called “functional encapsulation. but as “clients” of these libraries. but someone using the Card structure should not have to know anything about its internal structure. One use of data encapsulation is to hide implementation details from users or programmers that don’t need to know them. The programmer who writes the Card member functions needs to know which implementation to use. For example. The keyword private is used to protect parts of a structure definition. For example.” to distinguish it from “data encapsulation. we don’t need to know. we have been using apstring and apvector objects without ever discussing their implementations. There are many possibilities. 147 . we could have written the Card definition: struct Card { private: int suit. Data encapsulation is based on the idea that each structure definition should provide a set of functions that apply to the structure. } (int s) { suit = s. On the other hand. But there is another feature in C++ that also meets this definition. } s. Card (int s. it is called a class. } suit. confusingly. } (int r) { rank = r. } There are two sections of this definition. all we have to do is remove the set functions. I could have written the Card definition: class Card { int suit. The instance variables are private. structures in C++ meet the general definition of a class. As we have seen. getRank getSuit setRank setSuit () const { return rank. which means that they can be invoked by client programs. rank. In C++. a class is a user-defined type that includes a set of functions. The functions are public. which means that they can be read and written only by Card member functions. CLASSES AND INVARIANTS public: Card (). it is now easy to control which operations clients can perform on which instance variables. a class is just a structure whose instance variables are private by default. } r. it might be a good idea to make cards “read only” so that after they are constructed. a private part and a public part. public: Card (). For example. } . Another advantage of using accessor functions is that we can change the internal representations of cards without having to change any client programs. int r). int int int int }. int getRank () const int getSuit () const void setRank (int r) void setSuit (int s) }. To do that. { { { { return return rank = suit = rank. It is still possible for client programs to read and write the instance variables using the accessor functions (the ones beginning with get and set). 14. they cannot be changed. Card (int s. int r). } () const { return suit. For example.148 CHAPTER 14.2 What is a class? In most object-oriented programming languages. just by adding or removing labels. COMPLEX NUMBERS 149 I replaced the word struct with the word class and removed the private: label.14. and is usually written in the form x + yi. The following is a class definition for a user-defined type called Complex: class Complex { double real. The following figure shows the two coordinate systems graphically. Complex numbers are useful for many branches of mathematics and engineering. the instance variables real and imag are private. and the distance (or magnitude) of the point. and i represents the square root of -1. and we have to include the label public: to allow client code to invoke the constructors. there are two constructors: one takes no parameters and does nothing. most C++ programmers use class. . In fact.” regardless of whether they are defined as a struct or a class. y is the imaginary part. it is common to refer to all user-defined types in C++ as “classes. As usual. A complex number is the sum of a real part and an imaginary part. There is no real reason to choose one over the other. So far there is no real advantage to making the instance variables private. Instead of specifying the real part and the imaginary part of a point in the complex plane.3. }.3 Complex numbers As a running example for the rest of this chapter we will consider a class definition for complex numbers. 14. double i) { real = r. where x is the real part. the other takes two parameters and uses them to initialize the instance variables. There is another common representation for complex numbers that is sometimes called “polar form” because it is based on polar coordinates. and many computations are performed using complex arithmetic. except that as a stylistic choice. Also. imag = i. } Because this is a class definition. polar coordinates specify the direction (or angle) of the point relative to the origin. then the point might be clearer. public: Complex () { } Complex (double r. This result of the two definitions is exactly the same. anything that can be written as a struct can also be written as a class. Let’s make things a little more complicated. imag. 150 CHAPTER 14. bool cartesian. it is easy to convert from one form to another. x = r cos θ y = r sin θ So which representation should we use? Well. class Complex { double real. imag. public: Complex () { cartesian = false. and that converts between them automatically. Fortunately. where r is the magnitude (radius). } . One option is that we can write a class definition that uses both representations. and others are easier in polar coordinates (like multiplication). To go from Cartesian to polar. r θ = = x2 + y 2 arctan(y/x) To go from polar to Cartesian. and θ is the angle in radians. as needed. the whole reason there are multiple representations is that some operations are easier to perform in Cartesian coordinates (like addition). CLASSES AND INVARIANTS Cartesian coordinates imaginary axis Polar coordinates magnitude angle real axis Complex numbers in polar coordinates are written reiθ . double mag. polar. Complex (double r. double i) polar = false. theta. For example. Otherwise. we will develop accessor functions that will make those kinds of mistakes impossible. is the type of the corresponding instance variable. the angle and the magnitude of the complex number. the imaginary part. Setting the polar flag to false warns other functions not to access mag or theta until they have been set. in either representation. The other two variables. but it does not calculate the magnitude or angle. Now it should be clearer why we need to keep the instance variables private. There are now six instance variables. The return type. Here’s what getReal looks like: double Complex::getReal () { if (cartesian == false) calculateCartesian (). The second constructor uses the parameters to initialize the real and imaginary parts. ACCESSOR FUNCTIONS 151 { real = r. return real. Four of the instance variables are self-explanatory. } If the cartesian flag is true then real contains valid data. 14. it would be easy for them to make errors by reading uninitialized values. imag = i. and we can just return it. They contain the real part. cartesian = true.4. we have to call calculateCartesian to convert from polar coordinates to Cartesian coordinates: void Complex::calculateCartesian () { . the accessor functions give us an opportunity to make sure that the value of the variable is valid before we return it. polar = false.4 Accessor functions By convention. the do-nothing constructor sets both flags to false to indicate that this object does not contain a valid complex number (yet). naturally. In the next few sections. If client programs were allowed unrestricted access.14. which means that this representation will take up more space than either of the others. cartesian and polar are flags that indicate whether the corresponding values are currently valid. but we will see that it is very versatile. In this case. accessor functions have names that begin with get and end with the name of the instance variable they fetch. } }. When we invoke printCartesian it accesses real and imag without having to do any conversions. the program is forced to convert to polar coordinates and store the results in the instance variables. Since the output functions use the accessor functions. it is in Cartesian format only. As an exercise. When printPolar invokes getTheta. the program will compute automatically any values that are needed. cartesian = true. Then we set the cartesian flag. it will see that the polar coordinates are valid and return theta immediately. Complex c1 (2. For Complex objects.0). c1. we could use two functions: void Complex::printCartesian () { cout << getReal() << " + " << getImag() << "i" << endl. and printPolar invokes getMag. because invoking them might modify the instance variables. CLASSES AND INVARIANTS real = mag * cos (theta). Initially. The following code creates a Complex object using the second constructor. we want to be able to output objects in a human-readable form.printPolar(). 3. } The nice thing here is that we can output any Complex object in either format without having to worry about the representation. indicating that real and imag now contain valid data. } Assuming that the polar coordinates are valid.5 Output As usual when we define a new class. we can calculate the Cartesian coordinates using the formulas from the previous section. When we invoke printPolar. One unusual thing about these accessor functions is that they are not const. imag = mag * sin (theta). 14.152 CHAPTER 14.0. The output of this code is: . } void Complex::printPolar () { cout << getMag() << " e^ " << getTheta() << "i" << endl.printCartesian(). The good news is that we only have to do the conversion once. write a corresponding function called calculatePolar and then write getMag and getTheta. c1. sum.printCartesian(). we can use the accessor functions without worrying about the representation of the objects. anyway). double imag = a. Complex sum (real. The output of this program is 5 + 7i 14. addition is easy: you just add the real parts together and the imaginary parts together. we can just multiply the magnitudes and add the angles. 4. If the numbers are in polar coordinates. return sum. In polar coordinates. As usual.getReal(). imag).0). To invoke this function. it is easiest to convert them to Cartesian coordinates and then add them. c2). it is easy to deal with these cases if we use the accessor functions: Complex add (Complex& a.14.6 A function on Complex numbers A natural operation we might want to perform on complex numbers is addition.0.getImag() + b. we would pass both operands as arguments: Complex c1 (2.6. Complex& b) { double real = a.60555 e^ 0. a little harder.7 Another function on Complex numbers Another operation we might want is multiplication. Unlike addition. Complex sum = add (c1.getImag().getReal() + b. Complex c2 (3.0). If the numbers are in Cartesian coordinates. } Notice that the arguments to add are not const because they might be modified when we invoke the accessors. Again.982794i 14.getMag() * b. A FUNCTION ON COMPLEX NUMBERS 153 2 + 3i 3.0.getMag() . Complex mult (Complex& a. Complex& b) { double mag = a. multiplication is easy if the numbers are in polar coordinates and hard if they are in Cartesian coordinates (well. 3. if the cartesian flag is set then we expect real and imag to contain valid data. we expect mag and theta to be valid. For example.0). the cartesian coordinates are no longer valid. } A small problem we encounter here is that we have no constructor that accepts polar coordinates.getTheta() + b. In this case. Complex product.0). Finally. } As an exercise. Complex c2 (3. Complex product = mult (c1. That’s because if we change the polar coordinates. Really. product. polar = true. so when we invoke printCartesian it has to get converted back. if polar is set. we have to make sure that the cartesian flag is unset. we have to make sure that when mag and theta are set. 3. The output of this program is -6 + 17i There is a lot of conversion going on in this program behind the scenes. if both flags are set then we expect the other four variables to . c2). though. void Complex::setPolar (double m. It would be nice to write one.8 Invariants There are several conditions we expect to be true for a proper Complex object.0.printCartesian(). product. we also set the polar flag. we can try something like: Complex c1 (2. 4. double t) { mag = m. but remember that we can only overload a function (even a constructor) if the different versions take different parameters.0.154 CHAPTER 14. To test the mult function. theta). An alternative it to provide an accessor function that sets the instance variables. we would like a second constructor that also takes two doubles.getTheta(). At the same time. and we can’t have that.setPolar (mag. theta = t. CLASSES AND INVARIANTS double theta = a. return product. it’s amazing that we get the right answer! 14. both arguments get converted to polar coordinates. write the corresponding function named setCartesian. cartesian = false. When we call mult. The result is also in polar format. Similarly. In order to do that properly. ” That definition allows two loopholes. Is there an assumption we make about the current object? Yes. all bets are off. Notice that I said “maintain” the invariant. Looking at the Complex class. What that means is “If the invariant is true when the function is called. For example. and write code that makes it impossible to violate them. they should be specifying the same point in two different formats. then everything is fine. output an error message. One of the primary things that data encapsulation is good for is helping to enforce invariants. there may be some point in the middle of the function when the invariant is not true. As long as the invariant is restored by the end of the function. if not. though. PRECONDITIONS 155 be consistent. it is a good idea to think about your assumptions explicitly. These kinds of conditions are called invariants.9. The first step is to prevent unrestricted access to the instance variables by making them private. usually the best we can do is detect the error. 14. We have to be a little careful. document them as part of the program. your program might crash. and maybe write code that checks them. we assume that the polar . The other loophole is that we only have to maintain the invariant if it was true at the beginning of the function. First. If those assumptions turn out to be true.9 Preconditions Often when you write a function you make implicit assumptions about the parameters you receive. and we can show that every one of them maintains the invariants. If the invariant was violated somewhere else in the program. for the obvious reason that they do not vary—they are always supposed to be true. Otherwise. To make your programs more robust. it is straightforward to show that the function maintains each of the invariants I listed. and in some cases unavoidable. that is. Then the only way to modify the object is through accessor functions and modifiers. If we examine all the accessors and modifiers. it will still be true when the function is complete. then we can prove that it is impossible for an invariant to be violated.14. all is well.. and exit. let’s take another look at calculateCartesian. That’s ok. If the argument is false. One option is to add a comment to the function that warns programmers about the precondition. These comments are useful for people reading your programs. CLASSES AND INVARIANTS flag is set and that mag and theta contain valid data. The return value is an error code that tells the system (or whoever executed the program) that something went wrong. } real = mag * cos (theta). imag = mag * sin (theta). Here’s how to use it: void Complex::calculateCartesian () . void Complex::calculateCartesian () // precondition: the current object contains valid polar coordinates and the polar flag is set // postcondition: the current object will contain valid Cartesian coordinates and valid polar coordinates.156 CHAPTER 14. This kind of error-checking is so common that C++ provides a built-in function to check preconditions and print error messages. assert prints an error message and quits. but it is an even better idea to add code that checks the preconditions. If you include the assert. then this function will produce meaningless results. exit (1). } At the same time.h header file. you get a function called assert that takes a boolean value (or a conditional expression) as an argument. If that is not true. so that we can print an appropriate error message: void Complex::calculateCartesian () { if (polar == false) { cout << "calculateCartesian failed because the polar representation is invalid" << endl. and both the cartesian flag and the polar flag will be set { real = mag * cos (theta). As long as the argument is true. imag = mag * sin (theta). cartesian = true. assert does nothing. I also commented on the postconditions. cartesian = true. the things we know will be true when the function completes. } The exit function causes the program to quit immediately. cpp:63: void Complex::calculatePolar(): Assertion ‘cartesian’ failed. polar. public: Complex () { cartesian = false. there are member functions that are used internally by a class. Complex (double r.10 Private functions In some cases. but there is probably no reason clients should call them directly (although it would not do any harm). including the file name and line number of the assertion that failed. double mag. } The first assert statement checks the precondition (actually just part of it). imag. 14. polar = false. void calculateCartesian (). void calculatePolar ().14. } . If we wanted to protect these functions. calculatePolar and calculateCartesian are used by the accessor functions. we could declare them private the same way we do with instance variables. cartesian = true. imag = i.10. but that should not be invoked by client programs. I get the following message when I violate an assertion: Complex. the function name and the contents of the assert statement. theta. bool cartesian. For example. real = mag * cos (theta). In my development environment. PRIVATE FUNCTIONS 157 { assert (polar). double i) { real = r. the second assert statement checks the postcondition. In that case the complete class definition for Complex would look like: class Complex { private: double real. Abort There is a lot of information here to help me track down the error. imag = mag * sin (theta). assert (polar && cartesian). precondition: A condition that is assumed to be true at the beginning of a function. that should be true at all times in client code. getImag (). accessor function: A function that provides access (read or write) to a private instance variable. invariant: A condition. If the precondition is not true. getTheta (). }. } polar = false. double double double double getReal (). . a class is a structure with private instance variables. postcondition: A condition that is true at the end of a function. void setCartesian (double r. double i). void printCartesian ().11 Glossary class: In general use. usually pertaining to an object. The private label at the beginning is not necessary. void printPolar ().158 CHAPTER 14. CLASSES AND INVARIANTS cartesian = true. the function may not work. 14. getMag (). a class is a user-defined type with member functions. and that should be maintained by all member functions. void setPolar (double m. In C++. but it is a useful reminder. It is often a good idea for functions to check their preconditions. double t). if possible. parses input.h.Chapter 15 File Input/Output and apmatrixes In this chapter we will develop a program that reads and writes files. and demonstrates the apmatrix class. A stream is an abstract object that represents the flow of data from a source like the keyboard or a file to a destination like the screen or a file.. 15. These objects are defined in the header file fstream. there is no need to print the top half of the matrix. 159 . Also. Aside from demonstrating all these features. We will also implement a data structure called Set that expands automatically as you add elements. which you have to include. the real purpose of the program is to generate a two-dimensional table of the distances between cities in the United States. you have to create an ifstream object (for input files) or an ofstream object (for output files).1 Streams To get input from a file or send output to a file. because the distance from A to B is the same as the distance from B to A. ” Whenever you get data from an input stream. 15. apstring line. // get a single integer and store in x // get a whole line and store in line If we know ahead of time how much data is in a file. . if (infile. it adds a datum to the outgoing stream. We can do that using the ifstream constructor. we want to read the entire file. The result is an object named infile that supports all the same operations as cin.good() == false) { cout << "Unable to open the file named " << fileName. which has type ostream. eof.2 File input To get data from a file. exit (1). ifstream infile (fileName. and cout.. More often. when the program uses the << operator on an ostream. fail and bad. you don’t know whether the attempt succeeded until you check. Similarly. } while (true) { getline (infile. line).c_str()). we have to create a stream that flows from the file into the program. FILE INPUT/OUTPUT AND APMATRIXES We have already worked with two streams: cin. they are called good. which has type istream. The argument for this constructor is a string that contains the name of the file you want to open.. If the return value from eof is true then we have reached the end of the file and we know that the last attempt failed. Each time the program uses the >> operator or the getline function. ifstream infile ("file-name"). We will use good to make sure the file was opened successfully and eof to detect the “end of file. line). getline (infile. int x. but don’t know how big it is. it is straightforward to write a loop that reads the entire file and then stops. it removes a piece of data from the input stream.. infile >> x. if (infile. Here is a program that reads lines from a file and displays them on the screen: apstring fileName = . though. cin represents the flow of data from the keyboard to the program. including >> and getline.eof()) break. There are member functions for ifstreams that check the status of the input stream.160 CHAPTER 15. Immediately after opening the file. ofstream outfile ("output-file").4 Parsing input In Section 1. In addition. so that when getline fails at the end of the file. It is important to exit the loop between the input statement and the output statement. if (infile.good() == false || outfile.eof()) break. we invoke the good function. or you do not have permission to read it. FILE OUTPUT 161 cout << line << endl. the break statement allows us to exit the loop as soon as we detect the end of file. For example. if (infile. .3. we do not output the invalid data in line. 15. } while (true) { getline (infile. outfile << line << endl. exit (1). Usually there will be a break statement somewhere in the loop so that the program does not really run forever (although some programs do). we have to convert the apstring. For example." << endl.4 I defined “parsing” as the process of analyzing the structure of a sentence in a natural language or a statement in a formal language. when you read input from a file or from the keyboard you often have to parse it in order to extract the information you want and detect errors. } 15. we could modify the previous program to copy lines from one file to another. ifstream infile ("input-file"). the compiler has to parse your program before it can translate it into machine language.good() == false) { cout << "Unable to open one of the files. Because the ifstream constructor expects a C string as an argument. In this case.3 File output Sending output to a file is similar. line).15. most likely because it does not exist. } The function c str converts an apstring to a native C string. The statement while(true) is an idiom for an infinite loop. The return value is false if the system could not open the file. The backslash (\) indicates that we want to treat the next character literally. used to identify string values. Interestingly.find (’\"’). the sequence \’ represents a single-quote. void processLine (const apstring& line) { // the character we are looking for is a quotation mark char quote = ’\"’.” By searching for the quotation marks in a line of input. like “San Francisco.450 750 400 Each line of the file contains the names of two cities in quotation marks and the distance between them in miles. The first backslash indicates that we should take the second backslash seriously. . The outermost single-quotes indicate that this is a character value.100 700 800 1. we can find the beginning and end of each city name. substr is an apstring member function. The argument here looks like a mess. though.html so it may be wildly inaccurate. the starting index of the substring and the length. because the quotation mark is a special character in C++. but that doesn’t matter. The quotation marks are useful because they make it easy to deal with names that have more than one word.my/usiskl/usa/distance. If we want to find the first appearance of a quotation mark. it takes two arguments. but it represents a single character. we have to write something like: int index = line. as usual. I have a file called distances that contains information about the distances between major cities in the United States. FILE INPUT/OUTPUT AND APMATRIXES For example.162 CHAPTER 15. Parsing input lines consists of finding the beginning and end of each city name and using the substr function to extract the cities and distance. I got this information from a randomly-chosen web page. The format of the file looks like this: "Atlanta" "Atlanta" "Atlanta" "Atlanta" "Atlanta" "Atlanta" "Atlanta" "Chicago" "Boston" "Chicago" "Dallas" "Denver" "Detroit" "Orlando" 700 1. the sequence \\ represents a single backslash. The sequence \" represents a quotation mark. Searching for special characters like quotation marks can be a little awkward. a double quotation mark. find (quote). i<s. // find the other quotation marks using the find from Chapter 7 for (int i=1.quoteIndex[2] .substr (quoteIndex[2]+1. len2). // find the first quotation mark using the built-in find quoteIndex[0] = line.quoteIndex[0] .substr (quoteIndex[0]+1. in order.substr (quoteIndex[3]+1.quoteIndex[2] . // output the extracted information cout << city1 << "\t" << city2 << "\t" << distString << endl. 15. i++) { . Once we get rid of the commas.length() . At the end of the loop.length(). quote. city1 = line. int convertToInt (const apstring& s) { apstring digitString = "". they often use commas to group the digits. Most of the time when computers write large numbers. quoteIndex[i-1]+1). they don’t include commas. i<4.750. but it also provides an opportunity to write a comma-stripping function. If so. i++) { quoteIndex[i] = find (line. but it is a good starting place.1. we can use the library function atoi to convert to integer. the result string contains all the digits from the original string. so that’s ok. } Of course. and the built-in functions for reading numbers usually can’t handle them. PARSING NUMBERS 163 // store the indices of the quotation marks in a vector apvector<int> quoteIndex (4). one option is to traverse the string and check whether each character is a digit.5 Parsing numbers The next task is to convert the numbers in the file from strings to integers. That makes the conversion a little more difficult. distString = line. atoi is defined in the header file stdlib. as in 1.15. = line. len3). = quoteIndex[3] . When people write large numbers. len1).1.5. city2 = line. we add it to the result string.1. just displaying the extracted information is not exactly what we want. } // break int len1 apstring int len2 apstring int len3 apstring the line up into substrings = quoteIndex[1] .h. for (int i=0. To get rid of the commas. Both statements add a single character onto the end of the existing string. The expression digitString += s[i].c_str()). An ordered set is a collection of items with two defining properties: Ordering: The elements of the set have indices associated with them. If you try to add an element to a set. We have seen some examples already. and it already exists. we have to convert digitString to a C string before passing it as an argument. every element has an index we can use to identify it. we have to write an add function that searches the set to see if it already exists. it expands to make room for new elements.164 CHAPTER 15. Both none of the data structures we have seen so far have the properties of uniqueness or arbitrary size. including apstrings. To make the set expand as elements are added. 15. FILE INPUT/OUTPUT AND APMATRIXES if (isdigit (s[i])) { digitString += s[i]. Uniqueness: No element appears in the set more than once. } The variable digitString is an example of an accumulator. In addition. Both apstrings and apvectors have an ordering. it gets accumulates one new character at a time. } } return atoi (digitString. To achieve uniqueness. It is similar to the counter we saw in Section 7. . except that instead of getting incremented. we can take advantage of the resize function on apvectors. which are collections of characters. using string concatentation. Since atoi takes a C string as a parameter. and apvectors which are collections on any type. Here is the beginning of a class definition for a Set. is equivalent to digitString = digitString + s[i]. there is no effect. We can use these indices to identify elements of the set.9.6 The Set data structure A data structure is a container for grouping a collection of data into a single object. our implementation of an ordered set will have the following property: Arbitrary size: As we add elements to the set. THE SET DATA STRUCTURE 165 class Set { private: apvector<apstring> elements. elements = temp. public: Set (int n). When we use the [] operator to access the apvector. Keep in mind that the number of elements in the set.6. it checks to make sure the index is greater than or equal to zero and less than the length of the apvector. which might be smaller than the length of the apvector.15. Set::Set (int n) { apvector<apstring> temp (n). } The instance variables are an apvector of strings and an integer that keeps track of how many elements there are in the set. which are private. so we provide a get function but not a set function. To access the elements of a set. As we look at the rest of the Set member function. apstring getElement (int i) const. The Set constructor takes a single parameter. The index has to be less than the number of elements. int Set::getNumElements () const { return numElements. is not the same thing as the size of the apvector. getNumElements and getElement are accessor functions for the instance variables. } Why do we have to prevent client programs from changing getNumElements? What are the invariants for this type. }. and how could a client program break an invariant. numElements. though. which is the initial size of the apvector. int find (const apstring& s) const. int add (const apstring& s). Usually it will be smaller. see if you can convince yourself that they all maintain the invariants. numElements is a read-only variable. apstring Set::getElement (int i) const . int getNumElements () const. int numElements. we need to check a stronger condition. numElements = 0. The initial number of elements is always zero. } // add the new elements and return its index index = numElements.resize (elements. but in this case it might be useful to make it return the index of the element. elements[index] = s. it prints an error message (not the most useful message. numElements++. i++) { if (elements[i] == s) return i. the pattern for traversing and searching should be old hat: int Set::find (const apstring& s) const { for (int i=0. By now. } So that leaves us with add. .length() * 2).166 CHAPTER 15. i<numElements. // if the apvector is full. It is the number of elements in the set. exit (1). I admit). FILE INPUT/OUTPUT AND APMATRIXES { if (i < numElements) { return elements[i]. return its index int index = find (s). } else { cout << "Set index out of range. and exits. } The tricky thing here is that numElements is used in two ways. } } If getElement gets an index that is out of range. return index. double its size if (numElements == elements. but it is also the index of the next element to be added." << endl. The interesting functions are find and add. } return -1. int Set::add (const apstring& s) { // if the element is already in the set.length()) { elements. if (index != -1) return index. of course. Often the return type for something like add would be void. Here is a state diagram showing a Set object that initially contains space for 2 elements. apmatrix<int> m2 (3. Then in processLine we add both cities to the Set and store the index that gets returned.add (city1). apmatrix<double> m3 (rows.. called numrows and numcols. for “number of rows” and “number of columns.7 apmatrix An apmatrix is similar to an apvector except it is two-dimensional. cols. that means that the vector is full. 4). . In main we create the Set with an initial size of 2: Set cities (2). I modified processLine to take the cities object as a second parameter.15. Instead of a length. the index of the next element is 0. 15. int index1 = cities. the other the column number.” Each element in the matrix is indentified by two indices. To create a matrix. one specifies the row number. it has two dimensions.add (city2). apmatrix<double> m4 (m3). and we have to allocate more space (using resize) before we can add the new element. When the number of elements is equal to the length of the apvector. there are four constructors: apmatrix<char> m1. 0. int index2 = cities. APMATRIX 167 It takes a minute to convince yourself that that works.7. but consider this: when the number of elements is zero.0). } 15. with plenty of space to spare: apmatrix<int> distances (50. col++) { cout << m2[row][col] << "\t". 50. } } This loop prints each row of the matrix with tabs between the elements and newlines between the rows: for (int row=0.numrows(). m3[1][2] = 10. we use the [] operator to specify the row and column: m2[0][0] = 1. row < m2. The numrows and numcols functions get the number of rows and columns. The fourth is a copy constructor that takes another apmatrix as a parameter. except that it takes an additional parameter that is used to initialized the elements of the matrix. and even apmatrixes). The usual way to traverse a matrix is with a nested loop. the matrix will have one row and one column for each city. We’ll create the matrix in main. in that order. col++) { m2[row][col] = row + col. row++) { for (int col=0. col < m2. row < m2. which are the initial number of rows and columns. row++) { for (int col=0.numcols(). . we can make apmatrixes with any type of elements (including apvectors. The second takes two integers. If we try to access an element that is out of range. 0).numrows(). FILE INPUT/OUTPUT AND APMATRIXES The first is a do-nothing constructor that makes a matrix with both dimensions 0. col < m2. This loop sets each element of the matrix to the sum of its two indices: for (int row=0.168 CHAPTER 15. The third is the same as the second. Specifically. we are ready to put the data from the file into a matrix. Just as with apvectors.8 A distance matrix Finally. To access the elements of a matrix. } cout << endl. Remember that the row indices run from 0 to numrows() -1 and the column indices run from 0 to numcols() -1.0 * m2[0][0]. the program prints an error message and quits.numcols(). add (city2). i++) { cout << cities. use of the distance matrix is error prone because we have not provided accessor functions that perform error-checking. We did not know ahead of time how big to make the distance matrix. we add new information to the matrix by getting the indices of the two cities from the Set and using them as matrix indices: int dist = convertToInt (distString). The apmatrix class has a function called resize that makes this possible. } cout << endl. 2. } cout << "\t".getElement(i) << "\t". for (int i=0. What are some of the problems with the existing code? 1. i++) { cout << cities. A PROPER DISTANCE MATRIX 169 Inside processLine. i<cities. for (int j=0. The original data is available from this book’s web page. distances[index1][index2] = distance. distances[index2][index1] = distance. Finally.15. It would be better to allow the distance matrix to expand in the same way a Set does. It .getNumElements(). in main we can print the information in a human-readable form: for (int i=0. we are in a good position to evaluate the design and improve it. We have to pass the set of city names and the matrix itself as arguments to processLine. int index2 = cities.add (city1). 15.getNumElements(). The data in the distance matrix is not well-encapsulated. j++) { cout << distances[i][j] << "\t".9. i<cities. which is awkward. j<=i.9 A proper distance matrix Although this code works. Now that we have written a prototype. so we chose an arbitrary large number (50) and made it a fixed size. } cout << endl. int index1 = cities. This code produces the output shown at the beginning of the chapter.getElement(i) << "\t". Also. it is not as well organized as it should be. distances). void add (const apstring& city1. if (infile. for (int i=1. FILE INPUT/OUTPUT AND APMATRIXES might be a good idea to take the Set of city names and the apmatrix of distances. and combine them into a single object called a DistMatrix. const apstring& city2. void print ().eof()) break. } It also simplifies processLine: void processLine (const apstring& line. int distance (const apstring& city1. quoteIndex[i-1]+1). } distances. DistMatrix distances (2).print (). while (true) { getline (infile. int numCities () const.170 CHAPTER 15. int dist). }. int distance (int i. quote. i<4. Here is a draft of what the header for a DistMatrix might look like: class DistMatrix { private: Set cities. apstring cityName (int i) const. const apstring& city2) const. int j) const. i++) { quoteIndex[i] = find (line.find (quote). processLine (line. apmatrix<int> distances. line). DistMatrix& distances) { char quote = ’\"’. Using this interface simplifies main: void main () { apstring line. . apvector<int> quoteIndex (4). public: DistMatrix (int rows). ifstream infile ("distances"). quoteIndex[0] = line. len2). int len3 = line.15. accumulator: A variable used inside a loop to accumulate a result. often by getting something added or concatenated during each iteration.length() .quoteIndex[2] .substr (quoteIndex[0]+1.substr (quoteIndex[3]+1. stream: A data structure that represents a “flow” or sequence of data items from one place to another.substr (quoteIndex[2]+1. city2.quoteIndex[2] . . apstring distString = line.quoteIndex[0] . // add the new datum to the distances matrix distances. len1). int distance = convertToInt (distString). len3). In C++ streams are used for input and output. apstring city2 = line.1. apstring city1 = line.10 Glossary ordered set: A data structure in which every element appears only once and every element has an index that identifies it. 15. distance).1.1.add (city1. GLOSSARY 171 } // break the line up into substrings int len1 = quoteIndex[1] . } I will leave it as an exercise to you to implement the member functions of DistMatrix. int len2 = quoteIndex[3] .10. 172 CHAPTER 15. FILE INPUT/OUTPUT AND APMATRIXES . Revisions to the classes may have been made since that time. apstring // used to indicate not a position in the string extern const int npos.collegeboard. apstring(const char * s).Appendix A Quick reference for AP classes These class definitions are copied from the College Board web page.org/ap/computer-science/html/quick_ref. apstring(const apstring & str). ”Inclusion of the C++ classes defined for use in the Advanced Placement Computer Science courses does not constitute endorsement of the other material in this textbook by the College Board.htm with minor formatting changes. or the AP Computer Science Development Committee. // public member functions // constructors/destructor apstring(). This is probably a good time to repeat the following text. The versions of the C++ classes defined for use in the AP Computer Science courses included in this textbook were accurate as of 20 July 1999.” A. // assignment 173 // // // // construct empty string "" construct from string literal copy constructor destructor . ~apstring(). Educational Testing service. also from the College Board web page. // append str const apstring & operator+= (char ch). ). int find(const apstring & str) const. ). // concatenation operator + apstring operator+ ( const apstring & lhs. apstring operator+ ( const apstring & str. lhs. starting at pos explicit conversion to char * // indexing char operator[ ](int k) const. lhs. const apstring & str ). char ch ). // append char // The following free (non-member) functions operate on strings // I/O functions ostream & operator<< ( ostream & os. apstring operator+ ( char ch. lhs. istream & getline( istream & is. ). // range-checked indexing // modifiers const apstring & operator+= (const apstring & str). int len) const. A. QUICK REFERENCE FOR AP CLASSES const apstring & operator= (const apstring & str).2 apvector template <class itemType> class apvector . ). // // // // // // number of chars index of first occurrence of str index of first occurrence of ch substring of len chars. // range-checked indexing char & operator[ ](int k). // assign str const apstring & operator= (const char * s). apstring substr(int pos.174 APPENDIX A. int find(char ch) const. lhs. // comparison operators bool operator== ( const bool operator!= ( const bool operator< ( const bool operator<= ( const bool operator> ( const bool operator>= ( const apstring apstring apstring apstring apstring apstring & & & & & & lhs. const char * c_str() const. // assign s const apstring & operator= (char ch). istream & operator>> ( istream & is. // assign ch // accessors int length() const. ). apstring & str ). apstring & str ). lhs. const apstring & rhs ). const apstring & str ). const const const const const const apstring apstring apstring apstring apstring apstring & & & & & & rhs rhs rhs rhs rhs rhs ). A. const itemType & fillValue). int numcols() const. // capacity of vector // change size dynamically //can result in losing values A. // size is rows x cols apmatrix(int rows. // default constructor (size==0) apvector(int size). // default size is 0 x 0 apmatrix(int rows.3. // number of rows // number of columns . // accessors int numrows() const. // initial size of vector is size apvector(int size. // destructor // assignment const apvector & operator= (const apvector & vec). int cols. // copy constructor ~apvector(). APMATRIX 175 // public member functions // constructors/destructor apvector(). const itemType & operator[ ](int index) const. // accessors int length() const.3 apmatrix template <class itemType> class apmatrix // public member functions // constructors/destructor apmatrix(). // indexing // indexing with range checking itemType & operator[ ](int index). // all entries == fillValue apmatrix(const apmatrix & mat). int cols). // destructor // assignment const apmatrix & operator = (const apmatrix & rhs). // copy constructor ~apmatrix( ). const itemType & fillValue). // modifiers void resize(int newSize). // all entries == fillValue apvector(const apvector & vec). apvector<itemType> & operator[ ](int k). int newCols). // modifiers void resize(int newRows. QUICK REFERENCE FOR AP CLASSES // indexing // range-checked indexing const apvector<itemType> & operator[ ](int k) const. // resizes matrix to newRows x newCols // (can result in losing values) .176 APPENDIX A. 22 run-time error. 153 random. 121 Rectangle. 4. 141. 132 recursive. 141. 164 ostream. 36. 131. 34. 161 parsing number. 39. 167 statement. 92 prose. 11. 95. 82. 125 scaffolding. 76. 142 programming language. 92 pseudocode. 52 searching. 6 prototyping. 30. 7. 143 sorting. 107 public. 147. 4. 52. 36 redundancy. 152 overloading. 145 encapsulation. 123 printDeck. 133 multiple. 79. 158 precedence. 3. 37. 160 output. 52 rounding. 31 declaration. 103. 44. 128. 132. 53 break. 161 comment. 100. 129. 171 ordering. 9. 29 parameter passing. 88. 126 pass by reference. 6. 141 representation. 129 printCard. 82 inside loop. 155. 80 recursion. 142 parameter. 141. 9 parsing. 6 reference. 163 partial ordering. 19 assignment. 147 resize. 34. 75 pointer. 50 state. 13. 60 incremental. 90. 155. 63 bottom-up. 157 problem-solving. 156. 149 function. 162 stack. 103 eureka. 92 planning. 9 program development. 88. 171 counter. 1 programming style. 141 rank. 99. 171 shuffling. 52 return value. 145 pseudorandom. 166. 158 print Card. 78. 39 poetry. 76 state diagram. 169 return. 48. 143 special character. 7 conditional. 6 Point. 126. 4 same. 42. 106. 149 portability.180 INDEX ordered set. 129 seed. 79. 85. 139 private. 107 semantics. 13. 142. 39. 164. 2 postcondition. 46 Set. 36. 41. 123. 36. 138. 85 pattern accumulator. 68. 92 top-down. 149 pure function. 27. 78 abstract. 123 vector of Cards. 129 return type. 129 pi. 37. 110 polar coordinate. 82 parse. 17 precondition. 137. 76 . 85 pass by value. 76. 106 random number. 164 set ordered. 168 safe language. 145 infinite. 63 loop. 76 operations. 75 Rectangle. 45 variable. 107 copying. 102 stream. 68. 140 subdeck. 74. 82. 75. 61. 85 structure definition. 13. 132. 16 String. 54 . 99 element. 88 while statement. 87 structure. 97 typecasting. 82 instance variable. 58. 58 temporary variable. 40 vector. 67. 56 two-dimensional. 87 top-down design. 9 tab. 87. 19 boolean. 99 initialization. 141 switch statement. 135 int. 19 instance. 138. 45 double. 97. 171 status. 129 counting. 7. 100 of apstring. 54 statistics. 39. 52. 78 as return type. 133. 129 switch. 12. 11. 160 String. 148 as parameter. 121 swapCards. 80 Time. 151 local. 83. 136 syntax. 161 struct. 40 testing. 103 Turing. 13. 45 output. 11 vector. 77 Point. 88 return. 69. 60. 149. 123 of Cards. 159. 4. 127 void. 142 traverse. 110 Time. 11 string concatentation. 164 native C. 12. 21 enumerated. 142 suit. 136 while. 144 this. 48 type. 22 value. 19 bool. Alan. 34. 39. 138 of object.INDEX 181 for. 63 table. 99 temporary. 98 length.
https://www.scribd.com/doc/46921242/thinkCScpp
CC-MAIN-2018-22
refinedweb
47,772
70.19
17 Dec 23:14 2004 Re: tuple return <jastrachan@...> 2004-12-17 22:14:46 GMT 2004-12-17 22:14:46 GMT On 17 Dec 2004, at 22:05, John Rose wrote: > On Dec 17, 2004, at 13:48, jastrachan@... wrote: > >> That opens a little can of worms in the parser I'd imagine? Also that >> begs the question... >> >> x = 1, 2 >> >> is x a list, or array etc? > Yes, that's too ambiguous, at least if you try to work tuples into the > expression language. Agreed. > Example: def x = 1, y. One tuple variable or two variables? > Syntax is easy to fix, though; it's probably enough to require > parentheses: return (1,2), (x,y) = (y,x), etc. > At worst, some sort of ugly noisy tuple operator: return #(1,2), > #(x,y) = #(y,x) > > Better yet, I was thinking the job of tuples might be handled by > lists, given the right semantics for matching of lvalues which are > explicit list constructors: [x,y] = [y,z] Thats an idea. Not support tuples in the language (as its too much of a radical change & causes ambiguity all over the place) but use list notation on the lvalues [a, b, c] = [x, y, z] I like it. I don't think 'tuple returns' are so common as to require a drastic language change; so using the list notation on lvalues sounds a neat solution to me. > FP languages have data structure matching like that; it's really > handy. Sort of a 2.0 thing, maybe. Definitely - I'd like us to sort out the basics ASAP :) James -------
http://permalink.gmane.org/gmane.comp.lang.groovy.user/2909
CC-MAIN-2016-22
refinedweb
266
73.17
Connect and send data via WiFi from WiPy to LoPy Regarding the problems we found to do the same by BLE (), I' m asking if it is possible to send data via WiFi from WiPy to LoPy. Reading the documentation, it seems easy to connect, and then create a socket, but I prefer to ask you if it is possible before wasting my time... Thank you. @amartinez for server node it is not good to have while not wlan.isconnected(): time.sleep_ms(50) You do not connect wifi here only you start Access Point (AP) - look if it start on network list scan on client node side or your PC Update: It's not connecting really, I thought that it was printing the ifcongif but it's not. This is what it prints: @robert-hh thank you Robert. The connection is set correctly, now let's try to send data. Connection code: WiPy (Client - STA mode, transmitter): # WiPy sends data -> Client -> WLAN mode = STA import network import time import pycom # setup as a station wlan = network.WLAN(mode=network.WLAN.STA) wlan.connect('lopy-wlan', auth=(network.WLAN.WPA2, '')) while not wlan.isconnected(): time.sleep_ms(50) print(wlan.ifconfig()) pycom.rgbled(0x007f00) # green # now use socket as usual ... LoPy (Server - AP mode, listener): import network import time from network import WLAN # setup as a station wlan = network.WLAN(mode=network.WLAN.AP) wlan.init(mode=WLAN.AP, ssid='lopy-wlan', auth=(WLAN.WPA2,''), channel=7, antenna=WLAN.INT_ANT) #wlan.connect('your-ssid', auth=(network.WLAN.WPA2, 'your-key')) while not wlan.isconnected(): time.sleep_ms(50) print(wlan.ifconfig()) @amartinez The access point has to set an IP address. By default this is 192.168.4.1. The AP will also run an DHCP server, which distributes IP-addresses to the client. The Client has to connect to the AP. It might be confusing that there are two layers of connection needed: - One at the link level - Access point to Station (this is like plugging in a cable) - One at the socket level - Client to server @livius So, the server will be the listener (LoPy) and the Client sends the data (WiPy)? It's a bit confusing because on BLE its the contrary... In order to listen, have I to set an IP adress? @amartinez you can use STA_AP or in "server node" AP in "client" node STA on server you must listen look here for sample or here @livius thank you. Could you share any code to step on? Or any recommendations about the necessary code? What WLAN mode have I to choose? And what about the network security? I guess the connection is done similar than the example: import network import time # setup as a station wlan = network.WLAN(mode=network.WLAN.STA) wlan.connect('your-ssid', auth=(network.WLAN.WPA2, 'your-key')) while not wlan.isconnected(): time.sleep_ms(50) print(wlan.ifconfig()) # now use socket as usual ... And then, how do I send the data? @amartinez Yes, it is possible But i tested this with 2xWipy2 without lopy But it should work same.
https://forum.pycom.io/topic/1288/connect-and-send-data-via-wifi-from-wipy-to-lopy
CC-MAIN-2022-33
refinedweb
515
65.01
Why is selenium webdriver Firefox not working for unprivileged users? I am trying to use selenium to take screenshots in a Django view in python. Selenium firefox webdriver works well if I start it as root. However, when I try to start it with a non-superuser, it hangs when I try to instantiate the driver. Django is called through the apache user www-data , so it suffers from this problem. Is there a way to make the selenium firefox webdriver run as non-root? From a fresh install of Ubuntu 14.04 I did the following sudo apt-get install python-pip firefox xvfb pip install selenium pyvirtualdisplay useradd testuser And then in the python shell: from selenium import webdriver from pyvirtualdisplay import Display display = Display(visible=0, size=(800, 600)) display.start() driver = webdriver.Firefox() driver.get("") print driver.page_source.encode('utf-8') driver.quit() display.stop() If I login to python as root it works fine, if I use the testuser account the line driver = webdriver.Firefox() has no response or errors. I would be grateful for any suggestions on why this is happening. source to share I had the same problem with Selenium + Firefox on linux. The problem was that linux user: To run these tests Firefox must be able to create a profile (Firefox profile). This profile is in user_home/.mozilla/firefox/profiles So, in your case, make sure that: - This linux user can write in his own home. - In etc/passwd make sure that this user has a default shell, /bin/bash on the example of - In the directory where your webapp is located: try $ ls -larth : if all files in this are owned root , you can try to change the permissions in that folder to allow non-root users to access it (and then allowed to run Firefox + Selenium). You can also change the group permissions and add root and non-root users to this group. source to share
https://daily-blog.netlify.app/questions/2164956/index.html
CC-MAIN-2021-21
refinedweb
326
64.71
IRC log of dawg on 2005-09-13 Timestamps are in UTC. 14:27:46 [RRSAgent] RRSAgent has joined #dawg 14:27:46 [RRSAgent] logging to 14:27:53 [DanC] Meeting: DAWG Weekly 14:28:59 [DanC] Regrets: Souripriya_Das, JeenB 14:29:08 [DanC] Agenda: 14:29:16 [DanC] agenda + Toward Protocol Last Call 14:29:25 [DanC] agenda + SPARQL Protocol and WSDL 14:29:30 [LeeF] Zakim, who's on the phone? 14:29:30 [Zakim] sorry, LeeF, I don't know what conference this is 14:29:31 [Zakim] On IRC I see RRSAgent, Yoshio, Zakim, DaveB, AndyS, EliasT, LeeF, SteveH, afs, ericP, DanC 14:29:33 [AndyS] zakim, who is on the phone 14:29:33 [Zakim] I don't understand 'who is on the phone', AndyS 14:29:34 [DanC] agenda + comment: SPARQL Protocol: inconsistent parameter names 14:29:39 [DanC] Zakim, this will be dawg 14:29:39 [Zakim] ok, DanC, I see SW_DAWG()10:30AM already started 14:29:43 [AndyS] zakim, who is on the phone? 14:29:43 [Zakim] On the phone I see Lee_Feigenbaum, ??P20, ??P19 14:29:45 [Zakim] + +1.978.455.aaaa 14:29:59 [DanC] agenda + issues#valueTesting : "language tag issues" 14:30:01 [EliasT] Zakim, +1.978.455.aaaa is EliasT 14:30:05 [Zakim] +EliasT; got it 14:30:05 [AndyS] zakim, ??P20 is AndyS 14:30:06 [DanC] agenda + BASE IRI resolution comment 14:30:07 [Zakim] +AndyS; got it 14:30:11 [LeeF] Zakim, Lee_Feigenbaum is LeeF 14:30:11 [Zakim] +LeeF; got it 14:30:13 [Zakim] +Yoshio 14:30:13 [DanC] agenda + issues#valueTesting: handling type "error"s 14:30:19 [DanC] agenda + issues#rdfSemantics 14:30:20 [DaveB] Zakim, ??P19 is DaveB 14:30:21 [Zakim] +DaveB; got it 14:30:25 [DanC] agenda + issues#owlDisjunction 14:30:26 [Zakim] +Kendall_Clark 14:30:31 [DanC] agenda + SPARQL QL grammar 14:30:37 [DanC] agenda + issues#badIRIRef 14:30:45 [Zakim] +DanC 14:31:05 [DanC] Zakim, take up item 1 14:31:05 [Zakim] agendum 1. "Convene, take roll, review records and agenda" taken up [from DanC] 14:31:11 [DanC] Zakim, who is on the phone? 14:31:11 [Zakim] On the phone I see LeeF, AndyS, DaveB, EliasT, Yoshio, Kendall_Clark, DanC 14:31:17 [kendall] kendall has joined #dawg 14:31:38 [DanC] Zakim, pick a scribe 14:31:38 [Zakim] Not knowing who is chairing or who scribed recently, I propose DaveB 14:32:12 [DanC] DanC has changed the topic to: RDF Data Access 13 Sep scribe: DaveB 14:32:14 [DanC] scribe: DaveB 14:32:16 [SteveH] whats the conf. code? 14:32:20 [EliasT] 7333 14:32:21 [kendall] 7333 14:32:27 [DanC] Regrets+ JosD 14:32:29 [Zakim] +??P24 14:32:40 [SteveH] Zakim, ??P24 is SteveH 14:32:40 [Zakim] +SteveH; got it 14:33:12 [DaveB] minutes approvde 14:33:35 [DaveB] for 6 sep in 14:33:43 [DaveB] tag conflicts 20sep 14:34:06 [Zakim] +Rachel_Yager 14:34:19 [DaveB] looking for a chair for 20sep 14:34:32 [DaveB] current top canidated is Pat Hayes 14:34:44 [DaveB] as there are a pile of semantics issues 14:35:08 [ericP] DanC, on phone wiht hugo, plh soon 14:35:17 [DanC] roger. 14:35:35 [DanC] Zakim, pick a scribe 14:35:35 [Zakim] Not knowing who is chairing or who scribed recently, I propose DanC 14:35:39 [DanC] Zakim, pick a scribe 14:35:39 [Zakim] Not knowing who is chairing or who scribed recently, I propose Yoshio 14:35:44 [Yoshio] no 14:35:49 [DanC] Zakim, pick a scribe 14:35:49 [Zakim] Not knowing who is chairing or who scribed recently, I propose DaveB 14:35:51 [ericP] ...(re lack of output serialization in LC WD) 14:35:51 [DanC] Zakim, pick a scribe 14:35:51 [Zakim] Not knowing who is chairing or who scribed recently, I propose Yoshio 14:35:53 [DanC] Zakim, pick a scribe 14:35:53 [Zakim] Not knowing who is chairing or who scribed recently, I propose SteveH 14:35:59 [DaveB] 20 sep scribe: steveH 14:36:15 [kendall] I'm willing to backup chair, if needed 14:36:16 [DaveB] 20 sep chair: PatH (possibly) or ... 14:36:28 [AndyS] I did my action. 14:37:27 [DaveB] continuing other actions 14:37:39 [DanC] Zakim, next item 14:37:39 [Zakim] agendum 2. "Toward Protocol Last Call" taken up [from DanC] 14:38:02 [DaveB] publishing work happening today 14:38:10 [DaveB] KC action done, ericp action continued 14:38:23 [DaveB] ... had to make up a namespace name for sparql query interface 14:38:58 [DaveB] in ? 14:39:09 [DanC] <description targetNamespace=" "> 14:39:09 [DaveB] - 14:39:09 [DaveB] <description targetNamespace=" "> 14:39:25 [DaveB] DanC: now been put in the document 14:39:42 [DaveB] KC: was a namespace under proto-wd 14:39:53 [DanC] (it doesn't occur in the .html ; just in the .wsdl) 14:40:05 [kendall] 14:40:11 [EliasT] why "/#" vs "#"? 14:40:36 [DanC] KC's action is done... 14:40:45 [DanC] ACTION EricP: publish proto-wd v 1.68 + changes from as LCWD [continues] 14:40:51 [kendall] heh 14:40:54 [EliasT] heh 14:40:56 [kendall] s/joke/policy/ 14:40:58 [DanC] Zakim, next item 14:40:58 [Zakim] agendum 3. "SPARQL Protocol and WSDL" taken up [from DanC] 14:41:33 [DanC] ACTION: LeeF to draft WSDL 1.1 for SPARQL thingy with AndyS and Elias ETA 9 sep 14:41:38 [kendall] yay 14:41:38 [DanC] -- continues 14:41:44 [DaveB] LeeF: 1st draft of wsdl1.1 done, needs some polishing. doing some example java and python impl 14:41:52 [DaveB] ... if LC is this week, should be able to get code out next week 14:42:00 [DaveB] can send out current code pointer 14:42:18 [kendall] :> 14:42:22 [Zakim] +EricP 14:42:23 [LeeF] 14:42:47 [LeeF] (Java) 14:42:56 [DanC] ACTION: DanC to ask WSDL WG to review WSDL 1.1 and WSDL 2 SPARQL protocol stuff, once both are available 14:42:59 [DanC] -- continues 14:43:10 [DanC] ACTION: KC to work with WSDL WG on describing POST binding with application/x-form-encoded in WSDL 2 14:43:58 [DaveB] KC - have sent 1 mail with 3 issues, 2 are conceptually similar 14:44:06 [DaveB] one of those has turned into a LC issue with tracking number 14:44:20 [DaveB] and wsdlwg has considered a fix and response 14:44:42 [DaveB] ... will send hugo mail to co-ordinate 14:45:15 [Zakim] +Pat_Hayes 14:45:15 [DanC] -- continues 14:45:30 [Zakim] -EliasT 14:45:53 [patH] patH has joined #dawg 14:46:03 [DaveB] wsdl2.0 lc issues list: 14:47:10 [Zakim] +EliasT 14:47:26 [DanC] Zakim, next item 14:47:26 [Zakim] agendum 4. "comment: SPARQL Protocol: inconsistent parameter names" taken up [from DanC] 14:47:26 [DaveB] DanC: you wanted reminding once ericp was back online (chairing?) 14:48:35 [DaveB] PatH is happy to chair 14:48:54 [DaveB] on sep20, ericP backup 14:49:40 [DanC] 2005-09-06T15:25:59Z from arjohn.kampman 14:49:54 [DanC] 14:50:30 [DaveB] action done 14:50:38 [DanC] tracking wierdness. will fix. 14:50:46 [DanC] Zakim, next item 14:50:46 [Zakim] agendum 5. "issues#valueTesting : "language tag issues"" taken up [from DanC] 14:51:07 [DanC] # ACTION: ericp to draft lang-match design, summarizing and citing RFC3066 14:51:12 [DanC] #ACTION: ericp to draft lang-match design, summarizing and citing RFC3066 14:51:15 [DanC] ACTION: ericp to draft lang-match design, summarizing and citing RFC3066 14:51:20 [DanC] -- continues 14:51:40 [DanC] Zakim, next item 14:51:40 [Zakim] agendum 5 was just opened, DanC 14:51:45 [DanC] Zakim, close item 5 14:51:45 [Zakim] agendum 5, issues#valueTesting : "language tag issues", closed 14:51:46 [Zakim] I see 6 items remaining on the agenda; the next one is 14:51:48 [Zakim] 6. BASE IRI resolution comment [from DanC] 14:51:48 [DanC] Zakim, next item 14:51:48 [Zakim] agendum 6. "BASE IRI resolution comment" taken up [from DanC] 14:52:10 [DanC] # 14:52:10 [DanC] ACTION: ericP to send [OK?] message to Bjoern. re BASE IRI resolution comment 14:52:16 [DanC] -- continues 14:52:27 [DanC] Zakim, move to next agendum 14:52:27 [Zakim] agendum 6 was just opened, DanC 14:52:32 [DanC] Zakim, close this item 14:52:32 [Zakim] agendum 6 closed 14:52:34 [Zakim] I see 5 items remaining on the agenda; the next one is 14:52:35 [DanC] Zakim, move to next agendum 14:52:36 [Zakim] 7. issues#valueTesting: handling type "error"s [from DanC] 14:52:38 [Zakim] agendum 7. "issues#valueTesting: handling type "error"s" taken up [from DanC] 14:53:33 [DaveB] my mail 14:53:51 [ericP] A B | NOT A A && B A || B 14:53:51 [ericP] ------------------------------------- 14:53:51 [ericP] E E | E E E 14:53:51 [ericP] E T | E E T 14:53:51 [ericP] E F | E F E 14:53:53 [ericP] T E | F E T 14:53:55 [ericP] T T | F T T 14:53:58 [ericP] T F | F F T 14:54:00 [ericP] F E | T F E 14:54:03 [ericP] F T | T F T 14:54:06 [ericP] F F | T F F 14:54:35 [kendall] "E" is unknown here? 14:54:43 [kendall] or error? 14:54:44 [LeeF] E is Error 14:54:45 [DanC] "E" is like unkown, but it's type error 14:54:50 [kendall] ACK 14:57:52 [DaveB] the temp example (original comment) 14:58:08 [AndyS] 14:58:43 [DanC] DaveB: also matches SQL 14:58:57 [DaveB] PatH - there are lots of ternary logics... 14:59:49 [DaveB] we are looking at and going to approve the NOT A, and A&& B 15:00:19 [DanC] SWH: "error or true" is not true in SQL 15:00:21 [SteveH] mysql> SELECT NULL | 1; 15:00:21 [SteveH] +----------+ 15:00:21 [SteveH] | NULL | 1 | 15:00:21 [SteveH] +----------+ 15:00:21 [SteveH] | NULL | 15:00:22 [SteveH] +----------+ 15:00:40 [DaveB] jeen's doc says T | E -> T for SQL 15:00:55 [DanC] SWH: ah... with || , it does match 15:01:02 [DaveB] we mean logical OR (||) 15:01:25 [SteveH] sorry, typo 15:01:55 [DanC] ACTION DaveB: add to test suite the temperature case from timbl's comment on truth tables 15:02:09 [DaveB] from 15:02:50 [DaveB] PatH - there are other ways to do this, this form is a weak way 15:03:01 [DaveB] DanC - was this part borrowed from XQuery? ericp: No 15:03:44 [DanC] PROPOSED: to change the value testing truth table as per 2005JulSep/0410.html 15:04:14 [DanC] PROPOSED: to change the value testing truth table as per table 1 of 2005JulSep/0410.html 15:04:40 [DanC] so RESOLVED 15:04:49 [DanC] ACTION EricP: change the value testing truth table as per table 1 of 2005JulSep/0410.html 15:05:44 [kendall] I think this would all be a lot easier for us if Tim would just do all the work directly! :> 15:05:57 [DanC] ACTION EricP: respond to commentor 15:06:34 [ericP] -> ericP's proposal that the above truth table meets TimBl's requirements 15:07:45 [DanC] DanC: note gk's comments too 15:07:50 [DanC] Zakim, next item 15:07:50 [Zakim] agendum 8. "issues#rdfSemantics" taken up [from DanC] 15:08:44 [DaveB] issue 15:09:08 [ericP] -> gk's comments 15:09:18 [kendall] what's a lean graph? 15:09:30 [DaveB] kendall: it's defned the rdf semantics 15:09:40 [kendall] thx 15:10:15 [LeeF] Kendall - defined here, I think: 15:10:15 [LeeF] 15:10:17 [DaveB] discussion of comments in agenda 15:10:22 [DanC] Zakim, who's on the call? 15:10:22 [Zakim] On the phone I see LeeF, AndyS, DaveB, Yoshio, Kendall_Clark, DanC, SteveH, Rachel_Yager, EricP, Pat_Hayes, EliasT 15:13:24 [DaveB] ACTION AndyS: write email with 2 use cases on rdf-semantics issues for references 15:14:03 [DaveB] options include 15:14:09 [DaveB] deciding current semantics are ok 15:14:29 [DaveB] say what we have now is ok and postpone looking at this till later 15:14:37 [DaveB] other options involve us getting smarter 15:15:07 [DaveB] or, reduce the scope of the language down to one graph some of the semantics work gets easier 15:15:28 [DaveB] -- 15:16:04 [Zakim] -Rachel_Yager 15:16:05 [DaveB] SH: would probably get objections from removing multiple graphs. People have seen it and are expecting it. 15:16:26 [DaveB] KC: would have to explain tradeoffs of compat with owl / multi-graphs & aggregations 15:16:56 [DaveB] AndyS: EnricoF had distinguished core sparql (1 graph) and full sparql 15:18:00 [DaveB] DanC: there is some momentum for a separate semantics doc 15:18:15 [DaveB] ... but whose is it, a paper by Enrico, a WG note, a WG doc? 15:18:44 [DaveB] for such things as soundness and completeness for sparql 15:18:45 [AndyS] Enrico made other changes that I found to me a significant changes 15:19:13 [AndyS] Enrico made other changes that I found to be a significant changes 15:19:44 [DaveB] and a new doc would have a Schedule Impact 15:20:58 [EliasT] can we quote DanC on the logs, please? 15:21:26 [DaveB] "Semanticists should be obstetricians, not coroners of programming languages. -- John Reynolds" -- quotes DanC 15:21:36 [DaveB] ( found in ) 15:23:25 [DaveB] DaveB has not swapped this semantics stuff in. and am scared 15:24:37 [DaveB] Yoshio: owl disjunction should be one of the service aspects. no semantic obligation in the language. don't want to delay things more. 15:25:18 [AndyS] +1 to minimal like DISTINCT 15:25:30 [kendall] I think the OWL heads would be happy with that, if it worked out. 15:25:36 [AndyS] A feature of the thing (service) being asked. 15:25:43 [DaveB] DanC: would like to treat this like distinct 15:26:07 [DanC] (yes, I think that's what yoshio said, AndyS. A feature of the thing (service) being asked. ) 15:26:21 [Yoshio] exactly 15:26:23 [AndyS] Ack 15:26:26 [kendall] oh, I was talking about Republicans. :> 15:26:33 [DanC] Zakim, who's on the phone? 15:26:33 [Zakim] On the phone I see LeeF, AndyS, DaveB, Yoshio, Kendall_Clark, DanC, SteveH, EricP, Pat_Hayes, EliasT 15:26:35 [kendall] (sorry) 15:27:11 [DanC] Zakim, next item 15:27:11 [Zakim] agendum 9. "issues#owlDisjunction" taken up [from DanC] 15:27:17 [DaveB] issue 15:28:29 [DaveB] ref 15:28:44 [DaveB] ^- the "worker example" / "little house example" 15:29:51 [DaveB] DanC - thinks that IH would be satisfied if sparql was defined in terms of rdf-simple entailment 15:30:00 [DaveB] IH=Ian Horrocks 15:30:29 [kendall] sorry, didn't hear what he said 15:31:30 [DaveB] PatH - if we for e.g. based on owl-entailment we'd have to explain how the semantics such as disjunction translates into owl:oneOf (sp?) ... 15:31:40 [DaveB] (not scribed all of that) 15:33:10 [DanC] hope to make progress on these 2 issues 20 Sep, 4 Oct 15:33:16 [patH] I sugest we shouold not get invoolved with trying to make disjunction in a query fully relate to OWL disjunction. That buys us into a larger set of problkems than our charter allows. We should focus on RDf not OWL. 15:33:51 [DanC] Zakim, next item 15:33:51 [Zakim] agendum 10. "SPARQL QL grammar" taken up [from DanC] 15:35:11 [DaveB] good news: ">news: I've mostly updated to grammar in current editor's draft and got no shift/reduce conflicts. bad news: it's not passing previously working tests (i.e. I'm still fixing it) 15:35:18 [DanC] 1.489 15:35:31 [DanC] 15:35:52 [DanC] "The SPARQL grammar is LL(1) when the rules with uppercased names are used as terminals." 15:37:04 [patH] "if you were the only/tool in the world..." 15:37:31 [ericP] AndyS, Q_IRI_REF, roger -- tx 15:37:42 [DaveB] DanC: what about var names? 15:37:51 [DaveB] afs: can start with digits and underscores (rule 84) 15:38:00 [DanC] VARNAME prod 84 15:38:29 [kendall] zakim, mute me 15:38:29 [Zakim] Kendall_Clark should now be muted 15:38:37 [DaveB] AndyS: NCCHAR1 adds '_' from NCCHAR1p (used for namespace prefixes) 15:39:00 [kendall] fire engines and ambulances 15:41:46 [DaveB] dscusion of lang changes to grammar - possible new builtin, or qnamed-function 15:41:48 [DanC] REQUEST FOR TEST CASE: SELECT ?x WHERE {.} 15:42:00 [DaveB] ... and possibly import the xquery fn (with URI) for the language matching 15:42:51 [DanC] ACTION SteveH: review grammar tests 15:43:00 [DanC] ACTION DaveB: review grammar tests 15:43:24 [DaveB] that's the SyntaxDev dir and subdirs 15:44:00 [DaveB] AndyS: I've got TestBadSyntax working too, should that not be in the test namespace/manifest stuff? 15:44:15 [DanC] Zakim, next item 15:44:15 [Zakim] agendum 11. "issues#badIRIRef" taken up [from DanC] 15:44:32 [DanC] test case: SELECT ?x WHERE { <foo###bar> dc:title ?x } 15:44:33 [DaveB] (that was my message to Andy, not what he said) 15:44:46 [AndyS] Needs Steve to agree and update the doc and scripts 15:45:15 [DanC] "Any IRI references in a SPARQL query string must be valid according to RFC 3987 [RFC3987] and RFC 3986 [RFC3986]." 15:45:22 [SteveH] AndyS, can you point me to that tommorow? I have to run after the telecon 15:45:46 [DanC] (that stuff about BASE is redundant w.r.t. text ericp is wrangling) 15:45:48 [DaveB] -- "IRI References" unnumbered section in 15:47:42 [AndyS] Will add something like "any qname, and <> must be a valid IRI reference" by naming the rules that are involved 15:48:30 [DaveB] IIRC RDF core decided not to check uri syntax? 15:49:43 [DaveB] DanC: are there any cases where a syntactically valid query is invalid? 15:50:28 [patH] possible (?) use case might be using the query protocol to locae illegal URIs in an RDF document. Question is, why does it fall to SPARQL to be the URI censor? 15:50:38 [patH] locae/locate 15:51:05 [DaveB] DanC asked if a query with an unbound prefix is a valid sparql query. 15:53:06 [kendall] zakim, unmute me 15:53:06 [Zakim] Kendall_Clark should no longer be muted 15:54:23 [kendall] zakim, mute me 15:54:23 [Zakim] Kendall_Clark should now be muted 15:56:08 [Yoshio] q+ to ask if it implies every SPARQL server MUST check the validity or it will be unconformant? I think we could separate conformance of a query and of a server 15:56:15 [AndyS] Difficult to find a good IRI library (JJC is looking at this for us at the moment) 15:57:09 [AndyS] ARQ catches ### today - thinking of making it switchable 15:57:17 [DanC] PROPOSED: that SELECT ?x WHERE { <foo###bar> dc:title ?x } is not a SPARQL query string; that Q_IRI_REF's must conform to generic IRI syntax 15:57:24 [kendall] zakim, unmute me 15:57:24 [Zakim] Kendall_Clark should no longer be muted 15:57:30 [DanC] ack Yoshio 15:57:30 [Zakim] Yoshio, you wanted to ask if it implies every SPARQL server MUST check the validity or it will be unconformant? I think we could separate conformance of a query and of a server 15:57:36 [DanC] Zakim, who's on the phone? 15:57:36 [Zakim] On the phone I see LeeF, AndyS, DaveB, Yoshio, Kendall_Clark, DanC, SteveH, EricP, Pat_Hayes, EliasT 15:57:40 [kendall] zakim, mute me 15:57:40 [Zakim] Kendall_Clark should now be muted 15:58:04 [kendall] FWIW, I support the proposal that Q_IRI_REFs must conform to generic IRI syntax. 15:59:41 [DanC] y a y y y a n n n a 16:00:24 [DanC] PROPOSED: that SELECT ?x WHERE { <foo###bar> dc:title ?x } is not a SPARQL query string; that Q_IRI_REF's must conform to generic IRI syntax 16:01:01 [DanC] hayes, harris, andy, ericp abstain 16:01:11 [kendall] FYI: We're out of time. :> 16:01:40 [DanC] so RESOLVED. hayes, harris, andy, ericp abstain 16:01:52 [Zakim] -DaveB 16:01:53 [DanC] ADJOURN. 16:02:02 [DanC] dave, do you have what you need to produce the record? 16:02:03 [Zakim] -SteveH 16:02:08 [DanC] RRSAgent, make logs world-access 16:02:15 [DaveB] yes I think so 16:02:23 [kendall] zakim, unmute me 16:02:23 [Zakim] Kendall_Clark should no longer be muted 16:02:35 [EliasT] yay! 16:02:51 [EliasT] down with the protocols! 16:03:20 [EliasT] (except for SPARQL Protocol, of course) 16:03:43 [ericP] EliasT, please preface protocol comments with PROTOCOL: for tracking purposes 16:04:09 [Yoshio] I'm wondering if the reasons for abstain(ation?) has things to do with the restriction that every SPARQL server should check the validity, (but seems too late... :( 16:04:16 [EliasT] noted. thanks. :-) 16:04:29 [Zakim] -Kendall_Clark 16:04:45 [SteveH] Yoshio, yes, thats wy i abstained 16:04:55 [AndyS] me too 16:05:02 [patH] yoshio, I think the idea is that who checks is not specified, but legasl;ity is. 16:05:24 [Zakim] -EliasT 16:05:25 [Zakim] -DanC 16:05:27 [Zakim] -Pat_Hayes 16:05:28 [Zakim] -LeeF 16:05:28 [Zakim] -EricP 16:05:30 [Zakim] -AndyS 16:05:35 [Zakim] -Yoshio 16:05:36 [Zakim] SW_DAWG()10:30AM has ended 16:05:37 [Zakim] Attendees were EliasT, AndyS, LeeF, Yoshio, DaveB, Kendall_Clark, DanC, SteveH, Rachel_Yager, EricP, Pat_Hayes 16:06:17 [Yoshio] I (also) don't like the idea that every SPARQL server MUST check the validity. 16:07:13 [Yoshio] We may separate the validity of query from its detection 16:07:36 [DaveB] validity of a query I can live with 16:07:54 [DaveB] checking the syntax of every URI in the data is more of a burden 16:09:03 [LeeF] Is there a non-cumbersome way to say that queries with bad URIs are invalid but need not be checked while still expecting a query processor to check that "jifwjiew" is not a valid SPARQL query? 16:10:51 [EliasT] EliasT has left #dawg 16:10:56 [DaveB] not really unless it's something like match the sparql grammar without doing the checks given indirectly in references such as URIs 16:11:47 [Yoshio] For me, just expecting is OK in the sense that a server SHOULD check, but I'm not happy with "MUST" 16:11:54 [SteveH] well, sparql allready defines what a valid query looks like at the syntax level, and there was/is some extra text that tells you you have to look inside IRIs 16:15:52 [Yoshio] Yoshio has left #dawg 18:02:48 [Zakim] Zakim has left #dawg
http://www.w3.org/2005/09/13-dawg-irc
CC-MAIN-2016-30
refinedweb
3,985
61.7
When. The principle of attraction Let data attract behavior. I don’t suppose I invented this, but the intent behind the principle of attraction is that you should organize your modules and functions (behavior) around data structures and abstractions (data). In Elixir, the principle would tell us to organize our modules and functions around Elixir structs, behaviours, and protocols. Let’s take a look at an example of a popular Elixir library, Plug. Plug is a great library for building web applications. It handles anything (and everything) related to the request and response. If you come from the Ruby world, Plug will remind you of Rack. At the core of Plug are two things, a connection struct called Plug.Conn and a specification for what exactly is a plug. Once you notice those two things, you will see that all modules and functions revolve around one of those two things. Plug.Conn First, note that all functions within the Plug.Conn module are related to a connection struct, which is defined inside that very module. But if you take a closer look, you will also see how each of those functions takes in a connection struct. Here’s a list of a few functions defined in Plug.Conn, assign(conn, key, value) clear_session(conn) put_resp_content_type(conn, content_type, charset) put_resp_header(conn, key, value) put_session(conn, key, value) send_resp(conn, status, body) Notice a pattern? They all take conn, the connection struct, as their first argument, and though you can’t see it, they all return a (modified) connection struct. They do that because this module revolves around the Plug.Conn struct. And passing the connection struct as the first argument allows for composition via pipelines. Take a look at this example for interacting with a request, conn |> put_session(:current_user, user) |> put_resp_header(location, "/") |> put_resp_content_type("text/html") |> send_resp(302, "You are being redirected") Very clean, right? So, the first way to apply the principle of attraction is to organize your modules and functions around the struct that they are modifying. The struct attracts the functions. Plug as a specification The second way in which Plug is organized is around the notion of a plug. That may sound like a tautology, but what I mean is that many Plug modules make use of a plug or are themselves valid plugs (that is they follow the Plug specification). What is the Plug specification? Glad you asked. In order for a module to be a valid plug, it must define an init/1 function that takes a set of options and returns a set of options, and it must define a call/2 function that takes a connection struct as its first argument, the set of options as its second one, and it must return a connection struct. A function plug simply has to abide by the same specification as the call/2 function in the module plug, taking the connection struct and the options as arguments, and returning a connection struct. This is an example of a valid module plug, defmodule CustomPlug do def init(opts) do opts end def call(conn, _opts) do conn end end Now let’s take a look at how Plug, the library, builds modules around the notion of plugs. Plug.Builder is a module in the Plug library that allows us to define a pipeline of plugs that will be executed sequentially in the order in which they are defined. The magic really comes in when many modules in the Plug library are plugs themselves, and can be thus used in such a pipeline. Let’s look at an example, defmodule MyPlugPipeline do use Plug.Builder plug Plug.Logger plug Plug.RequestId plug Plug.Head plug :hello def hello(conn, _) do Plug.Conn.send_resp(conn, 200, "Hello world!") end end Note how Plug.Logger, Plug.RequestId, and Plug.Head are themselves plugs and for that reason can be used in the pipeline provided by Plug.Builder. We can also mix and match by defining our own function plug within the module (the plug :hello part). By organizing modules and functions around the plug abstraction, Plug.Builder allows us to compose rich pipelines with other modules and functions that satisfy the abstraction. What next? I certainly think there are other principles by which to organize your functional code, but I do recommend keeping this one handy. I have found it to be quite useful! It even works when modules are nested within other modules. For example, Plug.Conn does not have all the logic related to a connection struct in itself. Sometimes it uses other modules that are namespaced under Plug.Conn like Plug.Conn.Status. But if you look closely, Plug.Conn.Status also uses the principle of attraction by having all of its functions deal with the same piece of data, a status map defined inside the module.
https://thoughtbot.com/blog/organize-your-functional-code
CC-MAIN-2020-40
refinedweb
811
64.71
Hey guys, I know this is not a robot but I could really use a second set of eyes on this one... . Still tweaking my optimizer for Jansen (Klann) walking linkages. I started posting some of the more promising optimizations at Make.. There are two main concerns I have with the Theo Jansen linkages, which have shown up in rough prototypes., My Company was invited to the city of Karamay in Xinjiang China to demonstrate our robots at a Science Festival. Xinjiang is in the North West corner of China and borders a number of other countries. We had a 5 hour flight from Guangzhou (formerly Cantong) to Urmaqi and then another 1 hour flight to Karamay Where we were met by a lovely lady who's English name was Jenny. Click on the map below for a hi-resolution I have not put togethger documentation for my Bots code. The code is evolving too quickly for detailed up front documentation. I would like tos tate that a primary goal of doing this Bot was to help me learn Object Oreinted Programming, as well as get me used to programming again. it's been 20 years since I've written something more than a simple shell. python or Perl script. Thus I will warn you this code is chocked full of redundancies and inefficiencies. Bear with me, an old dog is learning new tricks, it's just taking time :) im working on the ankle servos, so im just using the example sweep, an i have them zeroed at 90 deg. I can get it from 90 to 180 an back but i cant get it to go 90 - 0. #include <Servo.h> Servo myservo; // create servo object to control a servo int pos = 90; void setup() { myservo.attach(9); } void loop() Platform While messing with my Arduino I found the circuit diagraming program Fritzing. I really love this program, it makes docummenting breadboard circuits increadibly easy. You can get the software from their site: fritzing.org. Hi everyone, im new to robot building and this will be my first robot, i do not have any materials for it yet i only have the completed code and a deadline of 4 weeks because of it being a school project aswell as a new hobby. After, HMOD-1 Update 1 HMOD-1 Update 2 HMOD-1 upper body under construction:
http://letsmakerobots.com/blog?page=8
CC-MAIN-2014-15
refinedweb
398
69.72
Components and supplies Necessary tools and machines About this 'Start now'. Step 2: Create your first product - In your account, at the sidebar on the left click on 'Things'. - The click on 'Create New Product' and you will see the following screen: - Fill out the name of your new product. - As 'Board' choose Arduino. - If you want, you can add a description. - We leave the format at JSON. - Click on 'Create'. Step 3: Activate your thing! - Click on your new product. - In the 'Things' section click on 'Get activation codes'. - Then click on 'Generate Activation Codes'. - You will be asked how many activation codes you need, leave it at 1 and click 'Generate'. - After that, you may have to reload the page. - Then click on the '+' sign on the right side. - A window opens, click on 'Accept'. 'Download 'Things' at the sidebar on the left. - Click on your product. - On the right side of the token you use click on 'Details'. - You wll see this page: - On the right side, we can play around with different visualizations or click on 'Real 'Edit Dashboard'. - Then on 'Add Widget'. - A window opens: - Enter a name for your widget. - In 'Data Source' choose 'Thing Resource'. - In Product choose your product. - Choose your thing. - In 'Resource' choose 'Temperature'. - In 'Value Range' choose 'Last Value'. - In 'Widget Type' choose 'Gauge'. - Activate the 'Realtime' option. - It should be looking something like this: - Click on 'Add'. - Now, at the dashboard scroll down at you will see our new widget: - We still have to choose the limits for our widgets, for now let's put -10 and 40. - Click on 'Save' and you should see the message: 'Values updated!' - Reload the page aaaaand: - You can see our beautiful widget! Step 11: Have a cold beer Cheers! ;) Code Fridge monitor sketchArduino #include <WiFi101.h> #include <WiFiClient.h> #include <OneWire.h> #include <thethingsiO_mkr1000.h> OneWire ds(2); #define WIFI_AP "YOUR ESSID HERE #define WIFI_PWD "YOUR PASSWORD HERE" int status = -1; int millis_start; #define TOKEN "YOUR TOKEN HERE" thethingsiOWiFi thing(TOKEN); void setup(void) { millis_start = millis(); Serial.begin(115200); startWifi(); } // because the result is a 16 bit signed integer, it should // be stored to an "int16_t" type, which is always 16 bits // even when compiled on a 32 bit processor.; fahrenheit = celsius * 1.8 + 32.0; Serial.print(" Temperature = "); Serial.print(celsius); Serial.print(" Celsius, "); Serial.print(fahrenheit); Serial.println(" Fahrenheit"); if (millis() >= millis_start + 10000){ thing.addValue("Temperature", celsius); thing.send(); millis_start = millis(); } } void startWifi(){ Serial.println("Connecting MKR1000 to network..."); // WiFi.begin(); // attempt to connect to Wifi network: while ( status != WL_CONNECTED ) { Serial.print("Attempting to connect to WPA SSID: "); Serial.println(WIFI_AP); WiFi.begin(WIFI_AP, WIFI_PWD); // wait 10 seconds for connection: delay(10000); status = WiFi.status(); } } Schematics Author thethings.iO - 1 project - 9 followers Published onApril 11, 2016 Members who respect this project you might like
https://create.arduino.cc/projecthub/thethingsio/monitor-fridge-with-arduino-mkr1000-and-thethings-io-b40819
CC-MAIN-2018-09
refinedweb
476
71.1
A Builder is used to create Topological Data Structures.It is the root of the Builder class hierarchy. More... #include <TopoDS_Builder.hxx> A Builder is used to create Topological Data Structures.It is the root of the Builder class hierarchy. There are three groups of methods in the Builder : The Make methods create Shapes. The Add method includes a Shape in another Shape. The Remove method removes a Shape from an other Shape. The methods in Builder are not static. They can be redefined in inherited builders. This Builder does not provide methods to Make Vertices, Edges, Faces, Shells or Solids. These methods are provided in the inherited Builders as they must provide the geometry. The Add method check for the following rules : Add the Shape C in the Shape S. Exceptions. Make an empty Compound. Make an empty Composite Solid. The basic method to make a Shape, used by all the Make methods. Make an empty Shell. Make a Solid covering the whole 3D space. Make an empty Wire. Remove the Shape C from the Shape S. Exceptions TopoDS_FrozenShape if S is frozen and cannot be modified.
https://dev.opencascade.org/doc/occt-6.9.0/refman/html/class_topo_d_s___builder.html
CC-MAIN-2022-27
refinedweb
188
78.96
Hide Forgot Document URL: Section Number and Name: NEW Describe the issue: We need to have information on how to change the log level for the various services, in the docs. Suggestions for improvement: Unclear; as it does not seem possible given the ansible role/values. But CEE needs a way to set/change the log level within the pod to debug issues with the service. Additional information: Eample issue: if heapster can't read data from all namespaces, hawkular can't pull the data! so if you run: > curl -s -k -H "Authorization: Bearer $HEAPSTER_TOKEN" -H "Hawkular-tenant: lab6" -X GET\&buckets=1 You get an error that can't be tracked down in the hawkular pod.
https://partner-bugzilla.redhat.com/show_bug.cgi?id=1514236
CC-MAIN-2020-34
refinedweb
118
57.61
Leanplum Source Good to know: Event source The Leanpl. Leanplum is a multi-channel customer engagement platform that helps Growth and Marketing teams to achieve their engagement and revenue goals. When you add Leanplum as a Source, Segment starts collecting Leanplum engagement events (for example, Email Open, Push Delivered), which you can then connect to a destination of your choice or load in your data warehouse. The Leanplum source integration is an event source, which means that it sends Leanplum engagements as events. Collections represent the different messaging events that Leanplum sends to Segment as a streaming source. In your Segment warehouse, each collection gets its own table, as well as a tracks table that aggregates all the events into a single table. This source is maintained by Leanplum. For any issues with the source, contact Leanplum Support. Good to know: This page is about the Leanplum Segment source, which sends data into Segment. There’s also a page about the Leanplum Segment destination, which receives data from Segment! Getting Started Leanplum calls the Source integration “Segment Feed” - this is the name you will see in their dashboard and documentation. - From the Segment Sources page click Add Source. - Configure your source and give it a name. This also generates a schema, which creates a namespace you can query against in a warehouse. We recommend that you name your source to represent the environment you are setting up (for example, Prod, Dev, Staging) - On the overview page you will see the Segment write key. Copy it. - Go to your Leanplum dashboard. In the navigation, under “More”, find your Partner Integrations page. Open the configuration for Segment. - Find the “Feed” setup, paste your Segment write key there and click “Save”. Congratulations! The integration is up and running! Events Below is a list of events Leanplum sends to Segment Event properties Below is a list of event properties, which might be associated with each Leanplum event Adding Destinations Now that your Source is set up, you can connect it to Destinations. Log into your downstream tools and check to see that your events are populating and that they contain all the properties you expect. If all your events and properties are not showing up, refer to the Source docs for troubleshooting. If you experience any issues with how the events arrive in Segment, contact the Leanplum team. Send data to Leanplum Segment and Leanplum work better together when connected bi-directionally. With the Leanplum Destination, you can send client-side or server-side data, as well as connect Personas; which you can then turn into precisely targeted personalized messages. Learn more at our Leanplum Destination docs. This page was last modified: 28 Aug 2020 Need support? Questions? Problems? Need more info? Contact us, and we can help!
https://segment.com/docs/connections/sources/catalog/cloud-apps/leanplum/
CC-MAIN-2021-43
refinedweb
464
64.41
I'm trying to make my use of futures as lightweight as possible. Here is my current test code : import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future import scala.util.Failure import scala.util.Success object Test1 extends App { def lift[A](a: A): Future[A] = Future { a } def ap[A, B](fct: Future[A => B], param: Future[A]): Future[B] = for { c <- param o <- fct } yield (o(c)) implicit def valToFuture[A](elem: A): Future[A] = lift(elem) implicit class FutureInfix[A, B](val x: Future[A => B]) extends AnyVal { def <*>(that: Future[A]) = ap(this.x, that) } val plus1: Int => Int = (x: Int) => x + 1 val cst1: Int = 1 val extracted: Future[Int] = ap(plus1, cst1) val extracted2: Future[Int] = lift(plus1) <*> lift(cst1) val extracted3: Future[Int] = plus1 <*> cst /* * - value <*> is not a member of Int ⇒ Int * - not found: value cst */ } a <*> b ap(a,b) I think you're bumping up against the "one at a time" rule. From Programming in Scala, (1st edition):. As @tkachuko has pointed out, there likely is a work-around for this limitation using implicit parameters, but one simple solution is to split FutureInfix into two parts. implicit class FromFutureInfix[A, B](x: Future[A => B]) { def <*>(that: Future[A]) = ap(x, that) } implicit class ToFutureInfix[A, B](x: A => B) { def <*>(that: A) = ap(x, that) }
https://codedump.io/share/p3qpBieR2VHm/1/stacking-implicits-conversions
CC-MAIN-2017-04
refinedweb
228
53.21
>>> On 01.07.10 at 10:32, George Dunlap <dunlapg@xxxxxxxxx> wrote: > On Thu, Jul 1, 2010 at 9:04 AM, Jan Beulich <JBeulich@xxxxxxxxxx> wrote: >> The point is to prevent the compiler from doing the memory reads >> more than once (which it is permitted to do on non-volatiles). As >> said in the submission comment, this could be done via barriers too, >> but one of the two has to be there. > > I understand what the volatile modifier is supposed to do. :-) > (Although I think you've got it backwards -- it forces the compiler to > do memory reads every time, instead of doing them only once and > caching them in a register.) My question is, why do you think the I don't think so - I made each function read the fields exactly once, storing into local variables as necessary. > volatile modifier is necessary? What kinds of situations are you > trying to protect against? What terrible havoc can a broken / rogue > xentrace binary wreak upon the hypervisor if we don't have the > volatiles in? The issue we had got reported: A crashed hypervisor. The thing is that code that uses fields that code outside the hypervisor may modify must in no case imply that consistency checks done earlier in the code still apply when re-reading the data from memory. Hence we have to make sure that reads happen exactly once, and checks plus any consumption happen on/from the values kept locally, not by re-reading the shared buffer fields. > Moreover, the purpose of volatile is slightly different than memory > barriers. AFAICT from the rather sparse documentation, "volatile" > doesn't prevent a compiler from re-ordering memory accesses that it > deems independent. That's what the memory barriers are for. Ordering isn't a problem here, but enforcing the read-once requirement can be done either way afaict. > At least one specific example where volatile helps would be appreciated. static inline struct t_rec *next_record(const struct t_buf *buf) { u32 x = buf->prod; *** no read at all *** if ( !tb_init_done || bogus(x, buf->cons) ) *** read buf->prod *** return NULL; if ( x >= data_size ) *** read buf->prod again *** x -= data_size; *** x = buf->prod - data_size; (reading buf->prod a third time) *** *** else *** *** x = buf->prod; *** ASSERT(x < data_size); return (struct t_rec *)&this_cpu(t_data)[x]; } Jan _______________________________________________ Xen-devel mailing list Xen-devel@xxxxxxxxxxxxxxxxxxx
http://old-list-archives.xen.org/archives/html/xen-devel/2010-07/msg00004.html
CC-MAIN-2016-30
refinedweb
390
59.84
memory¶ This page contains tutorials about the memory package. Calling a virtual function¶ This is a simple example for calling a virtual function in CS:S. import core from memory import DataType from memory import Convention from mathlib import Vector from entities.helpers import pointer_from_index from entities.helpers import index_from_pointer # CBaseEntity* CCSPlayer::GiveNamedItem(char const*, int) # Index on Windows is 400. On Linux it is 401. GIVE_NAMED_ITEM_INDEX = 400 if core.PLATFORM == 'windows' else 401 def give_named_item(index, item, slot=0): # Retrieve the player's pointer. ptr = pointer_from_index(index) # Now, we can get and wrap the virtual function. To do this, we need # to pass the index of the virtual function in the virtual function table # of the CCSPlayer class. This index might change after a game update. # We also need to specify the calling convention. Since it's a normal # member function, the calling convention is THISCALL. # For the third argument a tuple is required that defines the types of the # arguments of the function. In this case we need to pass a pointer # (the this-pointer), a string that specifies the item that should be # given and an integer that defines the slot/sub type of the item. # For the fourth and last argument we need to define the return type of the # virtual function. In this case the function returns a pointer to the # created entity. GiveNamedItem = ptr.make_virtual_function( GIVE_NAMED_ITEM_INDEX, Convention.THISCALL, (DataType.POINTER, DataType.STRING, DataType.INT), DataType.POINTER ) # Finally, we can call the virtual function! Since many functions in # Source.Python's API require an index instead of a pointer, we will # convert the returned pointer to an index. return index_from_pointer(GiveNamedItem(ptr, item, slot)) # Usage example: # entity_index = give_named_item(my_player_index, 'weapon_awp') Calling a virtual function with non atomic arguments¶ This example will cover calling a virtual function which requires two non atomic arguments. This example was made for CS:S. import core from memory import DataType from memory import Convention from mathlib import Vector from entities.helpers import pointer_from_index # void CBaseAnimating::GetVelocity(Vector*, Vector*) # Index on Windows is 140. On Linux it is 141. GET_VELOCITY_INDEX = 140 if core.PLATFORM == 'windows' else 141 def get_velocity(index): # Retrieve the entity's pointer. ptr = pointer_from_index(index) # Now, get and wrap the virtual function. Again, we need to pass the # virtual function index and the calling convention. # The tuple that defines the types of the arguments will now contain three # times Argument.POINTER. The first pointer stands for the this-pointer. # The other two stand for the Vector* arguments. # This time the function doesn't return anything. Instead the return value # is "returned" by modifying the two Vector arguments. This is a common # practice in C/C++ to return multiple return values. GetVelocity = ptr.make_virtual_function( GET_VELOCITY_INDEX, Convention.THISCALL, (DataType.POINTER, DataType.POINTER, DataType.POINTER), DataType.VOID ) # Since Source.Python exposes the Vector class, we don't even need to # reconstruct the memory structure of the both vectors. So, we just need # to create two new Vector objects. velocity = Vector() angle = Vector() # Finally, call the function! But what's happening here? Source.Python # converts both Vector objects to a Pointer object at first and then # accesses the memory addresses of the Vector objects which were allocated # internally. Pretty cool, eh? This works with every object whose class # was exposed by Source.Python and every object that is an instance of # CustomType. GetVelocity(ptr, velocity, angle) # After the function modified the vectors just return them. return (velocity, angle)
http://wiki.sourcepython.com/developing/module_tutorials/memory.html
CC-MAIN-2022-27
refinedweb
576
51.85
This package contains libraries and tools for NetFlow versions 1, 5 and 9, and IPFIX. It is available on PyPI as "netflow". Version 9 is the first NetFlow version using templates. Templates make dynamically sized and configured NetFlow data flowsets possible, which makes the collector's job harder. The library provides the netflow.parse_packet() function as the main API point (see below). By importing netflow.v1, netflow.v5 or netflow.v9 you have direct access to the respective parsing objects, but at the beginning you probably will have more success by running the reference collector (example below) and look into its code. IPFIX (IP Flow Information Export) is based on NetFlow v9 and standardized by the IETF. All related classes are contained in netflow.ipfix. Licensed under MIT License. See LICENSE. If you chose to use the classes provided by this library directly, here's an example for a NetFlow v5 export packet: 0005for example. netflow.parse_packet()function with the payload as first argument (takes string, bytes string and hex'd bytes). Example UDP collector server (receiving exports on port 2055): import netflow import socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(("0.0.0.0", 2055)) payload, client = sock.recvfrom(4096) # experimental, tested with 1464 bytes p = netflow.parse_packet(payload) # Test result: <ExportPacket v5 with 30 records> print(p.header.version) # Test result: 5 Or from hex dump: import netflow p = netflow.parse_packet("00050003000379a35e80c58622a...") # see test_netflow.py assert p.header.version == 5 # NetFlow v5 packet assert p.flows[0].PROTO == 1 # ICMP flow In NetFlow v9 and IPFIX, templates are used instead of a fixed set of fields (like PROTO). See collector.py on how to handle these. You must store received templates in between exports and pass them to the parser when new packets arrive. Not storing the templates will always result in parsing failures. Since v0.9.0 the netflow library also includes reference implementations of a collector and an analyzer as CLI tools. These can be used on the CLI with python3 -m netflow.collector and python3 -m netflow.analyzer. Use the -h flag to receive the respective help output with all provided CLI flags. Example: to start the collector run python3 -m netflow.collector -p 9000 -D. This will start a collector instance at port 9000 in debug mode. Point your flow exporter to this port on your host and after some time the first ExportPackets should appear (the flows need to expire first). After you collected some data, the collector exports them into GZIP files, simply named <timestamp>.gz (or the filename you specified with --file/ -o). To analyze the saved traffic, run python3 -m netflow.analyzer -f <gzip file>. The output will look similar to the following snippet, with resolved hostnames and services, transferred bytes and connection duration: 2017-10-28 23:17.01: SSH | 4.25M | 15:27 min | local-2 (<IPv4>) to local-1 (<IPv4>) 2017-10-28 23:17.01: SSH | 4.29M | 16:22 min | remote-1 (<IPv4>) to local-2 (<IPv4>) 2017-10-28 23:19.01: HTTP | 22.79M | 47:32 min | uwstream3.somafm.com (173...) to local-1 (<IPv4>) 2017-10-28 23:22.01: HTTPS | 1.21M | 3 sec | fra16s12-in-x0e.1e100.net (2a00:..) to local-1 (<IPv6>) 2017-10-28 23:23.01: SSH | 93.79M | 21 sec | remote-1 (<IPv4>) to local-2 (<IPv4>) 2017-10-28 23:51.01: SSH | 14.08M | 1:23.09 hours | remote-1 (<IPv4>) to local-2 (<IPv4>) Please note that the collector and analyzer are experimental reference implementations. Do not rely on them in production monitoring use cases! In any case I recommend looking into the netflow/collector.py and netflow/analyzer.py scripts for customization. Feel free to use the code and extend it in your own tool set - that's what the MIT license is for! The library was specifically written in combination with NetFlow exports from Hitoshi Irino's fork of softflowd (v1.0.0) - it should work with every correct NetFlow/IPFIX implementation though. If you stumble upon new custom template fields please let me know, they will make a fine addition to the netflow.v9.V9_FIELD_TYPES collection. The test files contain tests for all use cases in the library, based on real softflowd export packets. Whenever softflowd is referenced, a compiled version of softflowd 1.0.0 is meant, which is probably NOT the one in your distribution's package. During the development of this library, two ways of gathering these hex dumps were used. First, the tcpdump/Wireshark export way: softflowdwith the -r <pcap_file>flag. softflowd reads the captured traffic, produces the flows and exports them. Use the interface you are capturing packets on to send the exports to. E.g. capture on the localhost interface (with -i loor on loopback) and then let softflowd export to 127.0.0.1:1337. CFLOW"decode as" dissector on the export packets (e.g. based on the port). The datafields should then be shown correctly as Netflow payload. Second, a Docker way: eth0and exporting to e.g. 172.17.0.1:1337. softflowctl dump-flows. softflowctl expire-all. CFLOWand copy the hex value from the NetFlow packet. Your exported hex string should begin with 0001, 0005, 0009 or 000a, depending on the version. The collector is run in a background thread. The difference in transmission speed from the exporting client can lead to different results, possibly caused by race conditions during the usage of the GZIP output file.
https://awesomeopensource.com/project/bitkeks/python-netflow-v9-softflowd
CC-MAIN-2021-25
refinedweb
919
60.82
Opened 7 years ago Closed 3 years ago #10739 closed Bug (needsinfo) MySQL and order_by() Description (last modified by kmtracey) I've found a strange bug in our Damned Lies application (Open Source), so I've added a test case to identify it. actions_db [<ActionDb: UNDO (6)>, <ActionDb: RP (5)>, <ActionDb: UT (4)>, <ActionDb: RT (3)>, <ActionDb: UNDO (2)>, <ActionDb: RT (1)>] actions_db[0] <ActionDb: RT (1)> len(actions_db) 6 actions_db[0] <ActionDb: UNDO (6)> Attachments (1) Change History (12) comment:1 Changed 7 years ago by kmtracey comment:2 Changed 7 years ago by russellm - Resolution set to invalid - Status changed from new to closed In addition to using preview, if you could go so far as to, say, describe the actual problem, that would be just grand. I gather that you are getting unexpected output. The ticket title implies that the problem is related to MySQL and order_by(). Evidently a call to len() fixes the problem (or masks the problem in interesting ways). You provide a link to a 500 line test case, of which I'm guessing maybe the last 40 lines are relevant. Of course, that test case isn't standalone, and doesn't use standard Django model calls - it's deeply embedded in an application called "Damned Lies". Unfortunately, the fact that your project is open source doesn't mean that I'm going to find your problems for you. I have no doubt you have found a problem. If you want to get this problem resolved, you're going to need to meet us half way - with a minimal test case for reproducing the problem. "Download Damned Lies" is not that set of instructions. If you care to provide us with a minimal test case, feel free to reopen this ticket. comment:3 Changed 7 years ago by stephaner Russel, you're right my bug report sucks and I won't take offense for that! You're kind to reply with a long explanation :) I'll try to create a real bug report as soon as I've free time. The bug is really nasty because I can reproduce it on 2 of my PC but another Damned Lies developer can't so I'm intend to create a minimal Django project with fixtures and the failing test (I hope to be able to isolate the bug) then I'll test this minimal project on other Linux distributions before submitting the new report. I've also begun to test different MySQL settings. PS: I don't like MySQL, grrr! Changed 7 years ago by stephaner Contains really small files (models.py, tests.py and JSON dump) comment:4 Changed 7 years ago by stephaner - milestone changed from 1.0.3 to 1.1 - Resolution invalid deleted - Status changed from closed to reopened - Version changed from 1.0 to SVN The bug occurs on Ubuntu 8.10 (Python 2.5.2 and MySQL 5.0.67-0ubuntu6) with Django 1.0.2 and Django 1.1 (SVN) but not on Ubuntu 9.04 (Python 2.6). def test_mysql(self): actions_db = ActionDb.objects.filter(state_db__id=1).exclude(name='WC').order_by('-id') # So the last action is UNDO # but 'RT' is returned! self.assertEqual(actions_db[0].name, 'UNDO') # Here be dragons! A call to len() workaround the bug (try to move it)! len(actions_db) self.assertEqual(actions_db[0].name, 'UNDO') comment:5 Changed 7 years ago by russellm - milestone 1.1 deleted This doesn't appear to cause data loss, so I'm deferring this from the v1.1 schedule comment:6 Changed 7 years ago by Alex - Triage Stage changed from Unreviewed to Accepted comment:7 Changed 5 years ago by SmileyChris - - Status changed from reopened to new comment:11 Changed 3 years ago by akaariai - Resolution set to needsinfo - Status changed from new to closed I call for close of this bug. Seems to be about old versions of MySQL and/or Python, and if this was anything severe we would surely have heard more of this. Reformatted description. Please use preview.
https://code.djangoproject.com/ticket/10739
CC-MAIN-2016-26
refinedweb
677
63.29
The web.xml file is only used when deploying a Java app to a runtime that includes the Eclipse Jetty 9/ servlet 3 server. For more details, see the Eclipse Jetty 9.3 Runtime.. For more information about the web.xml standard, see the Metawerx web.xml reference wiki and the Servlet specification. About (e.g.> Note: The <jsp-file> must start with a forward slash ( /) if the JSP is in the application's root directory. may may an simple filter implementation that logs a message, and passes control down the chain, which may include other filters or a servlet, as described by the deployment descriptor: package mysite.server; import java.io.IOException; import java.util.logging.Logger;; public class> Note: Filters are not invoked on static assets, even if the path matches a filter-mapping pattern. Static files are served directly to the browser.> Note: At present, you cannot configure custom error handlers for some error conditions. Specifically, you cannot customize the 404 response page when no servlet mapping is defined for a URL, the 403 quota error page, or the 500 server error page that appears after an App Engine internal error. web.xml Features Not Supported. - Security Constraints are not supported: for equivalent functionality, see the bookshelf tutorial. - CONFIDENTIAL is not supported in web.xml.
https://cloud.google.com/appengine/docs/flexible/java/configuring-the-web-xml-deployment-descriptor
CC-MAIN-2018-47
refinedweb
218
58.69
Kotlin program to reverse a string recursively Introduction : In this kotlin programming tutorial, we will learn how to reverse a string recursively in kotlin. The program will take the string from the user and reverse it. We will use one separate method and call it recursively to reverse the string. Algorithm : The algorithm we are using is like below : 1. Ask the user to enter a string. Read and store it in a variable. 2. Pass the string to a different function. 3. Call this function recursively and add the first character to the end of the final string. 4. Keep adding the current character to the end to build the final reverse string. 5. Print out the string. Kotlin program : import java.util.Scanner fun main(args: Array) { //1 val scanner = Scanner(System.`in`) //2 println("Enter the string : ") var str = scanner.next() //3 println(reverseStr(str)) } //4 fun reverseStr(str: String): String{ //5 if(str.isEmpty()) return str //6 return reverseStr(str.substring(1)) + str[0] } Explanation : The commented numbers in the above program denote the step numbers below : 1. Create one Scanner object to read the user input data. 2. Ask the user to enter a string. Read the string and store it in str variable. 3. Call one different function reverseStr and print out the result. 4. reverseStr function takes one string as a parameter. It returns one String i.e. the reversed string. 5. Inside the function, check if the current string is empty or not. If empty, return the same string. 6. Else, call the reverseStr function again recursively. This time we are passing the substring starting from the second character. The final character we are adding to the end of the final string. This process will keep the start character adding to the end of the string on each step. Sample Output : Enter the string : this siht Enter the string : Hello olleH Enter the string : world dlrow Enter the string : universe esrevinu You might also like : - Trim leading whitespace characters using trimMargin in Kotlin - 6 different ways to sort an array in Kotlin - Kotlin program to find out the average marks of a list of students - How to use fold, foldIndexed, foldRight and foldRightIndexed in Kotlin - How to intersect two arrays in Kotlin - What is double bang or double exclamation operator in kotlin
https://www.codevscolor.com/kotlin-reverse-string/
CC-MAIN-2020-16
refinedweb
390
67.35
> > I, like everyone else in the universe, am writing a prog to > manipulate and > > organize mp3's... > > Nope, I just use iTunes :-) Oooh I wasn't going to bite but I will anyway! I have been using a mix of 'MP3 Tag Studio' and Musicbrainz which between them are a fair bit more powerful than Itunes but I need more power! > > So I subclass the 'path' object as 'mp3path' and add some of my own > methods. > > Sounds OK. > > > I have added a new method ID3tag to my MP3path class I want > > myMP3path.files to return a list of objects that can still > access my > > ID3tag method. > > In that case they need to have access to objects of your class. > Or do you mean you want other objects to access the ID3tag > method of the returned objects? ie the returned objects > should have ID3tag methods? I mean that any path object returned should have mp3 related methods. > > Options that have occurred to me: > > > > 1. Override every method in 'path' that returns paths with a wrapper > method > > that converts them into mp3paths. This seems ugly, boring and > pointless. > > Its the only sensible way if you want all path objects to be > your specialised variants. How else can the path objects be > treated as your objects unless they get converted at some > stage? But see below... ...<snip>... > > 3. Add methods dynamically into the path object. (Is this > 'decorator'?) > > No its not decorator and is even more messy! (unrelated question: How does adding methods to existing instances differ from decorator then? I get the feeling that a lot of common design patterns don't apply exactly the same way to Python because it is less restrictive of what you can do in the first place) > > looked at the instancemethod function in the standard library 'new' > module > > and this adds methiods to instances but not to classes so I would > have to do > > this for every instance. > > Exactly so. Yuk! Well! You say Yuk but I did a bit more digging and (thanks to Mark Pilgrim: is ) found that despite what is implied in the standard library docs, 'instancemethod' will happily add methods to classes. This new methods then get nicely inherited by instances of the class. So I end up with code like this: ___________________ from path import * import new, id3 # Methods to add to 'path' class def _mp3s(self): return [mp3s for mp3s in self.files('*.mp3')] def _hasmp3s(self): return (self.isdir() and len(self.mp3s())>0) # Bind new methods to add to 'path' class path.mp3s = new.instancemethod(_mp3s, None, path) path.hasmp3s = new.instancemethod(_hasmp3s, None, path) testmp3 = path('testmp3') first_directory = testmp3.dirs()[0] print first_directory.hasmp3s() >>>>True _____________________ (Obviously the code don't do much yet!) This seems cleaner to me than the alternative of overriding all the methods just to add a type wrapper. I'd be interested to know what trouble I might be storing up in terms of bad OO practice... > > 4. Forget the whole OO thang and just use functions. (Looking more > > attractive by the minute ;-) > > How would that help? You still have the same issues? > One thing you might like to consider is the composite pattern. > Here we distinguish between link nodes and leafnodes of a tree. > You only want path nodes to gave ID3tags methods if they are > leaf nodes(ie files) I assume? > > So you can write a function that determines the nature of > path node you get and only convert the leaf nodes to your > class type. That is instead of overriding path to retirn your > objects why not get the list of paths back and then convert > those as needed to your class? > Well, the class I am basing myself on doesn't differentiate between path's and filenames and I find that approach fairly nice (only one object type to deal with. Just use .isfile() or isdir() if you need to know). > Does that make sense - I don't think I'm explaining it very > well... And don't have time for an example! > Basically write a type conversion function (like int(), > str(),list() etc) and apply it as needed. > > Pseudo code: > > def mp3path(aVanillaPath): > mp3p = MP3Path() # create new instance > for attribute in aVanillaPath: # use getattr()??? > mp3p.attribute = attribute # copy inherited stuff > return mp3p > > for path in myPath.files(): > if path is leaf node # using isinstance or somesuch? > path = mp3path(path) > path.ID3tag() # do things with new path object > HTH > > Alan G. > >
https://mail.python.org/pipermail/tutor/2004-August/030899.html
CC-MAIN-2017-17
refinedweb
743
74.29
Is there something special you have to do to get a char type array to start at the beginning of a external file? What i am trying to do is read in a string from an external file into a char type array and then display it on the screen. I have a function created to read the info but i am having problems with it grabbing the right info for each array. Here is what the input file looks like, Samuel Spade 10 Automotive 22020.45 Annie Smith-Johnston 4 Appliances 25123.96 Dietrick Jones 15 Automotive 29450.88 John J. Jones, Jr. 8 Automotive 19555.55 Melissa Armstrong 12 Accounting 25945.66 Here is the code i have so far, //List preprocessor directives #include <iostream> #include <iomanip> #include <fstream> #include <string> #include <ctime> #include <cmath> //directive for math functions using namespace std; const int NAME_SIZE = 21; const int DEPART_SIZE = 16; const int YEARS_SIZE = 3; const int SALARY_SIZE = 9; //function prototypes int getAllData(char name[][NAME_SIZE], int& years, char depart[][DEPART_SIZE], double& salary); int main() //function heading { int actualnumber = 0; char name[100][NAME_SIZE]; int years; char depart[100][DEPART_SIZE]; double salary; getAllData(name, years, depart, salary); actualnumber = getAllData(name, years, depart, salary); int z = 0; while(z <= actualnumber) { cout << name[z] << endl; z++; } return 0; } int getAllData(char name[][NAME_SIZE], int& years, char depart[][DEPART_SIZE], double& salary) { ifstream infile ("PJ811_personnel.txt"); if (!infile) { //unable to open file, display msg and quit cout << "Error: cannot open PJ811_personnel.txt file\n"; } int count = 0; while(count < 100 && infile >> name[count]) { infile.getline(name[count], sizeof(name[count])); infile >> years; infile.get(depart[count], DEPART_SIZE); infile >> salary; count++; } return count; } Now all i was outputing to the screen so far was just the name array, just to see if it is working but here is what i get, Spade 10 Au Press any key to continue . . . for some reason it is cutting off the first name and starting at the space between the first name and last name but its also not looping it looks like and displaying the whole list. I cant figure out how to get it to start at the First name, if it started at the first name then it would stop before it got to the "10".(at least i think it would) I have tried puting a infile >> ws; before and after the infile for the name but nothing seems to work Anyone have any ideas?
http://www.dreamincode.net/forums/topic/181547-strings-and-char-type-arrays/
CC-MAIN-2017-04
refinedweb
411
57.4
go / / 3a6da3992a22839acb8257f6a68663ef712fda65 / . / content / using-go-modules.article blob: d93842e4dd8e4576bd09b96870b8ac787e7276cb [ file ] [ log ] [ blame ] Using Go Modules 19 Mar 2019 Tags: tools, versioning Tyler Bui-Palsulich Eno Compton * Introduction Go 1.11 and 1.12 include preliminary [[][support for modules]], Go’s [[][new dependency management system]] that makes dependency version information explicit and easier to manage. This blog post is an introduction to the basic operations needed to get started using modules. A followup post will cover releasing modules for others to use.]]. As of Go 1.11, the go command enables the use of modules when the current directory or any parent directory has a `go.mod`, provided the directory is _outside_ `$GOPATH/src`. (Inside `$GOPATH/src`, for compatibility, the go command still runs in the old GOPATH mode, even if a `go.mod` is found. See the [[][go command documentation]] for details.) Starting in Go 1.13, module mode will be the default for all development. This post walks through a sequence of common operations that arise when developing Go code with modules: - Creating a new module. - Adding a dependency. - Upgrading dependencies. - Adding a dependency on a new major version. - Upgrading a dependency to a new major version. - Removing unused dependencies. * Creating a new module Let's create a new module. Create a new, empty directory somewhere outside `$GOPATH/src`, `cd` into that directory, and then create a new source file, `hello.go`: package hello func Hello() string { return "Hello, world." } Let's write a test, too, in `hello_test.go`: package hello import "testing" func TestHello(t *testing.T) { want := "Hello, world." if got := Hello(); got != want { t.Errorf("Hello() = %q, want %q", got, want) } } At this point, the directory contains a package, but not a module, because there is no `go.mod` file. If we were working in `/home/gopher/hello` and ran `go`test` now, we'd see: $ go test PASS ok _/home/gopher/hello 0.020s $ The last line summarizes the overall package test. Because we are working outside `$GOPATH` and also outside any module, the `go` command knows no import path for the current directory and makes up a fake one based on the directory name: `_/home/gopher/hello`. Let's make the current directory the root of a module by using `go`mod`init` and then try `go`test` again: $ go mod init example.com/hello go: creating new go.mod: module example.com/hello $ go test PASS ok example.com/hello 0.020s $ Congratulations! You’ve written and tested your first module. The `go`mod`init` command wrote a `go.mod` file: $ cat go.mod module example.com/hello go 1.12 $ The `go.mod` file only appears in the root of the module. Packages in subdirectories have import paths consisting of the module path plus the path to the subdirectory. For example, if we created a subdirectory `world`, we would not need to (nor want to) run `go`mod`init` there. The package would automatically be recognized as part of the `example.com/hello` module, with import path `example.com/hello/world`. * Adding a dependency The primary motivation for Go modules was to improve the experience of using (that is, adding a dependency on) code written by other developers. Let's update our `hello.go` to import `rsc.io/quote` and use it to implement `Hello`: package hello import "rsc.io/quote" func Hello() string { return quote.Hello() } Now let’s run the test. (“Latest” is defined as the latest tagged stable (non-[[][prerelease]]) version, or else the latest tagged prerelease version, or else the latest untagged version.) In our example, `go`test` resolved the new import `rsc.io/quote` to the module `rsc.io/quote`v1.5.2`. It also downloaded two dependencies used by `rsc.io/quote`, namely `rsc.io/sampler` and `golang.org/x/text`. Only direct dependencies are recorded in the `go.mod` file: $ cat go.mod module example.com/hello go 1.12 require rsc.io/quote v1.5.2 $ A second `go`test` command will not repeat this work, since the `go.mod` is now up-to-date and the downloaded modules are cached locally (in `$GOPATH/pkg/mod`): $ go test PASS ok example.com/hello 0.020s $ Note that while the `go` command makes adding a new dependency quick and easy, it is not without cost. Your module now literally _depends_ on the new dependency in critical areas such as correctness, security, and proper licensing, just to name a few. For more considerations, see Russ Cox's blog post, “[[][Our Software Dependency Problem]].” As we saw above, adding one direct dependency often brings in other indirect dependencies too. The command `go`list`-m`all` lists the current module and all its dependencies: $ go list -m all example.com/hello golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c rsc.io/quote v1.5.2 rsc.io/sampler v1.3.0 $ In the `go`list` output, the current module, also known as the _main_module_, is always the first line, followed by dependencies sorted by module path. The `golang.org/x/text` version `v0.0.0-20170915032832-14c0d48ead0c` is an example of a [[][pseudo-version]], which is the `go` command's version syntax for a specific untagged commit. In addition to `go.mod`, the `go` command maintains a file named `go.sum` containing the expected [[][cryptographic hashes]] of the content of specific module versions: $... $ The `go` command uses the `go.sum` file to ensure that future downloads of these modules retrieve the same bits as the first download, to ensure the modules your project depends on do not change unexpectedly, whether for malicious, accidental, or other reasons. Both `go.mod` and `go.sum` should be checked into version control. * Upgrading dependencies With Go modules, versions are referenced with semantic version tags. A semantic version has three parts: major, minor, and patch. For example, for `v0.1.2`, the major version is 0, the minor version is 1, and the patch version is 2. Let's walk through a couple minor version upgrades. In the next section, we’ll consider a major version upgrade. From the output of `go`list`-m`all`, we can see we're using an untagged version of `golang.org/x/text`. Let's upgrade to the latest tagged version and test that everything still works: $ $ Woohoo! Everything passes. Let's take another look at `go`list`-m`all` and the `go.mod` file: $ ) $ The `golang.org/x/text` package has been upgraded to the latest tagged version (`v0.3.0`). The `go.mod` file has been updated to specify `v0.3.0` too. The `indirect` comment indicates a dependency is not used directly by this module, only indirectly by other module dependencies. See `go`help`modules` for details. Now let's try upgrading the `rsc.io/sampler` minor version. Start the same way, by running `go`get` and running tests: $ $ Uh, oh! The test failure shows that the latest version of `rsc.io/sampler` is incompatible with our usage. Let's list the available tagged versions of that module: $ go list -m -versions rsc.io/sampler rsc.io/sampler v1.0.0 v1.2.0 v1.2.1 v1.3.0 v1.3.1 v1.99.99 $ We had been using v1.3.0; v1.99.99 is clearly no good. Maybe we can try using v1.3.1 instead: $ $ Note the explicit `@v1.3.1` in the `go`get` argument. In general each argument passed to `go`get` can take an explicit version; the default is `@latest`, which resolves to the latest version as defined earlier. * Adding a dependency on a new major version Let's add a new function to our package: `func`Proverb` returns a Go concurrency proverb, by calling `quote.Concurrency`, which is provided by the module `rsc.io/quote/v3`. First we update `hello.go` to add the new function: package hello import ( "rsc.io/quote" quoteV3 "rsc.io/quote/v3" ) func Hello() string { return quote.Hello() } func Proverb() string { return quoteV3.Concurrency() } Then we add a test to `hello_test.go`: func TestProverb(t *testing.T) { want := "Concurrency is not parallelism." if got := Proverb(); got != want { t.Errorf("Proverb() = %q, want %q", got, want) } } Then we can test our code: $ go test go: finding rsc.io/quote/v3 v3.1.0 go: downloading rsc.io/quote/v3 v3.1.0 go: extracting rsc.io/quote/v3 v3.1.0 PASS ok example.com/hello 0.024s $ Note that our module now depends on both `rsc.io/quote` and `rsc.io/quote/v3`: $ go list -m rsc.io/q... rsc.io/quote v1.5.2 rsc.io/quote/v3 v3.1.0 $ Each different major version (`v1`, `v2`, and so on) of a Go module uses a different module path: starting at `v2`, the path must end in the major version. In the example, `v3` of `rsc.io/quote` is no longer `rsc.io/quote`: instead, it is identified by the module path `rsc.io/quote/v3`. This convention is called [[][semantic import versioning]], and it gives incompatible packages (those with different major versions) different names. In contrast, `v1.6.0` of `rsc.io/quote` should be backwards-compatible with `v1.5.2`, so it reuses the name `rsc.io/quote`. (In the previous section, `rsc.io/sampler` `v1.99.99` _should_ have been backwards-compatible with `rsc.io/sampler` `v1.3.0`, but bugs or incorrect client assumptions about module behavior can both happen.) The `go` command allows a build to include at most one version of any particular module path, meaning at most one of each major version: one `rsc.io/quote`, one `rsc.io/quote/v2`, one `rsc.io/quote/v3`, and so on. This gives module authors a clear rule about possible duplication of a single module path: it is impossible for a program to build with both `rsc.io/quote`v1.5.2` and `rsc.io/quote`v1.6.0`. At the same time, allowing different major versions of a module (because they have different paths) gives module consumers the ability to upgrade to a new major version incrementally. In this example, we wanted to use `quote.Concurrency` from `rsc/quote/v3`v3.1.0` but are not yet ready to migrate our uses of `rsc.io/quote`v1.5.2`. The ability to migrate incrementally is especially important in a large program or codebase. * Upgrading a dependency to a new major version Let's complete our conversion from using `rsc.io/quote` to using only `rsc.io/quote/v3`. Because of the major version change, we should expect that some APIs may have been removed, renamed, or otherwise changed in incompatible ways. Reading the docs, we can see that `Hello` has become `HelloV3`: $ go doc rsc.io/quote/v3 package quote // import "rsc.io/quote" Package quote collects pithy sayings. func Concurrency() string func GlassV3() string func GoV3() string func HelloV3() string func OptV3() string $ (There is also a [[][known bug]] in the output; the displayed import path has incorrectly dropped the `/v3`.) We can update our use of `quote.Hello()` in `hello.go` to use `quoteV3.HelloV3()`: package hello import quoteV3 "rsc.io/quote/v3" func Hello() string { return quoteV3.HelloV3() } func Proverb() string { return quoteV3.Concurrency() } And then at this point, there's no need for the renamed import anymore, so we can undo that: package hello import "rsc.io/quote/v3" func Hello() string { return quote.HelloV3() } func Proverb() string { return quote.Concurrency() } Let's re-run the tests to make sure everything is working: $ go test PASS ok example.com/hello 0.014s * Removing unused dependencies We've removed all our uses of `rsc.io/quote`, but it still shows up in `go`list`-m`all` and in our `go.mod` file: $ ) $ Why? Because building a single package, like with `go`build` or `go`test`,. The `go`mod`tidy` command cleans up these unused dependencies: $ $ * Conclusion Go modules are the future of dependency management in Go. Module functionality is now available in all supported Go versions (that is, in Go 1.11 and Go 1.12). This post introduced these workflows using Go modules: - `go`mod`init` creates a new module, initializing the `go.mod` file that describes it. - `go`build`, `go`test`, and other package-building commands add new dependencies to `go.mod` as needed. - `go`list`-m`all` prints the current module’s dependencies. - `go`get` changes the required version of a dependency (or adds a new dependency). - `go`mod`tidy` removes unused dependencies. We encourage you to start using modules in your local development and to add `go.mod` and `go.sum` files to your projects. To provide feedback and help shape the future of dependency management in Go, please send us [[][bug reports]] or [[][experience reports]]. Thanks for all your feedback and help improving modules.
https://go.googlesource.com/blog/+/3a6da3992a22839acb8257f6a68663ef712fda65/content/using-go-modules.article
CC-MAIN-2021-04
refinedweb
2,141
61.53
On 23/04/16 17:50, Eliot Kimber ekimber@xxxxxxxxxxxx wrote: > Upon reflection I can see that allowing unprefixed elements to be > associated with a namespace was perhaps not the best idea, <hat class="documentxml"> I heaved a sigh of relief at the time. Invalidating every document in the publishing business would not have been a wise move. > And as somebody pointed out to me privately, the fact that there was no > good solution for DTD-based grammars was a problem too. That could have been me; I certainly spent long enough whingeing about it. As it turned out, it isn't a problem provided your entire document is in a single namespace, which is the case for the vast majority of traditional book/journal documents I encounter, for the reason in your first sentence. > But I think we all expected DTDs to go away much faster than they did. I never saw them disappearing at all, and they haven't gone yet. 95% of my clients still use them (so maybe I'm serving 0.0001% of the business :-) even though the master schema is probably RNG. </hat> ///Peter
http://www.oxygenxml.com/archives/xsl-list/201604/msg00048.html
CC-MAIN-2018-17
refinedweb
190
68.2
This site uses strictly necessary cookies. More Information Hello, if I instantiate a sphere with a trigger collider "inside" of a wall, it doesn't happen what is supposed to happen. If I instantiate the sphere outside of the wall and move it into the wall, it works. Why, and how can I solve it? Answer by TonyLi · Jun 21, 2013 at 01:46 PM Review all the conditions on the Rigidbody Sleeping page. Are your objects set up correctly with rigidbodies or static colliders? Given your description, the sphere should probably be a static collider marked Is Trigger, and the sphere should have a rigidbody. If you instantiate one collider inside another, it will not register OnTriggerEnter messages, but it should register OnTriggerStay. The sphere is instantiated from the $$anonymous$$ainCharacter, as a way to make an attack. It Instantiates in front of him. If I get clse to the wall and hit the attack button, the sphere would be instantiated inside the wall, but nothing will happen despite the "OnTriggerStay" function it has... Please post screenshots of the fully-expanded Inspector view for the sphere and the wall. Sorry for late answer. Here are the screenshots Wall ball Those game objects look good to me. Can you post your Js_Attacks script? I suspect that you need to use OnTriggerStay ins$$anonymous$$d of OnCollisionStay. I'll suggest that as an answer. Here's a unitypackage that demonstrates a combination that works: Import it and open the scene in the Test folder. When you press play, you can move around with the first person controller. The X key spawns and destroys the ball. The ball prints collisions in the console. It's on my public dropbox, so no guarantees that it'll be there forever. But if someone's reading this in the future and it's gone, the settings and code are in the previous comments. Here's the ball-spawning code: public class SpawnBall : $$anonymous$$onoBehaviour { public GameObject ballPrefab; private GameObject ball = null; void Update() { if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.X)) { if (ball == null) { ball = Instantiate(ballPrefab, Vector3.zero, Quaternion.identity) as GameObject; ball.transform.parent = this.transform; ball.transform.localPosition = new Vector3(0f ,1f, 1f); } else { Destroy(ball); ball = null; } } } } Answer by YagoRG · May 01 at 03:42 PM I know I am way too late for this... but just in case anyone stumbles upon the same problem here's what worked for me. I solved it by calling the rigidbody and applying a foce of zero to it inside the void Update, that way it won't go to sleep. In my case was for a 2D game so it ended up looking like this: Rigidbody2D rb; // Update is called once per frame void Update() { rb.AddForce(Vector2.zero); } I bet there's better ways to do this but this one is really simple and works for a fast. Destroy instatiate object on trigger enter / collision,destroy instantiate prefab on trigger enter 0 Answers My code is instantiating many prefabs, i only want one. 1 Answer How do I make a platform fall after a player has left it? 2 Answers Collider not turning into trigger when painted to a scene 1 Answer Can OnTriggerEnter2D trigger again once triggered? 0 Answers EnterpriseSocial Q&A
https://answers.unity.com/questions/478415/ontriggerstay-doesnt-work-if-not-moving.html
CC-MAIN-2021-31
refinedweb
551
65.12
RPi.GPIO basics 4 – Setting up RPi.GPIO, numbering systems and inputs . But Pins have names too The slightly confusing part is that each pin also has a name, according to what it does. Some of them have alternative functions, but RPi.GPIO doesn’t currently control those, so we’ll ignore them for now. The best way to see which pin number does what is with a diagram… - red ones are +ve power (3V3 or 5V) - black ones are -ve ground - yellow ones are all dedicated general purpose I/O ports (OK, 18 does PWM as well, but forget that for now). The rest can all be used as GPIO ports, but do have other functions too. If you need 8 or less ports, it’s best to use the yellow ones because you’re less likely to have a conflict with other things. A quick rundown of what the others are… - greeny/grey – i2c interface - light grey – UART (serial port) - orange – SPI (Serial Peripheral Interface) How to set up BOARD and GPIO numbering schemes In RPi.GPIO you can use either pin numbers (BOARD) or the Broadcom GPIO numbers (BCM), but you can only use one system in each program. I habitually use the GPIO numbers, but neither way is wrong. Both have advantages and disadvantages. If you use pin numbers, you don’t have to bother about revision checking, as RPi.GPIO takes care of that for you. You still need to be aware of which pins you can and can’t use though, since some are power and GND. If you use GPIO numbers, your scripts will make better sense if you use a Gertboard, which also uses GPIO numbering. If you want to use the P5 header for GPIO28-31, you have to use GPIO numbering. If you want to control the LED on a Pi camera board (GPIO5) you also have to use GPIO numbering. The important thing is to pick the one that makes sense to you and use it. It’s also important to be aware of the other system in case you ever need to work on someone elses code. So, at the top of every script, after importing the RPi.GPIO module, we set our GPIO numbering mode. import RPi.GPIO as GPIO # for GPIO numbering, choose BCM GPIO.setmode(GPIO.BCM) # or, for pin numbering, choose BOARD GPIO.setmode(GPIO.BOARD) # but you can't have both, so only use one!!! So, with a drumroll and a fanfare of trumpets, it’s now time for us to set up some inputs. How to set up a GPIO port as an input Use the following line of code… GPIO.setup(Port_or_pin, GPIO.IN) …changing Port_or_pin to the number of the GPIO port or pin you want to use. I’m going to use the BCM GPIO numbering and port GPIO25, so it becomes… GPIO.setup(25, GPIO.IN) import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) # set up BCM GPIO numbering GPIO.setup(25, GPIO.IN) # set GPIO 25 as input We’ve just set up port 25 as an input. Next we need to be able to “read” the input. Reading inputs Inputs are Boolean values: 1 or 0, GPIO.HIGH or GPIO.LOW, True or False (this corresponds to the voltage on the port: 0V=0 or 3.3V=1). You can read the value of a port with this code… GPIO.input(25) But it may be more useful to use it as part of your logic… if GPIO.input(25): # if port 25 == 1 print "Port 25 is 1/GPIO.HIGH/True" …or store its value in a variable to use in a different part of the program… button_press = GPIO.input(25) So, building on what we’ve already done, here’s a very simple program to read and display the status of port 25, but it only does it once, then it cleans up and exits. import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) # set up BCM GPIO numbering GPIO.setup(25, GPIO.IN) # set GPIO 25 as input if GPIO.input(25): # if port 25 == 1 print "Port 25 is 1/GPIO.HIGH/True" else: print "Port 25 is 0/GPIO.LOW/False" GPIO.cleanup() # clean up after yourself The above is not really complete yet, what we need to do is add… - a loop, so we can make it read more than once - a time delay, so it won’t read the port thousands of times per second - a circuit with a button, so we can change the status of the port and see the input status change on the screen - a try: except KeyboardInterrupt: block so we can exit cleanly (we covered this yesterday) So, let’s make a little circuit In order to go any further with this, we need to make up a little circuit. The resistors are used to “pull down” the GPIO25 pin to 0 Volts GND (0V, 0, LOW, False) unless the button is pressed. When the button is pressed, GPIO25 is connected to 3.3V. If you don’t use the resistors, it might still work, but you risk having a “floating” port. It’s not dangerous, (it could be if you had something like a motor attached) but it’s not fully in control either. We’ll cover a bit more on floating ports, pull-ups and pull-downs in another article (probably part 6). If you don’t have a breadboard, resistors and buttons, you could cheat and just use a jumper wire to connect two pins directly, but you’ll need to be aware of what you’re doing. Here’s the code with all the extras added to read and display the button’s status, and exit cleanly when CTRL+C is pressed… import RPi.GPIO as GPIO from time import sleep # this lets us have a time delay (see line 12) GPIO.setmode(GPIO.BCM) # set up BCM GPIO numbering GPIO.setup(25, GPIO.IN) # set GPIO 25 as input try: while True: # this will carry on until you hit CTRL+C if GPIO.input(25): # if port 25 == 1 print "Port 25 is 1/GPIO.HIGH/True - button pressed" else: print "Port 25 is 0/GPIO.LOW/False - button not pressed" sleep(0.1) # wait 0.1 seconds except KeyboardInterrupt: GPIO.cleanup() # clean up after yourself This is what the above program’s output looks like… Polling loop This program uses a polling loop. It checks (polls) the input port 10 times per second. It works well, but is not very efficient. A more efficient, and more advanced way to handle this is with interrupts. I’ve written about how you can use interrupts in RPi.GPIO here. That was inputs with RPi.GPIO So now you know how to use RPi.GPIO to set up and read the status of an input port. In part 5, we’ll cover Outputs. A quick recap of what we’ve covered so far So now we’ve covered… - How to check what RPi.GPIO version you have - How to check what Pi board Revision you have - How to Exit GPIO programs cleanly, avoid warnings and protect your Pi - Setting up RPi.GPIO, numbering systems and inputs RasPiO® GPIO Reference Aids Our sister site RasPiO has three really useful reference products for Raspberry Pi GPIO work... […] for instance. So far, he’s covered the basics and has now turned his attention to both inputs and […] Strictly speaking, ground is 0V not a -ve voltage (although it does correspond to the -ve terminal on a battery). Actually, there’s nothing stopping you from calling setmode() multiple times in the same program – you just need to remember whether you’re in BOARD or BCM mode whenever you call a function that has a Port_or_pin as an argument. So obviously it’s not recommended to switch between BOARD and BCM within the same program ;-) Although if you do try to setup() a power or ground pin whilst using BOARD mode, RPi.GPIO will tell you you’ve chosen an invalid pin. All that being said, I personally use BCM mode (i.e. raw GPIO numbers) too because it’s what I’m familiar with using on other embedded boards, and it matches the numbers in sysfs if I want to manipulate the GPIOs directly from the command line Alex, would it be worth including a “GPIO pinouts for Rev 1 Pi” for the sake of completeness? (with maybe a link to the low-level-peripherals wiki page for folks that want to “Read more”) Looks like the Fritzing diagram is still using the Rev 1 pinout… Apologies if I’m being too pedantic! Don’t worry about the pedantry. I’ve tried to keep it simple and easy to understand. Ref the Rev 1/2 & Fritzing, you may note I’ve only used pins which are the same in Rev 1 and Rev 2 for these experiments. I habitually do that to keep things simple and avoid confusion. GPIO24 & GPIO25 are the same on all Pis made so far. The Fritzing Pi model I have won’t let me connect to any of the “DNC” pins either, (which are now GND) Well that’s an unfortunate surprise – I’ve just downloaded the latest 0.8.0b version of Fritzing (I’ve never even used it before) and it seems it still only has the Rev1 Pi, even though it was released in June 2013 (i.e. well after the release of the Rev2 Pis themselves) :-/ And the “Schematic” tab shows GPIO0 -> GPIO7, which is even more weird! Hmmm…. so I just went searching for updated Raspberry Pi Fritzing models, and found one from Binnery (which doesn’t have any pin-labels), and one from Adafruit, which has the same pin-labels as the model built-in to Fritzing, so I just submitted :-) Ooooh, although I now notice that you’re actually using the Adafruit Fritzing Pi model, and not the one built in to Fritzing. They’re almost the same though. Just found and added a comment to too ;) Yep – using the Adafruit Pi model. It would be nice if it was up to date, but I don’t think it being slightly out of date detracts from its usefulness in this context. It’s surely much clearer to see what wiring to do than if I just wrote in words “connect a wire between GPIO25 and a 1k resistor” etc. :) Oh, it’s definitely useful and much clearer than just text or even a photo would be! (sorry if I gave the wrong impression) Just my programmer’s pedantism kicking in again ;-) Programmers and Translators are the biggest pedants – along with Librarians, Lexicographers. Editors not so much, they just change things to make them read badly or just plain wrong ;) […] Part 4: “setting up RPi.GPIO, numbering systems and input”: […] Hi Alex Congratulations on your excellent Input & Output tutorials – very nicely explained for someone well down the learning curve. I have decided to follow your lessons and got a shiny new B+ Pi and a Cyntech B+ Paddle. I noticed that on running the one-button polling program above, without anything attached to the Pi, I get the “button not pressed” message repeatedly. This is what I expected. However, when I connect the Paddle to the Pi, again with nothing else attached, the program’s output changes back and forth between “button not pressed” and “button pressed” – about every couple of seconds. When I complete the circuit with button, 1k resistor, 10k resistor (actually 2 x 4.7 k) etc, I get the same result – just alternating between “pressed” and “not pressed” regardless of whether I press the button or not. I thought I would reverse the rainbow connector strip in case there was a connection problem, but with the same result. Do you have any suggestions? Sorry Alex – I got it working – I pushed the 40-way connectors in really hard and it now works. Cheers Any wires connected to a GPIO pin can act as an antenna (picking up any stray background interference) and can make a floating pin “more floating” if you’re not using pull-up or pull-down resistors. Alex has another tutorial somewhere about using the RPi’s internal pull-up / pull-down resistors, which makes external connections a little bit easier :) Many thanks This information is great. Thank you for sharing. I do have a question. What if it was reversed. Say you constantly have the button pressed and you want to it to know when it was not pressed. Thus it is always a high and want to trigger on a low? So, I guess if you are use to using wiringPi in C, and you wanna swich to Python, you gonna have to use BCM or Board numbering? And thank you, for all your work. Well written and understandable, even for a guy where english i second language and have less then 5 months experience with raspberry/linux and programming in generel… Or you could use ;-) Why adding 1k resistor? Just pull-down is enough. Inputs can handle 3V3. It’s just a little bit of extra current protection for the ports and is not strictly necessary, but it also does no harm. On “import RPi.GPIO as GPIO” i get “command not found”, whats wrong?
https://raspi.tv/2013/rpi-gpio-basics-4-setting-up-rpi-gpio-numbering-systems-and-inputs?replytocom=59314
CC-MAIN-2021-25
refinedweb
2,242
71.24
Resin. When Resin is used as both the client and the server, cache servers that are added or removed are automatically rescaled and updated in the client. Resin's implementation is written in Java, with some JNI performance enhancements. Memcached is a general-purpose distributed memory caching system, originally written in C, that was initially developed by Danga Interactive for LiveJournal, but is now used by many other sites including YouTube, Reddit, Facebook, and Twitter. The system uses a client-server architecture, where the servers maintain a key-value associative array; the clients populate this array and query it. Keys are up to 250 bytes long and values can be, at most, 1 megabyte in size. In the standard memcached implementation, servers keep the values in RAM; if a server runs out of RAM, it discards the oldest values. Resin's approach though is slightly different. InfoQ spoke to Scott Ferguson, the lead architect for Resin's memcached implementation, to find out more about it. InfoQ: How do you ensure compatibility with memcached? Also what, if any, memcached features do you not support? Memcached is a published wire protocol. Resin memcached implements the memcached protocol. We tested it against memcached clients. Currently we support all memcached features. This means Resin can function as a drop-in replacement for memcached solutions. Resin's memcached support is durable and fully elastic, allowing for the addition or removal of nodes, as needed, without getting extra hits to your database. InfoQ: How does the performance compare with the standard memcached library? We have not published any official benchmarks. Our internal benchmarks show that for some use cases it is a bit faster, for other use cases it is within 5%. Our implementation is fast. If you are doing a read dominate cache, our implementation should be equivalent to memcached proper with the added benefit of elasticity and persistence. InfoQ: In your blog post you state that "Data is automatically persisted and replicated between Triad hub servers. The size of the cache is limited only by the size of hard disks on the host OS". Doesn't persisting to disk change the performance characteristics considerably? Yes. If the value is served out of memory the speed is equivalent; if the value is served from disk it is slower. If you size your RAM large enough to hold all values then the performance will be on par with memcached. If you do not, then the performance will still be a lot faster than hitting a traditional database, but more likely on par with Membase. If you consider that the hot part of the cache will likely be in memory, then the overhead could be really low. It really depends on the use case and how you set things up. You can get performance as good as memcached. You are not limited to RAM for storage; elasticity is built-in so you don't get a lot of hits to your RDBM server when you add a new Resin memcached node. This is the major advantage. Resin's memcached is more elastic and easier to set up for cloud deployments. It ships with Resin too. It is easy to turn on and use. InfoQ: But isn't this also a change in behaviour? If I've coded to expect the memcached behaviour, I won't remove old items from the cache, I'll just assume they'll get thrown away. So won't I end up with an ever growing cache? No. Cache items can expire. You can set up an expiry just like you can with memcached. The actual eviction might happen later, but the behavior is the same. We also provide a JCache interface, so you can have characteristics of an infinite cache or fine grain controls and configuration of caches, as per JCache (JSR 107, which we track closely). Also, if you use JCache, we have implemented a GC-less in-memory cache; if the item is in this first level cache then the performance can be 1000x faster than going to the memcached tier. This is an easy setup that provides in-memory speeds backed by a memcached tier. As Scott Ferguson noted above, the client API for Resin's memcached is based on JSR 107, JCache (javax.cache), a proposed Java interface standard for memory caches. The configured cache can be injected like any CDI object: import javax.inject.*; import javax.cache.*; public class MyBean { @Inject Cache _memcache; } To configure Resin as a memcached server you add the following <listen>To configure Resin as a memcached server you add the following <listen>
http://www.infoq.com/news/2011/12/resin-memcached
CC-MAIN-2014-10
refinedweb
770
64.2
Awesome My friend and I have came up with perhaps the coolest abuse of technology to put together. Lets say you had a Laptop computer, a GPS, and an internet connection (Boost or Sprint or something). The computer has software that basically monitors the position of every other car playing the game. What game? Capture the flag. Imagine that. On the screen, you drive around. Suddenly, you pass a blip on the screen. The computer is telling you that the flag is on the road ahead. You get near it and press the "take flag" button. All of a sudden, every other car becomes aware your car is carying the flag. The speakers boom "Red flag taken!" and your position shows up on every other car. You bolt for your territory, and all the other cars are comming closer and closer. Once a car gets close enough to tag you (say 400 feet) they hit the "tag" button and you're out. "You have been tagged, go to the jail and wait 5 minutes". The flag lands on the ground (not really, but every car's computer knows where the flag is so it might as well be on the ground). The game continues. "YOU HAVE THE FLAG!" "RED FLAG DROPPED!" "CAR TAGGED!" "ENEMY PROXIMITY ALERT!" This could be really fun. I should start writing the software. Thoughts? Current projects: iGmod reloaded (Latest release) (put on hiatus indefinatly) Unlimited Internet and gps tracking for $6 a month with boost mobile! Carputer 2: "but officer, I had to run that light, I missed the flag 4 times already!!!" def sounds cool.... MY NEWEST INSTALL:modded infiniti fx with big screen first windows carpc install........my liquid cooled LVDS screen mmmm, sub letting this post if anyone was to let it, let me Sounds like fun. CarPC: Mini-MAC Coming Soon! I like the idea. I think the idea would probably make a better 'off road' or closed course game instead. D Bookmarks
http://www.mp3car.com/wireless-communications/115349-capture-the-flag.html
CC-MAIN-2015-48
refinedweb
331
85.49
User talk:Carlb/Archive3 From Uncyclopedia, the content-free encyclopedia Veja também: Usuário Discussão:Carlb See also: User talk:Carlb edit Server The server for *.uncyclopedia.info/*.pedia.ws was finally replaced on May 15, 2007 and a second server is being used to serve static content such as images, skins and downloadable backups. About time. Hopefully the sites should be running a little more quickly now. I shall be keeping an eye on things, in any case. Veja também pt:Forum:Desciclopédia_2.0! --Carlb 14:42, 2 June 2007 (UTC) edit unable to upload a newer version of image to zh-tw Dear carlb, I found that I cannot upload a newer version of image to zh-tw:Image:Example.jpg, even though I have uploaded the new version, the old version is still displayed (but with new version's resolution). I have tried to delete the page and re-upload, but the image still cannot be uploaded. The image I need to upload is [1], which is the original example image. Many thanks. --Leeyc0 06:46, 6 June 2007 (UTC) edit Huff request There's some school vanity I'd like huffed. Could you delete West Vancouver Secondary off the mirror please? Alksub - VFH CM WA RV {talk} 04:20, 8 June 2007 (UTC) edit Additions For the bot add the following entries isreal->Israel Isreal->Israel jewdism->Judaism Jewdism->Judaism Judasim->Judaism judasim->Judaism edit Style sheet problem Hello Carl. Currently, the style sheets is not being applied to any page in Japanese Uncyclpedia.[2] CSS files in ns:8 have been not changed recently though I checked them. [3] Can you know the cause of the problem, and fix it? -- | Kasuga | Talk | 11:05, 15 June 2007 (UTC) - Fixed:36, 15 June 2007 (UTC) edit No Forum_talk in Japanese Uncyclopedia ja.uncyclopedia.info has a Forum namespace (ns:110), but no Forum_talk (ns:111 ?) there. We should have a that stupid ns. thanks. bye. --話切徒 21:46, 19 June 2007 (UTC) - namespace creation can be done by any administrator via ja:Special:Namespaces. --Leeyc0 07:28, 24 June 2007 (UTC) edit zh.uncyclopedia.info upload image problem Dear Carlb, I found that we cannot upload images with Chinese character Destination filename recently. When we upload such images, it seems the image can be uploaded successfully, but when we see it's image page, the system cannot find the image and 404 not found error comes out when we tried to click the link. But the upload function is normal if we use alphanumeric characters for the file name. Please check it for us, many thanks. --Leeyc0 07:25, 24 June 2007 (UTC) - I suddenly found that a lot of recently uploaded (say in this month) images with Chinese character filename in zh.uncyclopedia.info disappered, for example in zh-tw:阿囧.--Leeyc0 07:47, 24 June 2007 (UTC) edit utilisation d'un pywikipediabot Bonjour, je suis PiRK de la désencyclopédie. J'ai vu que tu utilisais un bot (Hymie le robot) sur la désencyclopédie. Est-ce que c'est toujours possible de faire ça ? Si oui, je ne sais pas ce qu'il faut mettre sur la ligne family du fichier user-config.py. Est-ce que c'est family = 'desencyclopedie' ? --85.14.146.59 17:20, 26 June 2007 (UTC) Il faut ajouter une liste des uncyclopédias comme fichier de contrôle, puis ça doit fonctionner. Je crois que la version la plus récente d'uncyclopédia_family.py se trouve au Usuario:Chixpy/uncyclopedia_family.py; voir aussi Usuario:Gudproyect/uncyclopedia_family.py. - merci. On n'arrive pas à enregistrer le bot... La page Special:Makebot qui existe sur wikipédia n'existe pas sur la désencyclopédie. Est ce que tu sais comment faire ? --85.14.146.59 06:01, 5 July 2007 (UTC) Il faut demander à un membre du «staff» de Wikia de faire ça, inexpliquement on ne nous donne pas accès pour le faire. Pour les wikis qui ne sont pas chez Wikia, n'importe quel bureaucrat peut intervenir, mais... On peut faire fonctionner un pywikipediabot sans le drapeau «bot», tout ce que ce p'tit flag donne c'est de cacher les changements de fr:special:recentchanges. --Carlb 13:56, 6 July 2007 (UTC) edit liens interwiki J'ai vu sur la page [4] que tu t'occupes des liens interwikis. Celui de la désencyclopédie ne marche plus. Je pense qu'il faudrait remplacer desencyclopedie.com par desencyclopedie.wikia.com/. --85.14.146.59 17:37, 26 June 2007 (UTC) Mais desencyclopedie.com est une adresse légitime; ce domaine était donné à Wikia par Philo, le fondÉteur de la dÉsencyclopédie. Si Wikia continue de la briser d'une façon ou une autre, il n'y a pas grande chose que je puisse faire, malheureusement. Seulement leur personnel de support technique peut y intervenir, si (bien sûr) ils soient assez compétent pour le faire. On a déjà posé les mêmes questions ici au sujet de dÉ et de chinois simplifié car les problèmes, ce ne sont rien de nouveau. --Carlb 19:22, 26 June 2007 (UTC) - thanks! edit Korean Uncyclopedia has a problem When I open Korean Uncyclopedia, it says "백괴사전 has a problem." (백괴사전 is translation of "Uncyclopedia.") What should Korean Uncyclopedia's users do? ―에멜무지로 21:39, 29 June 2007 (UTC) Wait a minute and then hit shift-refresh or shift-reload in your browser. The page should then appear. --Carlb 13:59, 6 July 2007 (UTC) edit uncyclopedia.tw - - The newest URL - - The URL since the independent day - - Is it for test purpose before zh-tw Uncyclopedia's independence? - - Is it also for test purpose before zh-tw Uncyclopedia's independence? I believe I have to ask the users on uncyclopedia.tw. --Hant 16:24, 11 July 2007 (UTC) Thank You for uncyclopedia.hk. --Hant 13:46, 12 July 2007 (UTC) I think uncyclopedia.tw and uncyclopedia.hk are enough. No need to register uncyclopedia.mo. --Hant 14:10, 12 July 2007 (UTC) Thanks for asking; please let me know once they have consensus. :) The only way to get .mo is to register a company in Macau, then get .com.mo, then get .mo. Very expensive; I can't see anyone doing this. Anyone can register any domain (just so long as I know, to tell the server what pages to return for which domains) but it does seem easier just to use .tw (or .tw and .hk) if they're the same language. An .hk site could be useful if ever the community follows Wikipedia's pattern of a separate wiki for Cantonese (zh-yue.wikipedia.org) but for now it remains just a duplicate of So are the same now and any others just redirect to the .tw domain. After the community decides what they want to do, I shall update this accordingly. --Carlb 15:09, 12 July 2007 (UTC) - The members tend to keep uncyclopedia.tw, uncyclopedia.hk and zh.uncyclopedia.info alive. No redirect were purposed on these 3 URLs. Other URLs, just redirect to uncyclopedia.tw, as nobody care their disappearance. --Hant 13:23, 13 July 2007 (UTC) - Where is uncyclopedia.tw, uncyclopedia.hk and zh.uncyclopedia.info's server physically located? i.e. Which place's law is now applied on zh-tw uncyclopedia? --Hant 13:35, 13 July 2007 (UTC) The server itself is co-located at 151 Front St West, Toronto, Ontario, Canada. --Carlb 14:50, 13 July 2007 (UTC) edit The necessity of the policy of the making of policy Hello Mr.Carlb. I'm Beuraucrat of Japanese. We(I) have problem and please teach me method of English version. I make various rules recently for the cause of the agreement formation of the person of the community. But recently,The person who insisted that a rule to make a rule was necessary appeared. Therefore, please teach me How to making rules at the English version. The Japanese edition seems to become gradually Wikipedia and is tight:-). Thank you! -- by Muttley 15:34, 14 July 2007 (UTC) - The usual method appears to be to attempt to get a consensus between the administrators, either on IRC or by discussion on the wiki. A free Internet Relay Chat server is provided to projects like ours by freenode.net; once a few admins agree with an idea, it is opened for wider discussion by the community. --Carlb 09:39, 15 July 2007 (UTC) edit This comment does not exist I tried to leave a comment on Talk:This page does not exist, but I couldn't save it. I think it has something to do with the page's protection. --)}" /> - Um, this comment does exist... edit zh-tw upload image problem Dear carlb, I found that the upload image function has some problem. When I uploaded a new version of image, it seems that unable to display the new version. For example, I am uploading a new version of image to zh-tw:圖像:Example.jpg, which should be [5], but I found that it is still displaying the old version. Another example is zh-tw:圖像:Lucky Haruhi.jpg, the new version should be [6], but unable to display the new version, and I have reverted to old version now. (BTW, the first version is broken mysteriously.) --218.190.79.167 14:59, 24 July 2007 (UTC) - The previous message is left by me, but forgot to login.--Leeyc0 15:02, 24 July 2007 (UTC) edit Turkish Uncyclopedia Dear Carlb, We made an election in order to change our logo with a new one, so we designed a new logo for Turkish Uncyclopedia but i cand upload it. I uploaded the new one several times but the old logo which you've uploaded still appears there. Could you please help me to solve that problem? Thanks and Best Regards, Lord Assyrius Luciferianus edit Subpage feature activation Hello Carlb-san. In Japanese Uncyclopedia, subpage feature is activated in all talk namespaces and user namespace maybe. But we need this feature in the following namespaces too: - Uncyclopedia - Template - Category - Portal - UnNews - Forum Is it possible? thanks. --話切徒 17:57, 30 July 2007 (UTC) edit Poll Extension does not work in Japan One more thing... Japanese uncyclopedia has a poll extension tag (ja:Special:Version). But this extension does not work, and dump the following error messages. Error Table 'uncyc_ja.poll_vote' doesn't exist Table 'uncyc_ja.poll_vote' doesn't exist Table 'uncyc_ja.poll_message' doesn't exist Table 'uncyc_ja.poll_message' doesn't exist Table 'uncyc_ja.poll_info' doesn't exist Table 'uncyc_ja.poll_info' doesn't exist Table 'uncyc_ja.poll_message' doesn't exist could poll tag work properly? thanks. --話切徒 17:57, 30 July 2007 (UTC) edit 偉基論壇訊息 打擾管理員,如願意請進這裡應徵偽基論壇版主,但請先註明是管理員,謝謝。 edit Vandalism and open proxies Hikipedia has been vandalised frequently during last few weeks. Edits have been done behind open proxy so blocking does no good. Edits aren't probably done by a bot, so using ConfirmEdit extension to request confirm for every edit would just irritate other users. Would it be possible to adopt some kind of no open proxies policy on your server to prevent this kind of vandalism from happening? There is an extension (beta) which could be used by admins. There's also an another extension which could be useful in Hikipedia. Other useful tips for spam fighting are also welcome... --JAT 15:17, 11 August 2007 (UTC) - Thanks for extensions. Unfortunately we can't use SpamRegex, because its special page won't show up in fi:Special:Specialpages. Ability to block unwanted usernames would also be nice... --JAT 08:50, 16 August 2007 (UTC) - fi:Special:SpamRegex and fi:Special:RegexBlock should be working now. --Carlb 18:07, 22 August 2007 (UTC) edit Sub-namespace We need subpage feature in Korean Uncyclopedia, in these namespaces: - 백괴사전 (4) - 백괴사전토론 (5) Can you do this? --Peremen 00:06, 12 August 2007 (UTC) edit Again I think that you turned off subpage feature in these namespaces: - 사용자 (2) - 사용자토론 (3) Can you re-enable on these namespaces? There were several complains about this. --Peremen 02:32, 23 August 2007 (UTC) edit Is there anything happened in koun? I checked koun today, and something serious was happened. All locally-modified system messages has stopped to work. We changed the "Main Page" page, and it was returned to default value, even if ko:Mediawiki:Mainpage exists. Also, we heavily modified ko:Mediawiki:Monobook.css in many ways, for example, like font sizes and other styles. It has stopped to work, too. ko:Mediawiki:Recentchangestext also stopped working, too. Can you figure out what has happened and revert everything back? --Peremen 12:25, 17 August 2007 (UTC) edit unable to visit zh.uncyclopedia.info I found that I cannot visit Traditional Chinese Uncyclopedia. May you check for it? Thanks. --Leeyc0 15:10, 3 September 2007 (UTC) edit What happened to Lithuanian Uncyclopedia? What happened to Lithuanian Uncyclopedia? 91.35.142.40 18:10, 8 September 2007 (UTC) edit Hiya, boss. We in Hikipedia suuu-re need some subpages Excuse me, my lord, but we in Hikipedia (Finnish Uncyclopedia,, so forth) need this strange and outlandish "subpage feature" I have heard so much about. We are (I am) going to establish a brand new namespace, "Hikipeli", similar to the Uncyclopedia "Games", in which the subspace feature is needed. Also, I was noted that the subspace feature should be asked to the "Hikikirjasto" and "Ohje" (Help) -namespaces as well. I will vigilantly wait thy response, my lord. --Hjassan 13:39, 10 September 2007 (UTC) - For many of the help pages, such as fi:ohje:Aloittelijan ohje, it seems that various subpages exist but the main page does not. This may explain why the link from the subpage to the (missing) page above it is not generated and displayed? --205.150.76.42 06:18, 12 September 2007 (UTC) - I think we have some serious confusion between the "Hikipedia" and "Ohje" namespaces... edit zh.uncyclopedia.info image upload problem Hi carlb. I have received report from zh-tw user that they faced image upload problem again. The user tried to upload a resized version of image but failed. The affected image are zh-tw:圖像:StrikerS14-00.jpg. You can see that this image is still using old image even that new image is upload. (You can see that the aspect ratio is incorrect, the correct new version is zh-tw:圖像:一家.JPG). Another affected image is zh-tw:圖像:中正紀念堂.jpg. Although a smaller version is upload but you can see from this that the old version is still kept. (668x226 instead of supposed 496×226 as shown in history). The correct new version of this is zh-tw:圖像:中正.jpg. May you also check for other images that if they are also affected by this problem. Seems that there may be more undiscovered images are suffering from this problem. (See "zh-tw upload image problem" on 24 July 2007). --Leeyc0 16:21, 12 September 2007 (UTC) edit Japanese Uncyclopedia has SQL problem Hi Carl, long time no talk. Japanese Uncyclopedia has the problem now. The following error messages are displayed when we are about to edit the pages. データベース検索の文法エラー。これは恐らくソフトウェアのバグを表しています。 最後に実行を試みた問い合わせ: (SQLクエリー非表示) from within function "SearchMySQL4::update". MySQL returned error "145: Table './uncyc_ja/searchindex' is marked as crashed and should be repaired (localhost)". Mysteriously, the page's update itself has done though the error message is displayed. However, many users are discontented with that they cannot confirm the results of their updates directly. Moreover, the page's moves seem to be impossible. Please fix this situation.:21, 13 September 2007 (UTC) edit Desciclopedia ERROR URL COULD NOT BE RETRIEVET Se você for o Carlb da desciclo brasileiro, veja porque lá não tá pegando. 201.31.21.183 22:08, 14 September 2007 (UTC) User Brazil is User:Dragomaniaco/ass (minha assinatura) - Oncyclopedia seems to be having similar errors, as well as everything else on sophia.uncyclomedia.org. -.) 22:09, September 14, 2007 edit what's going on Korean Uncyclopedia? Localized namespace names aren't working properly. Instead of Korean one, Japanese one is displayed and Korean namespace names aren't working. I think there was a mistake, but it is serious problem. For example, the User: namespace in Korean is "사용자:", but currently, Japanese one "利用者:" is displayed. Other namespaces that is built-in in MediaWiki has same problem. (Not only User: Namespace) Can you fix it? --Peremen 02:23, 27 September 2007 (UTC) - That's odd, I look at ko:사용자:Peremen and it looks normal; ko:special:allpages appears to be using the Korean namespace names. --Carlb 05:56, 27 September 2007 (UTC) edit zh-tw image upload problem Dear carlb, Now we have another image upload problem. In zh-tw:圖像:庫羅諾的假面計畫.jpg seems that new version is uploaded, but when you include it in article (see the "To carlb" section in zh-tw:用戶討論:Leeyc0), the old version is still displayed. And when you click the latest version in "File history", the old version still displays (the yellowish one is the old version, the new version is the white background one). --Leeyc0 07:09, 28 September 2007 (UTC) edit zh-tw infinite redirect loop Dear carlb, I found that zh.uncyclopedia.info would redirect indefinitely to and the redirect would loop infinitely. May you have a check? Thanks. --Leeyc0 04:14, 4 October 2007 (UTC) - Hello again, Carl. According to a user's report, Japanese Uncyclpedia too seems to have had the same problem. It has recovered | 13:54, 4 October 2007 (UTC) edit Account mix-up with inciclopedia.wikia.com Dear carlb, I found that I appeared to logged in inciclopedia.wikia.com, which I never registered. (I have registered for zh-tw and ja uncyclopedia only, both with user name Leeyc0) May you have a check? The account in problem is Leeyc0 --Leeyc0 07:42, 16 October 2007 (UTC) - Inciclopedia's user list is shared with every other Wikia-hosted site except en:uncyclopedia. That'd include ar: ca: cs: de: el: fr: he: it: la: pl: ru: sk: yi: zh-cn: and several others in the Uncyclopedia set, plus many that have nothing much to do with Uncyclopedia. As far as I know, there is no way to mix up zh-tw: or ja: (both of which have their own independent userlists) with *.wikia.com (which uses a list shared with other wikia only) - 伪基百科 (zh-cn) is Wikia, 偽基百科 (zh-tw) is not. So yes, passwords for 伪基百科 would work on Inciclopédia. --Carlb 18:13, 17 October 2007 (UTC) edit A página não pode ser exibida (desciclopédia) Carlb, a desciclopédia tem problema. Dragomaniaco 20:59, 16 October 2007 (UTC) - Last word in #desciclopedia on this was "Posted On: 16 Oct 2007 07:04 PM (EDT) Hello, There was a fibre cut. We're working on restoring the service." (according to the datacentre - so looks like it's temporary). Backups on are on a different server, off-site, way off-site. --205.150.76.42 23:15, 16 October 2007 (UTC) - Hi Carl, I'm from Desciclopédia too. When the site returns? 200.215.113.107 14:03, 17 October 2007 (UTC) - Hello Carl. Japanese Uncyclopedia has been being downed for more than twelve hours. I can't access even the rebooting page. Can you restore it or check up the cause of the problem?:13, 17 October 2007 (UTC) - It's one of the Internet connections *to* my upstream provider that's the problem. I asked today and latest word was "On: 17 Oct 2007 01:40 PM (GMT-4) - WE'er still working on it with teleglobe." That's why the remote APC reset isn't accessible; it's on the same broken Internet connection as the main server itself. The images.uncyc.org and download.uncyc.org files are on the old server (Vancouver instead of Toronto) and would be unaffected (all the data for the various projects was backed up there on the 15th). Odd they didn't say how long this would be down, as a server with no Internet connection is rather pointless? Last I'd heard was that, if it was still down as of tonight (EDT), it would be moved to a different IP address (on some other Internet connection in the same datacentre), in order to get back everything except the ability to restart the server remotely. We've been offline for a day, this is unusual for even a small part of a major commercial datacentre. --Carlb 18:09, 17 October 2007 (UTC) edit server down? Cannot visit . :( --Hant 07:55, 18 October 2007 (UTC) - See the previous notice. The datacenter's internet connection broke down. --Leeyc0 08:30, 18 October 2007 (UTC) edit It's back! Unciklopédia in Hungarian language, and Uncommons are don't working. Why??? OsvátA - Looks like it will be down until tonight, and when it will be put back up it will have a different IP address. As stated above, this is affecting many Uncyclopedias and is a problem caused by an upstream provider. - It's back! I've had Vistapages move us to a new IP address (64.86.170.130 instead of 64.86.165.249) and operations appear to finally be returning to normal. If your local ISP has the old addresses cached, you may see problems on certain URL's until the outdated cached values expire. If this is happening, the site will look fine through Babelfish translation or through an anonymous proxy but not work if you try to access it directly. If a wiki has multiple domain names, one may work while another (pointing to the same place) may return an outdated address. This should clear itself automatically. --Carlb 18:31, 19 October 2007 (UTC) - Very good, Carlb. The Norwegian Ikkepedia is online! --Jeff no 18:48, 19 October 2007 (UTC) - BTW: We blame hackers from Wikipedia to be the culprits, as a part of their great plan to destroy all knowledge, replacing it with their own propaganda. --Jeff no 20:47, 19 October 2007 (UTC) - Hackers? Desciclopédia described the Wikipedia operatives as «terroristas». --Carlb 23:42, 19 October 2007 (UTC) - I also confirm that zh-tw and ja are up now. --Leeyc0 01:49, 20 October 2007 (UTC) - Yes, I can access Ja smoothly! We have no problem at present. Thank you very much! -- | 02:34, 20 October 2007 (UTC) edit Strange problem in zh-tw Special:DoubleRedirects Dear carlb, I found this minor problem in zh-tw:Special:DoubleRedirects. In this page, you can see a double redirect "脫肛 → 這篇文章在寫什麼鬼? → 偽基百科:這篇文章在寫什麼鬼?" But in fact, "脫肛" already redirected to "偽基百科:這篇文章在寫什麼鬼?" directly long ago. I have tried many methods, but still cannot get rid of this false double redirect. Maybe there is some problem in the database. May you do me a favour to remove this incorrect double redirect list. (By the way, there is a self redirect "無限", which means "infinite" in English. This is an intention infinite loop, so just keep it as if.) --Leeyc0 14:33, 22 October 2007 (UTC) edit oncyclopedie After 3 days of working perfectly, oncyclopedie is inaccessible again. ;_; D.G.Neree 14:05, 24 October 2007 (UTC) - Ikkepedia is also inaccessible... Norwegian Blue 14:35, 24 October 2007 (UTC) - We're back!!! ^_^ D.G.Neree 14:50, 24 October 2007 (UTC) - Yup. Norwegian Blue 14:52, 24 October 2007 (UTC) edit zh-tw: unable to edit my own user talk page Dear Carlb, when I am performing maintenance to my my talk page, I found that I cannot edit my talk page. When I edit my talk page, an mysql error ""Article::insertOn 1205: Lock wait timeout exceeded; try restarting transaction (localhost)" comes out. I can edit other pages normally. Would you please help me to fix the problem? Many thanks. --Leeyc0 00:43, 18 November 2007 (UTC) - Sometimes when I try to edit my talk page, no response at all and at last squid error comes out (zero sized reply). --Leeyc0 07:49, 18 November 2007 (UTC) - Same problem happens to my user page and zh-tw:用戶討論:Leeyc0/7 either. --Leeyc0 10:22, 19 November 2007 (UTC) edit Customary down Japanese Uncyclopedia is customary-serverdowned now, and perhaps other Uncyclopedias in the same server are in the same situation. I can no longer access the reboot page since the IP address was changed in October. Please reboot it., 30 November 2007 (UTC) - The problem appears to be not the server itself, but the Internet connection to the server. As such, reboot isn't going to help; I've reported the problem to helpdesk.vistapages.com and am waiting for them to fix it. --Carlb 15:45, 30 November 2007 (UTC) - The Norwegian Ikkepedia is still not «Up-and-go» --Jeff no 19:08, 30 November 2007 (UTC) - Response so far from my upstream provider has been "30 Nov 2007 01:26 PM - I believe Teleglobe is up to something. I will figure it out and let you know." --Carlb 19:28, 30 November 2007 (UTC) - Whatever they where up to, it's working again. Thanks! --Jeff no 19:31, 30 November 2007 (UTC) - Strange... I discovered that the CheckUser on ikkepedia.org does'nt work anymore.... Norwegian Blue 19:58, 30 November 2007 (UTC) - I just tried it; it gives some message about "can't find log file" but it does seem to be working. --Carlb 23:59, 30 November 2007 (UTC) - On zh-tw, I found that some configured namespace doesn't work now. From example, zh-tw:用戶:Leeyc0 has a link "Uncyclopedia:互助客棧/偽基鄉民", which should have its namespace configured in zh-tw:特殊:Namespaces, but it doesn't work now.--Leeyc0 03:18, 1 December 2007 (UTC) Thank you for the answer. And Ja:Un is working now. By the way, should we make the effort to decrease the edit frequency? In Japanese Uncyclopedia, some admins and users have many hundreds of edits per a day for unimportant maintenances. Most of them are trivial wikifies, and not indispensable work. If the huge amount of edits in Ja are harmful for our server, I can ask the admins and users for the self-imposed control of trivial maintenances.--, 1 December 2007 (UTC) - At this point, the discs on the main server are slightly over 50% full. There will be an additional server added in the new year, which will have more space. I don't forsee the number of edits causing a problem any time soon. --Carlb 15:43, 10 December 2007 (UTC) We are downed again! (at least the zh.uncyclopedia.info and ikkepedia.org) --Jeff no 21:30, 7 December 2007 (UTC) - Looks like Portugese and swedish sites are down too. --Trubadurix 23:24, 7 December 2007 (UTC) edit Subpage feature on zh-tw Dear carlb, I found that the subpage feature on namespace "uncyclopedia" is disabled. May you help us to enable it? --Leeyc0 12:25, 10 December 2007 (UTC) edit HTML markup auto closing problem Dear carlb, thank for your help before first. Now I found another problem about HTML markup and template. I need to create a template (e.g. zh-tw:用戶:Leeyc0/Test1) that one opens a <div> section, and the other template that closes the </div> section (e.g. zh-tw:用戶:Leeyc0/Test2). Now, I included these template like {{用戶:Leeyc0/Test1}} test {{用戶:Leeyc0/Test2}} (e.g. zh-tw:用戶:Leeyc0/Test) But I found that the <div> tag in zh-tw:用戶:Leeyc0/Test1 automatically closes first before being included in zh-tw:用戶:Leeyc0/Test. This caused problem for me to have a special formatted <div> section. May you check it for me? --User:Leeyc0 12:33, 12 December 2007 (UTC) - I tried installing a current version of MediaWiki (1.12alpha) here (so on a different 偽基百科 domain) as a test. We're currently at MediaWiki 1.11alpha on the actual .tw site. I do see some differences in the way <div> is being handled between the two MediaWiki versions. - In the new MediaWiki version, your test works. Oddly, the <div style="padding-left:7px; margin-bottom: 0.5em; text-align: left">{{languages}}</div> code used at the bottom of the main page, which looks fine in MediaWiki 1.11alpha, doesn't look right in the new version. Changing it to just be {{languages}} fixes this. - As such, it looks like there's nothing inherently wrong with your tags; the issues are caused by differences between various MediaWiki versions - they don't all handle <div> exactly the same way. In the next MediaWiki version, it looks like your test will be passed... with flying colours. :) --Carlb 21:31, 17 December 2007 (UTC) - After the upgrade, I found a strange problem for the "edit section" link. Originally the "edit section" link ([編輯]) is above the line, but now it is below the line. (See zh-tw:偽基百科:互助客棧/偽基鄉民 for example.) After the HTML code analysis, I found that the [編輯] HTML tag appears after the title, while in old version, the [編輯] HTML tag appears before the section title. Would you help us to check what's the problem in it? --Leeyc0 03:37, 18 December 2007 (UTC) - Just edited MediaWiki:Monobook.css as a workaround for this issue.--Leeyc0 07:25, 18 December 2007 (UTC) - For the {{language}} problem, it is not the new version problem, but due to a unclosed <p> tag near the end in the template. --Leeyc0 04:05, 18 December 2007 (UTC) - For you information, the job queue in zh-tw is very long (over 2000), since there were many broken (incorrect wiki syntax) templates that applied to many articles, and need to be regenerated after my fix. I think the server loading would be expected to be high during this period. --Leeyc0 11:17, 18 December 2007 (UTC) - Also, for some unknown reason, the image positioning is wrong, which overlapped the works like in zh-tw:講倒線. If you use the "show preview" function, it is OK, but after you actually save the article, the position goes wrong. --Leeyc0 09:32, 18 December 2007 (UTC) To be clear, I put the code snippet here. The original code is <h2><span class="editsection"> [<a href="/index.php?title=aaa&action=edit§ion=15" title="編輯段落: aaa">編輯</a>] </span><span class="mw-headline">aaa</span </h2> Now become <h2><span class="mw-headline">aaa</span> <span class="editsection">[<a href="/index.php?title=aaa&action=edit§ion=15" title="編輯段落: aaa">編輯</a>] </span> </h2> This cause some layout problems. --Leeyc0 10:00, 18 December 2007 (UTC) - This appears to be the result of a one-line change in one of the core MediaWiki files; I've moved the issue here. Changing that one line causes the section headers to appear as they did on previous MediaWiki versions. --Carlb 15:07, 18 December 2007 (UTC) edit MW1.12 upgrade: Some notes after yesterday's issue. Dear Carlb, Today I have inspected the page rendering issue again. First have a look in the HTML source. <style type="text/css" media="screen, projection">/*<![CDATA[*/ @import ""; @import ""; /*]]>*/</style> But I discovered that shared.css is 404 not found...--Leeyc0 10:45, 19 December 2007 (UTC) Oh, wait a minute, here it is, wedged behind the sofa. Sorry about that. --Carlb 20:13, 19 December 2007 (UTC) - After uploading shared.css, I discovered (the so-called buggy version) works normally, while the "edit" link in being too high now. Maybe that "bug" is actually caused by us that the CSS is missed...--Leeyc0 00:29, 20 December 2007 (UTC) edit RSS error after MW upgrade Dear carlb, an user in in zh-tw reported me RSS no longer works. See for the error. Thanks. --Leeyc0 07:40, 24 December 2007 (UTC) edit Errors on Ikkepedia Happy new year, Carlb. Has there been any software updates on Ikkepedia lately? On our forum, one of the forum templates is broken, and the new thread-button does not add the Forum: prefix anymore. --Trubadurix 07:24, 3 January 2008 (UTC) - We also had a lot of databese errors yesterday, and the check user function doesn't work. --Trubadurix 11:34, 3 January 2008 (UTC) Thank you, it's working now. --Trubadurix 07:15, 4 January 2008 (UTC) edit An IP in Finnish Hikipedia So, are you behind this IP-adress? --Crea(te)dit 07:33, 3 January 2008 (UTC) edit Japanese MediaWiki in trouble A Happy New Year! Mr.Carlb. We Japanese Uncyclopedia is in trouble that "SQL sever error". Especially on Check User and few special page, occurs "CheckUser::doUserIPsRequest". MySQL returned error "1072: Key column 'cuc_user_ip_time' doesn't exist in table (localhost)" and We can't user Check User function. Error message it self are occurss in other namespace, but he result is reflected definitely. It is thought that I am caused by version up. And please repair it. --Muttley 11:17, 3 January 2008 (UTC) edit zh-tw Watch function failed Dear carlb, an uncyclopedian discovered in zh-tw the watch function failed. When he press the "watch" tab, the tab changed to "watching" but stays there, and cannot add the page to watch list. Would you help us to check with this? --Leeyc0 10:40, 6 January 2008 (UTC) - Looks like a problem with $wgAjaxWatch, which appears on-by-default in MW 1.12 and rather buggy. For instance, when watching a page (page_id = 3507, page_title = 'ETC') it will add 3507 to the watchlist instead of adding ETC. Yuck. While special:watchlist/raw is unaffected, the watch(unwatch) tags on the individual articles won't work properly; setting $wgAjaxWatch=false in the configuration file makes this go away and act as previous MediaWiki versions had. --Carlb 02:23, 7 January 2008 (UTC) edit People's Republic of China Some fucking idiot messed things up big time. This is how the article use to look with my last edit and my many contributions to a developing article: Now go to the page; some complete pro-Communist-China douchebag edited the page to make THE ENTIRE THING SERIOUS, ABSOLUTELY SERIOUS AND BORING. Yes, I'm serious, it looks like it's straight out of - gasp - WIKIPEDIA! No joke. So I went to the edit page to show this guy what-for, and realized uncyclopedia doesn't have an "undo" option like wikipedia. There is way too much crap to wade through in order to fix this gigantic mess he created. Can you handle this asshole? You seem like a responsible administrator who knows what to do with douchebags like this.--PericlesofAthens 01:24, 9 January 2008 (UTC) - Looks like it has already been reverted by another admin. And yes, 'undo' does exist here as on Wikipedia. Go to the article's history, and from there compare the current version to the previous one - (edit)(undo) will appear as options. It's also possible to view any of the old revisions from the history page, then edit, then save - that puts the old version back, reverting it to its former state. - In general, copy-and-paste of entire Wikipedia articles to Uncyclopedia is a bad idea; their free license (GFDL) is incompatible with ours (CC-BY-NC-SA) and there's also the problem that the original authors of the text must retain attribution for their work. Besides, the purpose of the two wikis is too different - they're an encyclopaedia parody and we're a serious reference work. Or was that the other way around? And no, I'm actually irresponsible... --Carlb 01:38, 9 January 2008 (UTC) edit Servers It looks like the main server for Desciclopédia, Ansaikuropedia, Uncyclopedia.tw et al has been either running slowly or not responding since mid-afternoon. The issue has been reported to the data centre and I am awaiting a response the old server will be removed tonight. The hardware for the new server is here, but both servers will soon be operational with the second ready for redeployment hopefully this weekend. That should leave the Babel project less dependent on one pain main server should there be any further problems. --Carlb 20:56, 9 January 2008 (UTC) - Thanks for the report, Carl. But I can't understand the meaning of your last sentence because I have the problem in English. Are you saying "The problems of the Babel project will be solved by second server"? -- | 08:03, 10 January 2008 (UTC) - | 17:54, 11 January 2008 (UTC) edit Korean Uncyclopedia is reverted back to 1 year ago It seems that server is now working, but Korean Uncyclopedia lost a year of articles. Name was reverted to Feb 2007's, and all other contents, too. It is very serious problem for us, so I strongly want to restore all missing contents. --Peremen 00:36, 10 January 2008 (UTC) - Also Japanese and Chinese (tw) Uncyclopedia have been reverted to 1 year ago too. --에멜무지로 00:49, 10 January 2008 (UTC) - I've been spending the last six hours copying the data from the old server to the new server and it's still not done yet. Everything's here, it's just a lot of data to transfer. Still left to be done (as of 5:25am est) are zh-tw pt ja and some of the images for various projects. --Carlb 10:24, 10 January 2008 (UTC) - I've set the project name to 偽基百科. The sites are up and all wiki/database text has been uploaded, but there are still some images I shall need to put back online tomorrow for ja zh-tw zh-hk fi no. --Carlb 03:57, 12 January 2008 (UTC) edit Hungarian Today only hungarian Unciklopedia don't working. Why? OsvátA • Palackposta 15:47, 11 January 2008 (UTC) - Seems to be a network problem, nothing in the address range 64.86.167.* is responding, and this since 1:27GMT today. I've asked my provider to check this. - I also will be deploying a second main server to another Toronto data centre (hopefully) tomorrow - my third Uncyclopedia-related trip to Toronto in a little over a week. This server's sitting here freshly upgraded and ready for installation. - This should make it easier to deal with any future server problems as if one fails, we shall have a spare. --Carlb 17:34, 11 January 2008 (UTC) - Thanks. OsvátA Palackposta 18:23, 11 January 2008 (UTC) It's a full chaos. 7 days to be missing. Why? OsvátA Palackposta 18:11, 15 January 2008 (UTC) - The Internet connection to reset one of the two servers is down, so everything is running from the other server. The data for Jan 9-14 exists but needs to be copied from one server to the other; I can do that only once both servers are online. So not quite "missing", as we know exactly where they are: 151 Front St W, Toronto. I'll import those revisions once the second server comes back online. --Carlb 18:33, 15 January 2008 (UTC) edit Job queue in zh-tw Dear carlb, seems that the job queue displayed in zh-tw:Special:Statistics doesn't decrease, may you check for it? --Leeyc0 15:08, 14 January 2008 (UTC) edit Finnish Hikipedia Finnish Hikipedia had a few days ago some serious mental problems, any idea what that might have been? IE 7 had the page which said the server is under maintenance or the adress has changed and this lasted about three days. During those three days, at least I couldn't open Hikipedia and it seems that neither could the others or at least it was very slow. And in case it did open, all files were mixed and it showed me some pages that have not existed in months. It also showed some old versions of pages and the toolbar was sometimes pretty messy. Some pages were normal. And then some 30-minute problems occured a little afterwards for about 2 days. Since then Hikipedia has normalized. --Black Eagle 18:13, 14 January 2008 (UTC) - And most of the pictures didn't work properly. I'm not sure if they are in UnCommons or in Hikipedia, but the pictures were the last thing that was repaired. --Black Eagle 18:16, 14 January 2008 (UTC) Hikipedia is down again! As you can see here or here, almost every page that existed before is now gone! --Crea(te)dit 16:59, 15 January 2008 (UTC) - One of the two servers is down. When it comes back up, I shall export the most recent data (all recent edits from the last five or six days) in order to re-insert it into the database. The rest I should be able to reload in a few minutes... - It may be a good idea to post some sort of notice on the site itself? --Carlb 17:13, 15 January 2008 (UTC) - OK, thanks. --Crea(te)dit 17:36, 15 January 2008 (UTC) - We do have a notice, but people still tend to edit pages - what will happen to those edits after you reload all the changes between 8th and 16th? Will they just disappear? And...well, when are you going to do this, you mighty overlord? Black Eagle 22:04, 16 January 2008 (UTC) - The revisions from Jan 9-14, when imported tomorrow, will be inserted in the article history and appear before the current edits. Nothing will disappear, and the most recent version of the page will be displayed normally. I am picking up the other server at 1pm (edt) tomorrow and installing it in the new datacentre two hours later; by tomorrow evening I should have everything back in its proper place. --Carlb 23:28, 16 January 2008 (UTC) edit About lost articles Thanks for your recovery, Mr.Carlb. However, unfortunately articles written about from January 8 to 15th seems to disappear. Where gone these articles ? If can, please recover articles written this period, and if cannot, please tell me the fact about having occurred or your process in this period.-- by Muttley /Talk/ Mail 09:48, 16 January 2008 (UTC) - I confirmed the same phenomenon was generated also in other uncyclopedia pages.( http://백괴사전.org/ )--Sts 12:12, 16 January 2008 (UTC) - We have switched datacentres and are currently operating with just one of the two servers, now co-located to Teleglobe, 825 Milner, Scarborough, Toronto. As mentioned above (Finnish, Hungarian) the updates for Jan 9-14 are all on the other server and are at 151 Front St W, Toronto. The revisions will be imported into the main database as soon as I can retrieve that server from the old datacentre. So no, nothing has been lost and there's no need to re-create those pages manually. I'd expect that it will be at least a day before everything is back to normal. My apologies. --Carlb 13:44, 16 January 2008 (UTC) - I see. We continue making articles and judge the problem not to be it as it is. Thank you.--Muttley 14:26, 16 January 2008 (UTC) - How about deleted pages? I have deleted several pages in zh-tw during that period. Shall we need to delete the pages again after import? --Leeyc0 13:51, 16 January 2008 (UTC) - If they were still in the database on Jan 14th and were edited last week, they will be fully restored (and will need to be deleted again). If they were deleted earlier, the import of missing revisions should not affect them. --Carlb 14:01, 16 January 2008 (UTC) - I might have a plan: - Temporary Editing Block - New Memory(since 14th Jan) Storage - Old Memory Recover - New Memory Recover - Re-Open Hope that it can be useful.--Edward Knave(Say something here)15:02, 16 January 2008 (UTC) Once the second server is back here? The old revisions could be inserted to the main server's database without having to impose any temporary editing blocks at all: - Bring second server home, go to special:recentchanges to get list of edits since the 8th - Go to special:export to put the text of those edits into an XML file - Go to special:import on the main server and import those changes - Go to special:newimages to find which images need to be copied to the main server At that point, the text of any missing revisions are inserted into the article history before the current changes and images copied. One last check of special:log/delete to ensure that nothing has been inadvertently re-created, and done. --Carlb 16:56, 16 January 2008 (UTC) When your recovery have done, please tell us here.-- 12:35, 17 January 2008 (UTC) Godspeed to the recoverers.--Edward Knave(Say something here)12:56, 17 January 2008 (UTC) - We have the same problem at Ikkepedia.org, but it looks like you got it covered. Thanks for all the work you're doing for us, Carlb, we really appreciate it. --Trubadurix 22:10, 17 January 2008 (UTC) edit some problems happened to zh-tw after server restoration Dear carlb, Uncyclopedians in zh-tw discovered the following problems after server restoration: - In zh-tw:很黃很暴力, all images disappeared (which is uploaded during the history loss period). - favicon.ico disappeared Thanks in advance. --Leeyc0 11:55, 18 January 2008 (UTC) - I've checked for missing image descriptions; it finds many additional images, but some do seem to be unused or leftover from other-language projects. Would it be worth excluding images that aren't in use, don't have descriptions and already exist in commons.uncyclomedia.org? - I've also noticed that, since the servers were moved, automated e-mail sent from the site does reach me... unless I use a Hotmail address. Maybe their spam filters are rejecting the messages? --Carlb 17:22, 18 January 2008 (UTC) - Thanks carlb. In fact we are performing mass clean-up with those images, but in high delay. (In fact ALL administrators in zh-tw are in fact so busy that have limited time to perform clean up, and even one bureaucrat is undergoing compulsory military service that he is unable to be online.) --Leeyc0 04:17, 19 January 2008 (UTC) edit delay Hello Carl, for the last two days, there has been a delay in the editing results. When i save a page after editing, i see the result, but when i click on edit again, the source code is again as it was before the last edit. Also the change doesn't show in recent changes until after about fifteen minutes or so, as is the timelapse in edit mode. Today i logged in and when i opened a second window i was still logged out and couldn't log in on that page, although i was still logged in in the first window. Is there a database delay? D.G.Neree 02:33, 21 January 2008 (UTC) edit Done ? The recovery of the servers seems to have been considered to be it, but04:24, 25 January 2008 (UTC) - As far as I know, the sites are back to normal - the Jan 15+ revisions have been copied back to the main database, the wikis have been checked for missing images, the email-to-user is working. We are now using two servers instead of one, so hopefully things are going a wee bit faster now. --Carlb 01:46, 26 January 2008 (UTC) - Special thanks for your works that data recovery and reinforcement se06:29, 26 January 2008 (UTC) - P.S.Except site icon. edit Edit section link problem in zh-tw Dear carlb, I discovered that after you have upgraded MediaWiki in zh-tw, the "Edit section" link become too much above the title (because you have modified CSS (refer to 18 December discussion about MW 1.12 upgrade). Would you restore the CSS to default version? Thanks in advance. --Leeyc0 01:56, 26 January 2008 (UTC) edit Hikipedia has problems again I feel sorry for you, people just whine about something not working properly. =) Well anyway, Finnish Hikipedia occured this problem when editing: Sisäinen virhe Detected bug in an extension! Hook wfRegexBlockCheck failed to return a value; should return true to continue hook processing or false to abort. Backtrace: - 0 /home/sophia/domains/fi/includes/User.php(956): wfRunHooks('GetBlockedStatu...', Array) - 1 /home/sophia/domains/fi/includes/User.php(1095): User->getBlockedStatus(false) - 2 /home/sophia/domains/fi/includes/User.php(1108): User->isBlocked(false) - 3 /home/sophia/domains/fi/includes/Title.php(1049): User->isBlockedFrom(Object(Title)) - 4 /home/sophia/domains/fi/includes/EditPage.php(364): Title->getUserPermissionsErrors('edit', Object(User)) - 5 /home/sophia/domains/fi/includes/EditPage.php(323): EditPage->edit() - 6 /home/sophia/domains/fi/includes/Wiki.php(444): EditPage->submit() - 7 /home/sophia/domains/fi/includes/Wiki.php(48): MediaWiki->performAction(Object(OutputPage), Object(Article), Object(Title), Object(User), Object(WebRequest)) - 8 /home/sophia/domains/fi/index.php(89): MediaWiki->initialize(Object(Title), Object(OutputPage), Object(User), Object(WebRequest)) - 9 {main} What is this? Is the problem over there or is it here? Black Eagle 21:32, 26 January 2008 (UTC) - It seems to have been an error related to the use of one individual MediaWiki extension, which appeared briefly after the MediaWiki 1.12 upgrade. The old versions of MediaWiki were not as quick to display "detected bug in an extension" but a few old extensions now give errors under the new MediaWiki. --Carlb 05:22, 27 January 2008 (UTC) - The problems are gone now, did you do something? --Black Eagle 07:21, 27 January 2008 (UTC) edit Since you seem to know these things... Care to take a look. We were trying to create a link that would refresh the page. It's not good enough because it refreshes a random page. See the MediaWiki source and then click random page in a new window and see that the link doesn't work very well. Why does it do that and what can we do? --Black Eagle 12:10, 30 January 2008 (UTC) - Looks like MediaWiki:Sitenotice itself is being cached somewhere, so using it to generate the per-page "Päivitä" link won't work. The solution is/was to add this to the configuration file: # # add page-refresh tab # $wgHooks['SkinTemplateContentActions'][] = 'wfContentRefreshHook'; function wfContentRefreshHook( &$content_actions ) { global $wgRequest, $wgRequest, $wgTitle; $action = $wgRequest->getText( 'action' ); if ( $wgTitle->getNamespace() != NS_SPECIAL ) { $content_actions['purge'] = array( 'class' => false, 'text' => wfMsg( 'refresh' ), 'href' => $wgTitle->getLocalUrl( 'action=purge' ) ); } return true; } --Carlb 00:48, 3 February 2008 (UTC) edit Question about Forum:Suggestions on reducing the need for CVP An IP editor apparently misunderstood the shortcut UN:PT to mean the Portuguese version of Uncyclopedia. I would like to amend the discussion to indicate that this was a misunderstanding (or a poor attempt at sarcasm), but I took an unscheduled UncycloBreak and the topic went stale. Is there any way you could do this for me, or do not even administrators have permission to edit stale forum topics? Thank you very much. Oh, and sorry I didn't recognize the extent to which CVP was declining and redirection was rising. The problem really wasn't as bad as I thought it was, other than the need for more rewriting of articles. Pentium5dot1 05:20, 3 February 2008 (UTC) - Never mind; sorry for bugging you. Withdrawing request. --Pentium5dot1 23:46, 4 February 2008 (UTC) edit Deleted files Lately, I became an admin in Hikipedia. I tested can I undelete files, but I failed. Look at this. I can only undelete the description of the file, not the file itself. I don't want to undelete that image, but I just tested if I could. There is also some deleted files I can undelete, like this one. Has somebody deleted conclusively those images I can't undelete? Thanks. --Crea(te)dit 15:40, 4 February 2008 (UTC) - This seems to be determined by when the files were deleted. MediaWiki originally did not provide any support for image undeletion; this was something that was added to their software less than a year ago. While the current version archives the deleted images so that they may be recovered later, the versions of MediaWiki which were available when Hikipedia was originally built did not. - Sometimes the downloadable copy of the wikis at can be used to retrieve missing content, another possibility is to check if the image was copied from some other site (such as Wikimedia's commons) which may still have the original online. --Carlb 20:53, 4 February 2008 (UTC)
http://uncyclopedia.wikia.com/wiki/User_talk:Carlb/Archive3
CC-MAIN-2014-15
refinedweb
8,790
64.81
hu_ECPVSSignBegin() Creates an ECPVS signing context object. Synopsis: #include "huecpvs.h" int hu_ECPVSSignBegin(sb_Params eccParams, sb_PrivateKey privateKey, int hash, int kdf, int encoding, int mode, int flag, size_t ivLen, const unsigned char *iv, size_t padLen, sb_Context *ecpvsContext, sb_GlobalCtx sbCtx) Arguments: - eccParams An ECC parameters object. - privateKey An ECC private key object. - hash The hash algorithm to use. This is one of: HU_DIGEST_SHA1, HU_DIGEST_SHA224, HU_DIGEST_SHA256, HU_DIGEST_SHA384, or HU_DIGEST_SHA512. - kdf The KDF algorithm to use. This is one of: HU_KDF_ANSI_SHA1, HU_KDF_ANSI_SHA224, HU_KDF_ANSI_SHA256, HU_KDF_ANSI_SHA384, or HU_KDF_ANSI_SHA512. - encoding The symmetric encryption to use. Currently, the only valid value is HU_ECPVS_ENCRYPTION_STREAM. - mode The encryption mode for block symmetric ciphers. Ignored for the stream cipher HU_ECPVS_ENCRYPTION_STREAM. - flag If flag is set to HU_ECPVS_FLAG_RAW, no padding will be added to the recoverable message. When no padding is used, there has to be sufficient amount of redundancy in the recoverable part of the message. - ivLen The length (in bytes) of iv. Ignored for the stream cipher HU_ECPVS_ENCRYPTION_STREAM. - iv The initialization vector for block symmetric ciphers. Ignored for the stream cipher HU_ECPVS_ENCRYPTION_STREAM. - padLen The number of bytes of additional redundancy. It should be in the range 1..255. - ecpvsContext ECPVS context object pointer. - sbCtx A global context. Library:libhuapi (For the qcc command, use the -l huapi option to link against this library) Description: The ANSI X9.92-conformant usage of this API function should include only security primitives with the security level set at more than 80 bits. The ECC parameter object must have been created with an RNG context. Currently only the KDF-based symmetric stream cipher is supported (i.e. HU_ECPVS_ENCRYPTION_STREAM). This is the first of four API functions to be called during the ECPVS signing process. It is followed by one or more calls to hu_ECPVSSignEncrypt(), then one or more calls to hu_ECPVSSignUpdate(), and then finally a call to hu_ECPVSSignEnd(). Returns: - SB_ERR_NULL_PARAMS The eccParams object is NULL. - SB_ERR_BAD_PARAMS The eccParams object is invalid. - SB_ERR_NULL_GLOBAL_CTX Global context is NULL. - SB_ERR_NULL_PRIVATE_KEY The privateKey object is NULL. - SB_ERR_BAD_PRIVATE_KEY The privateKey object is invalid. - SB_ERR_NULL_CONTEXT_PTR The ecpvsContext is NULL. - SB_ERR_NULL_INPUT_BUF iv is NULL and ivLen is greater than 0. - SB_ERR_HASH_TYPE The hash algorithm is not supported. - SB_ERR_BAD_ALG The KDF algorithm or encryption is not supported. - SB_ERR_BAD_LENGTH The padLen is out of range or ivLen is too large. - SB_FAIL_ALLOC Memory allocation failure. - SB_SUCCESS Success. Last modified: 2014-05-14 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
https://developer.blackberry.com/native/reference/core/com.qnx.doc.crypto.lib_ref/topic/hu_ECPVSSignBegin.html
CC-MAIN-2019-35
refinedweb
405
53.47
Hi guys, I just started to use tinyXml because I need an xml parser for my program. I was wondering if I could ask you a bunch of questions about getting started. 1) to build the library I downloaded the file from sourceforge and I built it. In my project I just have to use the 2 .h files and the lib file. Is it correct? 2) I'm trying to compile the first example and it is working; I have one question though. If before #include <cstdio> #include "tinyxml.h" I try to define_ TIXML_USE_STL_ to use all the feature of stream and whatnot but I have a link error: unresolved external symbol "protected: virtual void __thiscall TiXmlDocument::StreamIn… Am I doing something wrong? Is there a solution? I would really like to use streams in my project. Any suggestions where to start to learn this library? Thanks in advance to everyone. Bye, Arro
https://sourceforge.net/p/tinyxml/discussion/172103/thread/c94969d1/
CC-MAIN-2017-47
refinedweb
155
76.52
Pycse is now using Python3 Posted February 25, 2016 at 07:09 PM | categories: python | tags: | View Comments Updated February 25, 2016 at 07:17 PM I spent the last couple of days going through the notes for pycse and updating it for Python 3! If you aren't familiar with pycse, it is an acronym for Python3 Calculations in Science and Engineering, and it is about 400 pages of examples spanning scientific and engineering computations, and a python module that extends numpy/scipy with some functions for adding events to differential equation solvers, and regression with confidence intervals. It is mostly done, and was pretty easy. The Python module for pycse ( ) should also be Python 3 compliant. Yep, on my Mac I have switched over to the Anaconda Python 3 from Continuum IO (thanks for that!). import sys print(sys.version) 3.5.1 |Anaconda 2.5.0 (x86_64)| (default, Dec 7 2015, 11:24:55) [GCC 4.2.1 (Apple Inc. build 5577)] Now we can succinctly do matrix multiplication like this: import numpy as np a = np.array([1, 2, 3]) a = np.array([1, 2, 3]) print(a @ a) # the matrix multiplication operator # instead of print(np.dot(a, a)) 14 14 Here is a summary of what the changes to the Python2 version of Pycse entailed. - Change all print statements to print functions. There were so many… - Eliminate use of tabs in some code blocks, Python3 is not flexible on that. I wrote this function to fix both of these for me (I use Emacs as my editor), which worked nicely: (defun fp () "convert print to print() allowing for line end comments. does not do multiline. and untabify" (interactive) (beginning-of-line) (re-search-forward "print " (line-end-position) t) (delete-char -1) (insert "(") ;; rm spaces (delete-forward-char (save-excursion (skip-chars-forward " "))) (when (re-search-forward "#" (line-end-position) 'move) (goto-char (match-beginning 0))) (skip-chars-backward " ") (insert ")") ;; untabify (let ((src (org-element-context))) (untabify (org-element-property :begin src) (org-element-property :end src)))) - reduce no longer exists, you have to use functools.reduce. Probably will not affect me much… - Strings are sometimes bytes, and need to be encoded/decoded depending on what you are doing. Otherwise, most things seemed to work fine. In a few places I had articles on Windows specific code, which I couldn't test on the Mac I work on now. Only one package was apparently not ready for Python3, and that was scimath from Enthought, which had units capability. Quantities worked fine though. For some reason I could not do interactive key-presses in matplotlib. I am not sure if that is a Python3, or my Mac setup for now. When I first wrote the Pycse book (in org-mode naturally), I must have had a default session setup for org-mode, because there was no :session information in a few of the src-block headers. I had to add these back in a few places. Overall the transition was pretty seamless. It looks like I will be transitioning to Python3 in teaching this fall! Big thanks to the Anaconda team for packaging Python 3.5 and making it so easy to install! Copyright (C) 2016 by John Kitchin. See the License for information about copying. Org-mode version = 8.2.10
http://kitchingroup.cheme.cmu.edu/blog/2016/02/25/Pycse-is-now-using-Python3/
CC-MAIN-2017-22
refinedweb
557
65.12
odbc - allstring? Dear Readers I wonder if there is a bug in odbc with the "allstring" option? I try to load an excel worksheet which has some cells - for example - "1,2,3" corresponding to multiple responses to a question. The cell in the first row happens to have a "1" as only one response was recieved. The variables in stata is all strings but the "1,2,3" type entries are missing. odbc load , dsn("XXX") table("YYY") allstring lower clear import excel works fine, so there is a work around, but it is inconvenient that odbc appears not to. Richard . * * For searches and help try: * * *
http://www.stata.com/statalist/archive/2011-11/msg00365.html
CC-MAIN-2015-48
refinedweb
107
79.8
ifonly keywordContains worked with if In creating a template I was trying to do something like: {$ if KeywordContains "homepage" $} show this bit here {$ endif $} but IF only uses blank and nonblank I want to use this because the extra fields are all in use. My thinking here is it gives the site designer the ability to turn things on and off easily across pages (assuming they can remember what all their little words meant). For now, I think I have to settle for creating another template Dan Friday, November 21, 2003 try this.... {$ foreach x (keywordcontains "homepage") $} {$ after $} do your stuff here A thousand pardons if the syntax isn't exactly right. I don't have CD installed here at my office. Basically this tests to see if the keyword has homepage in it. If it does, then only once (after) does it do your stuff. You may need additional conditions to limit to folders, etc. I use this a lot.... Jeff Kolker Friday, November 21, 2003 Thanks Jeff. But that only works if the script appears in an article though not inside a template. Is that where you're using the for loop? If any page contains "homepage" (doesn't matter if I limit the pages checked), the code turns up in all pages. Dan Friday, November 21, 2003 I use it in templates, and articles. I tend to group like documents in their own subfolders, which helps on some of the loops. You may just have to play with it some.... various (folder) or (filename) conditions may help. I'm like you and try to keep everything in one template. My website at has some of my suggested scripting and uses only one template, but it may not be exactly the same thing you are trying to do... Just figured it out - the actual script I am using is: {$ forEach x in (and(thisArticle)(keywordContains "homepage")) $} the bits that I want to show Dan Friday, November 28, 2003 Recent Topics Fog Creek Home
https://discuss.fogcreek.com/CityDesk/10652.html
CC-MAIN-2019-22
refinedweb
335
71.75
The SigTest product is a collection of tools that. The SigTest product consists of the following tools. Signature Test tool makes it easy to compare the signatures of two different implementations or different versions of the same API. When it compares different implementations of the same API, the tool verifies that all of the members are present, reports when new members are added, and checks the specified behavior of each API member. When it compares different versions of the same API, the tool checks that the old version can be replaced by the new one without adversely affecting existing clients of the API. API Coverage tool can be used to estimate the test coverage a test suite provides for an implementation of a specified API. It does this by determining how many public class members the test suite references within the API specification. The tool uses a signature file representation of the API specification as the source of specification analysis. It does not process a formal specification in any form. API Check tool tracks API changes and roughly. Part I of this manual describes how to use the Signature Test Tool, Part II describes how to use the API Coverage tool, Part III describes how to use the API Check tool, and Part IV contains two appendices that include step-by-step examples that show how to use the Signature Test tool and the rules used in the Signature Test API migration feature. This section describes functionality that is available to all the tools and their commands. All of the tools accept options from a option file as well as from the command line. Option files allow you to create complex command lines in a text editor and then reuse them. The option file is specified on the tool command line using the ”@” character as shown in the following example. java -jar sigtest.jar test @file In this case, file is the path to a option file. You can use a combination of option files and command-line options as shown in the following example. java -jar sigtest.jar test @file -package com.acme.api.printing.color In addition to options and their arguments, option files can also contain ”set” commands that you can use to set variables for use within the option file. The option file syntax is demonstrated in Example 2-1. Example 2-1 Option File #-------------------------------------------------- #This option file checks the API against JRE 1.6 #-------------------------------------------------- set HOME=/home/ersh set JRE=/opt/java/jre16 set AMCE_HOME=$(HOME)/projects/release set API=$(ACME_HOME)/lib/ams.jar static backward classpath=$(JRE)/lib/rt.jar:$(API) filename=$(ACME_HOME)/misc/reference.sig This option file is equivalent to the following command line. java -jar sigtest.jar test -static -backward -classpath /opt/java/jre16/lib/rt.jar:/home/ersh/projects/release/lib/ams.jar -filename /home/ersh/projects/acmesystem/msc/reference.sig -package com.acme.api.printing.color All of the tools and commands support the -version option as a way to display information about the tools and will list which signature files they are compatible with. In addition, you can specify the -version option as an argument directly to the JAR file as well as shown here. java -jar sigtest.jar -version
http://docs.oracle.com/javame/test-tools/sigtest/3_0/html/intro.htm
CC-MAIN-2014-41
refinedweb
542
56.55
Provided by: libncarg-dev_6.3.0-6build1_amd64 NAME AGSETC - Allows a user program to (in effect) store a character string as the value of a specified single parameter. SYNOPSIS CALL AGSETC (TPGN,CUSR) C-BINDING SYNOPSIS #include <ncarg/ncargC.h> void c_agsetc (char *tpgn, char *cusr) DESCRIPTION TPGN (an input expression of type CHARACTER) is a parameter identifier, as described for AGSETP, above. The specified parameter must be one of those which intrinsically have values of type character: 'LINE/END.', 'LABEL/NAME.', 'LINE/ TEXT.', or 'DASH/PATTERN/n.' CUSR (an input expression of type CHARACTER) is the desired character string. · If 'LINE/END.' is being set, only the first character of CUSR will be used. · If 'LABEL/NAME.' is being set, the length of the string CUSR will be taken to be "MAX(1,LEN(CUSR))". · If the text of a label is being set, CUSR must either be of the exact length specified by 'LINE/MAXIMUM.' (40 characters, by default) or shorter; if shorter, it must be terminated by the character defined by 'LINE/END.' (default: a '$'). · If a dash pattern is being set, the length of CUSR will be taken to be the minimum of "LEN(CUSR)" and the value specified by 'DASH/LENGTH.'. examples: agex05, agex06, agex07, agex08, agex09, agex13, tagupw, tautog, fagaxlbl, fagovrvw. ACCESS To use AGSETC or c_agsetc, See the autograph man page for a description of all Autograph error messages and/or informational messages..
http://manpages.ubuntu.com/manpages/xenial/en/man3/agsetc.3NCARG.html
CC-MAIN-2018-47
refinedweb
240
54.42
Answered by: Silverlight Error #2103 The mysterious error #2103 annoyed me for awhile. Of course, the lack of details about the error (typical for most SL errors) only prolonged my agony. I created a new Silverlight app and then changed the namespace from the default assembly name to another name of my chosing. Boom! Error #2103. Eventually, I did find the cause of this error. Apparently, the derived Application namespace MUST be the same as the assembly name. I just thought I'd pass this tidbit along as a little warning. W James Question Answers All replies For posterity, this error can also be caused by turning off Internet Information Services -> World Wide Web Services -> Common Http Features -> Static Content in the Windows Features under the Programs and Features Control Panel. This being off is the default setting. Another way to tell if this is off is that MIME Types will not be present in the IIS group of the Features View of the server (top node in tree) in IIS Manager for IIS 7.0. Verified in Vista Home Premium 64-bit SP1. I got the error #2103 because i tried to instantiate an object of some class in the constructor of the App-Class. App was my Startup-Object. The solution was to instantiate the object in the Application_Startup-Method instead of the constructor. Hope this helps anyone and he/she doesn't have to search for the error for hours :)
https://social.msdn.microsoft.com/Forums/silverlight/en-US/e7d0eb62-73ea-47d2-8cb1-a848ef63a54d/silverlight-error-2103?forum=silverlightnet
CC-MAIN-2016-44
refinedweb
243
62.88
Hi All, I’m super a super ruby nuby, so bare with me. I am working on a small app that has a particular form that I am having a rough time figuring out the best to way to handle. Basically here it is, each school has one or more classrooms, and each classroom can have one or more teachers. Here’s what I am trying to do (edit a school): - click on a link to edit a School - The school form loads and with it, all it’s classrooms are listed (I have this part ok) - part I’m trying to think of how to do is: - for each classroom, grabbing all the teachers…Would do this in the controller or the rhtml file itself? If in the controller, how? It’s probably a stupid question, but I can’t see it. Can you do a loop through each of the classrooms and assign them an array of teachers? here is the controller for the form so far: def view_school @school = School.find(params[:id]) @classrooms = Classroom.find(:all, :conditions => [“school_id = ?”, params[:id]) end
https://www.ruby-forum.com/t/best-way-about-doing-this/55994
CC-MAIN-2018-47
refinedweb
185
79.4
A CLI for managing python projects Project description PyMan is a small library that allows you to build your own CLI to manage your projects. This way you do not have to remember commands to run, you simply navigate your CLI to run those commands. Installing PyMan is available from the PyPi repository. This means that all you have to do to install PyMan is run the following in a console: $ pip install pyman Collecting pyman Using cached pyman-0.1.3-py2.py3-none-any.whl Installing collected packages: pyman Successfully installed pyman-0.1.3 Minimal Example import pyman pyman.Main("PyMan - Menu Example", [ pyman.Action.Cmd( "Hello World", "echo 'Testing PyMan'" ), pyman.Action.Exit() ]).cli() Example Output ================================================================ PyMan - Menu Example ================================================================ Main Menu -------------------- 1) Hello World 2) Exit -------------------- Choice: How It Works PyMan uses the idea of Pages and Actions. Each page is made up of a number of actions. You start off by instanciating the ‘Main Menu’ class, providing the title you wish to display: menu = pyman.Main("PyMan - Menu Example") From here you add other Pages or Actions menu.add([ pyman.Action.Exit() ]) pyman.Action.Exit is one of the in-built actions. Other inbuilt actions include: - pyman.Actions.Cmd - pyman.Actions.Back - pyman.Actions.Exit And finally, you start the CLI with: menu.cli() Documentation: ReadTheDocs Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/pyman/
CC-MAIN-2019-47
refinedweb
248
50.23
14 October 2010 09:37 [Source: ICIS news] SHANGHAI (ICIS)--China’s Xinjiang Tianye Group Co achieved on-spec production at its new 400,000 tonne/year carbide-based polyvinyl chloride (PVC) plant in China’s northwestern Xinjiang province on 6 October, a company source said on Thursday. The company had earlier begun trial runs in mid-September, the source added. "The start-up of the new plant went very smoothly, even beyond our expectations," the source said in Mandarin. The source also told ICIS that Xinjiang Tianye had recently ramped up the plant’s operating rate, but declined to provide an exact figure. With the start-up of the new plant, Xinjiang Tianye’s PVC production capacity has increased from 700,000 tonnes/year to ?xml:namespace> Meanwhile, the company also achieved on-spec production at its new 300,000 tonne/year caustic soda unit in late September, said the source. The new plant, which is also located at the same site in Xinjiang, has increased the company’s caustic soda capacity from 600,000 tonnes/year to 900,000 tonnes/year, the source added. For more on polyvinyl chloride and caustic soda,.
http://www.icis.com/Articles/2010/10/14/9401041/xinjiang+tianye+achieves+on-spec+production+at+new+pvc.html
CC-MAIN-2013-20
refinedweb
194
58.32
Stacks Authors: Darren Yao, Michael Cao A data structures that only allows insertion and deletion at one end. StacksStacks A stack is a Last In First Out (LIFO) data structure that supports three operations, all in time. Think of it like a real-world stack of papers. C++ C++ push: adds an element to the top of the stack pop: removes an element from the top of the stack top: retrieves the element at the top without removing it stack<int> s;s.push(1); // [1]s.push(13); // [1, 13]s.push(7); // [1, 13, 7]cout << s.top() << endl; // 7s.pop(); // [1, 13]cout << s.size() << endl; // 2 Java JavaJava push: adds an element to the top of the stack pop: removes an element from the top of the stack peek: retrieves the element at the top without removing it Stack<Integer> s = new Stack<Integer>();s.push(1); // [1]s.push(13); // [1, 13]s.push(7); // [1, 13, 7]System.out.println(s.peek()); // 7s.pop(); // [1, 13]System.out.println(s.size()); // 2 Python PythonPython Python does not have a built-in stack type, but a list can function like a stack. list.append(): Appends an element to the end. list[-1]: Retrieves the last element without removing it. list.pop(): Removes the last element and returns it (but you don't need to use the returned value). list.pop(n): Removes the nth element, 0-indexed. Note that removing elements is an O(n)operation. stack = [] # []stack.append(1) # [1]stack.append(2) # [1, 2]stack.append(3) # [1, 2, 3]v = stack[-1] # stack = [1, 2, 3] (unchanged), v = 3stack.pop() # [1, 2]v = stack.pop() # stack = [1], v = 2stack.append(4) # [1, 4]v = stack.pop(0) # stack = [4], v = 1 Application - Nearest Smaller ElementApplication - Nearest Smaller Element Focus Problem – try your best to solve this problem before continuing! Consider the following problem: Given an array, , of () integers, for every index , find the rightmost index such that and . To solve this, let's store a stack of pairs of and iterate over the array from left to right. For some index , we will compute , the rightmost index for , as follows: - Keep popping the top element off the stack as long as . This is because we know that the pair containing will never be the solution to any index , since is less than or equal to than and has an index further to the right. - If , set to , because a stack stores the most recently added values first (or in this case, the rightmost ones), will contain the rightmost value which is less than . Then, add () to the stack. The stack we used is called a monotonic stack because we keep popping off the top element of the stack which maintains it's monotonicity (the same property needed for algorithms like binary search) because the elements in the stack are increasing. ImplementationImplementation C++ #include <bits/stdc++.h>using namespace std;int N;int main() {ios_base::sync_with_stdio(0);cin.tie(0); Java /*** author: Kai Wang*/import java.io.*; import java.util.*;public class NearestSmallestVals {/*** We keep a stack of pairs (ind, value)* Traverse the array from left to right, use ans to store answers ProblemsProblems Module Progress: Join the USACO Forum! Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!
https://usaco.guide/gold/stacks
CC-MAIN-2022-40
refinedweb
568
66.64
- Threading in .NET - Exception Handling in .NET - The MSIL Disassembler - From Here Exception Handling in .NET When writing code, one thing you can be sure of is that errors may occur. Typically you code will call Application Programming Interfaces (APIs) or other functions, and those functions may run into trouble. One approach for dealing with these errors is to monitor return values from functions to make sure that the intended result happened. The idea is to look for a successful return code and continue execution or detect that a failure has occurred and then handle the error condition correctly and gracefully terminate execution. This works fine until you call a function or library that does not properly handle all possible error conditions. When this happens, the error can sometimes be passed back to your code and unexpected problems can occur. Exceptions provide a standardized way to generate and detect these errors before they can become a more serious problem in your application. Exceptions allow you to build applications that make a call to another function and then catch errors if they occur and handle them in the calling application. However, exception handling differs from one programming language to another, if it is even supported at all! The Common Language Runtime solves this problem for all applications that use it. This section focuses on exception handling construction for Managed C++ application using the Common Language Runtime. The concepts are the same as traditional C++ exception handling, but the details vary a little. Managed Exception Handling Using exceptions in applications when you are using the Common Language Runtime provides the following benefits: Exceptions can be handled regardless of the language that generated the exception or the one that is handling it. Exceptions can be thrown (generated) from one process to another or even from a remote machine. Exceptions can be thrown and caught in either managed or unmanaged code allowing you to work with exceptions outside of the environment that you are currently working in. Exceptions in the Common Language Runtime do not require any special syntax but allows each language to define its own. Exception handling, using the Common Language Runtime, is faster than using the Windows-based C++ error handling. The Exception Class At the center of exceptions in the Common Language Runtime is the Exception class. This base class is the class from which all other exception classes are derived. A portion of the hierarchy is shown in Figure 25.3. Two of the most common exception classes are SystemException and ApplicationException. Both of these classes inherit from Exception class but do not add any additional functionality. Why the two separate classes? It makes it easier to determine the origin and severity of the exception. Figure 25.3 Examples of classes derived from the Exception class. SystemException is used for exceptions that are generated by the CLR. The severity of the exception can be mild (such as a NULL reference exception) or more severe (such as a stack overflow exception.) SystemException is also the class from which ExternalException is derived. This allows the CLR to create managed exceptions that contain information about unmanaged exceptions. It is normally recommended that you do not catch exceptions of type SystemException. Let the runtime catch them, since the application is unlikely to be able to continue after the exception has occurred. ApplicationException is the base class for exceptions that are thrown as part of an application. You can derive your own exceptions from the ApplicationException class. This is the exception type that you will most often catch in your application. The Exception class contains several properties that can be examined when the exception has been caught. Table 25.3 lists the public properties and their description. The SystemException and ApplicationException classes inherit these properties.Table 25.3 Properties of the Exception Class Throwing Exceptions in Managed Code When an error occurs in your application, you should throw an exception to signal to the caller that an error has occurred. The way you do this in managed code is very simple, as demonstrated in Listing 25.4. Listing 25.4 Throwing an Exception in Managed Code #using<mscorlib.dll> using namespace System; int main() { Console::WriteLine(S"This is an example of throwing an exception"); throw new Exception(S"A sample exception"); return 0; } This simple sample only throws the exception, using the throw statement. The string that is passed to the new Exception object is passed to the Message property of the object and provides information to the handler of the exception. NOTE If you create a solution and use the code from Listing 25.4, then execute it under the debugger, you will see a dialog box that says that an unhandled exception has occurred. This dialog also provides information about the exception, if available, and gives you the option of continuing with execution or breaking into the code where the exception is being handled. If you execute the code normally, the Just in Time debugger (JIT) dialog will appear and give you the option of debugging the failure. Throwing an exception is easy. Handling the exception is also easy. Try/Catch Block Construction in Managed Code The Common Language Runtime exceptions use the same mechanism as the C++ language for exception handling, which is the Try/Catch statements. The use is very similar to the way as C++ exceptions. However, there are some minor differences. Normally, code that might throw an exception is in a try/catch block. Perhaps the throw statement is in a function, and the call to the function is in a try/catch block. This enables you to catch any exceptions thrown by the function. To extend the sample above you could add a try and catch block as shown in Listing 25.5. Listing 25.5 A General Try/Catch Block for Exception Handling #using<mscorlib.dll> using namespace System; int main() { try { Console::WriteLine(S" This is an example of throwing an exception"); throw new Exception(S"A sample exception"); } catch(Exception* e) { Console::WriteLine(S"An exception has been caught: "); Console::WriteLine(e->ToString()); } return 0; } The code in Listing 25.5 executes as the code of Listing 25.4 did, but now it traps the exception in the catch clause to examine the failure. First it writes to the screen that an exception has been caught and then it prints the important information in the exception object using the ToString method that is a member function of the Exception class. In the example in Listing 25.5, the catch clause will catch any exception of the Exception object type. Normally, you construct a catch clause for a specific exception to handle the failure in our code and exit the error condition gracefully. For example, you passed a function a NULL parameter and the function did not support this then a System.ArgumentNullException would be generated. try { DoesNotAcceptNULL(NULL); } catch(ArgumentNullException* e) { Console::WriteLine(S"A ArgumentNullException exception has been caught: "); Console::WriteLine(S"You should not pass NULL to this function"); } The difference here is in the catch clause. This one catches only arguments of type ArgumentNullException[md]other exceptions will not be caught. You can catch several types of exceptions by coding several catch blocks, as in Listing 25.6. Listing 25.6 Multiple Catch Blocks try { DoesNotAcceptNULL(char* pChar); } catch(ArgumentNullException* e) { Console::WriteLine(S"A ArgumentNullException exception has been caught: "); Console::WriteLine(S"You should not pass NULL to this function"); } catch(Exception* e) { Console::WriteLine(S"An error has occurred, terminating application."); } You can write catch blocks for each exception type you expect. If you catch exceptions in this manner, you will be able to tailor the response to an exception on a case by case basis. You can also have a general exception handler to handle the error cases that you do not need to do any special processing before exiting your code. CAUTION The order of the catch blocks is important. Catch clauses are checked in the order they appear in your code and so it is important to put catch blocks for specific exceptions before those for general. Failing to do this can cause unexpected results. Using the __finally Clause When an exception occurs, the control of the application is passed to the first exception handler that is found when the stack is unwound as it is with traditional C++ exceptions. After the handler has been executed, the function where the exception occurred is exited. Often you may have housekeeping code that should be executed, but that won't be executed after the exception handler has been invoked. This can result in a duplication of code within the catch block and at the end of the try block. The __finally mechanism ensures that your cleanup code is executed after the exception handler is done with its work. The __finally block defines the code that we want to execute after the exception handler is finished. The code in the __finally block is always executed, whether an exception was thrown or not, making it a perfect place for housekeeping work to be done for the function. Listing 25.6 shows an example. Listing 25.6 Using the __finally Block #using<mscorlib.dll> using namespace System; int main() { int* buffer; try { int* buffer = new int[256]; } catch(OutOfMemoryException* e) { // Handle the Out of Memory error condition if allocation failed Console::WriteLine(S"Memory allocation failed!"); } __finally { // Do my normal housecleaning work here delete buffer; } } CAUTION Remember that any code that is placed into the __finally clause will be executed whether an exception was handled or not. Do not include error-handling code in the __finally block.
https://www.informit.com/articles/article.aspx?p=29060&seqNum=2
CC-MAIN-2020-24
refinedweb
1,617
53.92
Jul 15, 2011 06:05 AM|LINK Hi, I am currently learning MVC 3.0 and have performed basic tasks insert, update etc on on table. Now I was to display my data from multiple tables ( Order and OrderDetail) in one view and also want to insert data in two tables from one view. What should my controller should pass to the view? I am using Ado.net Entity Data Model. I have gone on internet but for my disappointment no solution could appear to be suggesting any way out for this :( Please guide me how can I do this? All-Star 20888 Points Jul 15, 2011 06:39 AM|LINK Simple You define a View Model and put the object containing each the data of a table in a different property of the ViewModel Jul 15, 2011 07:28 AM|LINK @francesco I am using this code in my controller public ActionResult Index() { OrderViewData orderView = new OrderViewData(); orderView.OrderData = from o in db.Orders select o; orderView.OrderDetailData = from or in db.OrderDetails select or; return View(orderView); } Now I am passing this in my View as @model IEnumerable<MvcApplication.Models.OrderViewData> Now in foreach I get two table which I had made properties of the class OrderViewData.. Now how i display the specific columns from both tables on the view? Jul 15, 2011 07:36 AM|LINK Here I am posting the script i am using on view and the exception it throws @model IEnumerable<MvcApplication.Models.OrderViewData> @{ ViewBag.Title = "Index"; } <h2>Index</h2> <p> @Html.ActionLink("Create New", "Create") </p> <table> <tr> <th> OrderDesc </th> <th> Amount </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.OrderData) </td> <td> @Html.DisplayFor(modelItem => item.OrderDetailData) </td> @* <td> @Html.ActionLink("Edit", "Edit", new { id=item.OrderId }) | @Html.ActionLink("Details", "Details", new { id=item.OrderId }) | @Html.ActionLink("Delete", "Delete", new { id=item.OrderId }) </td>*@ </tr> } </table> And it throws this exception Please guide me considering me basic learning student ! All-Star 20888 Points Jul 15, 2011 08:31 AM|LINK YOu strongly typed your view with a model of type list. However you pass a single class that contains two lists. Thus please correct the @model directive of your view. Moreover, once you get data with linq, before putting them in a VieModel transform them into lists: (....linq statemnent.....).ToList() otherwise they are IQueryables, and IQueryables may cause problems when put in a View. About the two data....simple put them into two different html tables :) if this make sense in your application. If you want to align them someway, displaying them on the same htmlTable you have two merge couples of objects in the two lists into single objects containing properties form both objects Jul 15, 2011 09:00 AM|LINK I have made changes as you said..But my view is giving the same exception. Please tell what is problem with my view regarding the " correct @model directive"?? //My ViewModel class public class OrderViewData { // public List<Order> OrderData { get; set; } public List<OrderDetail> OrderDetailData { get; set; } } //My Index() code public ActionResult Index() { OrderViewData orderView = new OrderViewData(); orderView.OrderData = (from o in db.Orders select o).ToList(); orderView.OrderDetailData = (from or in db.OrderDetails select or).ToList(); return View(orderView); } // here is my @model directive @model List<MvcApplication.Models.OrderViewData> :-( Sep 20, 2011 03:18 PM|LINK @Toussef I try all the time to display two columns from two tables but somehow I don't find the solution i found your thread and I think it will help me a bit so can you please post me your correct code? thank you Member 6 Points 11 replies Last post Nov 30, 2012 01:44 PM by Evil Tuinhekje
http://forums.asp.net/p/1700177/4842454.aspx/1?Re+How+to+Display+Data+in+a+single+view+from+Multiple+Tables+in+MVC+3+0+
CC-MAIN-2013-20
refinedweb
625
57.77
This is the mail archive of the libstdc++@gcc.gnu.org mailing list for the libstdc++ project. On Thu, Dec 26, 2002 at 07:02:56PM -0500, Phil Edwards wrote: > I will move this to the 3.3 branch tomorrow, after additional testing and > a waiting period for comments. Done. Also, some additional comment fixes (cleanup plus one annoying typo) on both branches, as below. 2002-12-29 Phil Edwards <pme@gcc.gnu.org> * include/std/std_bitset.h: Better comments. Index: include/std/std_bitset.h =================================================================== RCS file: /cvs/gcc/gcc/libstdc++-v3/include/std/std_bitset.h,v retrieving revision 1.10 diff -u -3 -p -r1.10 std_bitset.h --- include/std/std_bitset.h 27 Dec 2002 00:03:16 -0000 1.10 +++ include/std/std_bitset.h 30 Dec 2002 03:57:52 -0000 @@ -570,6 +570,7 @@ namespace std struct _Sanitize<0> { static void _S_do_sanitize(unsigned long) { } }; + /** * @brief The %bitset class represents a @e fixed-size sequence of bits. * @@ -578,19 +579,19 @@ namespace std * (Note that %bitset does @e not meet the formal requirements of a * <a href="tables.html#65">container</a>. Mainly, it lacks iterators.) * - * The template argument, @a _Nb, may be any non-negative number of type - * size_t. + * The template argument, @a Nb, may be any non-negative number, + * specifying the number of bits (e.g., "0", "12", "1024*1024"). * - * A %bitset of size N uses U bits, where - * U = (N % (sizeof(unsigned long) * CHAR_BIT)). - * Thus, N - U bits are unused. (They are the high-order bits in the - * highest word.) It is a class invariant that those unused bits are - * always zero. + * In the general unoptimized case, storage is allocated in word-sized + * blocks. Let B be the number of bits in a word, then (Nb+(B-1))/B + * words will be used for storage. B - Nb%B bits are unused. (They are + * the high-order bits in the highest word.) It is a class invariant + * that those unused bits are always zero. * * If you think of %bitset as "a simple array of bits," be aware that * your mental picture is reversed: a %bitset behaves the same way as * bits in integers do, with the bit at index 0 in the "least significant - * / right-hand" position, and the bit at index N-1 in the "most + * / right-hand" position, and the bit at index Nb-1 in the "most * significant / left-hand" position. Thus, unlike other containers, a * %bitset's index "counts from right to left," to put it very loosely. * @@ -621,6 +622,7 @@ namespace std * @endcode * * Also see + * for a description of extensions. * * @if maint * Most of the actual code isn't contained in %bitset<> itself, but in the
http://gcc.gnu.org/ml/libstdc++/2002-12/msg00340.html
crawl-001
refinedweb
446
67.35
I'm a new programmer, I just was curious and wanted to write some code that would compare two .txt files char by char and check if they are identicle. this is the code that I wrote, Can someone help me figure out why it doesn't work? The compiler i'm using is microsoft visual C++ ver.6.0 my compiler shows 0 errors 0 warnings, but the .exe crashes Code:// alfred J. Denigris // write a program that tests if two text files are identicle. // 1_27_2009 #include <iostream> #include <fstream> using namespace std; ifstream getA; ifstream getB; bool test(char a, char b); int main() { int num=0; char chA, chB; ifstream getA; ifstream getB; getA.open("fileA.txt"); getB.open("fileB.txt"); while (!getA.eof() || !getB.eof()) { getA.get(chA); getB.get(chB); if (test(chA, chB) == true) cout <<" char number "<<num<<" is "<< chA << "for file a and "<< chB << " For file b. TRUE" <<endl; else cout <<" char number "<<num<<" is "<< chA << "for file a and "<< chB << " For file b. FALSE" <<endl; num++; } getA.close(); getB.close(); cout << "end"; return 0; } bool test(char a, char b) { if(a==b) return true; else return false; }
http://cboard.cprogramming.com/cplusplus-programming/111577-can-you-help-me-figure-out.html
CC-MAIN-2016-30
refinedweb
196
82.34
Created on 2001-12-19 04:52 by mathematician, last changed 2001-12-19 16:58 by gvanrossum. This issue is now closed. when pickle retrieves the __reduce__ method of a new style class that has a metaclass, instead of returning the metaclass's __reduce__ method bound to the class, it returns an unbound __reduce__ method of that class. >>> class metaclass(type): ... def __reduce__(self): ... """This is metaclass.__reduce__ ... """ ... return type.__reduce__(self) ... >>> class newclass(object): ... __metaclass__ = metaclass ... def __reduce__(self): ... """This is newclass.__reduce__ ... """ ... return object.__reduce__(self) ... >>> print newclass.__reduce__.__doc__ This is newclass.__reduce__ when pickle calls object.__reduce__ on newclass, it returns an unbound newclass.__reduce__ and not a bound metaclass.__reduce__. This has the unfortunate side effect of not correctly 'reducing' the class. I'm trying to figure out a solution. Logged In: YES user_id=118203 it's a shame the tabs do not appear above... --- Solution class metaclass(type): def __getattribute__(self, name): if name in ["__reduce__", "__getstate__", "__setstate__"]: return lambda s=self, f=getattr(type(self), name): f(s) return type.__getattribute__(self, name) this fixed my bug, but it may not work for everybody. My suggestion is if you are to pickle a new style class, you should call type(new_style_class).__reduce__(new_style_class) instead of new_style_class.__reduce__() Logged In: YES user_id=31435 Assigned to Guido. Dan, leading tabs vanish from the web view, but are visible in auto-emailed versions (it's a display issue, it's not that the database lost them) -- so don't worry about that. Logged In: YES user_id=6380 Very interesting! Good analysis too (took me a while with pdb to come to verify it :-). But neither class needs to define __reduce__ -- the one they inherit from their bases, type and object, will do the trick just as well. The problem is that there are two things competing to be newclass.__reduce__: on the one hand, the unbound method __reduce__ of newclass instances; on the other hand, the bound method __reduce__ of newclass, seen as a metaclass instance. Unfortunately, the unbound method wins, but pickle is expecting the bound method. I've tried experimenting with a few ways of fixing this (e.g. forcing pickle to get the bound __reduce__ method) but there seem to be powerful forces preventing me from getting this to work (and I don't mean just a screaming baby :-). I think maybe the right solution is to make pickle realize that newclass is a class, and prevent it from pickling it at all -- it should just pickle a reference to it (i.e. the module and class name) rather than attempting to pickle its contents. Stay tuned. Logged In: YES user_id=6380 I've got a patch for pickle.py; a similar patch needs to be developed for cPickle.c. I can't find a way to fix this purely by fixing the type object implementation -- pickle.py and cPickle.py just don't recognize classes with a custom metaclass as classes, because of their roots in pre-2.2 patterns. :-( Should we risk fixing this before 2.2 goes out? Logged In: YES user_id=31435 Sounds like I'd risk it, Guido: it's not like you could break 2.1's pickle behavior for new-style classes with a custom metaclass <wink>. Logged In: YES user_id=6380 Thanks for reporting! Fixed in CVS, with a simpler version of the patch below; also for cPickle. Adding tests too...
http://bugs.python.org/issue494904
crawl-003
refinedweb
577
75.5
OOP and Tkinter Discussion in 'Python' started by Ronny Mandal, May 15, 2006. - Similar Threads Please help!!! OOP and ASP.Net Tutorial (desperate search)Big Dave, Sep 28, 2004, in forum: ASP .Net - Replies: - 4 - Views: - 1,323 - CJ Taylor - Sep 28, 2004 - Replies: - 48 - Views: - 1,329 - Xah Lee - Jun 7, 2005 - Replies: - 8 - Views: - 493 - Bob - Jun 6, 2005 OOP and inline asm in VC++ 6Nico Vrouwe, Jul 29, 2003, in forum: C++ - Replies: - 2 - Views: - 593 - Nico Vrouwe - Jul 29, 2003 Tkinter (OOP?) help3c273, Dec 30, 2004, in forum: Python - Replies: - 2 - Views: - 575 - 3c273 - Jan 3, 2005 from Tkinter import *,win = Tk() "from Tkinter import *"Pierre Dagenais, Aug 3, 2008, in forum: Python - Replies: - 0 - Views: - 496 - Pierre Dagenais - Aug 3, 2008 What is the differences between tkinter in windows and Tkinter in theother platform?Hidekazu IWAKI, Dec 14, 2009, in forum: Python - Replies: - 1 - Views: - 591 - Peter Otten - Dec 14, 2009 Re: Using property() to extend Tkinter classes but Tkinter classesare old-style classes?Terry Reedy, Nov 28, 2010, in forum: Python - Replies: - 5 - Views: - 775 - Robert Kern - Nov 30, 2010
http://www.thecodingforums.com/threads/oop-and-tkinter.357699/
CC-MAIN-2016-40
refinedweb
186
65.66
Hi all I am having some problems with compiling my c++ code. I have had lots of experience in Java but c++ is new. I am trying to read in a file that contains words, sort them, then print them out to a new file in my program but the error is saying there is error on line 22 involving iterating through the elements of a vector. I am confused and any help is greatly appreciated! Code:#include <iostream> #include <list> #include <fstream> #include <string> using namespace std; int main() { string x; list<string> myList; ifstream inFile; ofstream outFile; inFile.open("dictionary"); while (inFile >> x) { myList.push_back(x); } inFile.close(); myList.sort(); outFile.open("sortedDictionary"); for (int i = 0; i < myList.size(); i++) { outFile << myList[i] << endl; } outFile.close(); return 0; }
https://cboard.cprogramming.com/cplusplus-programming/133892-new-cplusplus.html
CC-MAIN-2017-43
refinedweb
131
66.64
To count set bits in an integer, the Java code is as follows − import java.io.*; public class Demo{ static int set_bits_count(int num){ int count = 0; while (num > 0){ num &= (num - 1); count++; } return count; } public static void main(String args[]){ int num =11; System.out.println("The number of set bits in 11 is "); System.out.println(set_bits_count(num)); } } The number of set bits in 11 is 3 The above is an implementation of the Brian Kernighan algorithm. A class named Demo contains a static function named ‘set_bits_count’. This function checks if the number is 0, and if not, assigns a variable named ‘count’ to 0. It performs the ‘and’ operation on the number and the number decremented by 1. Next, the ‘count’ value is decremented after this operation. In the end, the count value is returned. In the main function, the value whose set bits need to be found is defined. The function is called by passing the number as a parameter. Relevant messages are displayed on the console.
https://www.tutorialspoint.com/java-program-to-count-set-bits-in-an-integer
CC-MAIN-2021-31
refinedweb
172
66.23
Truncated html email Discussion in 'ASP General' Warning in Modelsim - vector truncated, Jul 25, 2005, in forum: VHDL - Replies: - 2 - Views: - 6,749 - Duane Clark - Jul 25, 2005 System.Web.Mail.MailMessage gets truncatedBertus Dam, Aug 27, 2003, in forum: ASP .Net - Replies: - 5 - Views: - 971 - Bertus Dam - Aug 29, 2003 Truncated namespace in a class libraryPaul, Nov 25, 2003, in forum: ASP .Net - Replies: - 1 - Views: - 466 - Paul - Nov 25, 2003 aspx/html file bigger than 170KB truncatedz. f., Jan 27, 2005, in forum: ASP .Net - Replies: - 5 - Views: - 670 - David Wang [Msft] - Jan 31, 2005 Missing or Truncated Email Body Text - 2 Strange Examples...RickVidallon, Apr 24, 2007, in forum: ASP General - Replies: - 0 - Views: - 353 - RickVidallon - Apr 24, 2007
http://www.thecodingforums.com/threads/truncated-html-email.799359/
CC-MAIN-2015-35
refinedweb
122
71.55
Even Easier Machine Learning for Every Day Tasks Recently, the “Machine Learning for Everyday Tasks” post suddenly rising to the top of Hacker News drew our attention. In that post, Sergey Obukhov, software developer at San Francisco-based startup Mailgun, tries to debunk the myth that Machine Learning is a hard task: I have always felt like we can benefit from using machine learning for simple tasks that we do regularly. This certainly rings true to our ears at BigML, since we aim to democratize Machine Learning by providing developers, scientists, and business users powerful higher-level tools that package the most effective algorithms that Machine Learning has produced in the last two decades. In this post, we are going to show how much easier it is to solve the same problem tackled in the Hacker News post by using BigML. To this end, we have created a test dataset with similar properties to the one used in the original post so that we can replicate the same steps with analogous results. Predicting processing time The objective of this analysis is predicting how long it will take to parse HTML quotations embedded within e-mail conversations. Most messages are processed in a very short time, while some of them take much longer. Identifying those lengthier messages in advance is useful for several purposes, including load-balancing and giving more precise feedback to users. Our analysis is based on a CSV file containing a number of fictitious track records of our system performance when handling email messages: HTML length, Tag count, Processing Time We would like to classify a given incoming message as either slow or fast given its length and tag count based on previously collected data. Finding a definition for slow and fast through clustering The first step in our analysis is defining what slow and fast actually mean. The approach in the original post is clustering, which identifies groups of relatively homogeneous data points. Ideally, we would hope that this algorithm is able to collect all slow executions in one cluster and all fast executions in another. In the original post, the author has written a small program to calculate the optimal number of clusters. Then he uses that number as a parameter to actually build the clusters. The task of estimating the number of clusters to look for is so common that BigML provides a ready-made WhizzML script that does exactly that: Compute best K-means Clustering. Alternatively, BigML also provides the G-means algorithm for clustering, which is able to automatically identify the optimal number of clusters. For our analysis, we will use the Compute best K-means Clustering script, following these steps: - Create a dataset in BigML from your CSV file - Execute the Compute best K-means clustering script using that dataset. We can carry out those steps in a variety of ways, including: - Using BigML Dashboard, which makes it really easy to investigate a problem and build a machine learning solution for it in a pointing and click manner. - Writing a program that uses BigML REST API and the proper bindings that BigML provides for a number of popular languages, such as Python, Node.js, C#, Java, etc. - Using bigmler, a command-line tool, which makes it easier to automate ML tasks. - Using WhizzML, a server-side DSL (Domain Specific Language) that makes it possible to extend the BigML platform with your custom ML workflows. We are going to use the BigML bindings for Python as follows: import webbrowser from bigml.api import BigML api = BigML() source = api.create_source('./post-data.csv') dataset = api.create_dataset(source) api.ok(dataset) print "dataset" + dataset['resource'] execution = api.create_execution('script/57f50fb57e0a8d5dd200729f', {"inputs": [ ["dataset", dataset['resource']], ["k-min", 2], ["k-max", 10], ["logf", True], ["clean", True] ]}) api.ok(execution) best_cluster = execution['object']['execution']['result'] webbrowser.open("" + best_cluster) The result tells us that we have: - Two clusters (green and orange) that contain definitely slow instances. - The blue cluster includes the majority of instances, both fast and not-so-fast, as its statistical distribution in the cluster detail panel indicates: Seemingly, our threshold to distinguish fast tasks from slow tasks points to the green cluster. At this point, the original post gives up on using clustering as a means to determine a sensible threshold, and reverts to plotting time percentiles against tag count. Luckily for them, the percentile distribution shows a nice bubbling up at the 78th percentile, but in general this kind of analysis may not always yield such obvious distributions. As a matter of fact, detecting such an abnormalities can be even harder with multidimensional data. BigML makes it very simple to further investigate the properties of the above green cluster. We can simply create a dataset including only the data instances belonging to that cluster and then build a simple model to better understand its characteristics: centroid_dataset = api.create_dataset(best_cluster, { 'centroid' : '000000' }) api.ok(centroid_dataset) centroid_model = api.create_model(centroid_dataset) api.ok(centroid_model) webbrowser.open("" + centroid_model['resource']) This, in turn, produces the following model: If you inspect the properties of the tree nodes, you can see that the tree is clearly quickly split into two subtrees with all nodes on the left-hand subtree having processing times lower than 14.88 sec, and all nodes belonging to the subtree on the right with processing times greater than 16.13. This suggests that a good choice for the threshold between fast and slow can be approximately 15.5 sec. If we follow along the same steps as in the original post and apply the percentile analysis to our data instances here, we arrive at the following distribution: This distribution clearly starts growing faster between the 88th to the 89th percentile, confirming our choice of threshold: To summarize, we have found a comparable result by applying a much more generalizable analysis approach. Feature engineering With the proper threshold identified, we can mark all data instances with running times lower than 15.5 as fast and the rest as slow. This is another task that BigML can tackle easily via its built-in feature engineering capabilities on BigML Dashboard: Alternatively, we do the same in Python: extended_dataset = api.create_dataset(dataset, { "new_fields" : [ { "field" : '(if (< (f "time") 15.5) "fast" "slow")', "name" : "processing_speed" }]}) webbrowser.open("" + extended_dataset['resource']) Which produces the following dataset: Predicting slow and fast instances Once we have all our instances labeled a fast and slow, we can finally build a model to predict whether an unseen instance will be fast and slow to process. The following code creates the model from our extended_dataset: extended_dataset = api.create_dataset(dataset, { "excluded_fields" : ["000002"], "new_fields" : [ { "field" : '(if (< (f "time") 15.5) "fast" "slow")', "name" : "processing_speed" }]}) api.ok(extended_dataset) webbrowser.open("" + extended_dataset['resource']) Notice that we excluded the original time field from our model, since we are now relying on our new feature that tells apart the fast instances from slow ones. This step yields the following result that shows a nice split between fast and slow instances at around 9,589 tags (let’s call this _MAX_TAGS_COUNT): Admittedly, our example here is pretty trivial. As was the case in the original post, our prediction boils down to this conditional: def html_too_big(s): return s.count(' _MAX_TAGS_COUNT But, what if our dataset were more complex and/or the prediction involved more intricate calculations? This is another situation, where using a Machine Learning platform such as BigML provides an advantage over an ad-hoc solution. With BigML, predicting is just a matter of calling another function provided by our bindings: from bigml.model import Model final_model = "model/583dd8897fa04223dc000a0c" prediction_model = Model(final_model) prediction1 = prediction_model.predict({ "html length": 3000, "tag count": 1000 }) prediction2 = prediction_model.predict({ "html length": 30000, "tag count": 500 }) What’s more, predictions are fully local, which means no access to BigML servers is required! Conclusion Machine Learning can be used to solve everyday programming tasks. There are certainly different ways to do that, including tools like R and various Python libraries. However, those options have a steeper learning curve to master the details of the algorithms inside as well as the glue code to make them work together. One must also take into account the need to maintain and keep alive such glue code that can result in considerable technical debt. BigML, on the other hand, provides practitioners all the tools of the trade in one place in a tightly integrated fashion. BigML covers a wide range of analytics scenarios including initial data exploration, fully automated custom Machine Learning workflows, and production deployment of those solutions on large-scale datasets. A BigML workflow that solves a predictive problem can be easily embedded into a data pipeline, which unlike R or Python libraries does not require any desktop computational resources and can be reproduced on demand.
https://blog.bigml.com/2016/12/20/even-easier-machine-learning-for-every-day-tasks/
CC-MAIN-2019-35
refinedweb
1,460
50.16
Array is a container which can hold a fix number of items and these items should be of the same type. Most of the data structures make use of arrays to implement their algorithms. Following are the important terms to understand the concept of Array. Yes, since objects are also considered as datatypes (reference) in Java, you can create an array of the type of a particular class and, populate it with instances of that class. Following Java example have a class named Std and later in the program we are creating an array of type Std, populating it, and invoking a method on all the elements of the array. class Std { private static int year = 2018; private String name; private int age; public Std(String name, int age){ this.name = name; this.age = age; } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public void display(){ System.out.println("Name: "+this.name); System.out.println("Age: "+this.age); System.out.println("Year: "+Std.year); } } public class Sample { public static void main(String args[]) throws Exception { //Creating an array to store objects of type Std Std st[] = new Std[4]; //Populating the array st[0] = new Std("Bala", 18); st[1] = new Std("Rama", 17); st[2] = new Std("Raju", 15); st[3] = new Std("Raghav", 20); //Invoking display method on each object in the array for(int i = 0; i<st.length; i++) { st[i].display(); System.out.println(" "); } } } Name: Bala Age: 18 Year: 2018 Name: Rama Age: 17 Year: 2018 Name: Raju Age: 15 Year: 2018 Name: Raghav Age: 20 Year: 2018
https://www.tutorialspoint.com/can-we-store-objects-in-an-array-in-java
CC-MAIN-2022-05
refinedweb
271
61.56
Library for read/write access of binary data via structures The binstruct library allows you to access binary data using a predefined structure. The binary data can be provided in any form that allows an indexed access to single bytes. This could for example be an mmaped file. The data structure itself is defined in way similar to Django database table definitions by declaring a new class with its fields. Simple Example First you have to define the structure which you want to use to access your binary data. This is done by specifying all desired fields with their types and their position inside a new class. As an example let’s take the first of the ELF header which in C would look like this #define EI_NIDENT 16 typedef struct { unsigned char e_ident[EI_NIDENT]; uint16_t e_type; uint16_t e_machine; uint32_t e_version; // rest of the fields omitted for simplicity } ElfN_Ehdr; Using binstruct you now declare the following Python class from binstruct import * class ElfN_Ehdr(StructTemplate): e_ident = RawField(0, 16) e_type = UInt16Field(16) e_machine = UInt16Field(18) e_version = UInt32Field(20) Note that you have to specify the offset of the fields even though it would be possible to derive that from the size of the previous fields. I opted for this solution because it makes the implementation easier and because it allows for easier skipping of irrelevant or reserved fields. Now we can create an instance of this class by providing the constructor an indexable data structure and an offset. The indexable data structure is any Python object representing binary data to which you want to have “structured access”. The offset allows you to place the structure at any place inside the indexable data structure. For this example lets just use a simple list for the binary data binary_data = 24 * [0] header = ElfN_Ehdr(binary_data, 0) Now you can simply read and write any of the fields header.e_type = 0x0 header.e_ident[0] = 0x7f header.e_ident[1] = ord('E') header.e_ident[2] = ord('L') header.e_ident[3] = ord('F') print(header.e_type) print(header.e_ident[1]) The current implementation provides signed and unsigned fields for 8-bit, 16-bit and 32-bit integers, strings, raw data fields and even nested structures. For some ideas of how to use them, also checkout the unit tests. Contributing The library is fully standalone and only requires py.test to run the unit tests. To contribute any changes simply clone the project on GitHub:, push your changes to your own GitHub project and send a pull request. For any changes please make sure you have good unit tests. Download Files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/binstruct/
CC-MAIN-2017-39
refinedweb
451
62.88
. - Open Qt Creator 2.8.0 - Go to File>New File Or Project - Choose Projects>Applications>Qt Gui Application - For “Introduction and Project Location”, name your project “Hello World”, and browse to a memorable location where to create it in. - For “Kit Selection”, check “Qt 4.8.5 (minGW)” Note: there may be other kits available to you depending on if you have those installed - For “Class Information”, keep defaults. - For “Project Management”, keep defaults. Click Finish. - Qt Creator automatically loads newly generated “mainwindow.cpp” by default, ready to be edited. - Note: If you don’t have a debugger, then you won’t be able to debug. So when you run it, set it to Release mode. If there are any serious bugs, the compiler will still throw an error. - Hit Run. - At the very minimum, you will have a window that can run. But it doesn’t really do anything useful. - Close the window or Stop (the red square in the debugger tool strip). - Now, let’s actually do some real coding. Click on mainWindow.h to open it in the editor. - Make the following changes to mainWindow.h: Add protected: void paintEvent(QPaintEvent *); - Now that you have overriden the mainWindow widget’s default paintEvent, you must provide your own method for painting. Open mainWindow.cpp in the editor. Add #include "QPainter" and void MainWindow::paintEvent(QPaintEvent *) { QPainter painter(this); painter.drawText(QRect(20,20,200,200),"Hello World"); painter.end(); } - Save and run. - If everything is set properly, what you get is the same basic mainWindow plus your newfound ability to paint on the widget. I hope you found that helpful. This is your quickstart intro to QPainter, which is quite robust. You can now experiment with background colors, fonts, placement, and other drawing features. Happy coding!
https://www.eastfist.com/qt_tutorials/index.php/2013/08/27/hello-world-with-qpainter/
CC-MAIN-2019-09
refinedweb
299
69.38