|
JavaTM 2 Platform Standard Ed. 5.0 |
|||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Object java.net.Socket
public class Socket
This class implements client sockets (also called just "sockets"). A socket is an endpoint for communication between two machines.
The actual work of the socket is performed by an instance of the
SocketImpl
class. An application, by changing
the socket factory that creates the socket implementation,
can configure itself to create sockets appropriate to the local
firewall.
setSocketImplFactory(java.net.SocketImplFactory)
,
SocketImpl
,
SocketChannel
| Constructor Summary | |
|---|---|
|
Socket()
Creates an unconnected socket, with the system-default type of SocketImpl. |
|
Socket(InetAddress address,
int port)
Creates a stream socket and connects it to the specified port number at the specified IP address. |
|
Socket(InetAddress host,
int port,
boolean stream)
Deprecated. Use DatagramSocket instead for UDP transport. |
|
Socket(InetAddress address,
int port,
InetAddress localAddr,
int localPort)
Creates a socket and connects it to the specified remote address on the specified remote port. |
|
Socket(Proxy proxy)
Creates an unconnected socket, specifying the type of proxy, if any, that should be used regardless of any other settings. |
protected |
Socket(SocketImpl impl)
Creates an unconnected Socket with a user-specified SocketImpl. |
|
Socket(String host,
int port)
Creates a stream socket and connects it to the specified port number on the named host. |
|
Socket(String host,
int port,
boolean stream)
Deprecated. Use DatagramSocket instead for UDP transport. |
|
Socket(String host,
int port,
InetAddress localAddr,
int localPort)
Creates a socket and connects it to the specified remote host on the specified remote port. |
| Method Summary | |
|---|---|
void |
bind(SocketAddress bindpoint)
Binds the socket to a local address. |
void |
close()
Closes this socket. |
void |
connect(SocketAddress endpoint)
Connects this socket to the server. |
void |
connect(SocketAddress endpoint,
int timeout)
Connects this socket to the server with a specified timeout value. |
SocketChannel |
getChannel()
Returns the unique SocketChannel
object associated with this socket, if any. |
InetAddress |
getInetAddress()
Returns the address to which the socket is connected. |
InputStream |
getInputStream()
Returns an input stream for this socket. |
boolean |
getKeepAlive()
Tests if SO_KEEPALIVE is enabled. |
InetAddress |
getLocalAddress()
Gets the local address to which the socket is bound. |
int |
getLocalPort()
Returns the local port to which this socket is bound. |
SocketAddress |
getLocalSocketAddress()
Returns the address of the endpoint this socket is bound to, or null if it is not bound yet. |
boolean |
getOOBInline()
Tests if OOBINLINE is enabled. |
OutputStream |
getOutputStream()
Returns an output stream for this socket. |
int |
getPort()
Returns the remote port to which this socket is connected. |
int |
getReceiveBufferSize()
Gets the value of the SO_RCVBUF option for this Socket, that is the buffer size used by the platform for input on this Socket. |
SocketAddress |
getRemoteSocketAddress()
Returns the address of the endpoint this socket is connected to, or null if it is unconnected. |
boolean |
getReuseAddress()
Tests if SO_REUSEADDR is enabled. |
int |
getSendBufferSize()
Get value of the SO_SNDBUF option for this Socket, that is the buffer size used by the platform for output on this Socket. |
int |
getSoLinger()
Returns setting for SO_LINGER. |
int |
getSoTimeout()
Returns setting for SO_TIMEOUT. |
boolean |
getTcpNoDelay()
Tests if TCP_NODELAY is enabled. |
int |
getTrafficClass()
Gets traffic class or type-of-service in the IP header for packets sent from this Socket |
boolean |
isBound()
Returns the binding state of the socket. |
boolean |
isClosed()
Returns the closed state of the socket. |
boolean |
isConnected()
Returns the connection state of the socket. |
boolean |
isInputShutdown()
Returns whether the read-half of the socket connection is closed. |
boolean |
isOutputShutdown()
Returns whether the write-half of the socket connection is closed. |
void |
sendUrgentData(int data)
Send one byte of urgent data on the socket. |
void |
setKeepAlive(boolean on)
Enable/disable SO_KEEPALIVE. |
void |
setOOBInline(boolean on)
Enable/disable OOBINLINE (receipt of TCP urgent data) By default, this option is disabled and TCP urgent data received on a socket is silently discarded. |
void |
setPerformancePreferences(int connectionTime,
int latency,
int bandwidth)
Sets performance preferences for this socket. |
void |
setReceiveBufferSize(int size)
Sets the SO_RCVBUF option to the specified value for this Socket. |
void |
setReuseAddress(boolean on)
Enable/disable the SO_REUSEADDR socket option. |
void |
setSendBufferSize(int size)
Sets the SO_SNDBUF option to the specified value for this Socket. |
static void |
setSocketImplFactory(SocketImplFactory fac)
Sets the client socket implementation factory for the application. |
void |
setSoLinger(boolean on,
int linger)
Enable/disable SO_LINGER with the specified linger time in seconds. |
void |
setSoTimeout(int timeout)
Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. |
void |
setTcpNoDelay(boolean on)
Enable/disable TCP_NODELAY (disable/enable Nagle's algorithm). |
void |
setTrafficClass(int tc)
Sets traffic class or type-of-service octet in the IP header for packets sent from this Socket. |
void |
shutdownInput()
Places the input stream for this socket at "end of stream". |
void |
shutdownOutput()
Disables the output stream for this socket. |
String |
toString()
Converts this socket to a String . |
| Methods inherited from class java.lang.Object |
|---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
|---|
public Socket()
public Socket(Proxy proxy)
If there is a security manager, its checkConnect
method
is called with the proxy host address and port number
as its arguments. This could result in a SecurityException.
Examples:
Socket s = new Socket(Proxy.NO_PROXY);
will create
a plain socket ignoring any other proxy configuration.Socket s = new Socket(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("socks.mydom.com", 1080)));
will create a socket connecting through the specified SOCKS proxy
server.
proxy
- a Proxy
object specifying what kind
of proxying should be used.
IllegalArgumentException
- if the proxy is of an invalid type
or null
.
SecurityException
- if a security manager is present and
permission to connect to the proxy is
denied.ProxySelector
,
Proxy
protected Socket(SocketImpl impl) throws SocketException
impl
- an instance of a SocketImpl
the subclass wishes to use on the Socket.
SocketException
- if there is an error in the underlying protocol,
such as a TCP error.public Socket(String host, int port) throws UnknownHostException, IOException
If the specified host is null it is the equivalent of
specifying the address as InetAddress.getByName
(null).
In other words, it is equivalent to specifying an address of the
loopback interface.
If the application has specified a server socket factory, that
factory's createSocketImpl
method is called to create
the actual socket implementation. Otherwise a "plain" socket is created.
If there is a security manager, its
checkConnect
method is called
with the host address and port
as its arguments. This could result in a SecurityException.
host
- the host name, or null
for the loopback address.port
- the port number.
UnknownHostException
- if the IP address of
the host could not be determined.
IOException
- if an I/O error occurs when creating the socket.
SecurityException
- if a security manager exists and its
checkConnect
method doesn't allow the operation.setSocketImplFactory(java.net.SocketImplFactory)
,
SocketImpl
,
SocketImplFactory.createSocketImpl()
,
SecurityManager.checkConnect(java.lang.String, int)
public Socket(InetAddress address, int port) throws IOException
If the application has specified a socket factory, that factory's
createSocketImpl
method is called to create the
actual socket implementation. Otherwise a "plain" socket is created.
If there is a security manager, its
checkConnect
method is called
with the host address and port
as its arguments. This could result in a SecurityException.
address
- the IP address.port
- the port number.
IOException
- if an I/O error occurs when creating the socket.
SecurityException
- if a security manager exists and its
checkConnect
method doesn't allow the operation.setSocketImplFactory(java.net.SocketImplFactory)
,
SocketImpl
,
SocketImplFactory.createSocketImpl()
,
SecurityManager.checkConnect(java.lang.String, int)
public Socket(String host, int port, InetAddress localAddr, int localPort) throws IOException
If the specified host is null it is the equivalent of
specifying the address as InetAddress.getByName
(null).
In other words, it is equivalent to specifying an address of the
loopback interface.
If there is a security manager, its
checkConnect
method is called
with the host address and port
as its arguments. This could result in a SecurityException.
host
- the name of the remote host, or null
for the loopback address.port
- the remote portlocalAddr
- the local address the socket is bound tolocalPort
- the local port the socket is bound to
IOException
- if an I/O error occurs when creating the socket.
SecurityException
- if a security manager exists and its
checkConnect
method doesn't allow the operation.SecurityManager.checkConnect(java.lang.String, int)
public Socket(InetAddress address, int port, InetAddress localAddr, int localPort) throws IOException
If there is a security manager, its
checkConnect
method is called
with the host address and port
as its arguments. This could result in a SecurityException.
address
- the remote addressport
- the remote portlocalAddr
- the local address the socket is bound tolocalPort
- the local port the socket is bound to
IOException
- if an I/O error occurs when creating the socket.
SecurityException
- if a security manager exists and its
checkConnect
method doesn't allow the operation.SecurityManager.checkConnect(java.lang.String, int)
@Deprecated public Socket(String host, int port, boolean stream) throws IOException
If the specified host is null it is the equivalent of
specifying the address as InetAddress.getByName
(null).
In other words, it is equivalent to specifying an address of the
loopback interface.
If the stream argument is true
, this creates a
stream socket. If the stream argument is false
, it
creates a datagram socket.
If the application has specified a server socket factory, that
factory's createSocketImpl
method is called to create
the actual socket implementation. Otherwise a "plain" socket is created.
If there is a security manager, its
checkConnect
method is called
with the host address and port
as its arguments. This could result in a SecurityException.
If a UDP socket is used, TCP/IP related socket options will not apply.
host
- the host name, or null
for the loopback address.port
- the port number.stream
- a boolean
indicating whether this is
a stream socket or a datagram socket.
IOException
- if an I/O error occurs when creating the socket.
SecurityException
- if a security manager exists and its
checkConnect
method doesn't allow the operation.setSocketImplFactory(java.net.SocketImplFactory)
,
SocketImpl
,
SocketImplFactory.createSocketImpl()
,
SecurityManager.checkConnect(java.lang.String, int)
@Deprecated public Socket(InetAddress host, int port, boolean stream) throws IOException
If the stream argument is true
, this creates a
stream socket. If the stream argument is false
, it
creates a datagram socket.
If the application has specified a server socket factory, that
factory's createSocketImpl
method is called to create
the actual socket implementation. Otherwise a "plain" socket is created.
If there is a security manager, its
checkConnect
method is called
with host.getHostAddress()
and port
as its arguments. This could result in a SecurityException.
If UDP socket is used, TCP/IP related socket options will not apply.
host
- the IP address.port
- the port number.stream
- if true
, create a stream socket;
otherwise, create a datagram socket.
IOException
- if an I/O error occurs when creating the socket.
SecurityException
- if a security manager exists and its
checkConnect
method doesn't allow the operation.setSocketImplFactory(java.net.SocketImplFactory)
,
SocketImpl
,
SocketImplFactory.createSocketImpl()
,
SecurityManager.checkConnect(java.lang.String, int)
| Method Detail |
|---|
public void connect(SocketAddress endpoint) throws IOException
endpoint
- the SocketAddress
IOException
- if an error occurs during the connection
IllegalBlockingModeException
- if this socket has an associated channel,
and the channel is in non-blocking mode
IllegalArgumentException
- if endpoint is null or is a
SocketAddress subclass not supported by this socketpublic void connect(SocketAddress endpoint, int timeout) throws IOException
endpoint
- the SocketAddress
timeout
- the timeout value to be used in milliseconds.
IOException
- if an error occurs during the connection
SocketTimeoutException
- if timeout expires before connecting
IllegalBlockingModeException
- if this socket has an associated channel,
and the channel is in non-blocking mode
IllegalArgumentException
- if endpoint is null or is a
SocketAddress subclass not supported by this socketpublic void bind(SocketAddress bindpoint) throws IOException
If the address is null
, then the system will pick up
an ephemeral port and a valid local address to bind the socket.
bindpoint
- the SocketAddress
to bind to
IOException
- if the bind operation fails, or if the socket
is already bound.
IllegalArgumentException
- if bindpoint is a
SocketAddress subclass not supported by this socketisBound()
public InetAddress getInetAddress()
null
if the socket is not connected.public InetAddress getLocalAddress()
InetAddress.anyLocalAddress()
if the socket is not bound yet.public int getPort()
public int getLocalPort()
public SocketAddress getRemoteSocketAddress()
null
if it is unconnected.
SocketAddress
reprensenting the remote endpoint of this
socket, or null
if it is not connected yet.getInetAddress()
,
getPort()
,
connect(SocketAddress, int)
,
connect(SocketAddress)
public SocketAddress getLocalSocketAddress()
null
if it is not bound yet.
SocketAddress
representing the local endpoint of this
socket, or null
if it is not bound yet.getLocalAddress()
,
getLocalPort()
,
bind(SocketAddress)
public SocketChannel getChannel()
SocketChannel
object associated with this socket, if any.
A socket will have a channel if, and only if, the channel itself was
created via the SocketChannel.open
or ServerSocketChannel.accept
methods.
public InputStream getInputStream() throws IOException
If this socket has an associated channel then the resulting input
stream delegates all of its operations to the channel. If the channel
is in non-blocking mode then the input stream's read operations
will throw an IllegalBlockingModeException
.
Under abnormal conditions the underlying connection may be broken by the remote host or the network software (for example a connection reset in the case of TCP connections). When a broken connection is detected by the network software the following applies to the returned input stream :-
The network software may discard bytes that are buffered
by the socket. Bytes that aren't discarded by the network
software can be read using read
.
If there are no bytes buffered on the socket, or all
buffered bytes have been consumed by
read
, then all subsequent
calls to read
will throw an
IOException
.
If there are no bytes buffered on the socket, and the
socket has not been closed using close
, then
available
will
return 0
.
IOException
- if an I/O error occurs when creating the
input stream, the socket is closed, the socket is
not connected, or the socket input has been shutdown
using shutdownInput()
public OutputStream getOutputStream() throws IOException
If this socket has an associated channel then the resulting output
stream delegates all of its operations to the channel. If the channel
is in non-blocking mode then the output stream's write
operations will throw an IllegalBlockingModeException
.
IOException
- if an I/O error occurs when creating the
output stream or if the socket is not connected.public void setTcpNoDelay(boolean on) throws SocketException
on
- true
to enable TCP_NODELAY,
false
to disable.
SocketException
- if there is an error
in the underlying protocol, such as a TCP error.getTcpNoDelay()
public boolean getTcpNoDelay() throws SocketException
boolean
indicating whether or not TCP_NODELAY is enabled.
SocketException
- if there is an error
in the underlying protocol, such as a TCP error.setTcpNoDelay(boolean)
public void setSoLinger(boolean on, int linger) throws SocketException
on
- whether or not to linger on.linger
- how long to linger for, if on is true.
SocketException
- if there is an error
in the underlying protocol, such as a TCP error.
IllegalArgumentException
- if the linger value is negative.getSoLinger()
public int getSoLinger() throws SocketException
SocketException
- if there is an error
in the underlying protocol, such as a TCP error.setSoLinger(boolean, int)
public void sendUrgentData(int data) throws IOException
data
- The byte of data to send
IOException
- if there is an error
sending the data.public void setOOBInline(boolean on) throws SocketException
Note, only limited support is provided for handling incoming urgent data. In particular, no notification of incoming urgent data is provided and there is no capability to distinguish between normal data and urgent data unless provided by a higher level protocol.
on
- true
to enable OOBINLINE,
false
to disable.
SocketException
- if there is an error
in the underlying protocol, such as a TCP error.getOOBInline()
public boolean getOOBInline() throws SocketException
boolean
indicating whether or not OOBINLINE is enabled.
SocketException
- if there is an error
in the underlying protocol, such as a TCP error.setOOBInline(boolean)
public void setSoTimeout(int timeout) throws SocketException
timeout
- the specified timeout, in milliseconds.
SocketException
- if there is an error
in the underlying protocol, such as a TCP error.getSoTimeout()
public int getSoTimeout() throws SocketException
SocketException
- if there is an error
in the underlying protocol, such as a TCP error.setSoTimeout(int)
public void setSendBufferSize(int size) throws SocketException
Because SO_SNDBUF is a hint, applications that want to
verify what size the buffers were set to should call
getSendBufferSize()
.
size
- the size to which to set the send buffer
size. This value must be greater than 0.
SocketException
- if there is an error
in the underlying protocol, such as a TCP error.
IllegalArgumentException
- if the
value is 0 or is negative.getSendBufferSize()
public int getSendBufferSize() throws SocketException
SocketException
- if there is an error
in the underlying protocol, such as a TCP error.setSendBufferSize(int)
public void setReceiveBufferSize(int size) throws SocketException
Increasing the receive buffer size can increase the performance of network I/O for high-volume connection, while decreasing it can help reduce the backlog of incoming data.
Because SO_RCVBUF is a hint, applications that want to
verify what size the buffers were set to should call
getReceiveBufferSize()
.
The value of SO_RCVBUF is also used to set the TCP receive window that is advertized to the remote peer. Generally, the window size can be modified at any time when a socket is connected. However, if a receive window larger than 64K is required then this must be requested before the socket is connected to the remote peer. There are two cases to be aware of:
ServerSocket.setReceiveBufferSize(int)
before the ServerSocket
is bound to a local address.
size
- the size to which to set the receive buffer
size. This value must be greater than 0.
IllegalArgumentException
- if the value is 0 or is
negative.
SocketException
- if there is an error
in the underlying protocol, such as a TCP error.getReceiveBufferSize()
,
ServerSocket.setReceiveBufferSize(int)
public int getReceiveBufferSize() throws SocketException
SocketException
- if there is an error
in the underlying protocol, such as a TCP error.setReceiveBufferSize(int)
public void setKeepAlive(boolean on) throws SocketException
on
- whether or not to have socket keep alive turned on.
SocketException
- if there is an error
in the underlying protocol, such as a TCP error.getKeepAlive()
public boolean getKeepAlive() throws SocketException
boolean
indicating whether or not SO_KEEPALIVE is enabled.
SocketException
- if there is an error
in the underlying protocol, such as a TCP error.setKeepAlive(boolean)
public void setTrafficClass(int tc) throws SocketException
The tc must be in the range 0 <= tc <=
255
or an IllegalArgumentException will be thrown.
Notes:
for Internet Protocol v4 the value consists of an octet with precedence and TOS fields as detailed in RFC 1349. The TOS field is bitset created by bitwise-or'ing values such the following :-
IPTOS_LOWCOST (0x02)
IPTOS_RELIABILITY (0x04)
IPTOS_THROUGHPUT (0x08)
IPTOS_LOWDELAY (0x10)
Setting bits in the precedence field may result in a SocketException indicating that the operation is not permitted.
for Internet Protocol v6 tc
is the value that
would be placed into the sin6_flowinfo field of the IP header.
tc
- an int
value for the bitset.
SocketException
- if there is an error setting the
traffic class or type-of-servicegetTrafficClass()
public int getTrafficClass() throws SocketException
As the underlying network implementation may ignore the
traffic class or type-of-service set using setTrafficClass(int)
this method may return a different value than was previously
set using the setTrafficClass(int)
method on this Socket.
SocketException
- if there is an error obtaining the
traffic class or type-of-service value.setTrafficClass(int)
public void setReuseAddress(boolean on) throws SocketException
When a TCP connection is closed the connection may remain in a timeout state for a period of time after the connection is closed (typically known as the TIME_WAIT state or 2MSL wait state). For applications using a well known socket address or port it may not be possible to bind a socket to the required SocketAddress if there is a connection in the timeout state involving the socket address or port.
Enabling SO_REUSEADDR prior to binding the socket
using bind(SocketAddress)
allows the socket to be
bound even though a previous connection is in a timeout
state.
When a Socket is created the initial setting of SO_REUSEADDR is disabled.
The behaviour when SO_REUSEADDR is enabled or
disabled after a socket is bound (See isBound()
)
is not defined.
on
- whether to enable or disable the socket option
SocketException
- if an error occurs enabling or
disabling the SO_RESUEADDR socket option,
or the socket is closed.getReuseAddress()
,
bind(SocketAddress)
,
isClosed()
,
isBound()
public boolean getReuseAddress() throws SocketException
boolean
indicating whether or not SO_REUSEADDR is enabled.
SocketException
- if there is an error
in the underlying protocol, such as a TCP error.setReuseAddress(boolean)
public void close() throws IOException
Any thread currently blocked in an I/O operation upon this socket
will throw a SocketException
.
Once a socket has been closed, it is not available for further networking use (i.e. can't be reconnected or rebound). A new socket needs to be created.
If this socket has an associated channel then the channel is closed as well.
IOException
- if an I/O error occurs when closing this socket.isClosed()
public void shutdownInput() throws IOException
If you read from a socket input stream after invoking shutdownInput() on the socket, the stream will return EOF.
IOException
- if an I/O error occurs when shutting down this
socket.shutdownOutput()
,
close()
,
setSoLinger(boolean, int)
,
isInputShutdown()
public void shutdownOutput() throws IOException
IOException
- if an I/O error occurs when shutting down this
socket.shutdownInput()
,
close()
,
setSoLinger(boolean, int)
,
isOutputShutdown()
public String toString()
String
.
toString
in class Object
public boolean isConnected()
public boolean isBound()
bind(java.net.SocketAddress)
public boolean isClosed()
close()
public boolean isInputShutdown()
shutdownInput()
public boolean isOutputShutdown()
shutdownOutput()
public static void setSocketImplFactory(SocketImplFactory fac) throws IOException
When an application creates a new client socket, the socket
implementation factory's createSocketImpl
method is
called to create the actual socket implementation.
Passing null
to the method is a no-op unless the factory
was already set.
If there is a security manager, this method first calls
the security manager's checkSetFactory
method
to ensure the operation is allowed.
This could result in a SecurityException.
fac
- the desired factory.
IOException
- if an I/O error occurs when setting the
socket factory.
SocketException
- if the factory is already defined.
SecurityException
- if a security manager exists and its
checkSetFactory
method doesn't allow the operation.SocketImplFactory.createSocketImpl()
,
SecurityManager.checkSetFactory()
public void setPerformancePreferences(int connectionTime, int latency, int bandwidth)
Sockets use the TCP/IP protocol by default. Some implementations may offer alternative protocols which have different performance characteristics than TCP/IP. This method allows the application to express its own preferences as to how these tradeoffs should be made when the implementation chooses from the available protocols.
Performance preferences are described by three integers whose values indicate the relative importance of short connection time, low latency, and high bandwidth. The absolute values of the integers are irrelevant; in order to choose a protocol the values are simply compared, with larger values indicating stronger preferences. Negative values represent a lower priority than positive values. If the application prefers short connection time over both low latency and high bandwidth, for example, then it could invoke this method with the values (1, 0, 0). If the application prefers high bandwidth above low latency, and low latency above short connection time, then it could invoke this method with the values (0, 1, 2).
Invoking this method after this socket has been connected will have no effect.
connectionTime
- An int expressing the relative importance of a short
connection timelatency
- An int expressing the relative importance of low
latencybandwidth
- An int expressing the relative importance of high
bandwidth
|
JavaTM 2 Platform Standard Ed. 5.0 |
|||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
Copyright © 2004, 2010 Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.


ValD()
Syntax
Result.d = ValD(String$)Description
Converts a string into a double value. The string must be a double in decimal or in scientific (exponent) format. The number parsing stops at the first non numeric character.
Parameters
String$ The string to convert.
Return value
The double value of the string.
Remarks
Strings holding an integer can also be converted with Val(), and 32-bit floats with ValF() (with less accuracy than ValD()).
Example
Debug ValD("10.000024") ; will display 10.000024 Debug ValD("1.2345e-2") ; will display 0.012345
See Also
ValF(), Val(), Str(), StrF(), StrD()
Supported OS
All


{% load static i18n compress %}
Daily Updated Jobs Listings
Use this document as a way to quick start any new project.


Adding and Subtracting integers in Binary
When adding in binary, there are several outcomes. If you add 0 to 0 the result is 0. If you add 1 to 0 the result is 1. However if you add together two 1s the sum is 0 BUT you have to carry 1 over to the next column. If you add together 3 1s you carry 1 over but have a sum of 1:
Here is an example of adding 00101110 with 01111011:
When subtracting in Binary, if your top number is larger than your bottom number then you carry out a normal subtraction (subtract the bottom number from the top). However if your bottom number is larger than your top number you will have to borrow a 2 from the next column.
Here is an example of subtracting 01011101 from 10110001:


[gecode-users] Not all solutions, BAB vs. DFS
Guido Tack
tack at ps.uni-sb.de
Fri Sep 4 09:18:07 CEST 2009
Martin Kreißig wrote:
> Hello,
>
> I found out, that GECODe is a very good (if not the best) solution
> to my problem.
> The thing is, that I never used C++ before - everybody has to start
> at a point ;)
>
> So far I got used to it, but now - when finished - I don't get all
> solutions of my problem.
>
> Searching in this list I found out that I have to use the BAB search
> and add the option opt.solutions(0)...
You can use opt.solutions(0) with DFS, too.
> The program worked with DFS before.
> But now I get the error:
> "terminate called after throwing an instance of
> 'Gecode::SpaceConstrainUndefined' what(): Space::constrain: Attempt
> to use undefined constrain function"
BAB is for solving optimization problems, and requires implementing
the constrain function. If you don't want to do optimization, use DFS.
> My implementation does not follow the syntax given in the examples,
> like:
> "Script::run<Money,DFS,Options>(opt);"
>
> I am starting the search by this:
> DFS<CSP> dfs( csp_obj );
>
> So my question is - maybe a bit of a beginner one - this is not
> possible
> with BAB?
>
> How can I add the options variable in this implementation? BAB<CSP>
> dfs( csp_obj, opt ); is not working.
The dfs object has a next method that you can call in a loop to get
more than one solution. As soon as it returns NULL, the complete
search tree has been explored:
CSP* c = dfs.next();
while (c != NULL) {
c->print(); // e.g., output the current solution
delete c;
c = dfs.next();
}
Cheers,
Guido
More information about the gecode-users
mailing list


June 4
And he said unto me, My grace is sufficient for thee: for my strength is made perfect in weakness. Most gladly therefore will I rather glory in my infirmities, that the power of Christ may rest upon me.
2 Corinthians 12:9
When you run into an impossible situation, a situation you simply don't have the strength or the ability to handle, are you often tempted to simply give up and accept defeat? Don't! Instead shout, "Glory!" because the Word says God's strength is about to be made perfect in you.
The word translated "strength" in this scripture is dunamis. It means "God's miracle-working power." Just think about that. When your human strength ends, God has promised that His miraculous power will bring you through!
If you'll look in Acts 14, you can see that promise in action. The apostle Paul was stoned by a group of Jews, taken out of the city and left for dead. Paul's human strength had ended. He was absolutely powerless.
But the disciples gathered around him and prayed, and the Lord raised him up and he went on his way. In other words, when Paul didn't have enough human strength to overcome, God's miracle-working power was sufficient for him. It enabled him to be an overcomer in spite of his weakness!
So, if you are facing a crisis today. If you're sick and medicine has failed you. If your finances are out of control. If your family is falling apart. If bad habits have you hopelessly bound. If you've done absolutely all you know to do and you still haven't gotten results. Then rejoice! For when human strength ends, the power of God excels! Only believe! God's grace is sufficient for you!
Scripture Reading: Acts 14:1-22


Log in as administrator to check all the features of the application.
username: admin
password: admin
To see the app from students/teachers perspective:
Username: student/teacher
Password: student/teacher


Engineering
| Data Analyst Intern | Toronto, Canada |
| Data Engineer | Montreal, Canada |
| Machine Learning Engineer | |
| Full Stack Developer | |
| Full Stack Developer | |
| IT Project Manager | Mumbai, India |
| Lead Software Engineer | Montreal, Canada |
| Python Backend Engineer | Montreal, Canada |
Marketing
| Marketing Intern | Montreal, Canada |
| Market Research Specialist | Montreal, Canada |
Product Management
| Senior Product Owner | Montreal, Canada |
Sales
| Account Executive | Toronto, Canada |
| Account Executive |
Technical Support
| Call Center Technical Support | Mumbai, India |
| Call Center Training Specialist | Mumbai, India |


fun Long?.convertZatoshiToZec(scale: Int = ZEC_FORMATTER.maximumFractionDigits): BigDecimal
Convert a Zatoshi value into ZEC, right-padded to the given number of fraction digits, represented as a BigDecimal in order to preserve rounding that minimizes cumulative error when applied repeatedly over a sequence of calculations. Start with Zatoshi -> End with ZEC.
scale
- the number of digits to the right of the decimal place. Right-padding will be added,
if necessary.
Return
this Long Zatoshi value represented as ZEC using a BigDecimal with the given scale,
rounded accurately out to 128 digits.


Landing Page
Special Projects
This story is part of a series of specially designed stories that represents some of the best journalism The Post has to offer. Check out the rest of the special projects here.
05.31.18
If You Go:
What: Open Stage and Draft Night
When: 7:30 p.m., Mondays
Where: West End Cider House, 234 W. Washington St.
Admission: Free
If You Go:
What: Open Stage
When: 10 p.m., Wednesdays
Where: Casa Nueva, 6 W. State St.
Admission: Free
If You Go:
What: Musicians’ Open Stage
When: 8 p.m., Thursdays
Where: Donkey Coffee and Espresso, 17 W. Washington St.
Admission: Free
The Casa Nueva stage thrived with several musical acts during its last open mic night before finals week. Everyone was out for the last hoorah before the end of the year. Armed with mixed drinks, many students were there in support of friends who were performing.
Open mic nights allow people a safe space to perform and listen to music without the pressure of perfection. Casa Nueva, Donkey Coffee and Espresso and West End Cider House each put their own spin on open stage acts for different nights of the week.
At Casa Nueva, nearly every genre was covered, from country to rock to jazz, with acoustic guitars. Beyond that, some performers used different instruments such as violin, ukulele and harmonica. A woman even performed some freestyle rap and a Persian song. One man brought his violin-playing friend on stage at the end of his set. They played an instrumental version of “I Walk The Line” by Johnny Cash, and the crowd went wild for the duo.
Bret Anderson, a freshman studying music production at Hocking College, has played music since she was a kid and wants to make a career as a musician. She played one original song called “Something Better,” which is about how a partner helped her let go of past experiences.
She enjoys coming to open mic nights because it’s a fun, casual night out where she can promote her work outside of her circle of friends.
“They’re a way for me to play out and show off my music,” Anderson said.
Allison DeWitt, booking manager at Donkey Coffee and Espresso, hosts open mic night at the coffee shop. She said the audience has more attentive listeners than other locations because most people are quietly working on homework.
“It’s more intimate of a setting,” she said.
McKinley Law | FOR THE POST
Chris Biester performs at Casa Nueva for Open Mic Night on Wednesday, April 25, 2018.
DeWitt said Donkey’s stage has been graced with a 16-minute electric guitar solo, Japanese drums and even spoken word that involves instruments. Athens has a very broad music community that practices a range of music genres. The craft really brings people together and helps them communicate, she said.
The attention performers receive can make them anxious about playing, but ultimately they enjoy the appreciation their work gets when people give them a hearty round of applause, DeWitt said.
When there aren’t many people signed up for the night, DeWitt plays some original songs on the piano. She writes about any life experiences that people can relate to including heartbreak and friendship.
Chris Monday, host of the West End Cider House open mic night, has lived in Athens since 2000 and used to host the event at Casa Nueva with a few other people. He wanted to bring the same experience to Cider House at an earlier time for performers who didn’t want to go on late.
Monday tried to create a very laid back atmosphere at the venue. Cider House offers a few seating options, with several lush couches being the closest to where people perform their music and other artforms. He isn’t strict on line-up specifics — having less performers can mean longer sets.
Not many people in the crowd give their full attention to acts, which makes some performers feel more comfortable about playing, Monday said.
“If you have stage fright, this is a great place (to start out),” he said.
Monday wants more students from the Ohio University School of Music to perform at Cider House. He welcomes everyone to bring their musical talent, but wants more variety beyond songs played on acoustic guitar.
Monday said the venues that host open mic nights support each other and even share some of the same performers and audience members.
“That’s why we organize it on different nights,” he said. “We don’t look at it so much as a competition as much as we do a community.”
Landing Page
This story is part of a series of specially designed stories that represents some of the best journalism The Post has to offer. Check out the rest of the special projects here.


--- title: "Start a New Project" ---
If you have an idea that you believe can be turned into reality then why not start your own ENACTUS project? Starting a new project is a rewarding and enriching experience and one that you will never forget. It is a great way to make the most out of your time here at the LSE as well as benefitting society, making new friends and enhancing your personal skill set.
At first, starting your own project seems like a daunting task but as you will soon realise, this is not the case. We are dedicated in assisting you every step of the way to make setting up a new project an enjoyable experience.


Survey Questions
About You
Question 1
I enjoy taking names and kicking a$$.
Question 2
If I want your opinion, I’ll beat it out of you.
Question 3
If you're not a part of the solution, you're a part of the problem.
Question 4
A cookie has no soul, it's just a cookie.
Question 5
Ever notice how you come across somebody once in a while you shouldn’t have messed with? That’s me.
Find a friend


Beyond Cloud - The 3rd Computing Era
Over the last couple of weeks I’ve presented a more forward looking view of what lies beyond our current conception of cloud computing at CloudConnect in Las Vegas, a research symposium at UC Berkeley and to the Northern California chapter of the Young Presidents Organization. I’ve used these presentations to outline an evolving set of ideas anchored around the idea that we’re in the middle of the 2nd Era of Computing rapidly evolving towards the 3rd Era. The organizing principle behind the ‘Era’ concept is the degree of coupling in and between application code and the underlying infrastructure.
During the 1st Era of Computing applications were tightly coupled to underlying hardware in order to optimize the use of scarce and expensive computing resources. The 2nd Era in which we now find ourselves requires loosely coupled architectures to enable resilient, elastic and composable, cloud scale application and service workloads. However, the coming data volume and management demands of trillions of connected devices - the Internet of Things - combined with the need for truly friction free machine-2-machine transactions will rapidly drive the emergence of the 3rd Era of Computing. In the 3rd Era we will move from loosely coupled of truly uncoupled architectures where code is free to execute when and where it is needed enabled by a new fabric of trusted, frictionless, smart contract based transactions.


{% if page.comments %}
Book club moved to private location.
(your posts, usernames, and avatars transferred too, and you all have a note of the new location)
Any questions, you know how to get in touch


spacy-nlp-node-native[wip]
Spacyio nlp for nodejs with native bindings
Prerequisites
- spaCy installed
Getting started
npm install spacy-nlp-node-native
Usage
const spacyNlp = require("spacy-nlp-node-native");
spacyNlp.parse("test me", {});
API
- See documentation - https://pasupulaphani.github.io/spacy-nlp-node-native/
Run tests
npm test
Contribute
Discover how you can contribute by heading on over to the CONTRIBUTING.md
file.
Backers
Maintainers
These amazing people are maintaining this project:
Sponsors
No sponsors yet! Will you be the first?
Contributors
These amazing people have contributed code to this project:
- This could be you
Feel free to make changes. Please see the Contributors' Guide for more information on contributing to the documentation.


{% extends "base.html" %} {% block titleblock %} {{ view.page_title }} {% endblock %} {% block content %} {% load addclass %}
This section of the site is a guide to understanding the mechanics behind {{ game_name }}.
It is organized first by category, then by topic. The box to the right will let you skip to particular categories.
Your Help section is currently blank!
You're missing out on an opportunity to attract visitors (and potentially new players) to {{ game_name }}!
Use Evennia's Help System to tell the world about the universe you've created, its lore and legends, its people and creatures, and their customs and conflicts!
You don't even need coding skills-- writing Help Entries is no more complicated than writing an email or blog post. Once you publish your first entry, these ugly boxes go away and this page will turn into an index of everything you've written about {{ game_name }}.
The documentation you write is eventually picked up by search engines, so the more you write about how {{ game_name }} works, the larger your web presence will be-- and the more traffic you'll attract.
Everything you write can be viewed either on this site or within the game itself, using the in-game help commands.
Click here to start writing about {{ game_name }}!
Thanks for your interest, but we're still working on developing and documenting the {{ game_name }} universe!
Check back later for more information as we publish it.
Click here to go back to the main page.


Exploring Colors
Place on Top
Place on Parent
Place in another window
A black background seems to lend an air of mystery...


{% extends 'login-signup-base.html' %} {% block content %}
Sign in to start your session
- OR -
Forgot Password?


LOGO
Partnership Agreement Maker
Welcome Username,
Logout
Home
Routing Packages
Routing Templates
My Reviews
Footer
Create New Routing Template
Add
Cancel
Reviewer
Routing Sequence #
File Upload Access
Mary Meador
Research Technical Engineer & Applicant
<EMAIL_ADDRESS>000.000.0000
1
Add Alternate Approver
Add Courtesy Copy
Edit
X Remove
+ Add Reviewer
Add Reviewer
X CLOSE
First Name / Last Name
Center
Lookup
Results
Michael Meader
Mary Ann Meader
Research Technical Engineer & Applicant
Select
Chief, Structures and Materials Div
Select
Courtesy Copy Reviewers
Alternate Reviewers
First Name / Last Name
Center
Lookup
Results
Firstname Lastname
Research Technical Engineer & Applicant
<EMAIL_ADDRESS>000.000.0000
Select
Reviewer
Send Alternate Message Automatically
Firstname Lastname
Research Technical Engineer & Applicant
<EMAIL_ADDRESS>000.000.0000
Add Reviewer
X CLOSE
Mary Meador
Research Technical Engineer & Applicant
<EMAIL_ADDRESS>000.000.0000
Comment to Reviewer
Add
Cancel
Add Alternate Reviewer
X CLOSE
First Name / Last Name
Center
Lookup
Results
Firstname Lastname
Research Technical Engineer & Applicant
<EMAIL_ADDRESS>000.000.0000
Select
Reviewer
Send Alternate Message Automatically
Firstname Lastname
Research Technical Engineer & Applicant
<EMAIL_ADDRESS>000.000.0000
Add
Cancel
Add Courtesy Copy Reviewer
X CLOSE
First Name / Last Name
Center
Lookup
Results
Firstname Lastname
Research Technical Engineer & Applicant
<EMAIL_ADDRESS>000.000.0000
Select
Reviewer
Send CC Copy concurrent to reviewer
Firstname Lastname
Research Technical Engineer & Applicant
<EMAIL_ADDRESS>000.000.0000
Add
Cancel
Template name
Save as Draft


How to manage kids’ texts, calls, and contacts w/ Screen Time on iPhone, iPad, and iPod touch
by Michael PotuckApple is expanding its Screen Time software that gives parents more control of their family’s devices with a highly requested feature: the ability to manage kids’ texts, phone calls, FaceTime calls, and even contacts on iPhone, iPad, and iPod touch. Read on for how to set it all up in iOS 13.3 and later…
Since Screen Time debuted on iPhone, iPad, and iPod touch in iOS 12, there hasn’t been a way to fully manage kids’ texts, phone calls, FaceTime calls, and contacts. Now Apple has delivered granular control of those areas with iOS 13.3 and parents will no doubt be pumped for the feature.
For right now, iOS 13.3 is only available as a developer or public beta. You can learn more about Apple’s free public beta program here if you’d like to try it out. But before long, the feature will be available to all.
Below we’ll cover how to set up Screen Time on your kid’s device and how to set up Communication Limits, skip further below if you want to jump to the new limits.
How to manage your kid’s texts, calls, and contacts with Screen Time on iPhone, iPad, and iPod touch
Note: Both the Family Organizer’s device and the child’s device will need to be running iOS 13.3 or later
Set up Screen Time for your child’s device:
- You’ll need to be using Family Sharing, read more here about setting it up and creating a kid’s account if you haven’t already
- With Family Sharing going and your child’s account set up as a “child’s account,” head to Settings on your iPhone or iPad
- Navigate to Screen Time, swipe down and look for your child’s name, tap it
- Choose Turn On Screen Time
- Follow the prompts to set up Downtime, App Limits, Content & Privacy, etc.
- When finished head to the next steps below to turn on management of texts, calls, and contacts
Set up Communication Limits for your kid:
- Now with your kid’s account selected in Screen Time, tap Communication Limits
- You can control who they can text, call, and FaceTime as well as managing their contacts
- Tap each section to set rules for During Allowed Screen Time and During Downtime
- Tap the toggle next to Manage (your kid’s) Contacts to enable granular control of them
- After turning on Manage Contacts, you or your kid will need to approve the request on your kid’s device
Here’s how the process looks:
If you want to manage your kid’s contacts, toggle it on below the allowed communication section.
After turning it on, you or your child will need to approve it on their device under Screen Time > Requests: Manage Contacts > tap Approve.
When that’s done, as a Family Organizer, you’ll be able to manage contacts as shown in the image above on the right.
Read more 9to5Mac tutorials:
AirPods Pro:
- Shopping for AirPods Pro? Here’s how to find available stock without waiting weeks
- How to clean your dirty AirPods Pro and charging case
- AirPods Pro: How to customize Force Sensor controls
- AirPods Pro: How to use Ear Tip Fit Test and change tips
- AirPods Pro: How to use noise cancellation and Transparency mode
- AirPods Pro vs Powerbeats Pro: How specs, size, price, and more compare
- What’s the difference in AirPods and AirPods Pro? Here’s how size, price, and features compare
iPhone & iPad:
- How to remove Memoji Stickers from your iPhone keyboard
- How to use the Deep Fusion iPhone 11 and iPhone 11 Pro camera feature
- iOS 13: How to use custom fonts on iPhone and iPad
- How to edit messages on iPhone and iPad with two-finger tap
- How to use the ‘Remind when messaging’ feature on iPhone, iPad, and Mac
- How to change icons and colors for Reminders Lists on iPhone, iPad, and Mac
- How to make subtasks and sublists with Reminders in iOS 13 and macOS Catalina
- How to get started with and use ‘Sign in with Apple’ on iPhone, iPad, and Mac
- How to use the ultra wide camera on iPhone 11 and iPhone 11 Pro
macOS Catalina:
- How to get started with and use Voice Control in macOS Catalina
- How to check iPad and Mac Sidecar requirements
- How to get your Mac ready for macOS Catalina
- How to create a bootable macOS Catalina 10.15 USB install drive [Video]
- How to sync iPhone and iPad to your Mac in macOS Catalina without iTunes
FTC: We use income earning auto affiliate links. More.


458_XiaohaSun.java
class Solution {
/* bsearch or minmax;
bsearch is ok. the distance is 1 to Max_val;
given distance, put balls see if if can put m; if > m distance is to small; if < m; distance is too large.
if == m, we want it to move right.
*/
public int maxDistance(int[] position, int m) {
Arrays.sort(position);
int left = 1, right = Integer.MAX_VALUE;
while (left < right) {
int mid = right - (right - left) / 2;
if (requiredBall(position, mid) >= m) left = mid;
else right = mid - 1;
}
return left;
}
private int requiredBall(int[] pos, int minDist) {
int prev = pos[0];
int count = 1;
for (int i = 1; i < pos.length; i++) {
if (pos[i] - prev >= minDist) {
prev = pos[i];
count++;
}
}
return count;
}
}


@* * Copyright 2010-2013 Artima, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *@ @import controllers.Application.scaladocsPageUrl @userGuidePage("Using ScalaTest with sbt") {
ScalaTest's ScalaTestFramework
supports using ScalaTest from sbt.
In sbt version 0.10 and higher, simply add a line like this to your project file:
libraryDependencies += "org.scalatest" %% "scalatest" % "1.6.1" % "test"
The above line will work for any version of Scala 2.9. For example, it works for Scala 2.9.0-1. If you're using 2.8.1 or 2.8.2, you can write this:
libraryDependencies += "org.scalatest" %% "scalatest" % "1.5.1" % "test"
Your test sources files go into src/test/scala
. You can run all of them from the sbt console with:
> test
If you want to run particular suites, use test-only
and provide their fully qualified names in a space separated list:
> test-only org.acme.RedSuite org.acme.BlueSuite
You can configure the output shown when running with sbt in four ways: 1) turn off color, 2) show
short stack traces, 3) full stack traces, and 4) show durations for everything. To do so you must
pass a -o
argument to ScalaTest, and after the -o, place any combination of:
For example, "-oDF" would show full stack traces and durations (the amount of time spent in each test).
To pass arguments from sbt to ScalaTest you can either add test options globally, like this:
testOptions in Test += Tests.Argument("-oD")
Or if you are using more than one test framework, like this:
testOptions in Test += Tests.Argument(TestFrameworks.ScalaTest, "-oD")
You can also pass arguments for individual runs by placing them after --
, like this:
> test-only org.acme.RedSuite -- -oD


Your proxies
| # | IP/Host | Port | Username | Password | Status |
|---|
How to Use
- Sign up for a free account on DigitalOcean and then add your API key in the settings.
- Dont forget to create ONE SSH key and add it to your account (Optional).
- Grab your DigitalOcean Token in settings/tokens/new and copy/paste it into the settings page located below.


Mexican women use art to protest violence
Women's groups held protests at the Angel of Independence monument in Mexico City before the International Day for the Elimination of Violence against Women on Monday, using tools that include crochet hooks and paint to address violence and machismo in his country.
Dozens of women painted on a protective barricade around the Angel of Independence monument on the city's main avenue on Sunday, while others wove purple and pink hearts to chain.
The barricade was erected after feminists disfigured the statue with graffiti in August to denounce the alleged violations committed by the police in the capital, as well as the high murder rates of women across the country.
On average, 10 women are killed every day in Mexico, making it one of the most dangerous places in the world to be a woman.
The threat of violence is exacerbated by impunity for most perpetrators: less than one in 10 murders are resolved in Mexico.
Participants in the art installation at the Angel, meanwhile, said Sunday's flood of creativity was a way to reinsert the conversation about violence and other injustices that women face in Mexico.


Chapter 2 Introduction
The machine learning algorithms were trained to detect breast cancer using the Wisconsin Diagnostic Breast Cancer (WDBC) dataset[20]. The dataset consists of features which were computed from a digitized image of a fine needle aspirate (FNA) of a breast mass. The said features describe the characteristics of the cell nuclei found in the image.
2.1 Description of the data
<- read.csv("data/WBCD_data.csv")
dat ::kable(head(dat)) knitr
| id | diagnosis | radius_mean | texture_mean | perimeter_mean | area_mean | smoothness_mean | compactness_mean | concavity_mean | concave.points_mean | symmetry_mean | fractal_dimension_mean | radius_se | texture_se | perimeter_se | area_se | smoothness_se | compactness_se | concavity_se | concave.points_se | symmetry_se | fractal_dimension_se | radius_worst | texture_worst | perimeter_worst | area_worst | smoothness_worst | compactness_worst | concavity_worst | concave.points_worst | symmetry_worst | fractal_dimension_worst | X |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 842302 | M | 17.99 | 10.38 | 122.80 | 1001.0 | 0.11840 | 0.27760 | 0.3001 | 0.14710 | 0.2419 | 0.07871 | 1.0950 | 0.9053 | 8.589 | 153.40 | 0.006399 | 0.04904 | 0.05373 | 0.01587 | 0.03003 | 0.006193 | 25.38 | 17.33 | 184.60 | 2019.0 | 0.1622 | 0.6656 | 0.7119 | 0.2654 | 0.4601 | 0.11890 | NA |
| 842517 | M | 20.57 | 17.77 | 132.90 | 1326.0 | 0.08474 | 0.07864 | 0.0869 | 0.07017 | 0.1812 | 0.05667 | 0.5435 | 0.7339 | 3.398 | 74.08 | 0.005225 | 0.01308 | 0.01860 | 0.01340 | 0.01389 | 0.003532 | 24.99 | 23.41 | 158.80 | 1956.0 | 0.1238 | 0.1866 | 0.2416 | 0.1860 | 0.2750 | 0.08902 | NA |
| 84300903 | M | 19.69 | 21.25 | 130.00 | 1203.0 | 0.10960 | 0.15990 | 0.1974 | 0.12790 | 0.2069 | 0.05999 | 0.7456 | 0.7869 | 4.585 | 94.03 | 0.006150 | 0.04006 | 0.03832 | 0.02058 | 0.02250 | 0.004571 | 23.57 | 25.53 | 152.50 | 1709.0 | 0.1444 | 0.4245 | 0.4504 | 0.2430 | 0.3613 | 0.08758 | NA |
| 84348301 | M | 11.42 | 20.38 | 77.58 | 386.1 | 0.14250 | 0.28390 | 0.2414 | 0.10520 | 0.2597 | 0.09744 | 0.4956 | 1.1560 | 3.445 | 27.23 | 0.009110 | 0.07458 | 0.05661 | 0.01867 | 0.05963 | 0.009208 | 14.91 | 26.50 | 98.87 | 567.7 | 0.2098 | 0.8663 | 0.6869 | 0.2575 | 0.6638 | 0.17300 | NA |
| 84358402 | M | 20.29 | 14.34 | 135.10 | 1297.0 | 0.10030 | 0.13280 | 0.1980 | 0.10430 | 0.1809 | 0.05883 | 0.7572 | 0.7813 | 5.438 | 94.44 | 0.011490 | 0.02461 | 0.05688 | 0.01885 | 0.01756 | 0.005115 | 22.54 | 16.67 | 152.20 | 1575.0 | 0.1374 | 0.2050 | 0.4000 | 0.1625 | 0.2364 | 0.07678 | NA |
| 843786 | M | 12.45 | 15.70 | 82.57 | 477.1 | 0.12780 | 0.17000 | 0.1578 | 0.08089 | 0.2087 | 0.07613 | 0.3345 | 0.8902 | 2.217 | 27.19 | 0.007510 | 0.03345 | 0.03672 | 0.01137 | 0.02165 | 0.005082 | 15.47 | 23.75 | 103.40 | 741.6 | 0.1791 | 0.5249 | 0.5355 | 0.1741 | 0.3985 | 0.12440 | NA |
2.2 Check how may variables are there.
dim(dat)
## [1] 569 33
As you can see, there are 569 rows and 33 columns.
2.3 Check the colum names
colnames(dat)
## [1] "id" "diagnosis"
## [3] "radius_mean" "texture_mean"
## [5] "perimeter_mean" "area_mean"
## [7] "smoothness_mean" "compactness_mean"
## [9] "concavity_mean" "concave.points_mean"
## [11] "symmetry_mean" "fractal_dimension_mean"
## [13] "radius_se" "texture_se"
## [15] "perimeter_se" "area_se"
## [17] "smoothness_se" "compactness_se"
## [19] "concavity_se" "concave.points_se"
## [21] "symmetry_se" "fractal_dimension_se"
## [23] "radius_worst" "texture_worst"
## [25] "perimeter_worst" "area_worst"
## [27] "smoothness_worst" "compactness_worst"
## [29] "concavity_worst" "concave.points_worst"
## [31] "symmetry_worst" "fractal_dimension_worst"
## [33] "X"
The name of last column is X
is because the name is not provided in the data.


An Ambudance Of Katherines
Title Name:An Ambudance Of Katherines
Author Name:John Green
Publisher Name: Corgi Books
When it comes to relationships, Colin Singleton's type is girls named Katherine.
And when it comes to girls named Katherine, Colin is always getting dumped.
Nineteen times, to be exact.
On a road trip miles from home, this anagram-happy, washed-up child prodigy has ten thousand dollars in his pocket, a bloodthirsty feral hog on his trail, and an overweight Judge Judy-loving best friend riding shotgun - but no Katherines.
Colin is on a mission to prove The Theorem of Underlying Katherine Predictability, which he hopes will predict the future of any relationship, avenge Dumpees everywhere, and finally win him the girl.
Love, friendship, and a dead Austro-Hungarian archduke add up to surprising and heart-changing conclusions in this ingeniously layered comic novel about reinventing oneself.


TPU's GPU Database Portal & Updates ATi GPU Database AMD GPU Database Desktop GPUs Desktop GPUs Desktop Workstation GPUs Desktop Workstation GPUs Desktop IGP GPUs Desktop IGP GPUs Mobile GPUs Mobile GPUs Mobile Workstation GPUs Mobile Workstation GPUs Mobile IGP GPUs Mobile IGP ...
ParkMobile User Experience - Aaron Shekey Aaron Shekey is a product designer and musician in Minneapolis, MN.
Indie Soapbox Ten indies take the stage to share what's on their minds in this ever-popular conclusion to the summit! Individual topics range as widely as the individuals themselves, but these microtalks are sure to provoke, educate, and inspire.
Verified cryptographic provider a triple threat Working toward provably secure online communications requires a strong foundation on which to build protocols. Enter EverCrypt, a fully verified cryptographic provider offering a comprehensive suite of algorithms, agility, and multiplexing capabilities
Compass Rose by Pace A lateral-thinking puzzle game with in-game hints. To escape, you must rethink everything you know.
Steam cracks down on Trading Card abuse to combat "fake games" Trading Card farming is hurting the discovery algorithms
US $10.71 33% OFF|37mm diameter gearbox halll encoder micro spur gear motor Speed Reduction Geared Motor for robot smart small car-in DC Motor from Home Improvement on AliExpress Smarter Shopping, Better Living! Aliexpress.com
Fifteen years of WiX • Joy of Setup Fifteen and a bit years ago, I was a release engineering technical lead, responsible for the build and setup for a number of products. We used a commercial installer development tool for creating our MSI packages – of course we did, because there was no o...
Getting ready to say goodbye to Silverlight and hello to Blazor What I didn’t know at the time was that the December 9th release of Silverlight 5 in 2011 would be the final release of my then favorite…
Home Now Play This is a festival of experimental game design running at Somerset House in London from 6-14 April 2019, showcasing interactive and playful work as part of the London Games Festival.
Classic Game Postmortem: 'Lemmings' In this installment of the Classic Postmortem series, 'Lemmings' co-creator Mike Dailly will discuss the creation of the seminal DMA Design puzzle-platform game starring those allegedly suicidal rodents, which debuted on Amiga in 1991 and...
Troubleshoot blue screen errors - Windows Help Find out how to troubleshoot stop errors (also called "blue screen" errors) in Windows 10 by removing installed updates and using Windows recovery options.
MSVC hidden flags I had seen a while ago the “hidden” MSVC flags that output interesting information such as /d2cgsummary or d1reportAllClassLayout.
'Marvel's Spider-Man': A Technical Postmortem 'Marvel's Spider-Man' is Insomniac's biggest game to date. This talk looks back at how their technology evolved to make it possible, and the setbacks and pitfalls along the way. This session will discuss the challenges of rapidly growing asset...
ardalis/AspNetCoreStartupServices A simple demo listing all services available to an app at startup - ardalis/AspNetCoreStartupServices
Families We’re continually designing new features and parental controls to help make sure children use their devices in the ways their parents want them to.
Azure Front Door Service is now generally available Every internet facing web application, whether serving a large audience or a small set of users in a single region, is by default a global application. Whether you are running a large news website with millions of users across the globe, running a B2B app...


Welcome! 👋
I'm Andrew Sanchez, a passionate individual about Computer Science and Software Development. I
grew up Hollister, CA and majored in Computer Science at California State University, Monterey
Bay (CSUMB). I enjoyed my time at CSUMB as it gave me foundational CS skills to dive into new
technologies. Today you can find me learning about new technologies, playing video games, and
hanging out with my dog Luci.
The language of the web. JavaScript was one of the first languages that I grew to love.
I was first introduced into Git while in college. It was here that I realized Git makes everything easier when it comes to project collabration.
React was the first JavaScript library I picked up and learned. React gives developers the power to create fast and powerful single page applications.
My capstone project involved creating a Machine Learning chatbot, it was here that I learned how powerful and essential ML really is.
My goto for creating backend Services. With multitude of libraries to pair with, Node.js makes backend development a breeze.
Heroku was the first platform I ever used to deploy an application. Herokus CLI tools made it easy to deploy applications and best of all it was free to host my apps.
Simple project management application that is built with React, Redux, and Firebase. Application has authentication to allow users to login and create accounts. Users can create projects with title and add information about their project. Notifications area to show new users and new projects added. Project deployed with Google hosting.
View Project View RepositoryImage searching application. With the search bar, user can checkout pictures or find high quality res images from Unsplash. Once search is complete user is returned 10 tiles with images and their respected description. This application was built using React and uses the Unsplash API to retrieve free high res photos.
View Project View RepositoryFront-End web application built using Vue. The application is centered around a simple "ToDo" list that allows the user to create and delete tasks. Application already comes with 3 sample tasks that is retrieved from JSONPlaceholder.typicode.com/ to simulate communication to a backend service.
View RepositoryFront-End web game/application built using React. Game starts with all cards faced down with the objective of matching each card to a similar value. Utilized DeckOfCards API to retrieve a shuffled deck.
View Project View RepositoryFull-Stack web application that uses technologies React.JS, Express, PostgreSQL, and Node.JS. First designed the front-end with mockups and then built as React components. Back-end built as ReSTful API using Express and Node.js. Implemented a PostgreSQL database to be utilized for CRUD operations.
View Project View RepositoryWith a team designed, built, test, and refine a Amazon Web Services chatbot. Intents are designed around frequently asked questions such as “how can I pay my bill”, “when is my bill due”, and “what is my premium”. Amazon Lamda functions are then used to validate intent and respond appropriately.
View RepositoryProject centered around learning Machine Learning algorithms and applying them to data. Our goal was to predict video games sales off data collected in the past 15 years. Machine Learning algorithms used Linear Regression, Regression Trees, and Logistic Regression.
View Project View Repository


Before Change
def process_folder(self):
Iterate through the faces dir pulling out various information
logger.info("Loading file list from %s", self.folder)
for face in tqdm(os.listdir(self.folder), desc="Reading Face Hashes"):
if not self.valid_extension(face):
continue
filename = os.path.splitext(face)[0]
file_extension = os.path.splitext(face)[1]
face_hash = read_image_hash(os.path.join(self.folder, face))
retval = {"face_fullname": face,
After Change
Iterate through the faces dir pulling out various information
logger.info("Loading file list from %s", self.folder)
filelist = [os.path.join(self.folder, face)
for face in os.listdir(self.folder)
if self.valid_extension(face)]
for fullpath, face_hash in tqdm(read_image_hash_batch(filelist),
total=len(filelist),
desc="Reading Face Hashes"):
filename = os.path.basename(fullpath)
face_name, extension = os.path.splitext(filename)
retval = {"face_fullname": filename,
"face_name": face_name,
"face_extension": extension,
"face_hash": face_hash}
logger.trace(retval)
yield retval
def load_items(self):
Load the face names into dictionary
faces = dict()
for face in self.file_list_sorted:


|
GameBackbone
0.2.2
Framework for developing 2D video games.
|
Use this to write in a file. More...
#include <FileWriter.h>
Public Member Functions | |
| FileWriter (const FileWriter &reader)=default | |
| FileWriter (FileWriter &&reader)=default | |
| FileWriter & | operator= (const FileWriter &reader)=default |
| FileWriter & | operator= (FileWriter &&reader)=default |
| std::string | createWritableString (Array2D< std::string > *dataArray, char delimiter) const |
| Creates the writable string from an existing GB::Array2D populated with data. More... | |
| void | writeString (const std::string &inString, const std::string &filePath) const |
| Writes the string to a file. Throws a GB::Error::FileManager_BadFile exception if the file cannot be opened. More... | |
Use this to write in a file.
| std::string FileWriter::createWritableString | ( | Array2D< std::string > * | dataArray, |
| char | delimiter | ||
| ) | const |
Creates the writable string from an existing GB::Array2D populated with data.
| dataArray | The array populated with data. std::invalid_argument exception thrown if null or empty. |
| delimiter | The delimiter for the output string. |
| void FileWriter::writeString | ( | const std::string & | inString, |
| const std::string & | filePath | ||
| ) | const |
Writes the string to a file. Throws a GB::Error::FileManager_BadFile exception if the file cannot be opened.
| inString | The formatted string to be written. |
| filePath | The file path to write to. |


CROUCHING TIGER, HIDDEN DRAGON RATING: 7.5/10 --> Very good movie
For more reviews and movie screensavers, visit http://www.joblo.com/
The concept of wire-fu, a hyped up style of kung-fu using wires on film, has been running rampant since THE MATRIX popularized it last year. The two most prominent movies of this year to utilize the technique in their films were ROMEO MUST DIE and CHARLIE'S ANGELS, who basically just used it as a "charge" to distract from their lack of actual story. But with this film, director Ang Lee wants to take the element of kung-fu fighting to another level...that's right, fighting interspersed with an actual plot line!
PLOT: A great warrior preparing for "retirement" decides to pursue one last battle, as his legendary sword is stolen. Alongside his good friend, for whom he restrains a secret love, he sets out to get the sword back and take revenge upon the woman who killed his master.
CRITIQUE: An epic in every sense of the word, this film combines some of the coolest fight sequences ever put to the big screen with majestic cinematography and an all-encompassing tale of love, honor and fantasy. And by fantasy, I mean people literally flying across rooftops and fighting against one another while standing on skinny tree branches. That's right, you can pretty much forget about the concept of gravity in this movie! People fly while running, walk across water and run up walls in this film. Real cool stuff if you get "into it", but definitely unbelievable if you're not in on the spell. Which brings me to the actual story of the film. A hundred times better than most Hong Kong martial arts flicks, I can't say that I was mesmerized by this sorted tale. In fact, I thought some of the scenes were a little boring, especially the middle ones in the desert, which went on a little too long. I also didn't really get emotionally attached to any of the characters, or feel much for them by the end of the film. The story wasn't a bad one, it's just that some of the plot points nagged at me somewhat. Here are these great warriors searching for the evil Jade Fox, and even though she's the governess of the girl they're quite familiar with, they don't recognize her? And what about their relationship to the girl? Every time they see her, they either fight or embrace her. A little too ambiguous for my taste. But maybe that's just me.
I did however enjoy the overall story which effectively combined dramatic elements with humor, action and even a touch of romance. For me, the best parts of the movie were obviously the battle scenes, which just blew my friggin' eyes away! In fact, I suspect that most people who see this movie will find themselves staring at the screen and wondering how the hell they managed to put together all of those cool moves. But again, if wire-fu stunts don't do it for you, and fast-motion fight scenes ain't your cup of tea, don't go into this movie expecting GONE WITH THE WIND. It's a wonderfully photographed picture, with beautiful details in the settings, its authenticity and the obvious language spoken (the film is in Mandarin with English subtitles), but its wonder resonates most with its fight sequences, and if that sort of thing doesn't impress you, this film likely isn't for you. And for once, all of the actual fight scenes were filmed flawlessly. Really believable. For me, those were the elements which worked best in this film. Awesome, awesome battles, beautifully shot and an okay story.
Review Date: December 8, 2000 Director: Ang Lee Writers: James Schamus, Wang Hui Ling, and Tsai Kuo Jung Producers: Ang Lee, Li-Kong Hsu, William Kong Actors: Chow Yun Fat as Li Mu Bai Michelle Yeoh as Yu Shu Lien Zhang Ziyi as Jen Genre: Drama/Action Year of Release: 2000 ------------------------------------ JoBlo's Movie Emporium http://www.joblo.com/ ------------------------------------ (c) 2000 Berge Garabedian
The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.
Please direct comments/criticisms of the review to relevant newsgroups.
Broken URLs inthe reviews are the responsibility of the author.
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
Related links: index of all rec.arts.movies.reviews reviews


--- layout: archive title: Zulip Chat Archive permalink: /stream/113488-general/topic/.5Bvscode.5D.20completions.html ---
Sometimes I will type \langle
or whatever and vscode won't underline it and I will have to delete it all and keep typing \
until eventually the underline appears. Then when I click space it will complete.  Are there some settings that will prevent this?
Also is there a way to increase the delay when the completion underline dissappears? I just spent about a minute trying to get \McC
to complete.
Also is there a way to get the list of available completions to appear?
Also is there a way of making tab complete the symbols?
Is there a way of turning off the Lean inbuilt completions so I can just maintain my own snippets file?
VSCode will not underline the \
if you had a selection immediately before you started typing
I'm not observing this behavior
there is no delay for the completion underline - it is not time-based
The answer to all of your questions is "no" without hacking the extension itself
which might not be a bad idea, if you have a concrete plan for how to improve the situation
I can't replicate those behaviors
ok I wiped my settings.json and the behaviour went away
what was in there?
do you have any other extensions?
so something's interfering... let me slowly add the settings back in and see what the issue is
particularly one that messes with editor interaction like a vim mode
"editor.wordBasedSuggestions": false,
causes it
"editor.wordBasedSuggestions": true,
also causes it!
So does "editor.acceptSuggestionOnEnter": "smart",
set to any value
setting these in settings.json
is clobbering something that the extension needs
Shall I open a github issue?
I can't replicate any effect of editor.wordBasedSuggestions
nor editor.acceptSuggestionOnEnter
I figured it out. files.autoSaveDelay : x
also needs to be set. The delay for the underline to dissappear is the same as the autosave delay
yeah, I'm getting that
weird. Sorry it seemed correlated with editor.wordBasedSuggestions
but it was just my mind playing tricks.
I made a github issue: https://github.com/leanprover/vscode-lean/issues/80
I thought the 500ms delay was put in intentionally and you were just supposed to type really fast!
I usually don't need to save so aggressively, since vscode can quit and restart without losing unsaved data
Ok I've wopped a zero to the end of the delay time and it's utterly fabulous.
Fixed in vscode-lean 0.11.14, coming to a vscode installation near you any moment now.
BTW, the vim plugin is officially supported and tested since the main extension developer uses it exclusively.
Last updated: Apr 24 2020 at 19:02 UTC


Problem
- Data quality black box;
- Incomplete knowledge on avail data;
- Limited internal resources for dev & ops of tailored analysis tools
Solution
- Analysis service for data quality control;
- SaaS analysis operation & maintenance via cloud
Value
- Accelerated and direct support response;
- Unloads work from dev teams and improves system diagnosis;
- Operation and maintenance free usage


{{template config_path="design/email/header"}} {{inlinecss file="email-inline.css"}}
A new document has been emitted for you.
You can find it attached to this email or in your Account Dashboard.


Spoilers: Ben vows to change in EastEnders and makes a big gesture
Ben Mitchell (Max Bowden) has been going to some pretty dark places in EastEnders as of late, but in the coming episodes, he seemingly attempts to change his ways, as he makes a big gesture.
In an attempt to acquire the wrench Stacey (Lacey Turner) used to bludgeon Phil (Steve McFadden), Martin carried out Ben’s dirty work. However, Ben refused to let him go — even after he’d handed over said wrench — and blackmailed Martin once more, threatening to turn him over to the police for car theft.
Martin made several attempts to get out — and he even had Ben arrested — but Ben refused to budge, and even hung from the railway bridge in an attempt to show him who’s boss.
Martin’s life was hell, but when Kathy found out what Ben was up to, she scolded her son for being so cruel, and warned him to change his ways before it was too late.
Advertisement Advertisement
Yes, Ben’s demonstrated a much darker side to his personality in recent months — and it’s a side that both Kathy and Callum haven’t been to keen on, that’s for sure.
However, it seems as thought the young man could be about to start making up for at least some of the heartache he’s caused, as — in the coming episodes — he manages to help Sonia (Natalie Cassidy), and finds himself in rather high spirits as a result!
Viewers will remember that — during Hunter’s (Charlie Winter) siege — it was Sonia who saved Ben after he’d been shot, so perhaps he feels obliged to offer his support as a result?
Has Ben really turned over a new leaf? What’s more, is he even capable of doing so?
One to watch: Monday 25th November at 8pm on BBC One.


 Raise your drink high one of the greatest best friends sitcoms of all time.
Drinking Rules
Drink Once
Ted says: ""
Robin
says "Literally" or "But um..."
Marshall sings or talks about Mythical Monster (Big Foot, Lockness Monster, )
Lily:
medalls in someone else's business
says "yousonofabitch"
Barney:
says "Legen - wait for it - dary"
says "Awesome" or "Classic"
Voice Over
Flashback
Drink Twice
Ted says: ""
Robin says: "Literally" or "But um..."


This article was originally published in the April 2014 issue of NFJS the Magazine.
This article begins an introductory series on the Go programming language. Go is a language optimized for large-scale software engineering and is rapidly becoming the language of choice for building cloud services. It does this in a very interesting way, optimizing for simplicity rather than complexity and taking a “less is exponentially more” approach.
Three ways in which this really stands out are:
A pragmatic approach to component design (through implicitly satisfied interfaces)
The need to forget much of what you’ve learned about object-oriented programming (and to prefer composition over inheritance)
A concurrency model that mere mortals can use to great effect (via goroutines and channels)
Overall, it’s a language with the productivity of a dynamically-typed, interpreted language with the safety and efficiency found in a statically-typed, compiled language.
This series will focus on learning Go from the perspective of Java developers. We’ll begin with design ideas informed by Go’s primary method of abstraction: interfaces.

Object-oriented programming (OO) has dominated large-scale software engineering for quite some time now. While OO finds its roots in simulation programming, it moved into and began to dominate the mainstream of business programming with the advent of languages like C++ and Java. When we design programs in an OO language, we usually begin with an object model, defining a taxonomy of objects representing all of the entities, or nouns, in our business domain. Languages like C++ and Java support this via the class construct, with a class defining a template for creating a particular type of object. Classes normally can be extended, creating subclasses. This allows us to define a hierarchy of types that inherit characteristics and behavior from one another.
But what if I told you that classes were unnecessary? This may seem like heresy, but we already know it. JavaScript has the feel of an OO language, but it does not have classes at all. In fact, it utilizes what’s called prototype-based programming [PBP]. With prototype-based programming, we achieve reuse by cloning existing objects that serve as prototypes.
Those of us that have surfed the wave of functional programming have discovered that it’s indeed possible to structure large programs around a very basic set of types (sets, lists, maps, etc.), along with a large collection of behaviors, or functions, that can operate on those types. In these languages, we don’t really see anything resembling an object!
The Go programming language is somewhat unique in that it offers many OO-like constructs, but does not offer either classes or prototypes. But it is also not correct to refer to it as a functional language per se.
Favoring Composition Over Inheritance
While the Java programming language has always included a type system featuring inheritance, it has long been considered best practice to favor composition over inheritance. When Joshua Bloch, now Chief Java Architect at Google and then Distinguished Engineer at Sun Microsystems, wrote his seminal work Effective Java [EJ], he included as Item #16: “Favor composition over inheritance.”
When we use inheritance, we must be careful to implement subclasses such that they are in an is-a relationship with their parents. In other words, any context that expects an instance of the parent type should also work well with an instance of the subtype. We call this substitutabilty, which is expressed well by the Liskov Substitution Principle [LSP]. When we don’t follow this principle, we usually end up creating a lot of code that uses type checking to implement special behaviors. In doing so, we create fragile systems that don’t abide by the Open-Closed Principle [OCP].
When we instead utilize composition, we build classes that are in a has-a relationship with their components. If we’d like to encapsulate the relationship between a class and its components, we can apply delegation, forwarding method calls to the underlying component. This makes it appear as if our object is-a instance of another type in terms of behavior, without the problems associated with inheritance-based reuse.
The Go programming language also emphasizes composition over inheritance, in that it does not even provide inheritance as a language construct! Instead, it provides the ability to use composition at the type and behavior level. Let’s see how.
Structs FTW!
In Go we can define composite data types using structs.
You may be familiar with structs if you’ve spent any time programming in C.
Structs are simply a sequence of fields, each of which has a name and a type.
If you take a look at A Point
struct, you’ll see that we’ve defined a struct representing a point in Cartesian space.
Point
structtype Point struct {
X, Y float64
}
New Go types are defined using the type
keyword.
We give our type the name Point
.
It’s important to note that we’ve used uppercase here.
Visibility in Go is determined by the case of an identifier.
All code in Go is defined within a package.
If you’d like your types and functions to be visible beyond the confines of your package, you need to export them by starting them with an uppercase letter.
If you use a lowercase letter or underscore (_
), they will be unexported, roughly equivalent to the Java concept of private
.
You’ll quickly notice that we’ve defined two fields in our struct, X
and Y
, both of which take on the type float64
, representing a 64-bit floating-point number.
|
Note
|
Unlike Java, Go places the type declarations after the field names (the same applies when declaring function arguments) - you’ll get used to this eventually! |
X
and Y
are uppercase, they are exported from the struct.
Had they been x
and y
, they would be unexported, and therefore only visible within the struct.
To find out how we'll deal with that, hold on until the next section!Update (2014-07-09): My understanding of this point was corrected on Reddit. Case only affects visibility with respect to packages, so x
and y
would also be accessible to any code within the package enclosing the struct. See this example.
So how do we create one of our Point
s? We have a couple of options. First, we can utilize the new
function:
p := *new(point.Point)
p.X = 1
p.Y = 2
We prefixed our call to new
with an asterisk (*
) in order to dereference the pointer returned by new
.
Yes, that’s right, Go has pointers.
With that said, there’s no pointer arithmetic, so they’re not quite as scary as what we find in languages like C and C++.
They almost represent a happy medium between C and Java.
|
Note
|
You also don’t have to worry about freeing memory! Go is a garbage collected language. |
Built-in types in Go start zeroed, rather than nil
.
In the case of float64
, they take on the value 0
.
It’s good practice for our types to start zeroed as well, and we get that for free here.
Our newly initialized Point
represents the Cartesian coordinate (0,0). The next two statements move our Point
to (1,2).
We can eliminate the two step process by utilizing a composite literal:
p = point.Point{X: 1, Y: 2}
A composite literal creates a new instance each time it is evaluated, and initializes each field with the given value.
In addition, this particular Point
starts out dereferenced.
If we actually want a pointer to it, we need to prefix the literal with an ampersand (&
).
|
Note
|
It is generally considered idiomatic Go to prefer the composite literal style to using new .
|
Enough about structs, on to methods!

You can find one in Method for translating Point
s.
Point
sfunc (p Point) Translate(xDist float64, yDist float64) Point {
return Point{p.X + xDist, p.Y + yDist}
}
The Translate
method takes two distances along the x and y-axes, and translates a point from its current position to a new position by returning a new Point
literal that combines the current x and y coordinates with those distances.
We call Translate
in Calling Translate
, and the output is found in Output of calling Translate
.
Translate
q := p.Translate(5, 5)
fmt.Printf("Translated %v to %v\n", p, q)
Translate
$ go run point.go
Translated {1 2} to {6 7}
Because we’re not operating on a pointer to a Point
, there’s no way for us to affect the existing instance.
If we couple this with unexported fields, we’d have completely controlled access to a Point
instance’s fields.
If we want to mutate a Point
, we need our method to use a pointer as the receiver argument rather than a value.
We do this in Method for translating a Point
via a pointer.
Point
via a pointerfunc (p *Point) TranslatePointer(xDist float64, yDist float64) {
p.X = p.X + xDist
p.Y = p.Y + yDist
}
As you can see, rather than creating a new Point
and returning it, this method returns no value and directly mutates the Point
referred to by the pointer passed in as a receiver.
Notice that Go conveniently dereferences the pointer automatically when using the dot (.
) operator to access fields. We call this method on a pointer to a Point
in Calling TranslatePointer
(with output in Output of calling TranslatePointer
), again using an ampersand (&
) to tell Go we’d like a pointer to a Point
, not a Point
value.
TranslatePointer
qP := &point.Point{X: 1, Y: 2}
qP.TranslatePointer(5, 5)
fmt.Printf("Translated using pointer to %v\n", qP)
TranslatePointer
$ go run point.go
Translated using pointer to &{6 7}
Now that we have the capability to create types with associated methods, let’s look at how we can compose new composite types from existing ones.
Type composition with structs
Let’s imagine that we’d like to extend the concept of Point
and add the notion of color.
If we were working in Java, we might do the following:
public class ColorPoint extends Point {
private Color color;
// rest omitted...
}
Since Go doesn’t have the concept of classes or inheritance, we need to work with structs to accomplish our goal.
We can compose a type called ColorPoint
by embedding the Point
type and then adding the additional field representing color (Embedding Point
into ColorPoint
).
Point
into ColorPoint
const (
BLUE = iota
RED = iota
GREEN = iota
)
type ColorPoint struct {
Point Point
Color int
}
First note the use of the const
keyword.
We’re defining a set of integer constants to represent our colors.
This is the closest approximation that Go has to an enumerated type (such as Java’s enum
) and is usually more that sufficient.
The predeclared identifier iota
represents successive untyped integer constants.
It is reset to 0
whenever const
appears again in the source.
This has the effect in our code of setting BLUE
to 0
, RED
to 1
, and GREEN
to 2
.
Next we define our ColorPoint
type as a struct
.
We embed Point
as an exported field also called Point
, and we define an additional exported field called Color
that is typed as an int
.
Now, in Creating and printing a ColorPoint
, we’ll create an instance of ColorPoint
, and then we’ll print out both the previously defined Point
instance as well as the ColorPoint
instance (results in Output of creating and printing a ColorPoint
).
 Let’s press on.
Houston, we have a problem…
Here’s a summary of our problem:
-
We have
Point
s. -
We have
ColorPoint
s. -
ColorPoint
s are likePoint
s, but they are definitely notPoint
s since Go does not have inheritance. -
That said, we’d like to be able to write methods that can interoperate between them. What do we do?
As an example, since both Point
and ColorPoint
have x and y coordinates, it might be interesting if we could compute the Euclidean distance [EUC] between them.
As a reminder, the formula can be found in Euclidean distance formula.
As expressed here, you can think of p1 and q1 as the x coordinates for the two points, and p2 and q2 as the y coordinates for the two points.
So how do we implement a method that will allow us to compute this formula in such a way that will work with Point
s, ColorPoint
s, or both?
Go Interfaces
Fortunately Go contributes a very powerful version of interfaces to the abstraction conversation.
Go interfaces describe groups of behaviors in the form of method signatures that implementors of the interface must implement.
So far this doesn’t sound unlike Java interfaces. Let’s take a look at two Go interfaces in Positioner
and Distancer
interfaces.
Positioner
and Distancer
interfacestype Positioner interface {
Coordinates() Point
}
type Distancer interface {
DistanceTo(p Positioner) float64
}
Notice that interface
s are themselves types. This is important, because it allows us to define function and method signatures that accept interfaces as arguments. Positioner
's Coordinates()
method should provide us the position of any implementor in terms of a Point
. Distancer
's DistanceTo()
method will calculate the distance between any implementor and a Positioner
.
|
Note
|
It is idiomatic in Go for interface names to be suffixed with “-er.” |
However, unlike Java interfaces, where we might write:
public class Point implements Positioner, Distancer {
// implementation omitted...
}
Go does not have an implements
keyword.
In fact, if you think about the way we’ve defined structs and methods so far, the only place in which we indicated any attachment between a struct and a method is in the method signature itself, in the form of the receiver parameter.
So how does this work in Go?
Let’s talk about how interfaces are satsified.
In languages like Java, an interfaces is satisfied explicitly.
Classes are tagged with implements Interface
.
The compiler then looks up that interface and identifies all of the method signatures defined by it.
It then examines the class to ensure that all of those method signatures have a concrete implementation in either the class itself or one of its parents.
In Go, interfaces are satisfied implicitly. We do not tag structs in any way. For a type to implement an interface, it simply needs to implement all of the method signatures defined by that interface. When we use a type in the context of an interface (e.g. we pass a type into a function that expects an interface as one of its arguments), the compiler will check to see if that type satisfies the interface.
Let’s see how this falls out in practice.
First, let’s define a function that can calculate the distance between two Positioner
s (Calculates the distance between two Positioner
s).
Positioner
sfunc distanceBetween(a Positioner, b Positioner) float64 {
p := a.Coordinates()
q := b.Coordinates()
sqOfXDist := math.Pow(p.X-q.X, 2)
sqOfYDist := math.Pow(p.Y-q.Y, 2)
return math.Sqrt(sqOfXDist + sqOfYDist)
}
Next, in Point
satisfies Positioner
and Distancer
, we satisfy both interfaces for Point
.
Point
satisfies Positioner
and Distancer
func (p Point) Coordinates() Point {
return p
}
func (p Point) DistanceTo(pos Positioner) float64 {
return distanceBetween(p, pos)
}
In ColorPoint
satisfies Positioner
and Distancer
, we satisfy both interfaces for ColorPoint
.
ColorPoint
satisfies Positioner
and Distancer
func (cp ColorPoint) Coordinates() Point {
return cp.Point
}
func (cp ColorPoint) DistanceTo(pos Positioner) float64 {
return distanceBetween(cp, pos)
}
This all results in our ability to interchange Point
s and ColorPoint
s in calls to DistanceTo()
(Calculating the distance between Point
and ColorPoint
). The output of these calls is found in Output of calculating the distance between Point
and ColorPoint
.
Point
and ColorPoint
fmt.Printf("Dist b/w p and q = %v\n", p.DistanceTo(r))
fmt.Printf("Dist b/w q and p = %v\n", r.DistanceTo(p))
Point
and ColorPoint
$ go run point.go
Dist b/w p and q = 2
Dist b/w q and p = 2
At first glance this may not seem so impressive, nor may it seem to be that great of an advantage over what’s available to us in Java. The power, however, is hiding just under the surface. When we think about implementing an interface in Java, we usually are thinking in terms of taxonomy. Classes extend other classes, and as we’ve previously stated, that means that a child class ought to be substitutable for its parent [LSP]. When we implement an interface in Java, we are also usually thinking that the class is a version of that interface. We might have expressed our Cartesian coordinate taxonomy in Java as:
public interface Coordinate {
double distanceTo(Coordinate c);
}
public class Point implements Coordinate {
// implementation omitted
}
public class ColorPoint extends Point implements Coordinate {
// implementation omitted
}
When we do this, we soon hear ourselves talking about Coordinate
s as things, not as groups of behaviors.
Let’s contrast this with Go’s implicit satisfaction by adding an additional example.
Perhaps our program’s purpose is to keep track of animals in a wildlife preserve.
It’s quite natural that we’d have an Animal
type, and that type would have some way of keeping track of the animal’s current location (Animal
struct).
Animal
structtype Animal struct {
Name string
X, Y float64
}
In order to perform our desired distance calculations, we need Animal
to satisfy our two interfaces (Animal
satisfies Positioner
and Distancer
).
Animal
satisfies Positioner
and Distancer
func (a Animal) Coordinates() point.Point {
return point.Point{X: a.X, Y: a.Y}
}
func (a Animal) DistanceTo(pos point.Positioner) float64 {
thing := pos.Coordinates()
sqOfXDist := math.Pow(a.X-thing.X, 2)
sqOfYDist := math.Pow(a.Y-thing.Y, 2)
return math.Sqrt(sqOfXDist + sqOfYDist)
}
|
Note
|
Because distanceBetween() was not exported from the point package, we cannot use it in the animal package. Sometimes you’ll run into this situation in Go, which prefers “dependency hygiene” over reuse.
|
And now, we can perform our desired calculations (Mixing Animal
s and Point
s using interfaces).
We now know the distance between our penguin and our original point p
, and we also know that given the proximity of the seal (Output of mixing Animal
s and Point
s using interfaces), our penguin needs to start running!
Animal
s and Point
s using interfaces penguin := animal.Animal{Name: "penguin", X: 1, Y: 1}
seal := animal.Animal{Name: "seal", X: 1, Y: 4}
fmt.Printf("Dist b/w penguin and seal = %v\n", penguin.DistanceTo(seal))
fmt.Printf("Dist b/w penguin and point = %v\n", penguin.DistanceTo(p))
Animal
s and Point
s using interfaces$ go run point.go
Dist b/w penguin and seal = 3
Dist b/w penguin and point = 1
Now for the test.
Is it proper to think of an Animal
as being a Distancer
or Positioner
in terms of taxonomy?
Not really.
In fact, that seems like a coupling of concerns.
And if we were implementing this program in Java, a naive translation would probably cause us to do the following:
public class Animal implements Positioner, Distancer
So to summarize, Go interfaces allow us to use arbitrary types in contexts expecting a particular interface type, as long as the type in question implements all of the methods defined by that interface. Since interfaces are satisfied implicitly, we’re no longer pressured toward treating interfaces as part of a type taxonomy. Instead, we’re able to focus on them as groups of related behaviors.
This may seem like a concept popularized by dynamic languages called “duck typing” [DT]. In most cases, you call a method blindly, and allow the runtime dispatch system to determine if the object can respond to that method. While this is a similar concept, it is not a very good description of how Go works. Go actually employs “structural typing” [ST], which uses the compiler to determine interface satisfaction in a type safe manner.
Conclusion
I hope you’ve enjoyed this brief introduction to the Go programming language, as well as one of its most powerful features: interfaces. With interfaces we’re able to take a more pragmatic approach to component design, as we’re not forced to think in terms of taxonomies and deep type hierarchies. In the next installment we’ll explore Go’s approach to concurrency. Until next time my fellow gophers!
References
-
[EJ] Bloch, Joshua. Effective Java: Programming Language Guide. Addison-Wesley, 2001.
-
[EUC] Euclidean distance, Wikipedia. http://en.wikipedia.org/wiki/Euclidean_distance.
-
[DT] Duck typing, Wikipedia. http://en.wikipedia.org/wiki/Duck_typing
-
[LSP] Liskov substitution principle, Wikipedia. http://en.wikipedia.org/wiki/Liskov_substitution_principle
-
[PBP] Prototype-based programing, Wikipedia. http://en.wikipedia.org/wiki/Prototype-based_programming
-
[ST] Structural type system, Wikipedia. http://en.wikipedia.org/wiki/Structural_type_system