text
stringlengths
2
1.04M
meta
dict
extern crate jsonwebtoken as jwt; extern crate rustc_serialize; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; use jwt::{encode, decode}; use jwt::header::*; use jwt::algorithm::*; use jwt::result::*; use jwt::crypto::mac_signer::MacSigner; #[derive(Debug, Serialize, Deserialize)] struct Claims { sub: String, company: String } fn main() { let my_claims = Claims { sub: "b@b.com".to_owned(), company: "ACME".to_owned() }; let signer = MacSigner::new("secret".as_bytes()).unwrap(); let mut header = Header::default(); header.kid = Some("signing_key".to_owned()); header.alg = Algorithm::HS512; let token = match encode(header, &my_claims, &signer) { Ok(t) => t, Err(_) => panic!() // in practice you would return the error }; let token_data = match decode::<Claims, MacSigner>(&token, &signer) { Ok(c) => c, Err(err) => match err { JwtError::InvalidToken => panic!(), // Example on how to handle a specific error _ => panic!() } }; println!("{:?}", token_data.claims); println!("{:?}", token_data.header); }
{ "content_hash": "4427db27232b4b0e97037438d3c5ad9e", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 92, "avg_line_length": 26.42222222222222, "alnum_prop": 0.5912531539108494, "repo_name": "cmsd2/rust-jwt", "id": "7db2ba8048625449724ba80232636857b31651b3", "size": "1190", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/custom_header.rs", "mode": "33188", "license": "mit", "language": [ { "name": "PowerShell", "bytes": "1756" }, { "name": "Rust", "bytes": "86369" }, { "name": "Shell", "bytes": "1770" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <title>Using Exceptions - Zend Framework Manual</title> </head> <body> <table width="100%"> <tr valign="top"> <td width="85%"> <table width="100%"> <tr> <td width="25%" style="text-align: left;"> <a href="zend.exception.html">Zend_Exception</a> </td> <td width="50%" style="text-align: center;"> <div class="up"><span class="up"><a href="zend.exception.html">Zend_Exception</a></span><br /> <span class="home"><a href="manual.html">Programmer's Reference Guide</a></span></div> </td> <td width="25%" style="text-align: right;"> <div class="next" style="text-align: right; float: right;"><a href="zend.exception.basic.html">Basic usage</a></div> </td> </tr> </table> <hr /> <div id="zend.exception.using" class="section"><div class="info"><h1 class="title">Using Exceptions</h1></div> <p class="para"> <span class="classname">Zend_Exception</span> is simply the base class for all exceptions thrown within Zend Framework. </p> <div class="example"><div class="info"><p><b>Example #1 Catching an Exception</b></p></div> <div class="example-contents"><p> The following code listing demonstrates how to catch an exception thrown in a Zend Framework class: </p></div> <div class="programlisting php"><div class="phpcode"><div class="php" style="font-family: monospace;"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">try <span style="color: #66cc66;">&#123;</span></div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; <span style="color: #808080; font-style: italic;">// Calling Zend_Loader::loadClass() with a non-existant class will cause</span></div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; <span style="color: #808080; font-style: italic;">// an exception to be thrown in Zend_Loader:</span></div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; Zend_Loader::<span style="color: #006600;">loadClass</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'nonexistantclass'</span><span style="color: #66cc66;">&#41;</span>;</div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#125;</span> catch <span style="color: #66cc66;">&#40;</span>Zend_Exception <span style="color: #0000ff;">$e</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span></div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; <a href="http://www.php.net/echo"><span style="color: #000066;">echo</span></a> <span style="color: #ff0000;">&quot;Caught exception: &quot;</span> . <a href="http://www.php.net/get_class"><span style="color: #000066;">get_class</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$e</span><span style="color: #66cc66;">&#41;</span> . <span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>;</div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; <a href="http://www.php.net/echo"><span style="color: #000066;">echo</span></a> <span style="color: #ff0000;">&quot;Message: &quot;</span> . <span style="color: #0000ff;">$e</span>-&gt;<span style="color: #006600;">getMessage</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> . <span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>;</div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; <span style="color: #808080; font-style: italic;">// Other code to recover from the error</span></div></li> <li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#125;</span></div></li></ol></div></div></div> </div> <p class="para"> <span class="classname">Zend_Exception</span> can be used as a catch-all exception class in a catch block to trap all exceptions thrown by Zend Framework classes. This can be useful when the program can not recover by catching a specific exception type. </p> <p class="para"> The documentation for each Zend Framework component and class will contain specific information on which methods throw exceptions, the circumstances that cause an exception to be thrown, and the various exception types that may be thrown. </p> </div> <hr /> <table width="100%"> <tr> <td width="25%" style="text-align: left;"> <a href="zend.exception.html">Zend_Exception</a> </td> <td width="50%" style="text-align: center;"> <div class="up"><span class="up"><a href="zend.exception.html">Zend_Exception</a></span><br /> <span class="home"><a href="manual.html">Programmer's Reference Guide</a></span></div> </td> <td width="25%" style="text-align: right;"> <div class="next" style="text-align: right; float: right;"><a href="zend.exception.basic.html">Basic usage</a></div> </td> </tr> </table> </td> <td style="font-size: smaller;" width="15%"> <style type="text/css"> #leftbar { float: left; width: 186px; padding: 5px; font-size: smaller; } ul.toc { margin: 0px 5px 5px 5px; padding: 0px; } ul.toc li { font-size: 85%; margin: 1px 0 1px 1px; padding: 1px 0 1px 11px; list-style-type: none; background-repeat: no-repeat; background-position: center left; } ul.toc li.header { font-size: 115%; padding: 5px 0px 5px 11px; border-bottom: 1px solid #cccccc; margin-bottom: 5px; } ul.toc li.active { font-weight: bold; } ul.toc li a { text-decoration: none; } ul.toc li a:hover { text-decoration: underline; } </style> <ul class="toc"> <li class="header home"><a href="manual.html">Programmer's Reference Guide</a></li> <li class="header up"><a href="manual.html">Programmer's Reference Guide</a></li> <li class="header up"><a href="reference.html">Zend Framework Reference</a></li> <li class="header up"><a href="zend.exception.html">Zend_Exception</a></li> <li class="active"><a href="zend.exception.using.html">Using Exceptions</a></li> <li><a href="zend.exception.basic.html">Basic usage</a></li> <li><a href="zend.exception.previous.html">Previous Exceptions</a></li> </ul> </td> </tr> </table> </body> </html>
{ "content_hash": "72250f7263116a00f018e4ecc2c1bac7", "timestamp": "", "source": "github", "line_count": 138, "max_line_length": 695, "avg_line_length": 60.76086956521739, "alnum_prop": 0.6243291592128801, "repo_name": "wukchung/Home-development", "id": "99d183e16eeec1176660d2a412e17f5f7d2dc871", "size": "8385", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "documentation/manual/core/en/zend.exception.using.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
unsync_prefix = 'dbapi' unsync_commands = [ 'commands.db_import', 'commands.db_export', ]
{ "content_hash": "3e863a78b4ef1233b0c62c219c538d1a", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 25, "avg_line_length": 16.333333333333332, "alnum_prop": 0.6428571428571429, "repo_name": "PGower/Unsync", "id": "59beee9611ed299404c3c94aff9566a6e2285190", "size": "98", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "unsync/unsync/commands/dbapi/__init__.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "133964" } ], "symlink_target": "" }
namespace Wrapperator.Wrappers.Xml.Linq { /// <summary>Represents a node that can contain other nodes.</summary> /// <filterpriority>2</filterpriority> public class XContainerWrapper : XNodeWrapper, Wrapperator.Interfaces.Xml.Linq.IXContainer { public System.Xml.Linq.XContainer _XContainer { get; private set; } internal XContainerWrapper(System.Xml.Linq.XContainer xContainer) : base(xContainer) { _XContainer = xContainer; } public Wrapperator.Interfaces.Xml.Linq.IXNode FirstNode { get { return new Wrapperator.Wrappers.Xml.Linq.XNodeWrapper(_XContainer.FirstNode); } } public Wrapperator.Interfaces.Xml.Linq.IXNode LastNode { get { return new Wrapperator.Wrappers.Xml.Linq.XNodeWrapper(_XContainer.LastNode); } } public new Wrapperator.Interfaces.Xml.Linq.IXNode NextNode { get { return new Wrapperator.Wrappers.Xml.Linq.XNodeWrapper(_XContainer.NextNode); } } public new Wrapperator.Interfaces.Xml.Linq.IXNode PreviousNode { get { return new Wrapperator.Wrappers.Xml.Linq.XNodeWrapper(_XContainer.PreviousNode); } } public new string BaseUri { get { return _XContainer.BaseUri; } } public new Wrapperator.Interfaces.Xml.Linq.IXDocument Document { get { return new Wrapperator.Wrappers.Xml.Linq.XDocumentWrapper(_XContainer.Document); } } public new System.Xml.XmlNodeType NodeType { get { return _XContainer.NodeType; } } public new Wrapperator.Interfaces.Xml.Linq.IXElement Parent { get { return new Wrapperator.Wrappers.Xml.Linq.XElementWrapper(_XContainer.Parent); } } /// <summary>Adds the specified content as children of this <see cref="T:System.Xml.Linq.XContainer" />.</summary> /// <param name="content">A content object containing simple content or a collection of content objects to be added.</param> public void Add(object content) { _XContainer.Add(content); } /// <summary>Adds the specified content as children of this <see cref="T:System.Xml.Linq.XContainer" />.</summary> /// <param name="content">A parameter list of content objects.</param> public void Add(object[] content) { _XContainer.Add(content); } /// <summary>Adds the specified content as the first children of this document or element.</summary> /// <param name="content">A content object containing simple content or a collection of content objects to be added.</param> public void AddFirst(object content) { _XContainer.AddFirst(content); } /// <summary>Adds the specified content as the first children of this document or element.</summary> /// <param name="content">A parameter list of content objects.</param> /// <exception cref="T:System.InvalidOperationException">The parent is null.</exception> public void AddFirst(object[] content) { _XContainer.AddFirst(content); } /// <summary>Creates an <see cref="T:System.Xml.XmlWriter" /> that can be used to add nodes to the <see cref="T:System.Xml.Linq.XContainer" />.</summary> /// <returns>An <see cref="T:System.Xml.XmlWriter" /> that is ready to have content written to it.</returns> /// <filterpriority>2</filterpriority> public Wrapperator.Interfaces.Xml.IXmlWriter CreateWriter() { return new Wrapperator.Wrappers.Xml.XmlWriterWrapper(_XContainer.CreateWriter()); } /// <summary>Returns a collection of the descendant nodes for this document or element, in document order.</summary> /// <returns>An <see cref="T:System.Collections.Generic.IEnumerable`1" /> of <see cref="T:System.Xml.Linq.XNode" /> containing the descendant nodes of the <see cref="T:System.Xml.Linq.XContainer" />, in document order.</returns> public System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> DescendantNodes() { return _XContainer.DescendantNodes(); } /// <summary>Returns a collection of the descendant elements for this document or element, in document order.</summary> /// <returns>An <see cref="T:System.Collections.Generic.IEnumerable`1" /> of <see cref="T:System.Xml.Linq.XElement" /> containing the descendant elements of the <see cref="T:System.Xml.Linq.XContainer" />.</returns> public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Descendants() { return _XContainer.Descendants(); } /// <summary>Returns a filtered collection of the descendant elements for this document or element, in document order. Only elements that have a matching <see cref="T:System.Xml.Linq.XName" /> are included in the collection.</summary> /// <returns>An <see cref="T:System.Collections.Generic.IEnumerable`1" /> of <see cref="T:System.Xml.Linq.XElement" /> containing the descendant elements of the <see cref="T:System.Xml.Linq.XContainer" /> that match the specified <see cref="T:System.Xml.Linq.XName" />.</returns> /// <param name="name">The <see cref="T:System.Xml.Linq.XName" /> to match.</param> public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Descendants(Wrapperator.Interfaces.Xml.Linq.IXName name) { return _XContainer.Descendants(name == null ? default(System.Xml.Linq.XName) : name._XName); } /// <summary>Gets the first (in document order) child element with the specified <see cref="T:System.Xml.Linq.XName" />.</summary> /// <returns>A <see cref="T:System.Xml.Linq.XElement" /> that matches the specified <see cref="T:System.Xml.Linq.XName" />, or null.</returns> /// <param name="name">The <see cref="T:System.Xml.Linq.XName" /> to match.</param> public Wrapperator.Interfaces.Xml.Linq.IXElement Element(Wrapperator.Interfaces.Xml.Linq.IXName name) { return new Wrapperator.Wrappers.Xml.Linq.XElementWrapper(_XContainer.Element(name == null ? default(System.Xml.Linq.XName) : name._XName)); } /// <summary>Returns a collection of the child elements of this element or document, in document order.</summary> /// <returns>An <see cref="T:System.Collections.Generic.IEnumerable`1" /> of <see cref="T:System.Xml.Linq.XElement" /> containing the child elements of this <see cref="T:System.Xml.Linq.XContainer" />, in document order.</returns> public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Elements() { return _XContainer.Elements(); } /// <summary>Returns a filtered collection of the child elements of this element or document, in document order. Only elements that have a matching <see cref="T:System.Xml.Linq.XName" /> are included in the collection.</summary> /// <returns>An <see cref="T:System.Collections.Generic.IEnumerable`1" /> of <see cref="T:System.Xml.Linq.XElement" /> containing the children of the <see cref="T:System.Xml.Linq.XContainer" /> that have a matching <see cref="T:System.Xml.Linq.XName" />, in document order.</returns> /// <param name="name">The <see cref="T:System.Xml.Linq.XName" /> to match.</param> public System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Elements(Wrapperator.Interfaces.Xml.Linq.IXName name) { return _XContainer.Elements(name == null ? default(System.Xml.Linq.XName) : name._XName); } /// <summary>Returns a collection of the child nodes of this element or document, in document order.</summary> /// <returns>An <see cref="T:System.Collections.Generic.IEnumerable`1" /> of <see cref="T:System.Xml.Linq.XNode" /> containing the contents of this <see cref="T:System.Xml.Linq.XContainer" />, in document order.</returns> public System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> Nodes() { return _XContainer.Nodes(); } /// <summary>Removes the child nodes from this document or element.</summary> public void RemoveNodes() { _XContainer.RemoveNodes(); } /// <summary>Replaces the children nodes of this document or element with the specified content.</summary> /// <param name="content">A content object containing simple content or a collection of content objects that replace the children nodes.</param> public void ReplaceNodes(object content) { _XContainer.ReplaceNodes(content); } /// <summary>Replaces the children nodes of this document or element with the specified content.</summary> /// <param name="content">A parameter list of content objects.</param> public void ReplaceNodes(object[] content) { _XContainer.ReplaceNodes(content); } /// <summary>Adds the specified content immediately after this node.</summary> /// <param name="content">A content object that contains simple content or a collection of content objects to be added after this node.</param> /// <exception cref="T:System.InvalidOperationException">The parent is null.</exception> public new void AddAfterSelf(object content) { _XContainer.AddAfterSelf(content); } /// <summary>Adds the specified content immediately after this node.</summary> /// <param name="content">A parameter list of content objects.</param> /// <exception cref="T:System.InvalidOperationException">The parent is null.</exception> public new void AddAfterSelf(object[] content) { _XContainer.AddAfterSelf(content); } /// <summary>Adds the specified content immediately before this node.</summary> /// <param name="content">A content object that contains simple content or a collection of content objects to be added before this node.</param> /// <exception cref="T:System.InvalidOperationException">The parent is null.</exception> public new void AddBeforeSelf(object content) { _XContainer.AddBeforeSelf(content); } /// <summary>Adds the specified content immediately before this node.</summary> /// <param name="content">A parameter list of content objects.</param> /// <exception cref="T:System.InvalidOperationException">The parent is null.</exception> public new void AddBeforeSelf(object[] content) { _XContainer.AddBeforeSelf(content); } /// <summary>Returns a collection of the ancestor elements of this node.</summary> /// <returns>An <see cref="T:System.Collections.Generic.IEnumerable`1" /> of <see cref="T:System.Xml.Linq.XElement" /> of the ancestor elements of this node.</returns> public new System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Ancestors() { return _XContainer.Ancestors(); } /// <summary>Returns a filtered collection of the ancestor elements of this node. Only elements that have a matching <see cref="T:System.Xml.Linq.XName" /> are included in the collection.</summary> /// <returns>An <see cref="T:System.Collections.Generic.IEnumerable`1" /> of <see cref="T:System.Xml.Linq.XElement" /> of the ancestor elements of this node. Only elements that have a matching <see cref="T:System.Xml.Linq.XName" /> are included in the collection.The nodes in the returned collection are in reverse document order.This method uses deferred execution.</returns> /// <param name="name">The <see cref="T:System.Xml.Linq.XName" /> to match.</param> public new System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> Ancestors(Wrapperator.Interfaces.Xml.Linq.IXName name) { return _XContainer.Ancestors(name == null ? default(System.Xml.Linq.XName) : name._XName); } /// <summary>Creates an <see cref="T:System.Xml.XmlReader" /> for this node.</summary> /// <returns>An <see cref="T:System.Xml.XmlReader" /> that can be used to read this node and its descendants.</returns> /// <filterpriority>2</filterpriority> public new Wrapperator.Interfaces.Xml.IXmlReader CreateReader() { return new Wrapperator.Wrappers.Xml.XmlReaderWrapper(_XContainer.CreateReader()); } /// <summary>Creates an <see cref="T:System.Xml.XmlReader" /> with the options specified by the <paramref name="readerOptions" /> parameter.</summary> /// <returns>An <see cref="T:System.Xml.XmlReader" /> object.</returns> /// <param name="readerOptions">A <see cref="T:System.Xml.Linq.ReaderOptions" /> object that specifies whether to omit duplicate namespaces.</param> public new Wrapperator.Interfaces.Xml.IXmlReader CreateReader(System.Xml.Linq.ReaderOptions readerOptions) { return new Wrapperator.Wrappers.Xml.XmlReaderWrapper(_XContainer.CreateReader(readerOptions)); } /// <summary>Returns a collection of the sibling nodes after this node, in document order.</summary> /// <returns>An <see cref="T:System.Collections.Generic.IEnumerable`1" /> of <see cref="T:System.Xml.Linq.XNode" /> of the sibling nodes after this node, in document order.</returns> public new System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> NodesAfterSelf() { return _XContainer.NodesAfterSelf(); } /// <summary>Returns a collection of the sibling nodes before this node, in document order.</summary> /// <returns>An <see cref="T:System.Collections.Generic.IEnumerable`1" /> of <see cref="T:System.Xml.Linq.XNode" /> of the sibling nodes before this node, in document order.</returns> public new System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> NodesBeforeSelf() { return _XContainer.NodesBeforeSelf(); } /// <summary>Returns a collection of the sibling elements after this node, in document order.</summary> /// <returns>An <see cref="T:System.Collections.Generic.IEnumerable`1" /> of <see cref="T:System.Xml.Linq.XElement" /> of the sibling elements after this node, in document order.</returns> public new System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> ElementsAfterSelf() { return _XContainer.ElementsAfterSelf(); } /// <summary>Returns a filtered collection of the sibling elements after this node, in document order. Only elements that have a matching <see cref="T:System.Xml.Linq.XName" /> are included in the collection.</summary> /// <returns>An <see cref="T:System.Collections.Generic.IEnumerable`1" /> of <see cref="T:System.Xml.Linq.XElement" /> of the sibling elements after this node, in document order. Only elements that have a matching <see cref="T:System.Xml.Linq.XName" /> are included in the collection.</returns> /// <param name="name">The <see cref="T:System.Xml.Linq.XName" /> to match.</param> public new System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> ElementsAfterSelf(Wrapperator.Interfaces.Xml.Linq.IXName name) { return _XContainer.ElementsAfterSelf(name == null ? default(System.Xml.Linq.XName) : name._XName); } /// <summary>Returns a collection of the sibling elements before this node, in document order.</summary> /// <returns>An <see cref="T:System.Collections.Generic.IEnumerable`1" /> of <see cref="T:System.Xml.Linq.XElement" /> of the sibling elements before this node, in document order.</returns> public new System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> ElementsBeforeSelf() { return _XContainer.ElementsBeforeSelf(); } /// <summary>Returns a filtered collection of the sibling elements before this node, in document order. Only elements that have a matching <see cref="T:System.Xml.Linq.XName" /> are included in the collection.</summary> /// <returns>An <see cref="T:System.Collections.Generic.IEnumerable`1" /> of <see cref="T:System.Xml.Linq.XElement" /> of the sibling elements before this node, in document order. Only elements that have a matching <see cref="T:System.Xml.Linq.XName" /> are included in the collection.</returns> /// <param name="name">The <see cref="T:System.Xml.Linq.XName" /> to match.</param> public new System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> ElementsBeforeSelf(Wrapperator.Interfaces.Xml.Linq.IXName name) { return _XContainer.ElementsBeforeSelf(name == null ? default(System.Xml.Linq.XName) : name._XName); } /// <summary>Determines if the current node appears after a specified node in terms of document order.</summary> /// <returns>true if this node appears after the specified node; otherwise false.</returns> /// <param name="node">The <see cref="T:System.Xml.Linq.XNode" /> to compare for document order.</param> public new bool IsAfter(Wrapperator.Interfaces.Xml.Linq.IXNode node) { return _XContainer.IsAfter(node == null ? default(System.Xml.Linq.XNode) : node._XNode); } /// <summary>Determines if the current node appears before a specified node in terms of document order.</summary> /// <returns>true if this node appears before the specified node; otherwise false.</returns> /// <param name="node">The <see cref="T:System.Xml.Linq.XNode" /> to compare for document order.</param> public new bool IsBefore(Wrapperator.Interfaces.Xml.Linq.IXNode node) { return _XContainer.IsBefore(node == null ? default(System.Xml.Linq.XNode) : node._XNode); } /// <summary>Removes this node from its parent.</summary> /// <exception cref="T:System.InvalidOperationException">The parent is null.</exception> public new void Remove() { _XContainer.Remove(); } /// <summary>Replaces this node with the specified content.</summary> /// <param name="content">Content that replaces this node.</param> public new void ReplaceWith(object content) { _XContainer.ReplaceWith(content); } /// <summary>Replaces this node with the specified content.</summary> /// <param name="content">A parameter list of the new content.</param> public new void ReplaceWith(object[] content) { _XContainer.ReplaceWith(content); } /// <summary>Writes this node to an <see cref="T:System.Xml.XmlWriter" />.</summary> /// <param name="writer">An <see cref="T:System.Xml.XmlWriter" /> into which this method will write.</param> /// <filterpriority>2</filterpriority> public new void WriteTo(Wrapperator.Interfaces.Xml.IXmlWriter writer) { _XContainer.WriteTo(writer == null ? default(System.Xml.XmlWriter) : writer._XmlWriter); } /// <summary>Adds an object to the annotation list of this <see cref="T:System.Xml.Linq.XObject" />.</summary> /// <param name="annotation">An <see cref="T:System.Object" /> that contains the annotation to add.</param> public new void AddAnnotation(object annotation) { _XContainer.AddAnnotation(annotation); } /// <summary>Gets the first annotation object of the specified type from this <see cref="T:System.Xml.Linq.XObject" />.</summary> /// <returns>The <see cref="T:System.Object" /> that contains the first annotation object that matches the specified type, or null if no annotation is of the specified type.</returns> /// <param name="type">The <see cref="T:System.Type" /> of the annotation to retrieve.</param> public new object Annotation(Wrapperator.Interfaces.IType type) { return _XContainer.Annotation(type == null ? default(System.Type) : type._Type); } /// <summary>Get the first annotation object of the specified type from this <see cref="T:System.Xml.Linq.XObject" />. </summary> /// <returns>The first annotation object that matches the specified type, or null if no annotation is of the specified type.</returns> /// <typeparam name="T">The type of the annotation to retrieve.</typeparam> public new T Annotation<T>() where T : class { return _XContainer.Annotation<T>(); } /// <summary>Gets a collection of annotations of the specified type for this <see cref="T:System.Xml.Linq.XObject" />.</summary> /// <returns>An <see cref="T:System.Collections.Generic.IEnumerable`1" /> of <see cref="T:System.Object" /> that contains the annotations that match the specified type for this <see cref="T:System.Xml.Linq.XObject" />.</returns> /// <param name="type">The <see cref="T:System.Type" /> of the annotations to retrieve.</param> public new System.Collections.Generic.IEnumerable<object> Annotations(Wrapperator.Interfaces.IType type) { return _XContainer.Annotations(type == null ? default(System.Type) : type._Type); } /// <summary>Gets a collection of annotations of the specified type for this <see cref="T:System.Xml.Linq.XObject" />.</summary> /// <returns>An <see cref="T:System.Collections.Generic.IEnumerable`1" /> that contains the annotations for this <see cref="T:System.Xml.Linq.XObject" />.</returns> /// <typeparam name="T">The type of the annotations to retrieve.</typeparam> public new System.Collections.Generic.IEnumerable<T> Annotations<T>() where T : class { return _XContainer.Annotations<T>(); } /// <summary>Removes the annotations of the specified type from this <see cref="T:System.Xml.Linq.XObject" />.</summary> /// <param name="type">The <see cref="T:System.Type" /> of annotations to remove.</param> public new void RemoveAnnotations(Wrapperator.Interfaces.IType type) { _XContainer.RemoveAnnotations(type == null ? default(System.Type) : type._Type); } /// <summary>Removes the annotations of the specified type from this <see cref="T:System.Xml.Linq.XObject" />.</summary> /// <typeparam name="T">The type of annotations to remove.</typeparam> public new void RemoveAnnotations<T>() where T : class { _XContainer.RemoveAnnotations<T>(); } } }
{ "content_hash": "dc4b89a6040858c46a0bdc87d31d93f6", "timestamp": "", "source": "github", "line_count": 400, "max_line_length": 380, "avg_line_length": 54.7, "alnum_prop": 0.6956124314442413, "repo_name": "chrischu/Wrapperator", "id": "e8b48c01aae283ab5473b67ad43aa3aaa55fe193", "size": "22277", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Wrapperator.Wrappers/Xml/Linq/XContainerWrapper.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1447" }, { "name": "C#", "bytes": "3018734" }, { "name": "PowerShell", "bytes": "4501" } ], "symlink_target": "" }
from neutron_lib.api import extensions as api_extensions from neutron_lib.api import faults from neutron_lib import exceptions as n_exc from neutron_lib.plugins import directory from oslo_config import cfg from neutron._i18n import _ from neutron.api import extensions from neutron.api.v2 import resource from neutron.db.quota import driver from neutron.db.quota import driver_nolock from neutron.extensions import quotasv2 from neutron.quota import resource_registry DETAIL_QUOTAS_ACTION = 'details' RESOURCE_NAME = 'quota' ALIAS = RESOURCE_NAME + '_' + DETAIL_QUOTAS_ACTION QUOTA_DRIVER = cfg.CONF.QUOTAS.quota_driver RESOURCE_COLLECTION = RESOURCE_NAME + "s" DB_QUOTA_DRIVERS = tuple('.'.join([klass.__module__, klass.__name__]) for klass in (driver.DbQuotaDriver, driver_nolock.DbQuotaNoLockDriver, ) ) EXTENDED_ATTRIBUTES_2_0 = { RESOURCE_COLLECTION: {} } class DetailQuotaSetsController(quotasv2.QuotaSetsController): def _get_detailed_quotas(self, request, project_id): return self._driver.get_detailed_project_quotas( request.context, resource_registry.get_all_resources(), project_id) def details(self, request, id): if id != request.context.project_id: # Check if admin if not request.context.is_admin: reason = _("Only admin is authorized to access quotas for " "another project") raise n_exc.AdminRequired(reason=reason) return {self._resource_name: self._get_detailed_quotas(request, id)} class Quotasv2_detail(api_extensions.ExtensionDescriptor): """Quota details management support.""" # Ensure new extension is not loaded with old conf driver. extensions.register_custom_supported_check( ALIAS, lambda: QUOTA_DRIVER in DB_QUOTA_DRIVERS, plugin_agnostic=True) @classmethod def get_name(cls): return "Quota details management support" @classmethod def get_alias(cls): return ALIAS @classmethod def get_description(cls): return 'Expose functions for quotas usage statistics per project' @classmethod def get_updated(cls): return "2017-02-10T10:00:00-00:00" @classmethod def get_resources(cls): """Returns Extension Resources.""" controller = resource.Resource( DetailQuotaSetsController(directory.get_plugin()), faults=faults.FAULT_MAP) return [extensions.ResourceExtension( RESOURCE_COLLECTION, controller, member_actions={'details': 'GET'}, collection_actions={'tenant': 'GET', 'project': 'GET'})] def get_extended_resources(self, version): return EXTENDED_ATTRIBUTES_2_0 if version == "2.0" else {} def get_required_extensions(self): return ["quotas"]
{ "content_hash": "2955586c5614222bd48284b94f6c895a", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 78, "avg_line_length": 33.8876404494382, "alnum_prop": 0.639920424403183, "repo_name": "openstack/neutron", "id": "5087022a5258f03a94d19bb1dabb21651752d227", "size": "3651", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "neutron/extensions/quotasv2_detail.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Jinja", "bytes": "2773" }, { "name": "Mako", "bytes": "1047" }, { "name": "Python", "bytes": "15932611" }, { "name": "Ruby", "bytes": "1257" }, { "name": "Shell", "bytes": "83270" } ], "symlink_target": "" }
package tv.floe.metronome.linearregression.iterativereduce; import java.io.DataOutputStream; import java.io.IOException; import java.util.Collection; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.util.ToolRunner; import org.apache.mahout.classifier.sgd.UniformPrior; import org.apache.mahout.math.DenseMatrix; import tv.floe.metronome.io.records.RCV1RecordFactory; import tv.floe.metronome.io.records.RecordFactory; import tv.floe.metronome.linearregression.ModelParameters; import tv.floe.metronome.linearregression.ParallelOnlineLinearRegression; import tv.floe.metronome.linearregression.ParameterVector; import tv.floe.metronome.linearregression.RegressionStatistics; import tv.floe.metronome.utils.Utils; import com.cloudera.iterativereduce.ComputableMaster; //import com.cloudera.knittingboar.messages.iterativereduce.ParameterVectorUpdateable; //import com.cloudera.knittingboar.sgd.iterativereduce.POLRNodeBase; import com.cloudera.iterativereduce.yarn.appmaster.ApplicationMaster; /* import com.cloudera.knittingboar.messages.iterativereduce.ParameterVectorGradient; import com.cloudera.knittingboar.messages.iterativereduce.ParameterVectorUpdateable; import com.cloudera.knittingboar.records.CSVBasedDatasetRecordFactory; import com.cloudera.knittingboar.records.RCV1RecordFactory; import com.cloudera.knittingboar.records.RecordFactory; import com.cloudera.knittingboar.records.TwentyNewsgroupsRecordFactory; import com.cloudera.knittingboar.sgd.GradientBuffer; import com.cloudera.knittingboar.sgd.POLRModelParameters; import com.cloudera.knittingboar.sgd.ParallelOnlineLogisticRegression; import com.cloudera.knittingboar.sgd.iterativereduce.MasterNode; */ import com.google.common.collect.Lists; public class MasterNode extends NodeBase implements ComputableMaster<ParameterVectorUpdateable> { private static final Log LOG = LogFactory.getLog(MasterNode.class); ParameterVector global_parameter_vector = null; private long total_record_count = 0; private double y_sum = 0; private double y_avg = 0; // these are only used for saving the model public ParallelOnlineLinearRegression polr = null; public ModelParameters polr_modelparams; private RecordFactory VectorFactory = null; int iteration_count = 0; @Override public ParameterVectorUpdateable compute( Collection<ParameterVectorUpdateable> workerUpdates, Collection<ParameterVectorUpdateable> masterUpdates) { int x = 0; // gets recomputed each time RegressionStatistics regStats = new RegressionStatistics(); // reset boolean iterationComplete = true; double SSyy_partial_sum = 0; double SSE_partial_sum = 0; this.global_parameter_vector.parameter_vector = new DenseMatrix(1, this.FeatureVectorSize); float avg_err = 0; long totalBatchesTimeMS = 0; for (ParameterVectorUpdateable i : workerUpdates) { totalBatchesTimeMS += i.get().batchTimeMS; // if any worker is not done with hte iteration, trip the flag if (i.get().IterationComplete == 0 ) { iterationComplete = false; } avg_err += i.get().AvgError; iteration_count = i.get().CurrentIteration; if ( 0 == i.get().CurrentIteration ) { this.y_sum += i.get().y_partial_sum; this.total_record_count += i.get().TrainedRecords; } else { SSE_partial_sum += i.get().SSE_partial_sum; SSyy_partial_sum += i.get().SSyy_partial_sum; } x++; this.global_parameter_vector.AccumulateVector(i.get().parameter_vector.viewRow(0)); } long avgBatchSpeedMS = totalBatchesTimeMS / workerUpdates.size(); System.out.println( "\n[Master] ----- Iteration " + this.iteration_count + " -------" ); System.out.println( "> Workers: " + workerUpdates.size() + " "); System.out.println( "> Avg Batch Scan Time: " + avgBatchSpeedMS + " ms"); if ( iteration_count == 0 ) { // we want to cache this for later regStats.AddPartialSumForY(this.y_sum, this.total_record_count); this.global_parameter_vector.y_avg = regStats.ComputeYAvg(); this.y_avg = regStats.ComputeYAvg(); System.out.println("" + "> Computed Y Average: " + this.global_parameter_vector.y_avg ); } else { regStats.AccumulateSSEPartialSum(SSE_partial_sum); regStats.AccumulateSSyyPartialSum(SSyy_partial_sum); double r_squared = regStats.CalculateRSquared(); System.out.println( "> " + x + " R-Squared: " + r_squared ); } avg_err = avg_err / workerUpdates.size(); System.out.println("[Master] " + " AvgError: " + avg_err ); // now average the parameter vectors together this.global_parameter_vector.AverageVectors(workerUpdates.size()); ParameterVector vec_msg = new ParameterVector(); vec_msg.parameter_vector = this.global_parameter_vector.parameter_vector .clone(); if ( iteration_count == 0 ) { vec_msg.y_avg = this.global_parameter_vector.y_avg; } ParameterVectorUpdateable return_msg = new ParameterVectorUpdateable(); return_msg.set(vec_msg); // set the master copy! this.polr.SetBeta(this.global_parameter_vector.parameter_vector.clone()); // THIS NEEDS TO BE DONE, probably automated! workerUpdates.clear(); return return_msg; } @Override public ParameterVectorUpdateable getResults() { System.err.println(">>> getResults() - null!!!"); return null; } @Override public void setup(Configuration c) { this.conf = c; try { // feature vector size this.FeatureVectorSize = LoadIntConfVarOrException( "com.cloudera.knittingboar.setup.FeatureVectorSize", "Error loading config: could not load feature vector size"); this.NumberIterations = this.conf.getInt("app.iteration.count", 1); // protected double Lambda = 1.0e-4; this.Lambda = Double.parseDouble(this.conf.get( "com.cloudera.knittingboar.setup.Lambda", "1.0e-4")); // protected double LearningRate = 50; this.LearningRate = Double.parseDouble(this.conf.get( "com.cloudera.knittingboar.setup.LearningRate", "10")); // local input split path // this.LocalInputSplitPath = LoadStringConfVarOrException( // "com.cloudera.knittingboar.setup.LocalInputSplitPath", // "Error loading config: could not load local input split path"); // maps to either CSV, 20newsgroups, or RCV1 this.RecordFactoryClassname = LoadStringConfVarOrException( "com.cloudera.knittingboar.setup.RecordFactoryClassname", "Error loading config: could not load RecordFactory classname"); if (this.RecordFactoryClassname.equals(RecordFactory.CSV_RECORDFACTORY)) { // so load the CSV specific stuff ---------- System.out .println("----- Loading CSV RecordFactory Specific Stuff -------"); // predictor label names this.PredictorLabelNames = LoadStringConfVarOrException( "com.cloudera.knittingboar.setup.PredictorLabelNames", "Error loading config: could not load predictor label names"); // predictor var types this.PredictorVariableTypes = LoadStringConfVarOrException( "com.cloudera.knittingboar.setup.PredictorVariableTypes", "Error loading config: could not load predictor variable types"); // target variables this.TargetVariableName = LoadStringConfVarOrException( "com.cloudera.knittingboar.setup.TargetVariableName", "Error loading config: Target Variable Name"); // column header names this.ColumnHeaderNames = LoadStringConfVarOrException( "com.cloudera.knittingboar.setup.ColumnHeaderNames", "Error loading config: Column Header Names"); // System.out.println("LoadConfig(): " + this.ColumnHeaderNames); } } catch (Exception e) { e.printStackTrace(); System.err.println(">> Error loading conf!"); } this.SetupPOLR(); } // setup() public void SetupPOLR() { this.global_parameter_vector = new ParameterVector(); String[] predictor_label_names = this.PredictorLabelNames.split(","); String[] variable_types = this.PredictorVariableTypes.split(","); polr_modelparams = new ModelParameters(); polr_modelparams.setTargetVariable(this.TargetVariableName); // getStringArgument(cmdLine, // target)); polr_modelparams.setNumFeatures(this.FeatureVectorSize); polr_modelparams.setUseBias(true); // !getBooleanArgument(cmdLine, noBias)); List<String> typeList = Lists.newArrayList(); for (int x = 0; x < variable_types.length; x++) { typeList.add(variable_types[x]); } List<String> predictorList = Lists.newArrayList(); for (int x = 0; x < predictor_label_names.length; x++) { predictorList.add(predictor_label_names[x]); } polr_modelparams.setTypeMap(predictorList, typeList); polr_modelparams.setLambda(this.Lambda); // based on defaults - match // command line polr_modelparams.setLearningRate(this.LearningRate); // based on defaults - // match command line // setup record factory stuff here --------- if (RecordFactory.TWENTYNEWSGROUPS_RECORDFACTORY .equals(this.RecordFactoryClassname)) { } else if (RecordFactory.RCV1_RECORDFACTORY .equals(this.RecordFactoryClassname)) { this.VectorFactory = new RCV1RecordFactory(); } else { // need to rethink this /* this.VectorFactory = new CSVBasedDatasetRecordFactory( this.TargetVariableName, polr_modelparams.getTypeMap()); ((CSVBasedDatasetRecordFactory) this.VectorFactory) .firstLine(this.ColumnHeaderNames); */ } // just set something here polr_modelparams.setTargetCategories(this.VectorFactory .getTargetCategories()); // ----- this normally is generated from the POLRModelParams ------ this.polr = new ParallelOnlineLinearRegression( this.FeatureVectorSize, new UniformPrior()).alpha(1).stepOffset(1000) .decayExponent(0.9).lambda(this.Lambda).learningRate(this.LearningRate); polr_modelparams.setPOLR(polr); } @Override public void complete(DataOutputStream out) throws IOException { System.out.println("master::complete "); System.out.println("complete-ms:" + System.currentTimeMillis()); System.out.println("\n\nComplete: "); Utils.PrintVector( this.polr.getBeta().viewRow(0) ); LOG.debug("Master complete, saving model."); try { this.polr_modelparams.saveTo(out); } catch (Exception ex) { throw new IOException("Unable to save model", ex); } } public static void main(String[] args) throws Exception { MasterNode pmn = new MasterNode(); ApplicationMaster<ParameterVectorUpdateable> am = new ApplicationMaster<ParameterVectorUpdateable>( pmn, ParameterVectorUpdateable.class); ToolRunner.run(am, args); } }
{ "content_hash": "a1b496c0256e48b80f8ef162d959c4dd", "timestamp": "", "source": "github", "line_count": 352, "max_line_length": 104, "avg_line_length": 34.3125, "alnum_prop": 0.6490312965722802, "repo_name": "codeaudit/Metronome", "id": "9ba016fee26c104fcd20c60535ec2d8cfca03d19", "size": "12078", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/tv/floe/metronome/linearregression/iterativereduce/MasterNode.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1036172" }, { "name": "Python", "bytes": "2359" }, { "name": "R", "bytes": "6576" }, { "name": "Shell", "bytes": "206" } ], "symlink_target": "" }
<?php namespace DCarbone\PHPFHIRGenerated\R4\FHIRCodePrimitive; use DCarbone\PHPFHIRGenerated\R4\FHIRCodePrimitive; use DCarbone\PHPFHIRGenerated\R4\PHPFHIRConstants; use DCarbone\PHPFHIRGenerated\R4\PHPFHIRTypeInterface; /** * Class FHIRSubscriptionStatusList * @package \DCarbone\PHPFHIRGenerated\R4\FHIRCodePrimitive */ class FHIRSubscriptionStatusList extends FHIRCodePrimitive { // name of FHIR type this class describes const FHIR_TYPE_NAME = PHPFHIRConstants::TYPE_NAME_SUBSCRIPTION_STATUS_HYPHEN_LIST; /** @var string */ private $_xmlns = 'http://hl7.org/fhir'; /** * Validation map for fields in type SubscriptionStatus-list * @var array */ private static $_validationRules = [ self::FIELD_VALUE => [ PHPFHIRConstants::VALIDATE_ENUM => ['requested','active','error','off',], ], ]; /** * FHIRSubscriptionStatusList Constructor * @param null|string $value */ public function __construct($value = null) { parent::__construct($value); } /** * @return string */ public function _getFHIRTypeName() { return self::FHIR_TYPE_NAME; } /** * @return string */ public function _getFHIRXMLElementDefinition() { $xmlns = $this->_getFHIRXMLNamespace(); if (null !== $xmlns) { $xmlns = " xmlns=\"{$xmlns}\""; } return "<SubscriptionStatus_list{$xmlns}></SubscriptionStatus_list>"; } /** * Returns the validation rules that this type's fields must comply with to be considered "valid" * The returned array is in ["fieldname[.offset]" => ["rule" => {constraint}]] * * @return array */ public function _getValidationRules() { return self::$_validationRules; } /** * Validates that this type conforms to the specifications set forth for it by FHIR. An empty array must be seen as * passing. * * @return array */ public function _getValidationErrors() { $errs = parent::_getValidationErrors(); $validationRules = $this->_getValidationRules(); if (isset($validationRules[self::FIELD_VALUE])) { $v = $this->getValue(); foreach($validationRules[self::FIELD_VALUE] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_CODE_HYPHEN_PRIMITIVE, self::FIELD_VALUE, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_VALUE])) { $errs[self::FIELD_VALUE] = []; } $errs[self::FIELD_VALUE][$rule] = $err; } } } return $errs; } /** * @param \SimpleXMLElement|string|null $sxe * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRCodePrimitive\FHIRSubscriptionStatusList $type * @param null|int $libxmlOpts * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRCodePrimitive\FHIRSubscriptionStatusList */ public static function xmlUnserialize($sxe = null, PHPFHIRTypeInterface $type = null, $libxmlOpts = 591872) { if (null === $sxe) { return null; } if (is_string($sxe)) { libxml_use_internal_errors(true); $sxe = new \SimpleXMLElement($sxe, $libxmlOpts, false); if ($sxe === false) { throw new \DomainException(sprintf('FHIRSubscriptionStatusList::xmlUnserialize - String provided is not parseable as XML: %s', implode(', ', array_map(function(\libXMLError $err) { return $err->message; }, libxml_get_errors())))); } libxml_use_internal_errors(false); } if (!($sxe instanceof \SimpleXMLElement)) { throw new \InvalidArgumentException(sprintf('FHIRSubscriptionStatusList::xmlUnserialize - $sxe value must be null, \\SimpleXMLElement, or valid XML string, %s seen', gettype($sxe))); } if (null === $type) { $type = new FHIRSubscriptionStatusList; } elseif (!is_object($type) || !($type instanceof FHIRSubscriptionStatusList)) { throw new \RuntimeException(sprintf( 'FHIRSubscriptionStatusList::xmlUnserialize - $type must be instance of \DCarbone\PHPFHIRGenerated\R4\FHIRCodePrimitive\FHIRSubscriptionStatusList or null, %s seen.', is_object($type) ? get_class($type) : gettype($type) )); } FHIRCodePrimitive::xmlUnserialize($sxe, $type); $xmlNamespaces = $sxe->getDocNamespaces(false, false); if ([] !== $xmlNamespaces) { $ns = reset($xmlNamespaces); if (false !== $ns && '' !== $ns) { $type->_xmlns = $ns; } } return $type; } /** * @param null|\SimpleXMLElement $sxe * @param null|int $libxmlOpts * @return \SimpleXMLElement */ public function xmlSerialize(\SimpleXMLElement $sxe = null, $libxmlOpts = 591872) { if (null === $sxe) { $sxe = new \SimpleXMLElement($this->_getFHIRXMLElementDefinition(), $libxmlOpts, false); } parent::xmlSerialize($sxe); return $sxe; } }
{ "content_hash": "aa7cd40c14995ee624a019c1bd443b31", "timestamp": "", "source": "github", "line_count": 152, "max_line_length": 246, "avg_line_length": 34.69736842105263, "alnum_prop": 0.5919605612438377, "repo_name": "dcarbone/php-fhir-generated", "id": "438c51e8717ca9684b6926f418c5b5a27728ca1b", "size": "8163", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/DCarbone/PHPFHIRGenerated/R4/FHIRCodePrimitive/FHIRSubscriptionStatusList.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "113066525" } ], "symlink_target": "" }
#include "test/core/end2end/end2end_tests.h" #include <stdio.h> #include <string.h> #include <grpc/byte_buffer.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/time.h> #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/iomgr/exec_ctx.h" #include "src/core/lib/slice/slice_internal.h" #include "src/core/lib/transport/metadata.h" #include "src/core/lib/transport/service_config.h" #include "test/core/end2end/cq_verifier.h" #include "test/core/end2end/tests/cancel_test_helpers.h" static void* tag(intptr_t t) { return (void*)t; } static grpc_end2end_test_fixture begin_test(grpc_end2end_test_config config, const char* test_name, cancellation_mode mode, bool use_service_config, grpc_channel_args* client_args, grpc_channel_args* server_args) { grpc_end2end_test_fixture f; gpr_log(GPR_INFO, "Running test: %s/%s/%s/%s", test_name, config.name, mode.name, use_service_config ? "service_config" : "client_api"); f = config.create_fixture(client_args, server_args); config.init_server(&f, server_args); config.init_client(&f, client_args); return f; } static gpr_timespec n_seconds_from_now(int n) { return grpc_timeout_seconds_to_deadline(n); } static gpr_timespec five_seconds_from_now(void) { return n_seconds_from_now(5); } static void drain_cq(grpc_completion_queue* cq) { grpc_event ev; do { ev = grpc_completion_queue_next(cq, five_seconds_from_now(), nullptr); } while (ev.type != GRPC_QUEUE_SHUTDOWN); } static void shutdown_server(grpc_end2end_test_fixture* f) { if (!f->server) return; grpc_server_shutdown_and_notify(f->server, f->shutdown_cq, tag(1000)); GPR_ASSERT(grpc_completion_queue_pluck(f->shutdown_cq, tag(1000), grpc_timeout_seconds_to_deadline(5), nullptr) .type == GRPC_OP_COMPLETE); grpc_server_destroy(f->server); f->server = nullptr; } static void shutdown_client(grpc_end2end_test_fixture* f) { if (!f->client) return; grpc_channel_destroy(f->client); f->client = nullptr; } static void end_test(grpc_end2end_test_fixture* f) { shutdown_server(f); shutdown_client(f); grpc_completion_queue_shutdown(f->cq); drain_cq(f->cq); grpc_completion_queue_destroy(f->cq); grpc_completion_queue_destroy(f->shutdown_cq); } /* Cancel after accept, no payload */ static void test_cancel_after_round_trip(grpc_end2end_test_config config, cancellation_mode mode, bool use_service_config) { grpc_op ops[6]; grpc_op* op; grpc_call* c; grpc_call* s; grpc_metadata_array initial_metadata_recv; grpc_metadata_array trailing_metadata_recv; grpc_metadata_array request_metadata_recv; grpc_call_details call_details; grpc_status_code status; grpc_call_error error; grpc_slice details; grpc_byte_buffer* request_payload_recv = nullptr; grpc_byte_buffer* response_payload_recv = nullptr; grpc_slice request_payload_slice = grpc_slice_from_copied_string("hello world"); grpc_slice response_payload_slice = grpc_slice_from_copied_string("hello you"); grpc_byte_buffer* request_payload = grpc_raw_byte_buffer_create(&request_payload_slice, 1); grpc_byte_buffer* response_payload1 = grpc_raw_byte_buffer_create(&response_payload_slice, 1); grpc_byte_buffer* response_payload2 = grpc_raw_byte_buffer_create(&response_payload_slice, 1); int was_cancelled = 2; grpc_channel_args* args = nullptr; if (use_service_config) { grpc_arg arg; arg.type = GRPC_ARG_STRING; arg.key = const_cast<char*>(GRPC_ARG_SERVICE_CONFIG); arg.value.string = const_cast<char*>( "{\n" " \"methodConfig\": [ {\n" " \"name\": [\n" " { \"service\": \"service\", \"method\": \"method\" }\n" " ],\n" " \"timeout\": \"5s\"\n" " } ]\n" "}"); args = grpc_channel_args_copy_and_add(args, &arg, 1); } grpc_end2end_test_fixture f = begin_test(config, "cancel_after_round_trip", mode, use_service_config, args, nullptr); cq_verifier* cqv = cq_verifier_create(f.cq); gpr_timespec deadline = use_service_config ? gpr_inf_future(GPR_CLOCK_MONOTONIC) : five_seconds_from_now(); c = grpc_channel_create_call( f.client, nullptr, GRPC_PROPAGATE_DEFAULTS, f.cq, grpc_slice_from_static_string("/service/method"), get_host_override_slice("foo.test.google.fr:1234", config), deadline, nullptr); GPR_ASSERT(c); grpc_metadata_array_init(&initial_metadata_recv); grpc_metadata_array_init(&trailing_metadata_recv); grpc_metadata_array_init(&request_metadata_recv); grpc_call_details_init(&call_details); memset(ops, 0, sizeof(ops)); op = ops; op->op = GRPC_OP_SEND_INITIAL_METADATA; op->data.send_initial_metadata.count = 0; op->flags = 0; op->reserved = nullptr; op++; op->op = GRPC_OP_SEND_MESSAGE; op->data.send_message.send_message = request_payload; op->flags = 0; op->reserved = nullptr; op++; op->op = GRPC_OP_RECV_INITIAL_METADATA; op->data.recv_initial_metadata.recv_initial_metadata = &initial_metadata_recv; op->flags = 0; op->reserved = nullptr; op++; op->op = GRPC_OP_RECV_MESSAGE; op->data.recv_message.recv_message = &response_payload_recv; op->flags = 0; op->reserved = nullptr; op++; error = grpc_call_start_batch(c, ops, static_cast<size_t>(op - ops), tag(1), nullptr); GPR_ASSERT(GRPC_CALL_OK == error); error = grpc_server_request_call(f.server, &s, &call_details, &request_metadata_recv, f.cq, f.cq, tag(101)); GPR_ASSERT(GRPC_CALL_OK == error); CQ_EXPECT_COMPLETION(cqv, tag(101), 1); cq_verify(cqv); memset(ops, 0, sizeof(ops)); op = ops; op->op = GRPC_OP_RECV_MESSAGE; op->data.recv_message.recv_message = &request_payload_recv; op->flags = 0; op->reserved = nullptr; op++; op->op = GRPC_OP_SEND_INITIAL_METADATA; op->data.send_initial_metadata.count = 0; op->flags = 0; op->reserved = nullptr; op++; op->op = GRPC_OP_SEND_MESSAGE; op->data.send_message.send_message = response_payload1; op->flags = 0; op->reserved = nullptr; op++; error = grpc_call_start_batch(s, ops, static_cast<size_t>(op - ops), tag(102), nullptr); GPR_ASSERT(GRPC_CALL_OK == error); CQ_EXPECT_COMPLETION(cqv, tag(102), 1); CQ_EXPECT_COMPLETION(cqv, tag(1), 1); cq_verify(cqv); grpc_byte_buffer_destroy(request_payload_recv); grpc_byte_buffer_destroy(response_payload_recv); request_payload_recv = nullptr; response_payload_recv = nullptr; memset(ops, 0, sizeof(ops)); op = ops; op->op = GRPC_OP_RECV_STATUS_ON_CLIENT; op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv; op->data.recv_status_on_client.status = &status; op->data.recv_status_on_client.status_details = &details; op->flags = 0; op->reserved = nullptr; op++; op->op = GRPC_OP_RECV_MESSAGE; op->data.recv_message.recv_message = &response_payload_recv; op->flags = 0; op->reserved = nullptr; op++; error = grpc_call_start_batch(c, ops, static_cast<size_t>(op - ops), tag(2), nullptr); GPR_ASSERT(GRPC_CALL_OK == error); GPR_ASSERT(GRPC_CALL_OK == mode.initiate_cancel(c, nullptr)); memset(ops, 0, sizeof(ops)); op = ops; op->op = GRPC_OP_RECV_CLOSE_ON_SERVER; op->data.recv_close_on_server.cancelled = &was_cancelled; op->flags = 0; op->reserved = nullptr; op++; op->op = GRPC_OP_SEND_MESSAGE; op->data.send_message.send_message = response_payload2; op->flags = 0; op->reserved = nullptr; op++; error = grpc_call_start_batch(s, ops, static_cast<size_t>(op - ops), tag(103), nullptr); GPR_ASSERT(GRPC_CALL_OK == error); CQ_EXPECT_COMPLETION(cqv, tag(2), 1); CQ_EXPECT_COMPLETION(cqv, tag(103), 1); cq_verify(cqv); GPR_ASSERT(status == mode.expect_status || status == GRPC_STATUS_INTERNAL); GPR_ASSERT(was_cancelled == 1); grpc_metadata_array_destroy(&initial_metadata_recv); grpc_metadata_array_destroy(&trailing_metadata_recv); grpc_metadata_array_destroy(&request_metadata_recv); grpc_call_details_destroy(&call_details); grpc_byte_buffer_destroy(request_payload); grpc_byte_buffer_destroy(response_payload1); grpc_byte_buffer_destroy(response_payload2); grpc_byte_buffer_destroy(request_payload_recv); grpc_byte_buffer_destroy(response_payload_recv); grpc_slice_unref(details); grpc_call_unref(c); grpc_call_unref(s); if (args != nullptr) { grpc_core::ExecCtx exec_ctx; grpc_channel_args_destroy(args); } cq_verifier_destroy(cqv); end_test(&f); config.tear_down_data(&f); } void cancel_after_round_trip(grpc_end2end_test_config config) { unsigned i; for (i = 0; i < GPR_ARRAY_SIZE(cancellation_modes); i++) { test_cancel_after_round_trip(config, cancellation_modes[i], false /* use_service_config */); if (config.feature_mask & FEATURE_MASK_SUPPORTS_CLIENT_CHANNEL && cancellation_modes[i].expect_status == GRPC_STATUS_DEADLINE_EXCEEDED) { test_cancel_after_round_trip(config, cancellation_modes[i], true /* use_service_config */); } } } void cancel_after_round_trip_pre_init(void) {}
{ "content_hash": "192f575a7486721ff649223da34d7bf5", "timestamp": "", "source": "github", "line_count": 292, "max_line_length": 80, "avg_line_length": 33.42465753424658, "alnum_prop": 0.6299180327868853, "repo_name": "murgatroid99/grpc", "id": "4890b3013f396c6bd4f6b678c9e324031f527da4", "size": "10362", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/core/end2end/tests/cancel_after_round_trip.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "24926" }, { "name": "C", "bytes": "1453210" }, { "name": "C#", "bytes": "1646979" }, { "name": "C++", "bytes": "28778506" }, { "name": "CMake", "bytes": "481419" }, { "name": "DTrace", "bytes": "147" }, { "name": "Go", "bytes": "27069" }, { "name": "JavaScript", "bytes": "48756" }, { "name": "M4", "bytes": "43234" }, { "name": "Makefile", "bytes": "1064586" }, { "name": "Objective-C", "bytes": "266834" }, { "name": "Objective-C++", "bytes": "21939" }, { "name": "PHP", "bytes": "340922" }, { "name": "Python", "bytes": "2227399" }, { "name": "Ruby", "bytes": "799613" }, { "name": "Shell", "bytes": "412607" }, { "name": "Swift", "bytes": "3486" } ], "symlink_target": "" }
using Microsoft.Extensions.DependencyInjection; using Castle.Windsor.MsDependencyInjection; using Abp.Dependency; using AbpCoreEf6Sample.Identity; namespace AbpCoreEf6Sample.Migrator.DependencyInjection { public static class ServiceCollectionRegistrar { public static void Register(IIocManager iocManager) { var services = new ServiceCollection(); IdentityRegistrar.Register(services); WindsorRegistrationHelper.CreateServiceProvider(iocManager.IocContainer, services); } } }
{ "content_hash": "e9a40c9d85a27be56d175cc6be607ebd", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 95, "avg_line_length": 29.05263157894737, "alnum_prop": 0.7409420289855072, "repo_name": "aspnetboilerplate/aspnetboilerplate-samples", "id": "edafcab3520675c13c18be1a9a31dd97329cd9f8", "size": "554", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AbpCoreEf6Sample/aspnet-core/src/AbpCoreEf6Sample.Migrator/DependencyInjection/ServiceCollectionRegistrar.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "810" }, { "name": "Batchfile", "bytes": "238" }, { "name": "C#", "bytes": "5155046" }, { "name": "CSS", "bytes": "2951271" }, { "name": "CoffeeScript", "bytes": "585417" }, { "name": "Dockerfile", "bytes": "2615" }, { "name": "HTML", "bytes": "7236415" }, { "name": "JavaScript", "bytes": "73730233" }, { "name": "Less", "bytes": "195106" }, { "name": "Makefile", "bytes": "9583" }, { "name": "PowerShell", "bytes": "86362" }, { "name": "Ruby", "bytes": "5150" }, { "name": "SCSS", "bytes": "1430882" }, { "name": "Sass", "bytes": "23989" }, { "name": "Shell", "bytes": "7868" }, { "name": "Stylus", "bytes": "23527" }, { "name": "TypeScript", "bytes": "140579" } ], "symlink_target": "" }
import { isPresent } from 'angular2/src/core/facade/lang'; export class DomElementBinder { constructor({ textNodeIndices, hasNestedProtoView, eventLocals, localEvents, globalEvents, hasNativeShadowRoot } = {}) { this.textNodeIndices = textNodeIndices; this.hasNestedProtoView = hasNestedProtoView; this.eventLocals = eventLocals; this.localEvents = localEvents; this.globalEvents = globalEvents; this.hasNativeShadowRoot = isPresent(hasNativeShadowRoot) ? hasNativeShadowRoot : false; } } export class Event { constructor(name, target, fullName) { this.name = name; this.target = target; this.fullName = fullName; } } export class HostAction { constructor(actionName, actionExpression, expression) { this.actionName = actionName; this.actionExpression = actionExpression; this.expression = expression; } } //# sourceMappingURL=element_binder.js.map
{ "content_hash": "8d3ac9e5b17183c6013106ffda1fa154", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 124, "avg_line_length": 38.19230769230769, "alnum_prop": 0.6807653575025177, "repo_name": "rehnen/potato", "id": "8287ae60d0cb270ede8d53954960eb524b3f3729", "size": "993", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "node_modules/angular2/es6/dev/src/core/render/dom/view/element_binder.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "575" }, { "name": "JavaScript", "bytes": "3314" }, { "name": "TypeScript", "bytes": "1112" } ], "symlink_target": "" }
package com.kumuluz.ee.javamail.ri; import com.kumuluz.ee.common.config.MailServiceConfig; import com.kumuluz.ee.common.config.MailSessionConfig; import javax.mail.Session; import java.util.Map; import java.util.Properties; import java.util.logging.Logger; public class MailSessionFactory { private final static Logger LOG = Logger.getLogger(MailSessionFactory.class.getSimpleName()); private final static String TRANSPORT_PROTOCOL_KEY = "mail.transport.protocol"; private final static String STORE_PROTOCOL_KEY = "mail.store.protocol"; static Session create(MailSessionConfig cfg) { Properties properties = new Properties(); if (cfg.getDebug() != null) { properties.setProperty("mail.debug", cfg.getDebug().toString()); } if (cfg.getTransport() != null) { if (cfg.getTransport().getProtocol() != null) { String protocol = cfg.getTransport().getProtocol(); properties.setProperty(TRANSPORT_PROTOCOL_KEY, protocol); configureService(properties, cfg.getTransport(), protocol); } else { LOG.warning("The transport protocol for the Java Mail session is not defined. Please check your configuration."); } } if (cfg.getStore() != null) { if (cfg.getStore().getProtocol() != null) { String protocol = cfg.getStore().getProtocol(); properties.setProperty(STORE_PROTOCOL_KEY, protocol); configureService(properties, cfg.getStore(), protocol); } else { LOG.warning("The store protocol for the Java Mail session is not defined. Please check your configuration."); } } if (cfg.getProps() != null && cfg.getProps().size() > 0) { for (Map.Entry<String, String> prop : cfg.getProps().entrySet()) { properties.setProperty(prop.getKey(), prop.getValue()); } } return Session.getInstance(properties, new ManagedPasswordAuthenticator(cfg)); } private static void configureService(Properties properties, MailServiceConfig serviceConfig, String protocol) { String prefix = "mail." + protocol; if (serviceConfig.getHost() != null) { properties.setProperty(prefix + ".host", serviceConfig.getHost()); } if (serviceConfig.getPort() != null) { properties.setProperty(prefix + ".port", serviceConfig.getPort().toString()); } if (serviceConfig.getStarttls() != null) { properties.setProperty(prefix + ".starttls.enable", serviceConfig.getStarttls().toString()); } if (serviceConfig.getConnectionTimeout() != null) { properties.setProperty(prefix + ".connectiontimeout", serviceConfig.getConnectionTimeout().toString()); } if (serviceConfig.getTimeout() != null) { properties.setProperty(prefix + ".timeout", serviceConfig.getTimeout().toString()); } if (serviceConfig.getPassword() != null) { properties.setProperty(prefix + ".auth", Boolean.TRUE.toString()); } } }
{ "content_hash": "ca5aeb1a3c9db5dee2d8705381c117e1", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 129, "avg_line_length": 33.416666666666664, "alnum_prop": 0.6240648379052369, "repo_name": "kumuluz/kumuluzee", "id": "d707bff02d75eee1c9d76864857ef68e27a686e7", "size": "3208", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "components/javamail/ri/src/main/java/com/kumuluz/ee/javamail/ri/MailSessionFactory.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "621378" } ], "symlink_target": "" }
<html> <head> <title>User agent detail - Mozilla/5.0 (Linux; U; Android 4.0.3; zh-cn; ZTE U808 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body> <div class="container"> <div class="section"> <h1 class="header center orange-text">User agent detail</h1> <div class="row center"> <h5 class="header light"> Mozilla/5.0 (Linux; U; Android 4.0.3; zh-cn; ZTE U808 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 </h5> </div> </div> <div class="section"> <table class="striped"><tr><th></th><th colspan="3">General</th><th colspan="5">Device</th><th colspan="3">Bot</th><th colspan="2"></th></tr><tr><th>Provider</th><th>Browser</th><th>Engine</th><th>OS</th><th>Brand</th><th>Model</th><th>Type</th><th>Is mobile</th><th>Is touch</th><th>Is bot</th><th>Name</th><th>Type</th><th>Parse time</th><th>Actions</th></tr><tr><th colspan="14" class="green lighten-3">Source result (test suite)</th></tr><tr><td>ua-parser/uap-core<br /><small>vendor/thadafinser/uap-core/tests/test_device.yaml</small></td><td> </td><td> </td><td> </td><td style="border-left: 1px solid #555">ZTE</td><td>U808</td><td></td><td></td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td></td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-test">Detail</a> <!-- Modal Structure --> <div id="modal-test" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Testsuite result detail</h4> <p><pre><code class="php">Array ( [user_agent_string] => Mozilla/5.0 (Linux; U; Android 4.0.3; zh-cn; ZTE U808 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 [family] => ZTE U808 [brand] => ZTE [model] => U808 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><th colspan="14" class="green lighten-3">Providers</th></tr><tr><td>BrowscapPhp<br /><small>6012</small></td><td>Android 4.0</td><td>WebKit </td><td>Android 4.0</td><td style="border-left: 1px solid #555"></td><td></td><td>Mobile Phone</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.016</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-215ac98d-ccf8-4615-916e-5a819d6a59c9">Detail</a> <!-- Modal Structure --> <div id="modal-215ac98d-ccf8-4615-916e-5a819d6a59c9" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>BrowscapPhp result detail</h4> <p><pre><code class="php">stdClass Object ( [browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*android.4\.0.* build\/.*\).*applewebkit\/.*\(.*khtml,.*like gecko.*\).*version\/4\.0.*safari.*$/ [browser_name_pattern] => mozilla/5.0 (*linux*android?4.0* build/*)*applewebkit/*(*khtml,*like gecko*)*version/4.0*safari* [parent] => Android Browser 4.0 [comment] => Android Browser 4.0 [browser] => Android [browser_type] => Browser [browser_bits] => 32 [browser_maker] => Google Inc [browser_modus] => unknown [version] => 4.0 [majorver] => 4 [minorver] => 0 [platform] => Android [platform_version] => 4.0 [platform_description] => Android OS [platform_bits] => 32 [platform_maker] => Google Inc [alpha] => [beta] => [win16] => [win32] => [win64] => [frames] => 1 [iframes] => 1 [tables] => 1 [cookies] => 1 [backgroundsounds] => [javascript] => 1 [vbscript] => [javaapplets] => 1 [activexcontrols] => [ismobiledevice] => 1 [istablet] => [issyndicationreader] => [crawler] => [cssversion] => 3 [aolversion] => 0 [device_name] => general Mobile Phone [device_maker] => unknown [device_type] => Mobile Phone [device_pointing_method] => touchscreen [device_code_name] => general Mobile Phone [device_brand_name] => unknown [renderingengine_name] => WebKit [renderingengine_version] => unknown [renderingengine_description] => For Google Chrome, iOS (including both mobile Safari, WebViews within third-party apps, and web clips), Safari, Arora, Midori, OmniWeb, Shiira, iCab since version 4, Web, SRWare Iron, Rekonq, and in Maxthon 3. [renderingengine_maker] => Apple Inc ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>DonatjUAParser<br /><small>v0.5.0</small></td><td>Android Browser 4.0</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-f1436016-fdf1-4aea-b4be-1d7c99ab0661">Detail</a> <!-- Modal Structure --> <div id="modal-f1436016-fdf1-4aea-b4be-1d7c99ab0661" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>DonatjUAParser result detail</h4> <p><pre><code class="php">Array ( [platform] => Android [browser] => Android Browser [version] => 4.0 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>NeutrinoApiCom<br /><small></small></td><td>Android Webkit 4.0</td><td><i class="material-icons">close</i></td><td>Android 4.0.3</td><td style="border-left: 1px solid #555">Generic</td><td>Android 4.0</td><td>mobile-browser</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.25402</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-9b0fa449-ec1b-40c8-8b1c-9486eb3b9cbc">Detail</a> <!-- Modal Structure --> <div id="modal-9b0fa449-ec1b-40c8-8b1c-9486eb3b9cbc" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>NeutrinoApiCom result detail</h4> <p><pre><code class="php">stdClass Object ( [mobile_screen_height] => 480 [is_mobile] => 1 [type] => mobile-browser [mobile_brand] => Generic [mobile_model] => Android 4.0 [version] => 4.0 [is_android] => 1 [browser_name] => Android Webkit [operating_system_family] => Android [operating_system_version] => 4.0.3 [is_ios] => [producer] => Google Inc. [operating_system] => Android 4.0.x Ice Cream Sandwich [mobile_screen_width] => 320 [mobile_browser] => Android Webkit ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>PiwikDeviceDetector<br /><small>3.5.2</small></td><td>Android Browser </td><td>WebKit </td><td>Android 4.0</td><td style="border-left: 1px solid #555">ZTE</td><td>U808</td><td>smartphone</td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.011</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-21638055-738d-46ba-a1b1-f5114bc26475">Detail</a> <!-- Modal Structure --> <div id="modal-21638055-738d-46ba-a1b1-f5114bc26475" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>PiwikDeviceDetector result detail</h4> <p><pre><code class="php">Array ( [client] => Array ( [type] => browser [name] => Android Browser [short_name] => AN [version] => [engine] => WebKit ) [operatingSystem] => Array ( [name] => Android [short_name] => AND [version] => 4.0 [platform] => ) [device] => Array ( [brand] => ZT [brandName] => ZTE [model] => U808 [device] => 1 [deviceName] => smartphone ) [bot] => [extra] => Array ( [isBot] => [isBrowser] => 1 [isFeedReader] => [isMobileApp] => [isPIM] => [isLibrary] => [isMediaPlayer] => [isCamera] => [isCarBrowser] => [isConsole] => [isFeaturePhone] => [isPhablet] => [isPortableMediaPlayer] => [isSmartDisplay] => [isSmartphone] => 1 [isTablet] => [isTV] => [isDesktop] => [isMobile] => 1 [isTouchEnabled] => ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>SinergiBrowserDetector<br /><small>6.0.0</small></td><td>Navigator 4.0</td><td><i class="material-icons">close</i></td><td>Android 4.0.3</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td></td><td><i class="material-icons">close</i></td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-5415e7f2-ef7b-434c-abe0-b71ba9f6707c">Detail</a> <!-- Modal Structure --> <div id="modal-5415e7f2-ef7b-434c-abe0-b71ba9f6707c" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>SinergiBrowserDetector result detail</h4> <p><pre><code class="php">Array ( [browser] => Sinergi\BrowserDetector\Browser Object ( [userAgent:Sinergi\BrowserDetector\Browser:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 4.0.3; zh-cn; ZTE U808 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 ) [name:Sinergi\BrowserDetector\Browser:private] => Navigator [version:Sinergi\BrowserDetector\Browser:private] => 4.0 [isRobot:Sinergi\BrowserDetector\Browser:private] => [isChromeFrame:Sinergi\BrowserDetector\Browser:private] => ) [operatingSystem] => Sinergi\BrowserDetector\Os Object ( [name:Sinergi\BrowserDetector\Os:private] => Android [version:Sinergi\BrowserDetector\Os:private] => 4.0.3 [isMobile:Sinergi\BrowserDetector\Os:private] => 1 [userAgent:Sinergi\BrowserDetector\Os:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 4.0.3; zh-cn; ZTE U808 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 ) ) [device] => Sinergi\BrowserDetector\Device Object ( [name:Sinergi\BrowserDetector\Device:private] => unknown [userAgent:Sinergi\BrowserDetector\Device:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 4.0.3; zh-cn; ZTE U808 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 ) ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UAParser<br /><small>v3.4.5</small></td><td>Android 4.0.3</td><td><i class="material-icons">close</i></td><td>Android 4.0.3</td><td style="border-left: 1px solid #555">ZTE</td><td>U808</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-346c1a98-5fd3-454f-b6c8-350f2f505d8b">Detail</a> <!-- Modal Structure --> <div id="modal-346c1a98-5fd3-454f-b6c8-350f2f505d8b" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UAParser result detail</h4> <p><pre><code class="php">UAParser\Result\Client Object ( [ua] => UAParser\Result\UserAgent Object ( [major] => 4 [minor] => 0 [patch] => 3 [family] => Android ) [os] => UAParser\Result\OperatingSystem Object ( [major] => 4 [minor] => 0 [patch] => 3 [patchMinor] => [family] => Android ) [device] => UAParser\Result\Device Object ( [brand] => ZTE [model] => U808 [family] => ZTE U808 ) [originalUserAgent] => Mozilla/5.0 (Linux; U; Android 4.0.3; zh-cn; ZTE U808 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UserAgentStringCom<br /><small></small></td><td>Android Webkit Browser </td><td><i class="material-icons">close</i></td><td>Android 4.0.3</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.04901</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-9cdd8b45-a2eb-406b-bd27-7e48af38ffd4">Detail</a> <!-- Modal Structure --> <div id="modal-9cdd8b45-a2eb-406b-bd27-7e48af38ffd4" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UserAgentStringCom result detail</h4> <p><pre><code class="php">stdClass Object ( [agent_type] => Browser [agent_name] => Android Webkit Browser [agent_version] => -- [os_type] => Android [os_name] => Android [os_versionName] => [os_versionNumber] => 4.0.3 [os_producer] => [os_producerURL] => [linux_distibution] => Null [agent_language] => Chinese - China [agent_languageTag] => zh-cn ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>WhatIsMyBrowserCom<br /><small></small></td><td>Android Browser 4.0</td><td>WebKit 534.30</td><td>Android 4.0.3</td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.40604</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-9795f66f-7271-430e-973a-a5c0e14dc35a">Detail</a> <!-- Modal Structure --> <div id="modal-9795f66f-7271-430e-973a-a5c0e14dc35a" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>WhatIsMyBrowserCom result detail</h4> <p><pre><code class="php">stdClass Object ( [operating_system_name] => Android [simple_sub_description_string] => [simple_browser_string] => Android Browser 4 on Android (Ice Cream Sandwich) [browser_version] => 4 [extra_info] => Array ( ) [operating_platform] => [extra_info_table] => stdClass Object ( [System Build] => IML74K ) [layout_engine_name] => WebKit [detected_addons] => Array ( ) [operating_system_flavour_code] => [hardware_architecture] => [operating_system_flavour] => [operating_system_frameworks] => Array ( ) [browser_name_code] => android-browser [operating_system_version] => Ice Cream Sandwich [simple_operating_platform_string] => [is_abusive] => [layout_engine_version] => 534.30 [browser_capabilities] => Array ( ) [operating_platform_vendor_name] => [operating_system] => Android (Ice Cream Sandwich) [operating_system_version_full] => 4.0.3 [operating_platform_code] => [browser_name] => Android Browser [operating_system_name_code] => android [user_agent] => Mozilla/5.0 (Linux; U; Android 4.0.3; zh-cn; ZTE U808 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 [browser_version_full] => 4.0 [browser] => Android Browser 4 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>WhichBrowser<br /><small>2.0.10</small></td><td>Android Browser </td><td>Webkit 534.30</td><td>Android 4.0.3</td><td style="border-left: 1px solid #555">ZTE</td><td>U808</td><td>mobile:smart</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.06901</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-342c8d32-4765-40a8-8a5c-af3a38d19ae4">Detail</a> <!-- Modal Structure --> <div id="modal-342c8d32-4765-40a8-8a5c-af3a38d19ae4" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>WhichBrowser result detail</h4> <p><pre><code class="php">Array ( [browser] => Array ( [name] => Android Browser ) [engine] => Array ( [name] => Webkit [version] => 534.30 ) [os] => Array ( [name] => Android [version] => 4.0.3 ) [device] => Array ( [type] => mobile [subtype] => smart [manufacturer] => ZTE [model] => U808 ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Woothee<br /><small>v1.2.0</small></td><td>Safari 4.0</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>smartphone</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-3f285ff5-314b-4db4-9948-54572e92e7b6">Detail</a> <!-- Modal Structure --> <div id="modal-3f285ff5-314b-4db4-9948-54572e92e7b6" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Woothee result detail</h4> <p><pre><code class="php">Array ( [name] => Safari [vendor] => Apple [version] => 4.0 [category] => smartphone [os] => Android [os_version] => 4.0.3 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Wurfl<br /><small>1.6.4</small></td><td>Android Webkit 4.0</td><td><i class="material-icons">close</i></td><td>Android 4.0</td><td style="border-left: 1px solid #555">ZTE</td><td>U808</td><td>Smartphone</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.05901</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-1a1aee36-7ce7-4111-a391-8e2c501f1532">Detail</a> <!-- Modal Structure --> <div id="modal-1a1aee36-7ce7-4111-a391-8e2c501f1532" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Wurfl result detail</h4> <p><pre><code class="php">Array ( [virtual] => Array ( [is_android] => true [is_ios] => false [is_windows_phone] => false [is_app] => false [is_full_desktop] => false [is_largescreen] => true [is_mobile] => true [is_robot] => false [is_smartphone] => true [is_touchscreen] => true [is_wml_preferred] => false [is_xhtmlmp_preferred] => false [is_html_preferred] => true [advertised_device_os] => Android [advertised_device_os_version] => 4.0 [advertised_browser] => Android Webkit [advertised_browser_version] => 4.0 [complete_device_name] => ZTE U808 [form_factor] => Smartphone [is_phone] => true [is_app_webview] => false ) [all] => Array ( [brand_name] => ZTE [model_name] => U808 [unique] => true [ununiqueness_handler] => [is_wireless_device] => true [device_claims_web_support] => true [has_qwerty_keyboard] => true [can_skip_aligned_link_row] => true [uaprof] => [uaprof2] => [uaprof3] => [nokia_series] => 0 [nokia_edition] => 0 [device_os] => Android [mobile_browser] => Android Webkit [mobile_browser_version] => [device_os_version] => 4.0 [pointing_method] => touchscreen [release_date] => 2011_october [marketing_name] => [model_extra_info] => [nokia_feature_pack] => 0 [can_assign_phone_number] => true [is_tablet] => false [manufacturer_name] => [is_bot] => false [is_google_glass] => false [proportional_font] => false [built_in_back_button_support] => false [card_title_support] => true [softkey_support] => false [table_support] => true [numbered_menus] => false [menu_with_select_element_recommended] => false [menu_with_list_of_links_recommended] => true [icons_on_menu_items_support] => false [break_list_of_links_with_br_element_recommended] => true [access_key_support] => false [wrap_mode_support] => false [times_square_mode_support] => false [deck_prefetch_support] => false [elective_forms_recommended] => true [wizards_recommended] => false [image_as_link_support] => false [insert_br_element_after_widget_recommended] => false [wml_can_display_images_and_text_on_same_line] => false [wml_displays_image_in_center] => false [opwv_wml_extensions_support] => false [wml_make_phone_call_string] => wtai://wp/mc; [chtml_display_accesskey] => false [emoji] => false [chtml_can_display_images_and_text_on_same_line] => false [chtml_displays_image_in_center] => false [imode_region] => none [chtml_make_phone_call_string] => tel: [chtml_table_support] => false [xhtml_honors_bgcolor] => true [xhtml_supports_forms_in_table] => true [xhtml_support_wml2_namespace] => false [xhtml_autoexpand_select] => false [xhtml_select_as_dropdown] => false [xhtml_select_as_radiobutton] => false [xhtml_select_as_popup] => false [xhtml_display_accesskey] => false [xhtml_supports_invisible_text] => false [xhtml_supports_inline_input] => false [xhtml_supports_monospace_font] => false [xhtml_supports_table_for_layout] => true [xhtml_supports_css_cell_table_coloring] => true [xhtml_format_as_css_property] => false [xhtml_format_as_attribute] => false [xhtml_nowrap_mode] => false [xhtml_marquee_as_css_property] => false [xhtml_readable_background_color1] => #FFFFFF [xhtml_readable_background_color2] => #FFFFFF [xhtml_allows_disabled_form_elements] => true [xhtml_document_title_support] => true [xhtml_preferred_charset] => iso-8859-1 [opwv_xhtml_extensions_support] => false [xhtml_make_phone_call_string] => tel: [xhtmlmp_preferred_mime_type] => text/html [xhtml_table_support] => true [xhtml_send_sms_string] => sms: [xhtml_send_mms_string] => mms: [xhtml_file_upload] => supported [cookie_support] => true [accept_third_party_cookie] => true [xhtml_supports_iframe] => full [xhtml_avoid_accesskeys] => true [xhtml_can_embed_video] => none [ajax_support_javascript] => true [ajax_manipulate_css] => true [ajax_support_getelementbyid] => true [ajax_support_inner_html] => true [ajax_xhr_type] => standard [ajax_manipulate_dom] => true [ajax_support_events] => true [ajax_support_event_listener] => true [ajax_preferred_geoloc_api] => w3c_api [xhtml_support_level] => 4 [preferred_markup] => html_web_4_0 [wml_1_1] => false [wml_1_2] => false [wml_1_3] => false [html_wi_w3_xhtmlbasic] => true [html_wi_oma_xhtmlmp_1_0] => true [html_wi_imode_html_1] => false [html_wi_imode_html_2] => false [html_wi_imode_html_3] => false [html_wi_imode_html_4] => false [html_wi_imode_html_5] => false [html_wi_imode_htmlx_1] => false [html_wi_imode_htmlx_1_1] => false [html_wi_imode_compact_generic] => false [html_web_3_2] => true [html_web_4_0] => true [voicexml] => false [multipart_support] => false [total_cache_disable_support] => false [time_to_live_support] => false [resolution_width] => 480 [resolution_height] => 800 [columns] => 60 [max_image_width] => 320 [max_image_height] => 480 [rows] => 40 [physical_screen_width] => 53 [physical_screen_height] => 88 [dual_orientation] => true [density_class] => 1.0 [wbmp] => true [bmp] => false [epoc_bmp] => false [gif_animated] => false [jpg] => true [png] => true [tiff] => false [transparent_png_alpha] => true [transparent_png_index] => true [svgt_1_1] => true [svgt_1_1_plus] => false [greyscale] => false [gif] => true [colors] => 65536 [webp_lossy_support] => true [webp_lossless_support] => false [post_method_support] => true [basic_authentication_support] => true [empty_option_value_support] => true [emptyok] => false [nokia_voice_call] => false [wta_voice_call] => false [wta_phonebook] => false [wta_misc] => false [wta_pdc] => false [https_support] => true [phone_id_provided] => false [max_data_rate] => 3600 [wifi] => true [sdio] => false [vpn] => false [has_cellular_radio] => true [max_deck_size] => 2000000 [max_url_length_in_requests] => 256 [max_url_length_homepage] => 0 [max_url_length_bookmark] => 0 [max_url_length_cached_page] => 0 [max_no_of_connection_settings] => 0 [max_no_of_bookmarks] => 0 [max_length_of_username] => 0 [max_length_of_password] => 0 [max_object_size] => 0 [downloadfun_support] => false [directdownload_support] => true [inline_support] => false [oma_support] => true [ringtone] => false [ringtone_3gpp] => false [ringtone_midi_monophonic] => false [ringtone_midi_polyphonic] => false [ringtone_imelody] => false [ringtone_digiplug] => false [ringtone_compactmidi] => false [ringtone_mmf] => false [ringtone_rmf] => false [ringtone_xmf] => false [ringtone_amr] => false [ringtone_awb] => false [ringtone_aac] => false [ringtone_wav] => false [ringtone_mp3] => false [ringtone_spmidi] => false [ringtone_qcelp] => false [ringtone_voices] => 1 [ringtone_df_size_limit] => 0 [ringtone_directdownload_size_limit] => 0 [ringtone_inline_size_limit] => 0 [ringtone_oma_size_limit] => 0 [wallpaper] => false [wallpaper_max_width] => 0 [wallpaper_max_height] => 0 [wallpaper_preferred_width] => 0 [wallpaper_preferred_height] => 0 [wallpaper_resize] => none [wallpaper_wbmp] => false [wallpaper_bmp] => false [wallpaper_gif] => false [wallpaper_jpg] => false [wallpaper_png] => false [wallpaper_tiff] => false [wallpaper_greyscale] => false [wallpaper_colors] => 2 [wallpaper_df_size_limit] => 0 [wallpaper_directdownload_size_limit] => 0 [wallpaper_inline_size_limit] => 0 [wallpaper_oma_size_limit] => 0 [screensaver] => false [screensaver_max_width] => 0 [screensaver_max_height] => 0 [screensaver_preferred_width] => 0 [screensaver_preferred_height] => 0 [screensaver_resize] => none [screensaver_wbmp] => false [screensaver_bmp] => false [screensaver_gif] => false [screensaver_jpg] => false [screensaver_png] => false [screensaver_greyscale] => false [screensaver_colors] => 2 [screensaver_df_size_limit] => 0 [screensaver_directdownload_size_limit] => 0 [screensaver_inline_size_limit] => 0 [screensaver_oma_size_limit] => 0 [picture] => false [picture_max_width] => 0 [picture_max_height] => 0 [picture_preferred_width] => 0 [picture_preferred_height] => 0 [picture_resize] => none [picture_wbmp] => false [picture_bmp] => false [picture_gif] => false [picture_jpg] => false [picture_png] => false [picture_greyscale] => false [picture_colors] => 2 [picture_df_size_limit] => 0 [picture_directdownload_size_limit] => 0 [picture_inline_size_limit] => 0 [picture_oma_size_limit] => 0 [video] => false [oma_v_1_0_forwardlock] => false [oma_v_1_0_combined_delivery] => false [oma_v_1_0_separate_delivery] => false [streaming_video] => true [streaming_3gpp] => true [streaming_mp4] => true [streaming_mov] => false [streaming_video_size_limit] => 0 [streaming_real_media] => none [streaming_flv] => false [streaming_3g2] => false [streaming_vcodec_h263_0] => 10 [streaming_vcodec_h263_3] => -1 [streaming_vcodec_mpeg4_sp] => 2 [streaming_vcodec_mpeg4_asp] => -1 [streaming_vcodec_h264_bp] => 3.0 [streaming_acodec_amr] => nb [streaming_acodec_aac] => lc [streaming_wmv] => none [streaming_preferred_protocol] => rtsp [streaming_preferred_http_protocol] => apple_live_streaming [wap_push_support] => false [connectionless_service_indication] => false [connectionless_service_load] => false [connectionless_cache_operation] => false [connectionoriented_unconfirmed_service_indication] => false [connectionoriented_unconfirmed_service_load] => false [connectionoriented_unconfirmed_cache_operation] => false [connectionoriented_confirmed_service_indication] => false [connectionoriented_confirmed_service_load] => false [connectionoriented_confirmed_cache_operation] => false [utf8_support] => true [ascii_support] => false [iso8859_support] => false [expiration_date] => false [j2me_cldc_1_0] => false [j2me_cldc_1_1] => false [j2me_midp_1_0] => false [j2me_midp_2_0] => false [doja_1_0] => false [doja_1_5] => false [doja_2_0] => false [doja_2_1] => false [doja_2_2] => false [doja_3_0] => false [doja_3_5] => false [doja_4_0] => false [j2me_jtwi] => false [j2me_mmapi_1_0] => false [j2me_mmapi_1_1] => false [j2me_wmapi_1_0] => false [j2me_wmapi_1_1] => false [j2me_wmapi_2_0] => false [j2me_btapi] => false [j2me_3dapi] => false [j2me_locapi] => false [j2me_nokia_ui] => false [j2me_motorola_lwt] => false [j2me_siemens_color_game] => false [j2me_siemens_extension] => false [j2me_heap_size] => 0 [j2me_max_jar_size] => 0 [j2me_storage_size] => 0 [j2me_max_record_store_size] => 0 [j2me_screen_width] => 0 [j2me_screen_height] => 0 [j2me_canvas_width] => 0 [j2me_canvas_height] => 0 [j2me_bits_per_pixel] => 0 [j2me_audio_capture_enabled] => false [j2me_video_capture_enabled] => false [j2me_photo_capture_enabled] => false [j2me_capture_image_formats] => none [j2me_http] => false [j2me_https] => false [j2me_socket] => false [j2me_udp] => false [j2me_serial] => false [j2me_gif] => false [j2me_gif89a] => false [j2me_jpg] => false [j2me_png] => false [j2me_bmp] => false [j2me_bmp3] => false [j2me_wbmp] => false [j2me_midi] => false [j2me_wav] => false [j2me_amr] => false [j2me_mp3] => false [j2me_mp4] => false [j2me_imelody] => false [j2me_rmf] => false [j2me_au] => false [j2me_aac] => false [j2me_realaudio] => false [j2me_xmf] => false [j2me_wma] => false [j2me_3gpp] => false [j2me_h263] => false [j2me_svgt] => false [j2me_mpeg4] => false [j2me_realvideo] => false [j2me_real8] => false [j2me_realmedia] => false [j2me_left_softkey_code] => 0 [j2me_right_softkey_code] => 0 [j2me_middle_softkey_code] => 0 [j2me_select_key_code] => 0 [j2me_return_key_code] => 0 [j2me_clear_key_code] => 0 [j2me_datefield_no_accepts_null_date] => false [j2me_datefield_broken] => false [receiver] => false [sender] => false [mms_max_size] => 0 [mms_max_height] => 0 [mms_max_width] => 0 [built_in_recorder] => false [built_in_camera] => true [mms_jpeg_baseline] => false [mms_jpeg_progressive] => false [mms_gif_static] => false [mms_gif_animated] => false [mms_png] => false [mms_bmp] => false [mms_wbmp] => false [mms_amr] => false [mms_wav] => false [mms_midi_monophonic] => false [mms_midi_polyphonic] => false [mms_midi_polyphonic_voices] => 0 [mms_spmidi] => false [mms_mmf] => false [mms_mp3] => false [mms_evrc] => false [mms_qcelp] => false [mms_ota_bitmap] => false [mms_nokia_wallpaper] => false [mms_nokia_operatorlogo] => false [mms_nokia_3dscreensaver] => false [mms_nokia_ringingtone] => false [mms_rmf] => false [mms_xmf] => false [mms_symbian_install] => false [mms_jar] => false [mms_jad] => false [mms_vcard] => false [mms_vcalendar] => false [mms_wml] => false [mms_wbxml] => false [mms_wmlc] => false [mms_video] => false [mms_mp4] => false [mms_3gpp] => false [mms_3gpp2] => false [mms_max_frame_rate] => 0 [nokiaring] => false [picturemessage] => false [operatorlogo] => false [largeoperatorlogo] => false [callericon] => false [nokiavcard] => false [nokiavcal] => false [sckl_ringtone] => false [sckl_operatorlogo] => false [sckl_groupgraphic] => false [sckl_vcard] => false [sckl_vcalendar] => false [text_imelody] => false [ems] => false [ems_variablesizedpictures] => false [ems_imelody] => false [ems_odi] => false [ems_upi] => false [ems_version] => 0 [siemens_ota] => false [siemens_logo_width] => 101 [siemens_logo_height] => 29 [siemens_screensaver_width] => 101 [siemens_screensaver_height] => 50 [gprtf] => false [sagem_v1] => false [sagem_v2] => false [panasonic] => false [sms_enabled] => true [wav] => false [mmf] => false [smf] => false [mld] => false [midi_monophonic] => false [midi_polyphonic] => false [sp_midi] => false [rmf] => false [xmf] => false [compactmidi] => false [digiplug] => false [nokia_ringtone] => false [imelody] => false [au] => false [amr] => false [awb] => false [aac] => true [mp3] => true [voices] => 1 [qcelp] => false [evrc] => false [flash_lite_version] => [fl_wallpaper] => false [fl_screensaver] => false [fl_standalone] => false [fl_browser] => false [fl_sub_lcd] => false [full_flash_support] => true [css_supports_width_as_percentage] => true [css_border_image] => webkit [css_rounded_corners] => webkit [css_gradient] => none [css_spriting] => true [css_gradient_linear] => none [is_transcoder] => false [transcoder_ua_header] => user-agent [rss_support] => false [pdf_support] => true [progressive_download] => true [playback_vcodec_h263_0] => 10 [playback_vcodec_h263_3] => -1 [playback_vcodec_mpeg4_sp] => 0 [playback_vcodec_mpeg4_asp] => -1 [playback_vcodec_h264_bp] => 3.0 [playback_real_media] => none [playback_3gpp] => true [playback_3g2] => false [playback_mp4] => true [playback_mov] => false [playback_acodec_amr] => nb [playback_acodec_aac] => none [playback_df_size_limit] => 0 [playback_directdownload_size_limit] => 0 [playback_inline_size_limit] => 0 [playback_oma_size_limit] => 0 [playback_acodec_qcelp] => false [playback_wmv] => none [hinted_progressive_download] => true [html_preferred_dtd] => html4 [viewport_supported] => true [viewport_width] => device_width_token [viewport_userscalable] => no [viewport_initial_scale] => [viewport_maximum_scale] => [viewport_minimum_scale] => [mobileoptimized] => false [handheldfriendly] => false [canvas_support] => full [image_inlining] => true [is_smarttv] => false [is_console] => false [nfc_support] => false [ux_full_desktop] => false [jqm_grade] => A [is_sencha_touch_ok] => false [controlcap_is_smartphone] => default [controlcap_is_ios] => default [controlcap_is_android] => default [controlcap_is_robot] => default [controlcap_is_app] => default [controlcap_advertised_device_os] => default [controlcap_advertised_device_os_version] => default [controlcap_advertised_browser] => default [controlcap_advertised_browser_version] => default [controlcap_is_windows_phone] => default [controlcap_is_full_desktop] => default [controlcap_is_largescreen] => default [controlcap_is_mobile] => default [controlcap_is_touchscreen] => default [controlcap_is_wml_preferred] => default [controlcap_is_xhtmlmp_preferred] => default [controlcap_is_html_preferred] => default [controlcap_form_factor] => default [controlcap_complete_device_name] => default ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr></table> </div> <div class="section"> <h1 class="header center orange-text">About this comparison</h1> <div class="row center"> <h5 class="header light"> The primary goal of this project is simple<br /> I wanted to know which user agent parser is the most accurate in each part - device detection, bot detection and so on...<br /> <br /> The secondary goal is to provide a source for all user agent parsers to improve their detection based on this results.<br /> <br /> You can also improve this further, by suggesting ideas at <a href="https://github.com/ThaDafinser/UserAgentParserComparison">ThaDafinser/UserAgentParserComparison</a><br /> <br /> The comparison is based on the abstraction by <a href="https://github.com/ThaDafinser/UserAgentParser">ThaDafinser/UserAgentParser</a> </h5> </div> </div> <div class="card"> <div class="card-content"> Comparison created <i>2016-02-13 13:31:47</i> | by <a href="https://github.com/ThaDafinser">ThaDafinser</a> </div> </div> </div> <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/list.js/1.1.1/list.min.js"></script> <script> $(document).ready(function(){ // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered $('.modal-trigger').leanModal(); }); </script> </body> </html>
{ "content_hash": "c070022734bf357ebf4deb46ed9bb65e", "timestamp": "", "source": "github", "line_count": 1122, "max_line_length": 742, "avg_line_length": 41.381461675579324, "alnum_prop": 0.5379926771483954, "repo_name": "ThaDafinser/UserAgentParserComparison", "id": "3a25f0b6987d97990de03e8dd074b6785a94d89d", "size": "46431", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "v4/user-agent-detail/5c/da/5cdabf76-4995-430e-8615-a3e2bf95e501.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2060859160" } ], "symlink_target": "" }
"""Serializer tests Initializing Serializer Loading a document Saving a document Deleting a document """ from tempfile import mkdtemp from shutil import rmtree from colliberation.document import Document from colliberation.serializer import DiskSerializer from urllib import pathname2url from unittest import TestCase import pickle class Serializer_Test(TestCase): def setUp(self): self.folder = mkdtemp() self.path = self.folder + '\\test.py' self.url = "file:" + pathname2url( self.path).replace('\\', '/').strip('///') self.data = Document(name='test.py', content='hello world', version=6, url=self.url, metadata={ 'owner': 'foo', 'date': 11306, }, serializer=None) self.serializer = DiskSerializer() def tearDown(self): self.serializer = None rmtree(self.folder) def test_load(self): file = open(self.path, 'w') pickle.dump(self.data, file) file.close() data = self.serializer.load_document(self.url) self.assertEqual( data, self.data, 'Loaded data did not match test data.') def test_save_load(self): self.serializer.save_document(self.data) data = self.serializer.load_document(self.data.url) self.assertEqual(data, self.data) def test_delete(self): pass
{ "content_hash": "938ec9241ccd552904a4ae7688f5d4be", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 68, "avg_line_length": 29.692307692307693, "alnum_prop": 0.5712435233160622, "repo_name": "Varriount/Colliberation", "id": "38b3b8ba26efeb1ae5e4b416530ef26186edd390", "size": "1544", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "colliberation/tests/test_serializer.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "509005" }, { "name": "D", "bytes": "29" }, { "name": "GAP", "bytes": "14120" }, { "name": "Objective-C", "bytes": "1291" }, { "name": "Python", "bytes": "10503398" }, { "name": "Shell", "bytes": "1512" } ], "symlink_target": "" }
package org.codenergic.eventbus; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.function.BiConsumer; import java.util.function.Consumer; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.neovisionaries.ws.client.WebSocket; import com.neovisionaries.ws.client.WebSocketAdapter; import com.neovisionaries.ws.client.WebSocketException; import com.neovisionaries.ws.client.WebSocketFrame; final class EventBusAdapter implements EventBus { private static final int CONNECTING = 0; private static final int OPEN = 1; private static final int CLOSING = 2; private static final int CLOSED = 3; private final WebSocket webSocket; private final ObjectMapper objectMapper; private final int pingInterval; private final Timer timer = new Timer(); private final ExecutorService connectThreadPool = Executors.newCachedThreadPool(); private final Map<String, List<Consumer<Message>>> messageHandlers = new ConcurrentHashMap<>(); private final Map<String, Consumer<Message>> replyHandlers = new ConcurrentHashMap<>(); private final Map<Consumer<Message>, BiConsumer<Message, Throwable>> errorHandlers = new ConcurrentHashMap<>(); private Consumer<EventBus> onOpenHandler; private Consumer<EventBus> onCloseHandler; private TimerTask pingTask; private int state = CONNECTING; EventBusAdapter(WebSocket webSocket, ObjectMapper objectMapper, int pingInterval) { this.webSocket = webSocket; this.objectMapper = objectMapper; this.pingInterval = pingInterval; init(); } @Override public void close() { state = CLOSING; webSocket.disconnect(); } private void init() { this.webSocket.addListener(new WebSocketAdapter() { @Override public void onBinaryMessage(WebSocket ws, byte[] binary) throws Exception { onMessage(binary); } @Override public void onCloseFrame(WebSocket ws, WebSocketFrame frame) { state = CLOSED; pingTask.cancel(); Optional.ofNullable(onCloseHandler).ifPresent(h -> h.accept(EventBusAdapter.this)); } @Override public void onConnected(final WebSocket ws, Map<String, List<String>> headers) { state = OPEN; pingTask = new TimerTask() { @Override public void run() { // send ping ws.sendBinary("{\"type\":\"ping\"}".getBytes()); } }; timer.schedule(pingTask, 0, pingInterval); Optional.ofNullable(onOpenHandler).ifPresent(h -> h.accept(EventBusAdapter.this)); } }); } @Override public void onClose(Consumer<EventBus> connectionHandler) { this.onCloseHandler = connectionHandler; } private void onMessage(byte[] body) throws IOException { JsonNode json = objectMapper.readTree(body); String address = json.get("address").textValue(); Message message = objectMapper.treeToValue(json, Message.class); if (messageHandlers.containsKey(address)) { List<Consumer<Message>> handlers = messageHandlers.get(address); handlers.forEach(handler -> onMessage(handler, message)); } else if (replyHandlers.containsKey(address)) { Consumer<Message> handler = replyHandlers.get(address); onMessage(handler, message); replyHandlers.remove(address); errorHandlers.remove(handler); } } private void onMessage(Consumer<Message> messageHandler, Message message) { try { messageHandler.accept(message); } catch (Exception e) { errorHandlers.get(messageHandler).accept(message, e); } } @Override public void onOpen(Consumer<EventBus> connectionHandler) { this.onOpenHandler = connectionHandler; } @Override public CompletableFuture<EventBus> open() { return CompletableFuture.supplyAsync(this::openSync, connectThreadPool); } @Override public EventBus openSync() { try { webSocket.connect(); return this; } catch (WebSocketException e) { throw new IllegalStateException(e); } } @Override public void publish(String address, String message, Map<String, Object> headers) { sendMessage(Message.MessageType.PUBLISH, address, message, headers, null, null); } @Override public void registerHandler(String address, Map<String, Object> headers, Consumer<Message> handler, BiConsumer<Message, Throwable> errorHandler) { if (!messageHandlers.containsKey(address)) { messageHandlers.put(address, new ArrayList<>()); sendMessage(Message.MessageType.REGISTER, address, null, headers, null, null); } messageHandlers.get(address).add(handler); errorHandlers.put(handler, errorHandler); } @Override public void send(String address, String message, Map<String, Object> headers, Consumer<Message> replyHandler, BiConsumer<Message, Throwable> errorHandler) { sendMessage(Message.MessageType.SEND, address, message, headers, replyHandler, errorHandler); } private void sendMessage(Message.MessageType type, String address, String message, Map<String, Object> headers, Consumer<Message> replyHandler, BiConsumer<Message, Throwable> errorHandler) { if (state != OPEN) { throw new IllegalStateException("Connection is not currently open"); } Message msg; if (Message.MessageType.SEND.equals(type) && replyHandler != null) { String replyAddress = UUID.randomUUID().toString(); msg = new Message(Message.MessageType.SEND, address, headers, message, replyAddress); replyHandlers.put(replyAddress, replyHandler); if (errorHandler != null) { errorHandlers.put(replyHandler, errorHandler); } } else { msg = new Message(type, address, headers, message); } try { webSocket.sendBinary(objectMapper.writeValueAsBytes(msg)); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } } @Override public void unregisterHandler(String address, Map<String, Object> headers, Consumer<Message> handler) { List<Consumer<Message>> handlers = messageHandlers.get(address); if (handlers == null || handlers.isEmpty()) { return; } sendMessage(Message.MessageType.UNREGISTER, address, null, headers, null, null); handlers.remove(handler); errorHandlers.remove(handler); } }
{ "content_hash": "7e0c0727e8bcb798411ee3a4d841d73f", "timestamp": "", "source": "github", "line_count": 196, "max_line_length": 157, "avg_line_length": 32.79081632653061, "alnum_prop": 0.7515170374980551, "repo_name": "codenergic/eventbus-java-client", "id": "ffb39c2c29e56af1e1b25f49d5d973921b8a09e2", "size": "7046", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/codenergic/eventbus/EventBusAdapter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "23001" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace App\Controller; use App\Entity\Seizoen; use App\Entity\Spelregels; use Doctrine\Persistence\ManagerRegistry; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; /** * @Route("/{seizoen}/spelregels") */ class SpelregelsController extends AbstractController { public function __construct( private readonly ManagerRegistry $doctrine ) { } /** * @Route ("/", name="spelregels_index") * @ParamConverter ("seizoen", options={"mapping": {"seizoen": "slug"}}) * @Template () */ public function indexAction(Request $request, Seizoen $seizoen): array { $spelregels = $this->doctrine->getRepository(Spelregels::class)->createQueryBuilder('s') ->where('s.seizoen = :seizoen')->orderBy('s.id', 'DESC')->setMaxResults(1) ->setParameter('seizoen', $seizoen) ->getQuery()->getResult()[0] ?? null; return ['spelregels' => $spelregels, 'seizoen' => $seizoen]; } }
{ "content_hash": "c0ba251b6ed99b63928a834eaef13c8d", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 96, "avg_line_length": 32.68421052631579, "alnum_prop": 0.6876006441223832, "repo_name": "ErikTrapman/cyclear", "id": "631a43420715c9619cc4630f3ebcba2551b3c355", "size": "1242", "binary": false, "copies": "1", "ref": "refs/heads/release/5.x", "path": "src/Controller/SpelregelsController.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "159822" }, { "name": "HTML", "bytes": "180184" }, { "name": "JavaScript", "bytes": "93156" }, { "name": "PHP", "bytes": "484083" }, { "name": "Shell", "bytes": "1857" }, { "name": "Twig", "bytes": "115407" } ], "symlink_target": "" }
""" Barycenters =========== This example shows three methods to compute barycenters of time series. For an overview over the available methods see the :mod:`tslearn.barycenters` module. *tslearn* provides three methods for calculating barycenters for a given set of time series: * *Euclidean barycenter* is simply the arithmetic mean for each individual point in time, minimizing the summed euclidean distance for each of them. As can be seen below, it is very different from the DTW-based methods and may often be inappropriate. However, it is the fastest of the methods shown. * *DTW Barycenter Averaging (DBA)* is an iteratively refined barycenter, starting out with a (potentially) bad candidate and improving it until convergence criteria are met. The optimization can be accomplished with (a) expectation-maximization [1] and (b) stochastic subgradient descent [2]. Empirically, the latter "is [often] more stable and finds better solutions in shorter time" [2]. * *Soft-DTW barycenter* uses a differentiable loss function to iteratively find a barycenter [3]. The method itself and the parameter :math:`\\gamma=1.0` is described in more detail in the section on :ref:`DTW<dtw>`. There is also a dedicated :ref:`example<sphx_glr_auto_examples_clustering_plot_barycenter_interpolate.py>` available. [1] F. Petitjean, A. Ketterlin & P. Gancarski. A global averaging method for dynamic time warping, with applications to clustering. Pattern Recognition, Elsevier, 2011, Vol. 44, Num. 3, pp. 678-693. [2] D. Schultz & B. Jain. Nonsmooth Analysis and Subgradient Methods for Averaging in Dynamic Time Warping Spaces. Pattern Recognition, 74, 340-358. [3] M. Cuturi & M. Blondel. Soft-DTW: a Differentiable Loss Function for Time-Series. ICML 2017. """ # Author: Romain Tavenard, Felix Divo # License: BSD 3 clause import numpy import matplotlib.pyplot as plt from tslearn.barycenters import \ euclidean_barycenter, \ dtw_barycenter_averaging, \ dtw_barycenter_averaging_subgradient, \ softdtw_barycenter from tslearn.datasets import CachedDatasets # fetch the example data set numpy.random.seed(0) X_train, y_train, _, _ = CachedDatasets().load_dataset("Trace") X = X_train[y_train == 2] length_of_sequence = X.shape[1] def plot_helper(barycenter): # plot all points of the data set for series in X: plt.plot(series.ravel(), "k-", alpha=.2) # plot the given barycenter of them plt.plot(barycenter.ravel(), "r-", linewidth=2) # plot the four variants with the same number of iterations and a tolerance of # 1e-3 where applicable ax1 = plt.subplot(4, 1, 1) plt.title("Euclidean barycenter") plot_helper(euclidean_barycenter(X)) plt.subplot(4, 1, 2, sharex=ax1) plt.title("DBA (vectorized version of Petitjean's EM)") plot_helper(dtw_barycenter_averaging(X, max_iter=50, tol=1e-3)) plt.subplot(4, 1, 3, sharex=ax1) plt.title("DBA (subgradient descent approach)") plot_helper(dtw_barycenter_averaging_subgradient(X, max_iter=50, tol=1e-3)) plt.subplot(4, 1, 4, sharex=ax1) plt.title("Soft-DTW barycenter ($\gamma$=1.0)") plot_helper(softdtw_barycenter(X, gamma=1., max_iter=50, tol=1e-3)) # clip the axes for better readability ax1.set_xlim([0, length_of_sequence]) # show the plot(s) plt.tight_layout() plt.show()
{ "content_hash": "669b505415203aa60b4ad06a5c9d354d", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 82, "avg_line_length": 35.858695652173914, "alnum_prop": 0.7405274325553198, "repo_name": "rtavenar/tslearn", "id": "6dd2c6c973c9bcb21383b1193e132e4257056aae", "size": "3323", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "docs/examples/clustering/plot_barycenters.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Batchfile", "bytes": "6703" }, { "name": "Makefile", "bytes": "6789" }, { "name": "Python", "bytes": "444385" } ], "symlink_target": "" }
module.exports = { IOSBroadcast: require('./IOSBroadcast'), AddroidGroupcast: require('./IOSGroupcast'), IOSUnicast: require('./IOSUnicast'), IOSCustomizedcast: require('./IOSCustomizedcast') };
{ "content_hash": "5ea9d4a74b441be21a0fe7519cb3a379", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 50, "avg_line_length": 33, "alnum_prop": 0.7424242424242424, "repo_name": "Evilcome/umeng-node-sdk", "id": "affd9137eec25cfe53758e8af40fa779a1ffa4f5", "size": "198", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/notification/ios/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "10097" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. ~ ~ 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. --> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <servlet> <servlet-name>JsonLogService</servlet-name> <servlet-class>org.wso2.cep.sample.JsonConsumerLogService</servlet-class> </servlet> <servlet-mapping> <servlet-name>JsonLogService</servlet-name> <url-pattern>/log</url-pattern> </servlet-mapping> <servlet> <servlet-name>XmlLogService</servlet-name> <servlet-class>org.wso2.cep.sample.XmlConsumerLogService</servlet-class> </servlet> <servlet-mapping> <servlet-name>XmlLogService</servlet-name> <url-pattern>/xmllog</url-pattern> </servlet-mapping> </web-app>
{ "content_hash": "498c8f4288ec9f5ae6d1c9aed2369c2f", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 81, "avg_line_length": 36.627906976744185, "alnum_prop": 0.6730158730158731, "repo_name": "udani969/product-cep", "id": "4cd80c8891753a85f5deeffe19dd38ae8a3bc4cc", "size": "1575", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "modules/samples/consumers/http-performance/src/main/webapp/WEB-INF/web.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2270" }, { "name": "CSS", "bytes": "153211" }, { "name": "HTML", "bytes": "62982" }, { "name": "Handlebars", "bytes": "2864" }, { "name": "Java", "bytes": "927507" }, { "name": "JavaScript", "bytes": "2524985" }, { "name": "Shell", "bytes": "3219" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _05.Use_Your_Chains__Buddy { class Program { static void Main(string[] args) { } } }
{ "content_hash": "ce42bf18f8e70725e0e62f84f36213ea", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 39, "avg_line_length": 16.6, "alnum_prop": 0.642570281124498, "repo_name": "AlexanderStanev/SoftUni", "id": "45cf7946d782f0186291746f527d7127da75b54f", "size": "251", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "TechModule/RegexExercise/05. Use Your Chains, Buddy/Program.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "626874" }, { "name": "CSS", "bytes": "153135" }, { "name": "HTML", "bytes": "20403" }, { "name": "PHP", "bytes": "5839" } ], "symlink_target": "" }
#include <unistd.h> #include "../lib/iface_locators.h" #include "../lib/sockets.h" #include "../lib/mem_util.h" #include "../lib/oor_log.h" #include "../lib/timers_utils.h" #include "../lib/util.h" #include "lisp_xtr.h" typedef struct _timer_map_reg_argument { map_local_entry_t *mle; map_server_elt *ms; } timer_map_reg_argument; typedef struct _timer_encap_map_reg_argument { map_local_entry_t *mle; map_server_elt *ms; locator_t *src_loct; lisp_addr_t *rtr_rloc; } timer_encap_map_reg_argument; typedef struct _timer_inf_req_argument { map_local_entry_t *mle; locator_t *loct; map_server_elt *ms; }timer_inf_req_argument; static oor_ctrl_dev_t *xtr_ctrl_alloc(); static int xtr_ctrl_construct(oor_ctrl_dev_t *dev); static void xtr_ctrl_dealloc(oor_ctrl_dev_t *dev); static void xtr_ctrl_destruct(oor_ctrl_dev_t *dev); static void xtr_run(oor_ctrl_dev_t *dev); static int xtr_recv_msg(oor_ctrl_dev_t *dev, lbuf_t *msg, uconn_t *uc); static int xtr_if_link_update(oor_ctrl_dev_t *dev, char *iface_name, uint8_t status); int xtr_if_addr_update(oor_ctrl_dev_t *dev, char *iface_name, lisp_addr_t *old_addr, lisp_addr_t *new_addr, uint8_t status); int xtr_route_update(oor_ctrl_dev_t *dev, int command, char *iface_name ,lisp_addr_t *src_pref, lisp_addr_t *dst_pref, lisp_addr_t *gateway); static fwd_info_t * xtr_get_forwarding_entry(oor_ctrl_dev_t *dev, packet_tuple_t *tuple); /*************************** PROCESS MESSAGES ********************************/ static int xtr_recv_enc_ctrl_msg(lisp_xtr_t *xtr, lbuf_t *msg, void **ecm_hdr, uconn_t *int_uc); static int xtr_recv_map_request(lisp_xtr_t *xtr, lbuf_t *buf, void *ecm_hdr, uconn_t *int_uc, uconn_t *ext_uc); static inline int xtr_recv_map_reply(lisp_xtr_t *xtr, lbuf_t *buf, uconn_t *uc); static int xtr_recv_map_notify(lisp_xtr_t *xtr, lbuf_t *buf); static int xtr_recv_info_nat(lisp_xtr_t *xtr, lbuf_t *buf, uconn_t *uc); static int xtr_build_and_send_map_reg(lisp_xtr_t * xtr, mapping_t * m, map_server_elt *ms, uint64_t nonce); static int xtr_build_and_send_encap_map_reg(lisp_xtr_t * xtr, mapping_t * m, map_server_elt *ms, lisp_addr_t *etr_addr, lisp_addr_t *rtr_addr, uint64_t nonce); static int xtr_build_and_send_smr_mreq(lisp_xtr_t *xtr, mapping_t *smap, lisp_addr_t *deid, lisp_addr_t *drloc); static int xtr_build_and_send_info_req(lisp_xtr_t * xtr, mapping_t * m, locator_t *loct, map_server_elt *ms, uint64_t nonce); /**************************** LOGICAL PROCESSES ******************************/ /****************************** Map Register *********************************/ static int xtr_program_map_register_for_mapping(lisp_xtr_t *xtr, map_local_entry_t *mle); static int xtr_map_register_cb(oor_timer_t *timer); /****************************** Encap Map Register ***************************/ static int xtr_encap_map_register_cb(oor_timer_t *timer); static int xtr_program_encap_map_reg_of_loct_for_map(lisp_xtr_t *xtr, map_local_entry_t *mle, locator_t *src_loct); /*********************************** SMR *************************************/ static void xtr_smr_process_start(lisp_xtr_t *xtr); static int xtr_smr_notify_mcache_entry(lisp_xtr_t *xtr, mapping_t *src_map, mapping_t *dst_map); static int xtr_smr_process_start_cb(oor_timer_t *timer); static int xtr_program_smr(lisp_xtr_t *xtr, int time); static glist_t * xtr_get_map_local_entry_to_smr(lisp_xtr_t *xtr); /****************************** Info Request *********************************/ static int xtr_program_initial_info_request_process(lisp_xtr_t *xtr); static int xtr_program_info_req_per_loct(lisp_xtr_t *xtr, map_local_entry_t *mle, locator_t *loct); static int xtr_info_request_cb(oor_timer_t *timer); /**************************** AUXILIAR FUNCTIONS *****************************/ static int xtr_iface_event_signaling(lisp_xtr_t * xtr, iface_locators * if_loct); /****************************** NAT traversal ********************************/ static int xtr_update_nat_info(lisp_xtr_t *xtr, map_local_entry_t *mle, locator_t *loct, glist_t *rtr_list); static void xtr_update_rtrs_caches(lisp_xtr_t *xtr); static void xtr_update_rtrs_cache_afi(lisp_xtr_t *xtr, int afi); static glist_t * nat_select_rtrs(glist_t * rtr_list); /*****************************************************************************/ static map_local_entry_t * get_map_loc_ent_containing_loct_ptr(local_map_db_t *local_db, locator_t *locator); /******************************* TIMERS **************************************/ static timer_map_reg_argument * timer_map_reg_argument_new_init(map_local_entry_t *mle, map_server_elt *ms); static void timer_map_reg_arg_free(timer_map_reg_argument * timer_arg); static timer_encap_map_reg_argument * timer_encap_map_reg_argument_new_init(map_local_entry_t *mle, map_server_elt *ms, locator_t *src_loct, lisp_addr_t *rtr_addr); static void timer_encap_map_reg_arg_free(timer_encap_map_reg_argument * timer_arg); static void timer_encap_map_reg_stop_using_locator(map_local_entry_t *mle, locator_t *loct); static timer_inf_req_argument * timer_inf_req_argument_new_init(map_local_entry_t *mle, locator_t *loct, map_server_elt *ms); static void timer_inf_req_arg_free(timer_inf_req_argument * timer_arg); static void timer_inf_req_stop_using_locator(map_local_entry_t *mle, locator_t *loct); /* implementation of ctrl base functions */ ctrl_dev_class_t xtr_ctrl_class = { .alloc = xtr_ctrl_alloc, .construct = xtr_ctrl_construct, .dealloc = xtr_ctrl_dealloc, .destruct = xtr_ctrl_destruct, .run = xtr_run, .recv_msg = xtr_recv_msg, .if_link_update = xtr_if_link_update, .if_addr_update = xtr_if_addr_update, .route_update = xtr_route_update, .get_fwd_entry = xtr_get_forwarding_entry }; static oor_ctrl_dev_t * xtr_ctrl_alloc() { lisp_xtr_t *xtr; xtr = xzalloc(sizeof(lisp_xtr_t)); return(&xtr->super); } static int xtr_ctrl_construct(oor_ctrl_dev_t *dev) { lisp_xtr_t *xtr = lisp_xtr_cast(dev); lisp_addr_t addr; mapping_t *pxtr_4_map, *pxtr_6_map; mcache_entry_t *def_ipv4_mc, *def_ipv6_mc; lisp_tr_init(&xtr->tr); /* set up databases */ xtr->local_mdb = local_map_db_new(); xtr->map_servers = glist_new_managed((glist_del_fct)map_server_elt_del); xtr->pitrs = glist_new_managed((glist_del_fct)lisp_addr_del); def_ipv4_mc = mcache_entry_new(); def_ipv6_mc = mcache_entry_new(); if (!xtr->local_mdb || !xtr->map_servers || !xtr->pitrs || !def_ipv4_mc || !def_ipv6_mc) { return(BAD); } /* Add entries used to add the PeTR or RTRs in case of NAT */ lisp_addr_ippref_from_char(FULL_IPv4_ADDRESS_SPACE, &addr); pxtr_4_map = mapping_new_init(&addr); mapping_set_action(pxtr_4_map,ACT_NATIVE_FWD); mcache_entry_init_static(def_ipv4_mc, pxtr_4_map); mcache_add_entry(xtr->tr.map_cache,mcache_entry_eid(def_ipv4_mc),def_ipv4_mc); lisp_addr_ippref_from_char(FULL_IPv6_ADDRESS_SPACE, &addr); pxtr_6_map = mapping_new_init(&addr); mapping_set_action(pxtr_6_map,ACT_NATIVE_FWD); mcache_entry_init_static(def_ipv6_mc, pxtr_6_map); mcache_add_entry(xtr->tr.map_cache,mcache_entry_eid(def_ipv6_mc),def_ipv6_mc); OOR_LOG(LDBG_1, "Finished constructing xTR"); return(GOOD); } static void xtr_ctrl_dealloc(oor_ctrl_dev_t *dev) { lisp_xtr_t *xtr = lisp_xtr_cast(dev); free(xtr); OOR_LOG(LDBG_1, "Freed xTR ..."); } static void xtr_ctrl_destruct(oor_ctrl_dev_t *dev) { map_local_entry_t * map_loc_e; void *it; lisp_xtr_t *xtr = lisp_xtr_cast(dev); lisp_tr_uninit(&xtr->tr); local_map_db_foreach_entry(xtr->local_mdb, it) { map_loc_e = (map_local_entry_t *)it; ctrl_unregister_mapping_dp(dev,map_local_entry_mapping(map_loc_e)); } local_map_db_foreach_end; local_map_db_del(xtr->local_mdb); glist_destroy(xtr->pitrs); glist_destroy(xtr->map_servers); oor_timer_stop(xtr->smr_timer); OOR_LOG(LDBG_1,"xTR device destroyed"); } static void xtr_run(oor_ctrl_dev_t *dev) { lisp_xtr_t *xtr = lisp_xtr_cast(dev); map_local_entry_t *map_loc_e; mcache_entry_t *ipv4_petrs_mc,*ipv6_petrs_mc; locator_t *loct; void *it; int num_eids = 0; if (xtr->super.mode == MN_MODE){ OOR_LOG(LDBG_1, "\nStarting xTR MN ...\n"); } if (xtr->super.mode == xTR_MODE){ OOR_LOG(LDBG_1, "\nStarting xTR ...\n"); } if (glist_size(xtr->map_servers) == 0) { OOR_LOG(LWRN, "**** NO MAP SERVER CONFIGURED. Your EID will not be registered in the Mapping System."); oor_timer_sleep(2); } if (glist_size(xtr->tr.map_resolvers) == 0) { OOR_LOG(LCRIT, "**** NO MAP RESOLVER CONFIGURED. You can not request mappings from the mapping system"); oor_timer_sleep(2); } ipv4_petrs_mc = get_proxy_etrs_for_afi(&xtr->tr, AF_INET); ipv6_petrs_mc = get_proxy_etrs_for_afi(&xtr->tr, AF_INET6);; if (mcache_has_locators(ipv4_petrs_mc) == FALSE && mcache_has_locators(ipv6_petrs_mc) == FALSE) { OOR_LOG(LWRN, "No Proxy-ETR defined. Packets to non-LISP destinations " "will be forwarded natively (no LISP encapsulation). This " "may prevent mobility in some scenarios."); oor_timer_sleep(2); } else { xtr->tr.fwd_policy->updated_map_cache_inf(xtr->tr.fwd_policy_dev_parm,ipv4_petrs_mc); notify_datap_rm_fwd_from_entry(&(xtr->super),mcache_entry_eid(ipv4_petrs_mc),FALSE); xtr->tr.fwd_policy->updated_map_cache_inf(xtr->tr.fwd_policy_dev_parm,ipv6_petrs_mc); notify_datap_rm_fwd_from_entry(&(xtr->super),mcache_entry_eid(ipv6_petrs_mc),FALSE); } /* Check configured parameters when NAT-T activated. */ if (xtr->nat_aware == TRUE) { if (glist_size(xtr->map_servers) > 1) { OOR_LOG(LERR, "NAT aware on -> This version of OOR is limited to one Map Server."); exit_cleanup(); } if (glist_size(xtr->map_servers) == 1 && lisp_addr_ip_afi(((map_server_elt *)glist_first_data(xtr->map_servers))->address) != AF_INET) { OOR_LOG(LERR, "NAT aware on -> This version of OOR is limited to IPv4 Map Server."); exit_cleanup(); } if (glist_size(xtr->tr.map_resolvers) > 0) { OOR_LOG(LINF, "NAT aware on -> No Map Resolver will be used."); glist_remove_all(xtr->tr.map_resolvers); } if (xtr->tr.probe_interval > 0) { xtr->tr.probe_interval = 0; OOR_LOG(LINF, "NAT aware on -> disabling RLOC probing"); } /* Set local locators to unreachable*/ local_map_db_foreach_entry(xtr->local_mdb, it) { map_loc_e = (map_local_entry_t *)it; num_eids++; if (num_eids > 1){ OOR_LOG(LERR, "NAT aware on -> Only one EID prefix supported."); exit_cleanup(); } mapping_foreach_locator(map_local_entry_mapping(map_loc_e),loct){ locator_set_R_bit(loct,0); /* We don't support LCAF in NAT */ if (lisp_addr_lafi(locator_addr(loct)) == LM_AFI_LCAF){ OOR_LOG(LERR, "NAT aware on -> This version of OOR doesn't support LCAF when NAT is enabled."); exit_cleanup(); } }mapping_foreach_locator_end; OOR_LOG(LERR, "NAT aware on -> Removing PETRs"); /* Remove PeTR. The locators will be used for RTRs */ mapping_remove_locators(mcache_entry_mapping(ipv4_petrs_mc)); mapping_remove_locators(mcache_entry_mapping(ipv6_petrs_mc)); } local_map_db_foreach_end; } if (xtr->super.mode == MN_MODE){ /* Check number of EID prefixes */ if (local_map_db_num_ip_eids(xtr->local_mdb, AF_INET) > 1) { OOR_LOG(LERR, "OOR in mobile node mode only supports one IPv4 EID " "prefix and one IPv6 EID prefix"); exit_cleanup(); } if (local_map_db_num_ip_eids(xtr->local_mdb, AF_INET6) > 1) { OOR_LOG(LERR, "OOR in mobile node mode only supports one IPv4 EID " "prefix and one IPv6 EID prefix"); exit_cleanup(); } } OOR_LOG(LDBG_1, "\n"); OOR_LOG(LDBG_1, " ****** Summary of the xTR configuration ******\n"); local_map_db_dump(xtr->local_mdb, LDBG_1); mcache_dump_db(xtr->tr.map_cache, LDBG_1); map_servers_dump(xtr, LDBG_1); OOR_LOG(LDBG_1, "************* %13s ***************", "Map Resolvers"); glist_dump(xtr->tr.map_resolvers, (glist_to_char_fct)lisp_addr_to_char, LDBG_1); OOR_LOG(LDBG_1, "*******************************************\n"); proxy_etrs_dump(xtr, LDBG_1); OOR_LOG(LDBG_1, "************* %13s ***************", "Proxy-ITRs"); glist_dump(xtr->pitrs, (glist_to_char_fct)lisp_addr_to_char, LDBG_1); OOR_LOG(LDBG_1, "*******************************************\n"); if (glist_size(xtr->tr.allowed_dst_eids) != 0){ OOR_LOG(LDBG_1, "************* %13s ***************", "Allowed dst. EIDs"); glist_dump(xtr->tr.allowed_dst_eids, (glist_to_char_fct)lisp_addr_to_char, LDBG_1); OOR_LOG(LDBG_1, "*******************************************\n"); } local_map_db_foreach_entry(xtr->local_mdb, it) { /* Register EID prefix to control */ map_loc_e = (map_local_entry_t *)it; if (ctrl_register_mapping_dp(&(xtr->super),map_local_entry_mapping(map_loc_e))!=GOOD){ OOR_LOG(LERR, "Couldn't register the mapping %s in the data plane", lisp_addr_to_char(map_local_entry_eid(map_loc_e))); exit_cleanup(); } /* Update forwarding info of the local mappings. When it is created during conf file process, * the local rlocs are not set. For this reason should be calculated again. It can not be removed * from the conf file process -> In future could appear fwd_map_info parameters*/ xtr->tr.fwd_policy->updated_map_loc_inf(xtr->tr.fwd_policy_dev_parm,map_loc_e); } local_map_db_foreach_end; if (xtr->nat_aware){ xtr_program_initial_info_request_process(xtr); }else{ /* SMR proxy-ITRs list to be updated with new mappings. * Initial Map register is sent during this process */ xtr_program_smr(xtr, 1); } /* RLOC Probing proxy ETRs */ tr_program_mce_rloc_probing(&xtr->tr, ipv4_petrs_mc); tr_program_mce_rloc_probing(&xtr->tr, ipv6_petrs_mc); } static int xtr_recv_msg(oor_ctrl_dev_t *dev, lbuf_t *msg, uconn_t *uc) { int ret = 0; lisp_msg_type_e type; lisp_xtr_t *xtr = lisp_xtr_cast(dev); void *ecm_hdr = NULL; uconn_t *int_uc, *ext_uc = NULL, aux_uc; type = lisp_msg_type(msg); if (type == LISP_ENCAP_CONTROL_TYPE) { if (xtr_recv_enc_ctrl_msg(xtr, msg, &ecm_hdr, &aux_uc)!=GOOD){ return (BAD); } type = lisp_msg_type(msg); ext_uc = uc; int_uc = &aux_uc; OOR_LOG(LDBG_1, "xTR: Received Encapsulated %s", lisp_msg_hdr_to_char(msg)); }else{ int_uc = uc; } switch (type) { case LISP_MAP_REQUEST: ret = xtr_recv_map_request(xtr, msg, ecm_hdr, int_uc, ext_uc); break; case LISP_MAP_REPLY: ret = xtr_recv_map_reply(xtr, msg, int_uc); break; case LISP_MAP_REGISTER: break; case LISP_MAP_NOTIFY: ret = xtr_recv_map_notify(xtr, msg); break; case LISP_INFO_NAT: ret = xtr_recv_info_nat(xtr, msg, int_uc); break; default: OOR_LOG(LDBG_1, "xTR: Unidentified type (%d) control message received", type); ret = BAD; break; } if (ret != GOOD) { OOR_LOG(LDBG_1,"xTR: Failed to process LISP control message"); return (BAD); } else { OOR_LOG(LDBG_3, "xTR: Completed processing of LISP control message"); return (ret); } } static int xtr_if_link_update(oor_ctrl_dev_t *dev, char *iface_name, uint8_t status) { lisp_xtr_t * xtr = lisp_xtr_cast(dev); iface_locators * if_loct = NULL; locator_t * locator = NULL; map_local_entry_t * map_loc_e = NULL; glist_entry_t * it = NULL; glist_entry_t * it_m = NULL; if_loct = (iface_locators *)shash_lookup(xtr->tr.iface_locators_table,iface_name); if (if_loct == NULL){ OOR_LOG(LDBG_2, "xtr_if_status_change: Iface %s not found in the list of ifaces for xTR device", iface_name); return (BAD); } /* Change the status of the affected locators */ glist_for_each_entry(it,if_loct->ipv4_locators){ locator = (locator_t *)glist_entry_data(it); locator_set_state(locator,status); } glist_for_each_entry(it,if_loct->ipv6_locators){ locator = (locator_t *)glist_entry_data(it); locator_set_state(locator,status); } /* Transition check */ if (if_loct->status_changed == TRUE){ if_loct->status_changed = FALSE; }else{ if_loct->status_changed = TRUE; } /* Recalculate forwarding info of the affected mappings */ glist_for_each_entry(it_m, if_loct->map_loc_entries){ map_loc_e = (map_local_entry_t *)glist_entry_data(it_m); xtr->tr.fwd_policy->updated_map_loc_inf(xtr->tr.fwd_policy_dev_parm,map_loc_e); notify_datap_rm_fwd_from_entry(&(xtr->super),map_local_entry_eid(map_loc_e),TRUE); } xtr_iface_event_signaling(xtr, if_loct); return (GOOD); } int xtr_if_addr_update(oor_ctrl_dev_t *dev, char *iface_name, lisp_addr_t *old_addr, lisp_addr_t *new_addr, uint8_t status) { lisp_xtr_t * xtr = lisp_xtr_cast(dev); iface_locators * if_loct = NULL; glist_t * loct_list = NULL; glist_t * locators = NULL; locator_t * locator = NULL; map_local_entry_t * map_loc_e = NULL; mapping_t * mapping = NULL; int afi = AF_UNSPEC; glist_entry_t * it = NULL; glist_entry_t * it_aux = NULL; glist_entry_t * it_m = NULL; lisp_addr_t ** prev_addr = NULL; if_loct = (iface_locators *)shash_lookup(xtr->tr.iface_locators_table,iface_name); if (if_loct == NULL){ OOR_LOG(LDBG_2, "xtr_if_addr_update: Iface %s not found in the list of ifaces for xTR device", iface_name); return (BAD); } if (lisp_addr_cmp(old_addr, new_addr) == 0){ return (GOOD); } /*Check if the address has been removed*/ if (lisp_addr_is_no_addr(new_addr)){ /* Process removed address */ if (lisp_addr_lafi(old_addr) == AF_INET){ locators = if_loct->ipv4_locators; prev_addr = &(if_loct->ipv4_prev_addr); }else{ locators = if_loct->ipv6_locators; prev_addr = &(if_loct->ipv6_prev_addr); } glist_for_each_entry_safe(it,it_aux,locators){ locator = (locator_t *)glist_entry_data(it); if (!lisp_addr_is_ip(locator_addr(locator))){ OOR_LOG(LERR,"OOR doesn't support change of non IP locator!!!"); } map_loc_e = get_map_loc_ent_containing_loct_ptr(xtr->local_mdb,locator); if(map_loc_e == NULL){ continue; } mapping = map_local_entry_mapping(map_loc_e); mapping_desactivate_locator(mapping,locator); /* Recalculate forwarding info of the mappings with activated locators */ xtr->tr.fwd_policy->updated_map_loc_inf(xtr->tr.fwd_policy_dev_parm,map_loc_e); notify_datap_rm_fwd_from_entry(&(xtr->super),map_local_entry_eid(map_loc_e),TRUE); } /* prev_addr is the previous address before starting the transition process */ if (*prev_addr == NULL){ *prev_addr = lisp_addr_clone(old_addr); } goto done; } /* Process new address */ afi = lisp_addr_lafi(new_addr) == LM_AFI_IP ? lisp_addr_ip_afi(new_addr) : AF_UNSPEC; switch(afi){ case AF_INET: locators = if_loct->ipv4_locators; prev_addr = &(if_loct->ipv4_prev_addr); break; case AF_INET6: locators = if_loct->ipv6_locators; prev_addr = &(if_loct->ipv6_prev_addr); break; default: OOR_LOG(LDBG_2, "xtr_if_addr_update: AFI of the new address not known"); return (BAD); } /* Update the address of the affected locators */ glist_for_each_entry_safe(it,it_aux,locators){ locator = (locator_t *)glist_entry_data(it); /* The locator was not active during init process */ if (lisp_addr_is_no_addr(locator_addr(locator))==TRUE){ /* If locator was not active, activate it */ map_loc_e = get_map_loc_ent_containing_loct_ptr(xtr->local_mdb,locator); if(map_loc_e == NULL){ continue; } /* Check if exists an active locator with the same address. * If it exists, remove not activated locator: Duplicated */ mapping = map_local_entry_mapping(map_loc_e); if (mapping_get_loct_with_addr(mapping,new_addr) != NULL){ OOR_LOG(LDBG_2, "xtr_if_addr_change: A non active locator is duplicated. Removing it"); loct_list = mapping_get_loct_lst_with_afi(mapping,LM_AFI_NO_ADDR,0); iface_locators_unattach_locator(xtr->tr.iface_locators_table,locator); glist_remove_obj_with_ptr(locator,loct_list); continue; } /* Activate locator */ mapping_activate_locator(mapping,locator,new_addr); /* Recalculate forwarding info of the mappings with activated locators */ xtr->tr.fwd_policy->updated_map_loc_inf(xtr->tr.fwd_policy_dev_parm,map_loc_e); notify_datap_rm_fwd_from_entry(&(xtr->super),map_local_entry_eid(map_loc_e),TRUE); }else{ if (!lisp_addr_is_ip(locator_addr(locator))){ OOR_LOG(LERR,"OOR doesn't support change of non IP locator!!!"); } locator_clone_addr(locator,new_addr); } } /* Transition check */ /* prev_addr is the previous address before starting the transition process */ if (*prev_addr != NULL){ if (lisp_addr_cmp(*prev_addr, new_addr) == 0){ lisp_addr_del(*prev_addr); *prev_addr = NULL; } }else{ if (old_addr != NULL){ *prev_addr = lisp_addr_clone(old_addr); }else{ *prev_addr = lisp_addr_new_lafi(LM_AFI_NO_ADDR); } } /* Reorder locators */ glist_for_each_entry(it_m, if_loct->map_loc_entries){ map_loc_e = (map_local_entry_t *)glist_entry_data(it_m); mapping = map_local_entry_mapping(map_loc_e); mapping_sort_locators(mapping, new_addr); } done: xtr_iface_event_signaling(xtr, if_loct); return (GOOD); } int xtr_route_update(oor_ctrl_dev_t *dev, int command, char *iface_name ,lisp_addr_t *src_pref, lisp_addr_t *dst_pref, lisp_addr_t *gateway) { lisp_xtr_t * xtr = lisp_xtr_cast(dev); iface_locators * if_loct = NULL; if_loct = (iface_locators *)shash_lookup(xtr->tr.iface_locators_table,iface_name); xtr_iface_event_signaling(xtr, if_loct); return (GOOD); } static fwd_info_t * xtr_get_forwarding_entry(oor_ctrl_dev_t *dev, packet_tuple_t *tuple) { lisp_xtr_t *xtr = lisp_xtr_cast(dev); fwd_info_t *fwd_info; mcache_entry_t *mce = NULL, *mce_petrs = NULL; map_local_entry_t *map_loc_e = NULL; lisp_addr_t *eid, *simple_eid; lisp_addr_t *src_eid, *dst_eid; int iidmlen; uint8_t native_fwd = FALSE; fwd_info = fwd_info_new(); if(fwd_info == NULL){ OOR_LOG(LWRN, "tr_get_fwd_entry: Couldn't allocate memory for fwd_info_t"); return (NULL); } /* lookup local mapping for source EID */ map_loc_e = local_map_db_lookup_eid(xtr->local_mdb, &tuple->src_addr, FALSE); if (!map_loc_e){ // In VPP we should continue with the pocess in order to crete a route to the gatway address #ifndef VPP OOR_LOG(LDBG_3, "The source address %s is not a local EID. This should never happen", lisp_addr_to_char(&tuple->src_addr)); return (NULL); #else native_fwd = TRUE; fwd_info->neg_map_reply_act = ACT_NATIVE_FWD; eid = &tuple->src_addr; simple_eid = eid; #endif }else{ eid = map_local_entry_eid(map_loc_e); simple_eid = lisp_addr_get_ip_pref_addr(eid); if (lisp_addr_is_iid(eid)){ tuple->iid = lcaf_iid_get_iid(lisp_addr_get_lcaf(eid)); }else{ tuple->iid = 0; } } if (tuple->iid > 0){ iidmlen = 32; src_eid = lisp_addr_new_init_iid(tuple->iid, &tuple->src_addr, iidmlen); dst_eid = lisp_addr_new_init_iid(tuple->iid, &tuple->dst_addr, iidmlen); }else{ src_eid = lisp_addr_clone(&tuple->src_addr); dst_eid = lisp_addr_clone(&tuple->dst_addr); } /* Get the mcache entry for destination EID */ if (xtr->nat_aware){ // Map cache entry of RTRs mce = mcache_get_all_space_entry(xtr->tr.map_cache, lisp_addr_ip_afi( &tuple->dst_addr)); }else{ mce = mcache_lookup(xtr->tr.map_cache, dst_eid); } if (!mce) { /* No map cache entry, initiate map cache miss process */ OOR_LOG(LDBG_1, "No map cache for EID %s. Sending Map-Request!", lisp_addr_to_char(dst_eid)); handle_map_cache_miss(&xtr->tr, dst_eid, src_eid); /* Get the temporal mce created */ mce = mcache_lookup(xtr->tr.map_cache, dst_eid); fwd_info->associated_entry = lisp_addr_clone(mcache_entry_eid(mce)); } else{ fwd_info->associated_entry = lisp_addr_clone(mcache_entry_eid(mce)); if (mcache_entry_active(mce) == NOT_ACTIVE) { OOR_LOG(LDBG_2, "Already sent Map-Request for %s. Waiting for reply!", lisp_addr_to_char(dst_eid)); } } mce_petrs = get_proxy_etrs_for_afi(&xtr->tr, lisp_addr_ip_afi(simple_eid)); /* native_fwd can be TRUE for VPP if src packet is not an EID */ if (!native_fwd){ xtr->tr.fwd_policy->get_fwd_info(xtr->tr.fwd_policy_dev_parm,map_loc_e,mce,mce_petrs,tuple, fwd_info); } /* Assign encapsulated that should be used */ fwd_info->encap = xtr->tr.encap_type; lisp_addr_del(src_eid); lisp_addr_del(dst_eid); return (fwd_info); } inline lisp_xtr_t * lisp_xtr_cast(oor_ctrl_dev_t *dev) { /* make sure */ lm_assert(dev->ctrl_class == &xtr_ctrl_class); return(CONTAINER_OF(dev, lisp_xtr_t, super)); } /*************************** PROCESS MESSAGES ********************************/ static int xtr_recv_enc_ctrl_msg(lisp_xtr_t *xtr, lbuf_t *msg, void **ecm_hdr, uconn_t *int_uc) { packet_tuple_t inner_tuple; *ecm_hdr = lisp_msg_pull_ecm_hdr(msg); if (ECM_SECURITY_BIT(*ecm_hdr)){ switch (lisp_ecm_auth_type(msg)){ default: OOR_LOG(LDBG_2, "Not supported ECM auth type %d",lisp_ecm_auth_type(msg)); return (BAD); } } if (lisp_msg_parse_int_ip_udp(msg) != GOOD) { return (BAD); } pkt_parse_inner_5_tuple(msg, &inner_tuple); uconn_init(int_uc, inner_tuple.dst_port, inner_tuple.src_port, &inner_tuple.dst_addr,&inner_tuple.src_addr); *ecm_hdr = lbuf_lisp_hdr(msg); return (GOOD); } static int xtr_recv_map_request(lisp_xtr_t *xtr, lbuf_t *buf, void *ecm_hdr, uconn_t *int_uc, uconn_t *ext_uc) { lisp_addr_t *seid = NULL; lisp_addr_t *deid = NULL; lisp_addr_t *smr_src_eid, *smr_req_eid, *aux_eid; map_local_entry_t *map_loc_e = NULL; mapping_t *map = NULL; glist_t *itr_rlocs = NULL; void *mreq_hdr = NULL; void *mrep_hdr = NULL; int i = 0; lbuf_t *mrep = NULL; lbuf_t b; uconn_t send_uc; /* local copy of the buf that can be modified */ b = *buf; seid = lisp_addr_new(); deid = lisp_addr_new(); mreq_hdr = lisp_msg_pull_hdr(&b); if (lisp_msg_parse_addr(&b, seid) != GOOD) { goto err; } if (MREQ_RLOC_PROBE(mreq_hdr) && MREQ_REC_COUNT(mreq_hdr) > 1) { OOR_LOG(LDBG_1, "More than one EID record in RLOC probe. Discarding!"); goto err; } if (MREQ_SMR(mreq_hdr) && MREQ_REC_COUNT(mreq_hdr) > 1) { OOR_LOG(LDBG_1, "More than one EID record in SMR request. Discarding!"); goto err; } /* Process additional ITR RLOCs */ itr_rlocs = laddr_list_new(); lisp_msg_parse_itr_rlocs(&b, itr_rlocs); /* Process records and build Map-Reply */ mrep = lisp_msg_create(LISP_MAP_REPLY); for (i = 0; i < MREQ_REC_COUNT(mreq_hdr); i++) { if (lisp_msg_parse_eid_rec(&b, deid) != GOOD) { goto err; } OOR_LOG(LDBG_1, " dst-eid: %s", lisp_addr_to_char(deid)); /* Check the existence of the requested EID */ map_loc_e = local_map_db_lookup_eid(xtr->local_mdb, deid, TRUE); if (!map_loc_e) { OOR_LOG(LDBG_1,"EID %s not locally configured!", lisp_addr_to_char(deid)); goto err; } map = map_local_entry_mapping(map_loc_e); lisp_msg_put_mapping(mrep, map, MREQ_RLOC_PROBE(mreq_hdr) ? &int_uc->la: NULL); /* If packet is a Solicit Map Request, process it */ if (lisp_addr_lafi(seid) != LM_AFI_NO_ADDR && MREQ_SMR(mreq_hdr)) { /* The req EID of the received msg which is a prefix will be the src EID of the new msg. It is converted to IP */ aux_eid = lisp_addr_get_ip_pref_addr(deid); lisp_addr_set_lafi(aux_eid,LM_AFI_IP); //aux_eid is part of deid-> we convert deid to IP smr_src_eid = deid; smr_req_eid = seid; if(tr_reply_to_smr(&xtr->tr,smr_src_eid,smr_req_eid) != GOOD) { goto err; } /* Return if RLOC probe bit is not set */ if (!MREQ_RLOC_PROBE(mreq_hdr)) { goto done; }; } } mrep_hdr = lisp_msg_hdr(mrep); MREP_RLOC_PROBE(mrep_hdr) = MREQ_RLOC_PROBE(mreq_hdr); MREP_NONCE(mrep_hdr) = MREQ_NONCE(mreq_hdr); /* SEND MAP-REPLY */ if (map_reply_fill_uconn(&xtr->super, itr_rlocs, int_uc, ext_uc, &send_uc) != GOOD){ OOR_LOG(LDBG_1, "Couldn't send Map-Reply, no itr_rlocs reachable"); goto err; } OOR_LOG(LDBG_1, "Sending %s", lisp_msg_hdr_to_char(mrep)); send_msg(&xtr->super, mrep, &send_uc); done: glist_destroy(itr_rlocs); lisp_msg_destroy(mrep); lisp_addr_del(seid); lisp_addr_del(deid); return(GOOD); err: glist_destroy(itr_rlocs); lisp_msg_destroy(mrep); lisp_addr_del(seid); lisp_addr_del(deid); return(BAD); } static inline int xtr_recv_map_reply(lisp_xtr_t *xtr, lbuf_t *buf, uconn_t *uc) { return (tr_recv_map_reply(&xtr->tr,buf,uc)); } static int xtr_recv_map_notify(lisp_xtr_t *xtr, lbuf_t *buf) { lisp_addr_t *eid; map_local_entry_t *map_loc_e; mapping_t *m; void *hdr, *auth_hdr; locator_t *probed ; map_server_elt *ms; nonces_list_t *nonces_lst; oor_timer_t *timer; timer_map_reg_argument *timer_arg_mn; timer_encap_map_reg_argument *timer_arg_emn; int i, res = BAD; lbuf_t b; /* local copy */ b = *buf; hdr = lisp_msg_pull_hdr(&b); /* Check NONCE */ nonces_lst = htable_nonces_lookup(nonces_ht, MNTF_NONCE(hdr)); if (!nonces_lst){ OOR_LOG(LDBG_1, "No Map Register sent with nonce: %"PRIx64 " Discarding message!", htonll(MNTF_NONCE(hdr))); return(BAD); } timer = nonces_list_timer(nonces_lst); if (MNTF_I_BIT(hdr)==1){ OOR_LOG(LDBG_1,"Received Data Map-Notify"); timer_arg_emn = (timer_encap_map_reg_argument *)oor_timer_cb_argument(timer); ms = timer_arg_emn->ms; if (MNTF_R_BIT(hdr)==1){ /* We subtract the RTR authentication field. Is not used in the authentication * calculation of the map notify.*/ // XXX Speculate that this field is removed by RTR so length is 0 lbuf_set_size(buf, lbuf_size(buf) - sizeof(auth_record_hdr_t)); } }else{ timer_arg_mn = (timer_map_reg_argument *)oor_timer_cb_argument(timer); ms = timer_arg_mn->ms; } auth_hdr = lisp_msg_pull_auth_field(&b); res = lisp_msg_check_auth_field(buf,auth_hdr, ms->key); if (res != GOOD){ OOR_LOG(LDBG_1, "Map-Notify message is invalid"); return(BAD); } for (i = 0; i < MNTF_REC_COUNT(hdr); i++) { m = mapping_new(); if (lisp_msg_parse_mapping_record(&b, m, &probed) != GOOD) { mapping_del(m); return(BAD); } eid = mapping_eid(m); map_loc_e = local_map_db_lookup_eid_exact(xtr->local_mdb, eid); if (!map_loc_e) { OOR_LOG(LDBG_1, "Map-Notify confirms registration of UNKNOWN EID %s." " Dropping!", lisp_addr_to_char(eid)); continue; } OOR_LOG(LDBG_1, "Map-Notify message confirms correct registration of %s", lisp_addr_to_char(eid)); OOR_LOG(LDBG_1, "Scheduling next Map-Register in %d seconds", MAP_REGISTER_INTERVAL); mapping_del(m); htable_nonces_reset_nonces_lst(nonces_ht,nonces_lst); oor_timer_start(timer,MAP_REGISTER_INTERVAL); } return(GOOD); } static int xtr_recv_info_nat(lisp_xtr_t *xtr, lbuf_t *buf, uconn_t *uc) { lisp_addr_t *inf_reply_eid, *inf_req_eid, *nat_lcaf_addr, *rtr_addr; void *info_nat_hdr, *info_nat_hdr_2, *auth_hdr; lbuf_t b; nonces_list_t *nonces_lst; timer_inf_req_argument *timer_arg; int len, ttl; glist_t *rtr_lst, *final_rtr_lst; glist_entry_t *rtr_it; map_local_entry_t *mle; mapping_t *map; uint8_t smr_required = FALSE; /* local copy of the buf that can be modified */ b = *buf; info_nat_hdr = lisp_msg_pull_hdr(&b); if (INF_REQ_R_bit(info_nat_hdr) == INFO_REQUEST){ OOR_LOG(LDBG_1, "xTR received an Info-Request. Discarding message"); return(BAD); } /* Check NONCE */ nonces_lst = htable_nonces_lookup(nonces_ht, INF_REQ_NONCE(info_nat_hdr)); if (!nonces_lst){ OOR_LOG(LDBG_2, " Nonce %"PRIx64" doesn't match any Info-Request nonce. " "Discarding message!", htonll(INF_REQ_NONCE(info_nat_hdr))); return(BAD); } timer_arg = oor_timer_cb_argument(nonces_list_timer(nonces_lst)); mle = timer_arg->mle; auth_hdr = lisp_msg_pull_auth_field(&b); info_nat_hdr_2 = lbuf_pull(&b, sizeof(info_nat_hdr_2_t)); /* Get EID prefix for the info reply and compare with the one of the info request*/ inf_reply_eid = lisp_addr_new(); len = lisp_addr_parse(lbuf_data(&b), inf_reply_eid); if (len <= 0) { lisp_addr_del(inf_reply_eid); return(BAD); } lbuf_pull(&b, len); lisp_addr_set_plen(inf_reply_eid, INF_REQ_2_EID_MASK(info_nat_hdr_2)); inf_req_eid = map_local_entry_eid(mle); if (lisp_addr_cmp(inf_reply_eid,inf_req_eid)!=0){ OOR_LOG(LDBG_2, "EID from Info-Request and Info-Reply are different (%s - %s)", lisp_addr_to_char(inf_req_eid),lisp_addr_to_char(inf_reply_eid)); lisp_addr_del(inf_reply_eid); return (BAD); } lisp_addr_del(inf_reply_eid); /* We obtain the key to use in the authentication process from the argument of the timer */ if (lisp_msg_check_auth_field(buf,auth_hdr,timer_arg->ms->key) != GOOD) { OOR_LOG(LDBG_1, "Info-Reply message validation failed for EID %s with key " "%s. Stopping processing!", lisp_addr_to_char(inf_req_eid), timer_arg->ms->key); return (BAD); } nat_lcaf_addr = lisp_addr_new(); len = lisp_addr_parse(lbuf_data(&b), nat_lcaf_addr); if (len <= 0) { lisp_addr_del(nat_lcaf_addr); OOR_LOG(LDBG_2, "tr_recv_info_nat: Can not parse NAT LCAF address"); return(BAD); } rtr_lst = nat_type_get_rtr_addr_lst(lcaf_addr_get_nat(lisp_addr_get_lcaf(nat_lcaf_addr))); /* Select the RTR list to use */ final_rtr_lst = nat_select_rtrs(rtr_lst); if (glist_size(final_rtr_lst) == 0){ OOR_LOG(LDBG_1, "Info-Reply Message doesn't have any compatible RTR"); glist_destroy(final_rtr_lst); lisp_addr_del(nat_lcaf_addr); return (BAD); } /* Check if selected RTR list has changed */ map = map_local_entry_mapping(mle); glist_for_each_entry(rtr_it,final_rtr_lst){ rtr_addr = (lisp_addr_t *)glist_entry_data(rtr_it); if (!mapping_get_loct_with_addr(map,rtr_addr)){ smr_required = TRUE; break; } } if (xtr_update_nat_info(xtr,mle,timer_arg->loct,final_rtr_lst) == GOOD){ /* Configure Encap Map Register */ xtr_program_encap_map_reg_of_loct_for_map(xtr, mle,timer_arg->loct); /* Reprogram time for next Info Request interval */ htable_nonces_reset_nonces_lst(nonces_ht,nonces_lst); ttl = ntohl(INF_REQ_2_TTL(info_nat_hdr_2)); oor_timer_start(nonces_lst->timer, ttl*60); OOR_LOG(LDBG_1,"Info-Request of %s to %s from locator %s scheduled in %d minutes.", lisp_addr_to_char(map_local_entry_eid(mle)), lisp_addr_to_char(timer_arg->ms->address), lisp_addr_to_char(locator_addr(timer_arg->loct)), ttl); } /* SMR proxy-ITRs list to be updated with new mappings */ if (smr_required){ OOR_LOG(LDBG_1,"Selected RTR list has changed. Programming SMR"); xtr_program_smr(xtr, 1); } lisp_addr_del(nat_lcaf_addr); glist_destroy(final_rtr_lst); return (GOOD); } /* build and send generic map-register with one record * for each map server */ static int xtr_build_and_send_map_reg(lisp_xtr_t * xtr, mapping_t * m, map_server_elt *ms, uint64_t nonce) { lbuf_t * b = NULL; void * hdr, *auth_hdr; lisp_addr_t * drloc = NULL; uconn_t uc; b = lisp_msg_mreg_create(m, ms->key_type); if (!b) { return(BAD); } hdr = lisp_msg_hdr(b); MREG_PROXY_REPLY(hdr) = ms->proxy_reply; MREG_NONCE(hdr) = nonce; auth_hdr = hdr + sizeof(info_nat_hdr_t); if (lisp_msg_fill_auth_data(b,auth_hdr,ms->key_type, ms->key) != GOOD) { return(BAD); } drloc = ms->address; OOR_LOG(LDBG_1, "%s, EID: %s, MS: %s", lisp_msg_hdr_to_char(b), lisp_addr_to_char(mapping_eid(m)), lisp_addr_to_char(drloc)); uconn_init(&uc, LISP_CONTROL_PORT, LISP_CONTROL_PORT, NULL, drloc); send_msg(&xtr->super, b, &uc); lisp_msg_destroy(b); return(GOOD); } static int xtr_build_and_send_encap_map_reg(lisp_xtr_t * xtr, mapping_t * m, map_server_elt *ms, lisp_addr_t *etr_addr, lisp_addr_t *rtr_addr, uint64_t nonce) { lbuf_t * b; void * hdr, *auth_hdr; uconn_t uc; b = lisp_msg_mreg_create(m, ms->key_type); lisp_msg_put_xtr_id_site_id(b, &xtr->xtr_id, &xtr->site_id); hdr = lisp_msg_hdr(b); MREG_NONCE(hdr) = nonce; MREG_PROXY_REPLY(hdr) = 1; MREG_IBIT(hdr) = 1; MREG_RBIT(hdr) = 1; if (lisp_addr_ip_afi(ms->address) != lisp_addr_ip_afi(etr_addr)){ OOR_LOG(LDBG_1, "build_and_send_ecm_map_reg: Map Server AFI not compatible with selected" " local RLOC (%s)", lisp_addr_to_char(etr_addr)); lisp_msg_destroy(b); return (BAD); } auth_hdr = hdr + sizeof(map_register_hdr_t); if (lisp_msg_fill_auth_data(b, auth_hdr, ms->key_type, ms->key) != GOOD) { OOR_LOG(LDBG_2, "build_and_send_ecm_map_reg: Error filling the authentication data"); return(BAD); } lisp_msg_encap(b, LISP_CONTROL_PORT, LISP_CONTROL_PORT, etr_addr,ms->address); hdr = lisp_msg_ecm_hdr(b); /* TODO To use when implementing draft version 4 or higher */ ECM_RTR_PROCESS_BIT(hdr) = 1; OOR_LOG(LDBG_1, "%s, Inner IP: %s -> %s, EID: %s, RTR: %s", lisp_msg_hdr_to_char(b), lisp_addr_to_char(etr_addr), lisp_addr_to_char(ms->address), lisp_addr_to_char(mapping_eid(m)), lisp_addr_to_char(rtr_addr)); uconn_init(&uc, xtr->tr.encap_port, LISP_CONTROL_PORT, etr_addr, rtr_addr); send_msg(&xtr->super, b, &uc); lisp_msg_destroy(b); return(GOOD); } static int xtr_build_and_send_smr_mreq(lisp_xtr_t *xtr, mapping_t *smap, lisp_addr_t *deid, lisp_addr_t *drloc) { uconn_t uc; lbuf_t * b = NULL; lisp_addr_t *seid = NULL; lisp_addr_t *srloc = NULL; void *hdr = NULL; glist_t *itr_rlocs = NULL; int res = GOOD; seid = mapping_eid(smap); itr_rlocs = ctrl_default_rlocs(ctrl_dev_get_ctrl_t(&xtr->super)); /* build Map-Request */ b = lisp_msg_mreq_create(seid, itr_rlocs, deid); if (b == NULL){ lisp_msg_destroy(b); return (BAD); } hdr = lisp_msg_hdr(b); MREQ_SMR(hdr) = 1; OOR_LOG(LDBG_1, "%s, itr-rlocs: %s, src-eid: %s, req-eid: %s ", lisp_msg_hdr_to_char(b), laddr_list_to_char(itr_rlocs), lisp_addr_to_char(seid), lisp_addr_to_char(deid)); glist_destroy(itr_rlocs); srloc = ctrl_default_rloc(xtr->super.ctrl, lisp_addr_ip_afi(drloc)); if (!srloc) { OOR_LOG(LDBG_2, "No compatible RLOC was found to send SMR Map-Request " "for local EID %s", lisp_addr_to_char(seid)); lisp_msg_destroy(b); return(BAD); } uconn_init(&uc, LISP_CONTROL_PORT, LISP_CONTROL_PORT, srloc, drloc); res = send_msg(&xtr->super, b, &uc); lisp_msg_destroy(b); return(res); } /* build and send generic map-register with one record * for each map server */ static int xtr_build_and_send_info_req(lisp_xtr_t * xtr, mapping_t * m, locator_t *loct, map_server_elt *ms, uint64_t nonce) { lbuf_t * b = NULL; void *hdr, *auth_hdr; lisp_addr_t *srloc, *drloc; uconn_t uc; b = lisp_msg_inf_req_create(m, ms->key_type); if (!b) { return(BAD); } hdr = lisp_msg_hdr(b); INF_REQ_NONCE(hdr) = nonce; auth_hdr = hdr + sizeof(info_nat_hdr_t); if (lisp_msg_fill_auth_data(b, auth_hdr, ms->key_type, ms->key) != GOOD) { return(BAD); } srloc = locator_addr(loct); drloc = ms->address; OOR_LOG(LDBG_1, "%s, EID: %s, MS: %s", lisp_msg_hdr_to_char(b), lisp_addr_to_char(mapping_eid(m)), lisp_addr_to_char(drloc)); uconn_init(&uc, LISP_CONTROL_PORT, LISP_CONTROL_PORT, srloc, drloc); send_msg(&xtr->super, b, &uc); lisp_msg_destroy(b); return(GOOD); } /**************************** LOGICAL PROCESSES ******************************/ /****************************** Map Register *********************************/ int xtr_program_map_register(lisp_xtr_t *xtr) { void *map_local_entry_it; map_local_entry_t *mle; oor_timer_t *timer; timer_map_reg_argument *timer_arg; map_server_elt *ms; glist_entry_t *ms_it; if (glist_size(xtr->map_servers) == 0){ return (BAD); } local_map_db_foreach_entry(xtr->local_mdb, map_local_entry_it) { mle = (map_local_entry_t *)map_local_entry_it; /* Cancel timers associated to the map register of the local map entry */ stop_timers_of_type_from_obj(mle,MAP_REGISTER_TIMER,ptrs_to_timers_ht, nonces_ht); /* Configure map register for each map server */ glist_for_each_entry(ms_it,xtr->map_servers){ ms = (map_server_elt *)glist_entry_data(ms_it); timer_arg = timer_map_reg_argument_new_init(mle,ms); timer = oor_timer_with_nonce_new(MAP_REGISTER_TIMER, xtr, xtr_map_register_cb, timer_arg,(oor_timer_del_cb_arg_fn)timer_map_reg_arg_free); htable_ptrs_timers_add(ptrs_to_timers_ht, mle, timer); xtr_map_register_cb(timer); } } local_map_db_foreach_end; return(GOOD); } int xtr_program_map_register_for_mapping(lisp_xtr_t *xtr, map_local_entry_t *mle) { oor_timer_t *timer; timer_map_reg_argument *timer_arg; map_server_elt *ms; glist_entry_t *ms_it; if (glist_size(xtr->map_servers) == 0){ return (BAD); } /* Cancel timers associated to the map register of the local map entry */ stop_timers_of_type_from_obj(mle,MAP_REGISTER_TIMER,ptrs_to_timers_ht, nonces_ht); /* Configure map register for each map server */ glist_for_each_entry(ms_it,xtr->map_servers){ ms = (map_server_elt *)glist_entry_data(ms_it); timer_arg = timer_map_reg_argument_new_init(mle,ms); timer = oor_timer_with_nonce_new(MAP_REGISTER_TIMER, xtr, xtr_map_register_cb, timer_arg,(oor_timer_del_cb_arg_fn)timer_map_reg_arg_free); htable_ptrs_timers_add(ptrs_to_timers_ht, mle, timer); xtr_map_register_cb(timer); } return(GOOD); } static int xtr_map_register_cb(oor_timer_t *timer) { timer_map_reg_argument *timer_arg = oor_timer_cb_argument(timer); nonces_list_t *nonces_lst = oor_timer_nonces(timer); lisp_xtr_t *xtr = oor_timer_owner(timer); mapping_t *map = map_local_entry_mapping(timer_arg->mle); map_server_elt *ms = timer_arg->ms; uint64_t nonce; if ((nonces_list_size(nonces_lst) -1) < 10000){// xtr->probe_retries){ nonce = nonce_new(); if (xtr_build_and_send_map_reg(xtr, map, ms, nonce) != GOOD){ return (BAD); } if (nonces_list_size(nonces_lst) > 0) { OOR_LOG(LDBG_1,"Sent Map-Register retry for mapping %s to %s " "(%d retries)", lisp_addr_to_char(mapping_eid(map)), lisp_addr_to_char(ms->address), nonces_list_size(nonces_lst)); } else { OOR_LOG(LDBG_1,"Sent Map-Register for mapping %s to %s " , lisp_addr_to_char(mapping_eid(map)), lisp_addr_to_char(ms->address)); } htable_nonces_insert(nonces_ht, nonce,nonces_lst); oor_timer_start(timer, OOR_INITIAL_MREG_TIMEOUT); return (GOOD); }else{ /* If we have reached maximum number of retransmissions, change remote * locator status */ /* Reprogram time for next Map Register interval */ htable_nonces_reset_nonces_lst(nonces_ht,nonces_lst); oor_timer_start(timer, MAP_REGISTER_INTERVAL); OOR_LOG(LWRN,"Map-Register of %s to %s dit not receive reply. Retrying in %d seconds", lisp_addr_to_char(mapping_eid(map)), lisp_addr_to_char(ms->address), MAP_REGISTER_INTERVAL); return (BAD); } } /****************************** Encap Map Register ***************************/ static int xtr_encap_map_register_cb(oor_timer_t *timer) { timer_encap_map_reg_argument *timer_arg = oor_timer_cb_argument(timer); nonces_list_t *nonces_lst = oor_timer_nonces(timer); lisp_xtr_t *xtr = oor_timer_owner(timer); mapping_t *map = map_local_entry_mapping(timer_arg->mle); map_server_elt *ms = timer_arg->ms; lisp_addr_t *etr_addr = locator_addr(timer_arg->src_loct); lisp_addr_t *rtr_addr = timer_arg->rtr_rloc; uint64_t nonce; if ((nonces_list_size(nonces_lst) -1) < xtr->tr.probe_retries){ nonce = nonce_new(); if (xtr_build_and_send_encap_map_reg(xtr, map, ms, etr_addr, rtr_addr, nonce) != GOOD){ return (BAD); } if (nonces_list_size(nonces_lst) > 0) { OOR_LOG(LDBG_1,"Sent Encap Map-Register retry for mapping %s to MS %s from RLOC %s through RTR %s" "(%d retries)", lisp_addr_to_char(mapping_eid(map)), lisp_addr_to_char(ms->address), lisp_addr_to_char(etr_addr),lisp_addr_to_char(rtr_addr),nonces_list_size(nonces_lst)); } else { OOR_LOG(LDBG_1,"Sent Encap Map-Register for mapping %s to MS %s from RLOC %s through RTR %s" , lisp_addr_to_char(mapping_eid(map)),lisp_addr_to_char(ms->address), lisp_addr_to_char(etr_addr),lisp_addr_to_char(rtr_addr)); } htable_nonces_insert(nonces_ht, nonce,nonces_lst); oor_timer_start(timer, OOR_INITIAL_MREG_TIMEOUT); return (GOOD); }else{ /* If we have reached maximum number of retransmissions, change remote * locator status */ /* Reprogram time for next Map Register interval */ htable_nonces_reset_nonces_lst(nonces_ht,nonces_lst); oor_timer_start(timer, MAP_REGISTER_INTERVAL); OOR_LOG(LDBG_1,"Encap Map-Register for mapping %s to MS %s from RLOC %s through RTR %s did not receive reply." " Retry in %d seconds", lisp_addr_to_char(mapping_eid(map)),lisp_addr_to_char(ms->address), lisp_addr_to_char(etr_addr),lisp_addr_to_char(rtr_addr), MAP_REGISTER_INTERVAL); return (BAD); } } int xtr_program_encap_map_reg_of_loct_for_map(lisp_xtr_t *xtr, map_local_entry_t *mle, locator_t *src_loct) { oor_timer_t *timer; timer_encap_map_reg_argument *timer_arg; map_server_elt *ms; glist_t *timers_lst, *rtr_addr_lst; glist_entry_t *ms_it, *timers_it, *rtr_it; lisp_addr_t *rtr_addr; if (glist_size(xtr->map_servers) == 0){ return (BAD); } /* * We configure the timers using the map_local_entry_t pointer instead of locator * as we want to isolate locatars form timers */ /* Cancel timers associated to encap map register associated to the locator */ timers_lst = htable_ptrs_timers_get_timers_of_type_from_obj(ptrs_to_timers_ht, mle, ENCAP_MAP_REGISTER_TIMER); glist_for_each_entry(timers_it,timers_lst){ timer = (oor_timer_t *)glist_entry_data(timers_it); timer_arg = oor_timer_cb_argument(timer); if(src_loct == timer_arg->src_loct){ stop_timer_from_obj(mle,timer,ptrs_to_timers_ht, nonces_ht); // Continue processing as it could be more than one map server, RTR } } glist_destroy(timers_lst); /* Configure encap map register for each RTR associated with the locator and MS*/ rtr_addr_lst = mle_rtr_addr_list_of_loct(mle, locator_addr(src_loct)); glist_for_each_entry(rtr_it,rtr_addr_lst){ rtr_addr = (lisp_addr_t *)glist_entry_data(rtr_it); glist_for_each_entry(ms_it,xtr->map_servers){ ms = (map_server_elt *)glist_entry_data(ms_it); timer_arg = timer_encap_map_reg_argument_new_init(mle,ms,src_loct,rtr_addr); timer = oor_timer_with_nonce_new(ENCAP_MAP_REGISTER_TIMER, xtr, xtr_encap_map_register_cb, timer_arg,(oor_timer_del_cb_arg_fn)timer_encap_map_reg_arg_free); htable_ptrs_timers_add(ptrs_to_timers_ht, mle, timer); xtr_encap_map_register_cb(timer); } } return(GOOD); } /*********************************** SMR *************************************/ /* Send a solicit map request for each rloc of all eids in the map cache * database */ static void xtr_smr_process_start(lisp_xtr_t *xtr) { map_local_entry_t * map_loc_e = NULL; glist_t * map_loc_e_list = NULL; //<map_local_entry_t *> glist_entry_t * it = NULL; OOR_LOG(LDBG_1,"\n**** Re-Register and send SMRs for mappings with updated " "RLOCs ****"); /* Get a list of mappings that require smrs */ map_loc_e_list = xtr_get_map_local_entry_to_smr(xtr); /* Send map register and SMR request for each mapping */ //glist_dump(map_loc_e_list,(glist_to_char_fct)map_local_entry_to_char,LDBG_1); glist_for_each_entry(it, map_loc_e_list) { map_loc_e = (map_local_entry_t *)glist_entry_data(it); xtr_smr_start_for_locl_mapping(xtr, map_loc_e); } glist_destroy(map_loc_e_list); OOR_LOG(LDBG_2,"*** Finished sending notifications ***\n"); } void xtr_smr_start_for_locl_mapping(lisp_xtr_t *xtr, map_local_entry_t *map_loc_e) { mcache_entry_t * mce; mapping_t * mcache_map; mapping_t * map; glist_entry_t * it_pitr; lisp_addr_t * pitr_addr; lisp_addr_t * eid; assert(map_loc_e); map = map_local_entry_mapping(map_loc_e); eid = mapping_eid(map); if (!xtr->nat_aware){ xtr_program_map_register_for_mapping(xtr, map_loc_e); } OOR_LOG(LDBG_1, "Start SMR for local EID %s", lisp_addr_to_char(eid)); /* TODO: spec says SMRs should be sent only to peer ITRs that sent us * traffic in the last minute. Should change this in the future*/ /* XXX: works ONLY with IP */ mcache_foreach_active_entry_in_ip_eid_db(xtr->tr.map_cache, eid, mce) { mcache_map = mcache_entry_mapping(mce); xtr_smr_notify_mcache_entry(xtr, map, mcache_map); } mcache_foreach_active_entry_in_ip_eid_db_end; /* SMR proxy-itr */ OOR_LOG(LDBG_1, "Sending SMRs to PITRs"); glist_for_each_entry(it_pitr, xtr->pitrs){ pitr_addr = (lisp_addr_t *)glist_entry_data(it_pitr); xtr_build_and_send_smr_mreq(xtr, map, eid, pitr_addr); } } /* solicit SMRs for 'src_map' to all locators of 'dst_map'*/ static int xtr_smr_notify_mcache_entry(lisp_xtr_t *xtr, mapping_t *src_map, mapping_t *dst_map) { lisp_addr_t *deid = NULL, *drloc = NULL; locator_t *loct = NULL; deid = mapping_eid(dst_map); mapping_foreach_active_locator(dst_map, loct){ if (loct->state == UP){ drloc = locator_addr(loct); xtr_build_and_send_smr_mreq(xtr, src_map, deid, drloc); } }mapping_foreach_active_locator_end; return(GOOD); } static int xtr_smr_process_start_cb(oor_timer_t *timer) { xtr_smr_process_start((lisp_xtr_t *)oor_timer_cb_argument(timer)); return(GOOD); } static int xtr_program_smr(lisp_xtr_t *xtr, int time) { OOR_LOG(LDBG_1,"Rescheduling SMR in %d seconds",time); if (!xtr->smr_timer) { xtr->smr_timer = oor_timer_without_nonce_new(SMR_TIMER, xtr, xtr_smr_process_start_cb, xtr, NULL); } oor_timer_start(xtr->smr_timer, time); return(GOOD); } /* * Return the list of mappings that has experimented changes in their * locators. At the same time iface_locators status is reseted * @param xtr * @return glist_t with the list of modified mappings (mapping_t *) */ static glist_t * xtr_get_map_local_entry_to_smr(lisp_xtr_t *xtr) { glist_t * map_loc_e_to_smr = glist_new();//<map_local_entry_t> glist_t * iface_locators_list = NULL; iface_locators * if_loct = NULL; glist_entry_t * it = NULL; glist_entry_t * it_loc = NULL; glist_t * locators[2] = {NULL,NULL}; map_local_entry_t * map_loc_e = NULL; locator_t * locator = NULL; int ctr; iface_locators_list = shash_values(xtr->tr.iface_locators_table); glist_for_each_entry(it,iface_locators_list){ if_loct = (iface_locators *)glist_entry_data(it); /* Select affected locators */ if (if_loct->status_changed == TRUE){ locators[0] = if_loct->ipv4_locators; locators[1] = if_loct->ipv6_locators; }else{ if(if_loct->ipv4_prev_addr != NULL){ locators[0] = if_loct->ipv4_locators; } if(if_loct->ipv6_prev_addr != NULL){ locators[1] = if_loct->ipv6_locators; } } /* Reset iface_locators status */ if_loct->status_changed = FALSE; lisp_addr_del(if_loct->ipv4_prev_addr); lisp_addr_del(if_loct->ipv6_prev_addr); if_loct->ipv4_prev_addr = NULL; if_loct->ipv6_prev_addr = NULL; /* Select not repeated mappings*/ for (ctr=0 ; ctr<2 ; ctr++){ if (locators[ctr] != NULL){ glist_for_each_entry(it_loc,locators[ctr]){ locator = (locator_t *)glist_entry_data(it_loc); map_loc_e = get_map_loc_ent_containing_loct_ptr(xtr->local_mdb, locator); if (map_loc_e != NULL && glist_contain(map_loc_e, map_loc_e_to_smr) == FALSE){ glist_add(map_loc_e, map_loc_e_to_smr); } } } } } glist_destroy(iface_locators_list); return (map_loc_e_to_smr); } /****************************** Info Request *********************************/ static int xtr_program_initial_info_request_process(lisp_xtr_t *xtr) { void *map_local_entry_it; oor_timer_t *timer; timer_inf_req_argument *timer_arg; map_local_entry_t *mle; mapping_t *map; locator_t *loct; map_server_elt *ms; glist_entry_t *ms_it; if (glist_size(xtr->map_servers) == 0){ return (BAD); } local_map_db_foreach_entry(xtr->local_mdb, map_local_entry_it) { mle = (map_local_entry_t *)map_local_entry_it; map = map_local_entry_mapping(mle); /* Cancel timers associated to the info request process of the local map entry */ stop_timers_of_type_from_obj(mle,INFO_REQUEST_TIMER,ptrs_to_timers_ht, nonces_ht); mapping_foreach_active_locator(map,loct){ // Only send info request for local locators if (!locator_L_bit(loct)){ continue; } glist_for_each_entry(ms_it,xtr->map_servers){ ms = (map_server_elt *)glist_entry_data(ms_it); timer_arg = timer_inf_req_argument_new_init(mle,loct,ms); map_local_entry_dump(mle,LINF); timer = oor_timer_with_nonce_new(INFO_REQUEST_TIMER, xtr, xtr_info_request_cb, timer_arg,(oor_timer_del_cb_arg_fn)timer_inf_req_arg_free); htable_ptrs_timers_add(ptrs_to_timers_ht, mle, timer); xtr_info_request_cb(timer); } }mapping_foreach_active_locator_end; } local_map_db_foreach_end; return(GOOD); } static int xtr_program_info_req_per_loct(lisp_xtr_t *xtr, map_local_entry_t *mle, locator_t *loct) { oor_timer_t *timer; timer_inf_req_argument *timer_arg; map_server_elt *ms; glist_entry_t *ms_it; if (glist_size(xtr->map_servers) == 0){ return (BAD); } /* Program info request for each Map Server */ glist_for_each_entry(ms_it,xtr->map_servers){ ms = (map_server_elt *)glist_entry_data(ms_it); timer_arg = timer_inf_req_argument_new_init(mle,loct,ms); timer = oor_timer_with_nonce_new(INFO_REQUEST_TIMER, xtr, xtr_info_request_cb, timer_arg,(oor_timer_del_cb_arg_fn)timer_inf_req_arg_free); htable_ptrs_timers_add(ptrs_to_timers_ht, mle, timer); oor_timer_start(timer, OOR_INF_REQ_HANDOVER_TIMEOUT); } return(GOOD); } static int xtr_info_request_cb(oor_timer_t *timer) { timer_inf_req_argument *timer_arg = oor_timer_cb_argument(timer); nonces_list_t *nonces_lst = oor_timer_nonces(timer); lisp_xtr_t *xtr = oor_timer_owner(timer); mapping_t *map = map_local_entry_mapping(timer_arg->mle); locator_t *loct = timer_arg->loct; map_server_elt *ms = timer_arg->ms; uint64_t nonce; if ((nonces_list_size(nonces_lst) -1) < xtr->tr.map_request_retries){ nonce = nonce_new(); if (nonces_list_size(nonces_lst) > 0) { OOR_LOG(LDBG_1,"Sent Info-Request retry for mapping %s to %s from locator %s" "(%d retries)", lisp_addr_to_char(mapping_eid(map)), lisp_addr_to_char(ms->address), lisp_addr_to_char(locator_addr(loct)), nonces_list_size(nonces_lst)); } else { timer_encap_map_reg_stop_using_locator(timer_arg->mle, loct); OOR_LOG(LDBG_1,"Sent Info-Request for mapping %s to %s from locator %s", lisp_addr_to_char(mapping_eid(map)),lisp_addr_to_char(ms->address), lisp_addr_to_char(locator_addr(loct))); } if (xtr_build_and_send_info_req(xtr, map, loct, ms, nonce) != GOOD){ return (BAD); } htable_nonces_insert(nonces_ht, nonce,nonces_lst); oor_timer_start(timer, OOR_INITIAL_INF_REQ_TIMEOUT); return (GOOD); }else{ /* We reached maximum number of retransmissions */ /* Reprogram time for next Info Request interval */ htable_nonces_reset_nonces_lst(nonces_ht,nonces_lst); oor_timer_start(timer, OOR_SLEEP_INF_REQ_TIMEOUT); OOR_LOG(LWRN,"Info-Request of %s to %s from locator %s did not receive reply. Retrying in %d seconds", lisp_addr_to_char(mapping_eid(map)), lisp_addr_to_char(ms->address), lisp_addr_to_char(locator_addr(loct)), OOR_SLEEP_INF_REQ_TIMEOUT); return (BAD); } } /**************************** AUXILIAR FUNCTIONS *****************************/ /* Configure SMR or info request depending on NAT traversal */ static int xtr_iface_event_signaling(lisp_xtr_t * xtr, iface_locators * if_loct) { locator_t *loct; lisp_addr_t *loct_addr; map_local_entry_t *mle; glist_t *timers_lst; glist_entry_t *mle_it, *timer_it; mapping_t *map; oor_timer_t *timer; if(xtr->nat_aware == TRUE){ if (glist_size(if_loct->ipv4_locators) == 0){ return (GOOD); } loct = glist_first_data(if_loct->ipv4_locators); loct_addr = locator_addr(loct); if (lisp_addr_is_no_addr(loct_addr)==TRUE){ return (GOOD); } glist_for_each_entry(mle_it,if_loct->map_loc_entries){ mle = (map_local_entry_t *)glist_entry_data(mle_it); map = map_local_entry_mapping(mle); loct = mapping_get_loct_with_addr(map,loct_addr); /* Stop timers associtated with the locator */ timer_inf_req_stop_using_locator(mle, loct); timer_encap_map_reg_stop_using_locator(mle, loct); if (locator_state(loct) == UP){ OOR_LOG(LDBG_2,"xtr_if_event: Reconfiguring Info-Request process for locator %s of " "the mapping %s.", lisp_addr_to_char(loct_addr), lisp_addr_to_char(mapping_eid(map))); xtr_program_info_req_per_loct(xtr, mle, loct); }else{ /* Reprogram all the Encap Map Registers of the other interfaces associated to the mapping * If status is up this process will be done when receiving the Info Reply*/ timers_lst = htable_ptrs_timers_get_timers_of_type_from_obj(ptrs_to_timers_ht, mle, ENCAP_MAP_REGISTER_TIMER); glist_for_each_entry(timer_it, timers_lst){ timer = (oor_timer_t *)glist_entry_data(timer_it); oor_timer_start(timer, OOR_INF_REQ_HANDOVER_TIMEOUT); } glist_destroy(timers_lst); } } }else{ xtr_program_smr(xtr, OOR_SMR_TIMEOUT); } return (GOOD); } /****************************** NAT traversal ********************************/ static int xtr_update_nat_info(lisp_xtr_t *xtr, map_local_entry_t *mle, locator_t *loct, glist_t *rtr_list) { mle_nat_info_update(mle, loct, rtr_list); /* Update forwarding info of the local entry*/ xtr->tr.fwd_policy->updated_map_loc_inf(xtr->tr.fwd_policy_dev_parm,mle); notify_datap_rm_fwd_from_entry(&(xtr->super),map_local_entry_eid(mle),TRUE); /* Update forwarding info of rtrs */ xtr_update_rtrs_caches(xtr); return (GOOD); } static void xtr_update_rtrs_caches(lisp_xtr_t *xtr) { xtr_update_rtrs_cache_afi(xtr, AF_INET); xtr_update_rtrs_cache_afi(xtr, AF_INET6); } static void xtr_update_rtrs_cache_afi(lisp_xtr_t *xtr, int afi) { lisp_addr_t *rtr_addr; map_local_entry_t *mle; mcache_entry_t *rtrs_mce; mapping_t *map; locator_t *rtr_loct; glist_t *rtr_addr_list; glist_entry_t *addr_it; rtrs_mce = mcache_get_all_space_entry(xtr->tr.map_cache, afi); // XXX check before if we have any change in order to avoid modify the data plane map = mcache_entry_mapping(rtrs_mce); /* Remove the list of rtr locators */ mapping_remove_locators(map); /* Regenerate rtr list using the information of local map entries */ local_map_db_foreach_entry(xtr->local_mdb,mle){ rtr_addr_list = mle_rtr_addr_list(mle); glist_for_each_entry(addr_it, rtr_addr_list){ rtr_addr = (lisp_addr_t *)glist_entry_data(addr_it); rtr_loct = locator_new_init(rtr_addr,UP,0,1,1,100,255,0); mapping_add_locator(map,rtr_loct); } glist_destroy(rtr_addr_list); }local_map_db_foreach_end; /* Update forwarding info of rtrs */ xtr->tr.fwd_policy->updated_map_cache_inf(xtr->tr.fwd_policy_dev_parm,rtrs_mce); notify_datap_reset_all_fwd(&(xtr->super)); } static glist_t * nat_select_rtrs(glist_t * rtr_list) { glist_t *final_rtr_list = glist_new_managed((glist_del_fct)lisp_addr_del); lisp_addr_t *rtr_addr; addr_list_rm_not_compatible_addr(rtr_list, IPv4_SUPPORT); //TODO Select RTR process rtr_addr = (lisp_addr_t *)glist_first_data(rtr_list); if (rtr_addr){ glist_add(lisp_addr_clone(rtr_addr), final_rtr_list); } return (final_rtr_list); } /********************************** Dump ************************************/ void proxy_etrs_dump(lisp_xtr_t *xtr, int log_level) { locator_t *locator = NULL; mcache_entry_t * ipv4_petrs_mc,*ipv6_petrs_mc; ipv4_petrs_mc = mcache_get_all_space_entry(xtr->tr.map_cache,AF_INET); ipv6_petrs_mc = mcache_get_all_space_entry(xtr->tr.map_cache,AF_INET6); OOR_LOG(log_level, "****************** Proxy ETR List for IPv4 EIDs **********************"); OOR_LOG(log_level, "| Locator (RLOC) | Status | Priority/Weight |"); /* Start rloc probing for each locator of the mapping */ mapping_foreach_active_locator(mcache_entry_mapping(ipv4_petrs_mc),locator){ OOR_LOG(log_level,"%s",locator_to_char(locator)); }mapping_foreach_active_locator_end; OOR_LOG(log_level, "**********************************************************************\n"); OOR_LOG(log_level, "****************** Proxy ETR List for IPv6 EIDs **********************"); OOR_LOG(log_level, "| Locator (RLOC) | Status | Priority/Weight |"); /* Start rloc probing for each locator of the mapping */ mapping_foreach_active_locator(mcache_entry_mapping(ipv6_petrs_mc),locator){ OOR_LOG(log_level,"%s",locator_to_char(locator)); }mapping_foreach_active_locator_end; OOR_LOG(log_level, "**********************************************************************\n"); } void map_servers_dump(lisp_xtr_t *xtr, int log_level) { map_server_elt * ms = NULL; glist_entry_t * it = NULL; char str[80]; size_t str_size = sizeof(str); if (glist_size(xtr->map_servers) == 0 || is_loggable(log_level) == FALSE) { return; } OOR_LOG(log_level, "******************* Map-Servers list ********************************"); OOR_LOG(log_level, "| Locator (RLOC) | Key Type |"); glist_for_each_entry(it, xtr->map_servers) { ms = (map_server_elt *)glist_entry_data(it); snprintf(str,str_size, "| %39s |", lisp_addr_to_char(ms->address)); if (ms->key_type == NO_KEY) { snprintf(str + strlen(str), str_size - strlen(str), " NONE |"); } else if (ms->key_type == HMAC_SHA_1_96) { snprintf(str + strlen(str), str_size - strlen(str), " HMAC-SHA-1-96 |"); } else { snprintf(str + strlen(str), str_size - strlen(str), " HMAC-SHA-256-128 |"); } OOR_LOG(log_level, "%s", str); } OOR_LOG(log_level, "*********************************************************************\n"); } /**************************** Map Server struct ******************************/ map_server_elt * map_server_elt_new_init(lisp_addr_t *address,uint8_t key_type, char *key, uint8_t proxy_reply) { map_server_elt *ms = NULL; ms = xzalloc(sizeof(map_server_elt)); if (ms == NULL){ OOR_LOG(LWRN,"Couldn't allocate memory for a map_server_elt structure"); return (NULL); } ms->address = lisp_addr_clone(address); ms->key_type = key_type; ms->key = strdup(key); ms->proxy_reply = proxy_reply; return (ms); } void map_server_elt_del (map_server_elt *map_server) { if (map_server == NULL){ return; } lisp_addr_del (map_server->address); free(map_server->key); free(map_server); } static map_local_entry_t * get_map_loc_ent_containing_loct_ptr(local_map_db_t *local_db, locator_t *locator) { map_local_entry_t *map_loc_e; map_local_entry_t *map_loc_e_res = NULL; mapping_t *mapping = NULL; uint8_t found = FALSE; void *it = NULL; local_map_db_foreach_entry_with_break(local_db, it, found) { map_loc_e = (map_local_entry_t *)it; mapping = map_local_entry_mapping(map_loc_e); if (mapping_has_locator(mapping, locator) == TRUE){ found = TRUE; map_loc_e_res = map_loc_e; } } local_map_db_foreach_with_break_end(found); if (!map_loc_e_res){ OOR_LOG(LDBG_2, "get_map_loc_ent_containing_loct_ptr: No mapping has been found with locator %s", lisp_addr_to_char(locator_addr(locator))); } return (map_loc_e_res); } /******************************* TIMERS **************************************/ /************************** Map Register timer *******************************/ static timer_map_reg_argument * timer_map_reg_argument_new_init(map_local_entry_t *mle, map_server_elt *ms) { timer_map_reg_argument *timer_arg = xmalloc(sizeof(timer_map_reg_argument)); timer_arg->mle = mle; timer_arg->ms = ms; return(timer_arg); } static void timer_map_reg_arg_free(timer_map_reg_argument * timer_arg) { free(timer_arg); } /*********************** Encap Map Register timer ****************************/ static timer_encap_map_reg_argument * timer_encap_map_reg_argument_new_init(map_local_entry_t *mle, map_server_elt *ms, locator_t *src_loct, lisp_addr_t *rtr_addr) { timer_encap_map_reg_argument *timer_arg = xmalloc(sizeof(timer_encap_map_reg_argument)); timer_arg->mle = mle; timer_arg->ms = ms; timer_arg->src_loct = src_loct; timer_arg->rtr_rloc = lisp_addr_clone(rtr_addr); return(timer_arg); } static void timer_encap_map_reg_arg_free(timer_encap_map_reg_argument * timer_arg) { lisp_addr_del(timer_arg->rtr_rloc); free(timer_arg); } /* * Stop all the timers of type ENCAP_MAP_REGISTER_TIMER associated with the map local entry * introduced as a parameter and using the specified locator. */ static void timer_encap_map_reg_stop_using_locator(map_local_entry_t *mle, locator_t *loct) { glist_t *timers_lst; glist_entry_t *timer_it; oor_timer_t *timer; timer_encap_map_reg_argument * timer_arg; timers_lst = htable_ptrs_timers_get_timers_of_type_from_obj(ptrs_to_timers_ht, mle, ENCAP_MAP_REGISTER_TIMER); glist_for_each_entry(timer_it,timers_lst){ timer = (oor_timer_t *)glist_entry_data(timer_it); timer_arg = (timer_encap_map_reg_argument *)oor_timer_cb_argument(timer); if (timer_arg->src_loct == loct){ stop_timer_from_obj(mle,timer,ptrs_to_timers_ht,nonces_ht); } } glist_destroy(timers_lst); } /************************** Info Request timer *******************************/ static timer_inf_req_argument * timer_inf_req_argument_new_init(map_local_entry_t *mle, locator_t *loct, map_server_elt *ms) { timer_inf_req_argument *timer_arg = xmalloc(sizeof(timer_inf_req_argument)); timer_arg->mle = mle; timer_arg->loct = loct; timer_arg->ms = ms; return (timer_arg); } static void timer_inf_req_arg_free(timer_inf_req_argument * timer_arg) { free(timer_arg); } /* * Stop all the timers of type INFO_REQUEST_TIMER associated with the map local entry * introduced as a parameter and using the specified locator. */ static void timer_inf_req_stop_using_locator(map_local_entry_t *mle, locator_t *loct) { glist_t *timers_lst; glist_entry_t *timer_it; oor_timer_t *timer; timer_inf_req_argument * timer_arg; timers_lst = htable_ptrs_timers_get_timers_of_type_from_obj(ptrs_to_timers_ht, mle, INFO_REQUEST_TIMER); glist_for_each_entry(timer_it,timers_lst){ timer = (oor_timer_t *)glist_entry_data(timer_it); timer_arg = (timer_inf_req_argument *)oor_timer_cb_argument(timer); if (timer_arg->loct == loct){ stop_timer_from_obj(mle,timer,ptrs_to_timers_ht,nonces_ht); } } glist_destroy(timers_lst); }
{ "content_hash": "011c594871e7e8eabc0d6e312d00bd73", "timestamp": "", "source": "github", "line_count": 2022, "max_line_length": 131, "avg_line_length": 36.225519287833826, "alnum_prop": 0.5824322848405418, "repo_name": "OpenOverlayRouter/oor", "id": "352357736c84c370a92e8ae06503bc1006b651ce", "size": "73944", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "oor/control/lisp_xtr.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2061698" }, { "name": "C++", "bytes": "15826" }, { "name": "CMake", "bytes": "7531" }, { "name": "CSS", "bytes": "7237" }, { "name": "Dockerfile", "bytes": "681" }, { "name": "GDB", "bytes": "311" }, { "name": "HTML", "bytes": "407539" }, { "name": "Java", "bytes": "121451" }, { "name": "Lex", "bytes": "8650" }, { "name": "M4", "bytes": "100997" }, { "name": "Makefile", "bytes": "246354" }, { "name": "Objective-C", "bytes": "4833" }, { "name": "Roff", "bytes": "61394" }, { "name": "Ruby", "bytes": "4624" }, { "name": "Shell", "bytes": "652533" }, { "name": "Swift", "bytes": "55202" }, { "name": "XSLT", "bytes": "441" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Html; namespace MoG { public static class MenuExtensions { public static MvcHtmlString MenuItem( this HtmlHelper htmlHelper, string text, string action, string controller, string liCssClass = null, object routevalues = null ) { var li = new TagBuilder("li"); if (!String.IsNullOrEmpty(liCssClass)) { li.AddCssClass(liCssClass); } var routeData = htmlHelper.ViewContext.RouteData; var currentAction = routeData.GetRequiredString("action"); var currentController = routeData.GetRequiredString("controller"); if (string.Equals(currentAction, action, StringComparison.OrdinalIgnoreCase) && string.Equals(currentController, controller, StringComparison.OrdinalIgnoreCase)) { li.AddCssClass("active"); } li.InnerHtml = String.Format("<a href=\"{0}\">{1}</a>", new UrlHelper(htmlHelper.ViewContext.RequestContext).Action(action, controller,routevalues).ToString() , text); return MvcHtmlString.Create(li.ToString()); } } }
{ "content_hash": "362b87bd78120fb701847723be07b954", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 117, "avg_line_length": 34.6, "alnum_prop": 0.5932080924855492, "repo_name": "jrocket/MOG", "id": "ed34b8933c2dd3f1bc14dd168b434ef11fabd0c8", "size": "1386", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MoG/HtmlExtensions/MenuItem.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "188" }, { "name": "C#", "bytes": "784769" }, { "name": "CSS", "bytes": "354460" }, { "name": "JavaScript", "bytes": "1388702" } ], "symlink_target": "" }
volatile long work_counter; int req_count; pthread_mutex_t q_lock; void grab_lock() { pthread_mutex_lock(&q_lock); } void ungrab_lock() { pthread_mutex_unlock(&q_lock); } void do_work() { for (int i = 0; i < 50000; ++i) ++work_counter; // Burn CPU } void * request_processor(void *dummy) { printf("[*] Request processor initialized.\n"); while (1) { grab_lock(); do_work(); ungrab_lock(); } return NULL; } void flush_work() { usleep(10000); // 10ms } void * backend_handler(void *dummy) { printf("[*] Backend handler initialized.\n"); while (1) { grab_lock(); ++req_count; if (req_count % 1000 == 0) { printf("[-] Handled %d requests.\n", req_count); } if (req_count % 37 == 0) { flush_work(); } ungrab_lock(); } return NULL; } #define NTHREADS 2 int main() { pthread_t req_processors[NTHREADS]; pthread_t backend; pthread_mutex_init(&q_lock, NULL); for (int i = 0; i < NTHREADS; ++i) { pthread_create(&req_processors[i], NULL, request_processor, NULL); } pthread_create(&backend, NULL, backend_handler, NULL); printf("[*] Ready to process requests.\n"); pthread_join(backend, NULL); printf("[*] Exiting.\n"); return 0; }
{ "content_hash": "6efbc316af4937ddabc1fddb6b23b727", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 74, "avg_line_length": 20.630769230769232, "alnum_prop": 0.5510812826249067, "repo_name": "goldshtn/linux-tracing-workshop", "id": "51b40dfb2e66737d1b4e8b078fad4b7aba2e5f78", "size": "1402", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "blocky.c", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "5827" }, { "name": "C#", "bytes": "11074" }, { "name": "C++", "bytes": "9556" }, { "name": "CSS", "bytes": "111" }, { "name": "Dockerfile", "bytes": "346" }, { "name": "HTML", "bytes": "200390" }, { "name": "Java", "bytes": "28575" }, { "name": "JavaScript", "bytes": "12576" }, { "name": "Makefile", "bytes": "11575" }, { "name": "Python", "bytes": "39971" }, { "name": "Shell", "bytes": "10535" }, { "name": "TSQL", "bytes": "1312" } ], "symlink_target": "" }
package org.basex.util; import org.basex.core.*; import org.basex.core.jobs.*; /** * Interruptible string implementation. * Inspired by https://stackoverflow.com/questions/910740/cancelling-a-long-running-regex-match * * @author BaseX Team 2005-22, BSD License * @author Christian Gruen * @author gojomo */ public class InterruptibleString implements CharSequence { /** String. */ private final String string; /** * Constructor. * @param string string */ public InterruptibleString(final String string) { this.string = string; } @Override public char charAt(final int index) { checkStop(); return string.charAt(index); } @Override public int length() { return string.length(); } @Override public InterruptibleString subSequence(final int start, final int end) { return new InterruptibleString(string.substring(start, end)); } @Override public String toString() { return string; } /** * Checks if search should be interrupted. */ public static void checkStop() { if(Thread.interrupted()) throw new JobException(Text.INTERRUPTED); } }
{ "content_hash": "a3311de32f99f18115982fe4c870707f", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 95, "avg_line_length": 21.339622641509433, "alnum_prop": 0.6914235190097259, "repo_name": "BaseXdb/basex", "id": "15fc5660a3866160f828edb42d72d90e25726c4b", "size": "1131", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "basex-core/src/main/java/org/basex/util/InterruptibleString.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ActionScript", "bytes": "9374" }, { "name": "Batchfile", "bytes": "2082" }, { "name": "C", "bytes": "18636" }, { "name": "C#", "bytes": "13450" }, { "name": "C++", "bytes": "7796" }, { "name": "CSS", "bytes": "4002" }, { "name": "Common Lisp", "bytes": "3213" }, { "name": "Haskell", "bytes": "4066" }, { "name": "Java", "bytes": "8102078" }, { "name": "JavaScript", "bytes": "15505" }, { "name": "Makefile", "bytes": "1249" }, { "name": "PHP", "bytes": "12135" }, { "name": "Perl", "bytes": "7807" }, { "name": "Python", "bytes": "15214" }, { "name": "QMake", "bytes": "377" }, { "name": "R", "bytes": "14374" }, { "name": "Raku", "bytes": "10718" }, { "name": "Rebol", "bytes": "4736" }, { "name": "Ruby", "bytes": "7365" }, { "name": "Scala", "bytes": "11698" }, { "name": "Shell", "bytes": "3658" }, { "name": "Visual Basic .NET", "bytes": "11963" }, { "name": "XQuery", "bytes": "254128" }, { "name": "XSLT", "bytes": "381" } ], "symlink_target": "" }
@interface TwoAxisBounceController : UIViewController @property (nonatomic, strong) UIView *bouncingView; @end
{ "content_hash": "4d3b356b6f43313e0de47f868ed5424c", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 53, "avg_line_length": 22.6, "alnum_prop": 0.8141592920353983, "repo_name": "yaoxiaoyong/ZAActivityBar", "id": "f4e0760614f6ad2ef773aedc484d8d508aca9c43", "size": "276", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "External/SKBounceAnimation/SKBounceAnimation/TwoAxisBounceController.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "73977" }, { "name": "Ruby", "bytes": "780" } ], "symlink_target": "" }
layout: page title: Irwin - Martin Wedding date: 2016-05-24 author: Cheryl Mccullough tags: weekly links, java status: published summary: Etiam sit amet convallis mi, vel aliquet quam. banner: images/banner/wedding.jpg booking: startDate: 03/03/2018 endDate: 03/06/2018 ctyhocn: DENCCHX groupCode: IMW published: true --- Etiam a eros libero. Mauris nec tincidunt diam. Curabitur lobortis sodales gravida. Morbi condimentum quam nibh, sed molestie turpis pellentesque vel. Interdum et malesuada fames ac ante ipsum primis in faucibus. Etiam varius tellus eu lectus condimentum sodales. Vivamus bibendum diam sed sapien posuere iaculis. In quis justo vel neque luctus lacinia. Sed elementum luctus diam, a tincidunt neque ultrices ut. Cras luctus tristique rutrum. * Cras pulvinar nisl at neque convallis, non eleifend dolor tincidunt * Fusce at mauris ut mi rutrum finibus in in nulla * Duis tincidunt ligula nec risus egestas interdum * Donec a neque vel ligula consequat tincidunt eget eu quam. Cras vulputate risus nec nulla ornare, suscipit varius sem posuere. Duis mattis nibh eget eros feugiat iaculis. Nullam congue nulla non sollicitudin consectetur. Donec ullamcorper ut justo eget venenatis. Nunc non enim at augue vulputate dictum. Suspendisse placerat tempus dapibus. In magna ante, viverra sit amet leo vel, sodales vulputate tortor. In hac habitasse platea dictumst. Sed posuere urna et dolor molestie, eget fringilla mi ullamcorper. Integer in mauris dolor. Morbi vitae mattis lorem. Sed sed porta orci, nec ultrices sem. Maecenas sed est id risus porta sagittis vitae sit amet lorem. Sed ac semper nisi, id egestas dui. Donec nulla sapien, euismod id varius ut, euismod sit amet ipsum. Vestibulum sapien eros, sodales in cursus eget, faucibus sed mi. In hac habitasse platea dictumst. Morbi et libero erat. Donec vel ligula eget mauris rhoncus venenatis sit amet et massa. Ut sed congue tellus. Nulla facilisi. Vivamus convallis porttitor massa convallis euismod. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Curabitur ullamcorper turpis quis nisl dictum, sed molestie nunc pretium.
{ "content_hash": "c50036efd7e5659dcd5b2dbec067e577", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 766, "avg_line_length": 89.91666666666667, "alnum_prop": 0.8076923076923077, "repo_name": "KlishGroup/prose-pogs", "id": "63b9ea9af806a001a41ed0c16356fa22cc0bcd34", "size": "2162", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "pogs/D/DENCCHX/IMW/index.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <CrawlItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Text>pizza odlična kao i uvijek, a stigla za manje od 15 minuta. ODLIČNO!!</Text> <Rating>6</Rating> <Source>http://pauza.hr/menu/stross</Source> </CrawlItem>
{ "content_hash": "d9f56f03d1758aafcab54d31a9e0f0ed", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 110, "avg_line_length": 53.333333333333336, "alnum_prop": 0.696875, "repo_name": "Tweety-FER/tar-polarity", "id": "19f62e79a949b78e84aff1094ad958a72e6a0a88", "size": "322", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CropinionDataset/reviews_original/Train/comment2928.xml", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "4796" }, { "name": "Python", "bytes": "9870" } ], "symlink_target": "" }
#pragma once #include <string> #include <unordered_map> #include <folly/Range.h> namespace facebook { namespace memcache { class McReply; namespace mcrouter { // define stat_name_t #define STAT(name,...) name##_stat, #define STUI STAT #define STUIR STAT #define STSI STAT #define STSS STAT enum stat_name_t { #include "stat_list.h" num_stats, }; #undef STAT #undef STUI #undef STUIR #undef STSI #undef STSS // Forward declarations class McrouterInstance; struct proxy_t; /** statistics ftw */ struct stat_s; typedef std::string(*string_fn_t)(void*); enum stat_type_t { stat_string_fn, stat_string, stat_uint64, stat_int64, stat_double, // stat_percentile, // TBD num_stat_types }; enum stat_group_t { mcproxy_stats = 0x1, detailed_stats = 0x2, cmd_all_stats = 0x4, cmd_in_stats = 0x8, cmd_out_stats = 0x10, cmd_error_stats = 0x20, ods_stats = 0x40, rate_stats = 0x100, count_stats = 0x200, outlier_stats = 0x400, all_stats = 0xffff, server_stats = 0x10000, memory_stats = 0x20000, suspect_server_stats = 0x40000, unknown_stats = 0x10000000, }; /** defines a statistic: name, type, and data */ struct stat_t { folly::StringPiece name; int group; stat_type_t type; int aggregate; union { string_fn_t string_fn; char* string; uint64_t uint64; int64_t int64; double dbl; void* pointer; } data; }; /** prototypes are stupid */ void init_stats(stat_t* stats); void stat_incr(stat_t*, stat_name_t, int64_t); void stat_decr(stat_t*, stat_name_t, int64_t); void stat_incr_safe(stat_t*, stat_name_t); void stat_decr_safe(stat_t*, stat_name_t); /** * Current aggregation of rate of stats[idx] (which must be an aggregated * rate stat), units will be per second. */ double stats_aggregate_rate_value(const McrouterInstance& router, int idx); void stat_set_uint64(stat_t*, stat_name_t, uint64_t); uint64_t stat_get_uint64(stat_t*, stat_name_t); uint64_t stat_get_config_age(const stat_t* stats, uint64_t now); McReply stats_reply(proxy_t*, folly::StringPiece); void prepare_stats(McrouterInstance& router, stat_t* stats); void set_standalone_args(folly::StringPiece args); }}} // facebook::memcache::mcrouter
{ "content_hash": "44bf0a840e4a45ad8fcf001cbba6a4f4", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 75, "avg_line_length": 22.714285714285715, "alnum_prop": 0.6364779874213836, "repo_name": "evertrue/mcrouter", "id": "e2877bd30f7c842a48ee50bf176d02818e2363b3", "size": "2692", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "mcrouter/stats.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "363977" }, { "name": "C++", "bytes": "1343125" }, { "name": "Python", "bytes": "153762" }, { "name": "Ragel in Ruby Host", "bytes": "14762" }, { "name": "Shell", "bytes": "8366" } ], "symlink_target": "" }
extern const struct luaL_Reg CvLatentSvmDetector_m[]; #endif
{ "content_hash": "aa29bbd58659fa9fe5de418d86ec74c4", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 53, "avg_line_length": 30.5, "alnum_prop": 0.8032786885245902, "repo_name": "successinfo-org/CAPKit", "id": "a45cad837337c2dc67db93c0948c424a3cde9501", "size": "461", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Debug/CAPKit.framework/Headers/CvLatentSvmDetector.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "21692" }, { "name": "C++", "bytes": "34799" }, { "name": "CSS", "bytes": "3363" }, { "name": "Lua", "bytes": "5707" }, { "name": "Objective-C", "bytes": "125431" }, { "name": "Ruby", "bytes": "1665" }, { "name": "Shell", "bytes": "103" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <script> if('{{ jump }}'){ location.hash = '{{ jump }}'; } </script> <meta charset="utf-8"> <meta name="description" content="Udacity Multi User blog"> <meta name="author" content="//o.cx"> <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes"> <meta name="mobile-web-app-capable" content="yes"> <meta id="theme-color" name="theme-color" content="#307699"> <!-- TODO --> <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/3.0.2/css/font-awesome.css"> <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro" rel="stylesheet"> <link rel="stylesheet" href="/bower_components/bootstrap-fileinput/css/fileinput.min.css" /> {% if redirect %} <meta http-equiv="refresh" content="5; URL={{ redirect }}"> {% endif %} <link rel="stylesheet" href="/css/bootstrap.wrapper.css"> <title>Oliver Schleede - Multi User Blog</title> </head> <body class="udpy-blog"> <header id="header"> <nav role="navigation" class="navbar navbar-default navbar-static-top"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" data-target="#navbarCollapse" data-toggle="collapse" class="navbar-toggle"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <span class="logo"><a href="{{ config.blog_prefix }}" class="navbar-brand">UdPy Blog</a></span> </div> <!-- Collection of nav links and other content for toggling --> <div id="navbarCollapse" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="{{ config.blog_prefix }}" data-blog-control="get-home">Home</a></li> <li><a href="{{ config.blog_prefix }}newpost" data-blog-control="get-post-create">New Post</a></li> {% if user.legit %} <li><a class="hidden-sm hidden-md hidden-lg" href="{{ config.blog_prefix }}logout" data-blog-control="get-logout">Log out</a></li> {% else %} <li><a class="hidden-sm hidden-md hidden-lg" href="{{ config.blog_prefix }}login" data-blog-control="get-login">Log in</a></li> <li><a class="hidden-sm hidden-md hidden-lg" href="{{ config.blog_prefix }}signup" data-blog-control="get-signup">Sign up</a></li> {% endif %} </ul> {% if user.legit %} <form class="navbar-form navbar-right hidden-xs"> <div class="form-group"> <a href="{{ config.blog_prefix }}logout"><button type="button" class="btn btn-default" data-blog-control="get-logout">Log out</button></a> </div> </form> <form class="navbar-form navbar-right hidden-xs"> <span>Hello<br> {{ user.username }}</span> </form> {% else %} {% if not login_page %} <form class="navbar-form navbar-right hidden-xs"> <div class="form-group"> <a href="{{ config.blog_prefix }}signup" data-blog-control="get-signup"><button type="button" class="btn btn-primary">Sign up</button></a> </div> </form> <form class="navbar-form navbar-right hidden-xs"> <div class="form-group"> <a href="{{ config.blog_prefix }}login" data-blog-control="get-login"><button type="button" class="btn btn-default">Login</button></a> </div> </form> {% endif %} {% endif %} </div> </div> </nav> </header> <div class="container"> {% block content %}{% endblock %} </div> <footer id="footer"> <div class="container"> <div class="row"> <div class="col-sm-3"> <h2 class="logo"><a href="{{ config.blog_prefix }}" data-blog-control="get-home">UdPy Blog</a></h2> </div> <div class="col-sm-6"> <h5>Get started</h5> <ul> <li><a href="{{ config.blog_prefix }}" data-blog-control="get-home">Home</a></li> {% if user.legit %} <li><a class="hidden-sm" href="{{ config.blog_prefix }}logout" data-blog-control="get-logout">Log out</a></li> {% else %} <li><a class="hidden-sm" href="{{ config.blog_prefix }}login" data-blog-control="get-login">Log in</a></li> <li><a class="hidden-sm" href="{{ config.blog_prefix }}signup" data-blog-control="get-signup">Sign up</a></li> {% endif %} <li><a href="{{ config.blog_prefix }}newpost" data-blog-control="get-post-create">New Post</a></li> </ul> </div> <div class="col-sm-3"> <div class="social-networks"> <a href="https://github.com/ojonatan/udacity.com-nd004-p2-multi-user-blog" target="_blank" class="github"><i class="icon-github"></i></a> </div> </div> </div> </div> <div class="footer-copyright"> <p>© 2017 Copyright Text </p> <div class="stats"> <div class="stats-label">Users:</div> <div class="stats-value">{{ stats.users_count }}</div> <div class="stats-label">Posts</div> <div class="stats-value">{{ stats.posts_count }}</div> <div class="stats-label">Comments</div> <div class="stats-value">{{ stats.comments_count }}</div> </div> <div class="stats"> <div class="stats-label">Likes</div> <div class="stats-value">{{ stats.likes_count }}</div> <div class="stats-label">Images</div> <div class="stats-value">{{ stats.images_count }}</div> <div class="stats-label">BLOBs</div> <div class="stats-value">{{ stats.blobstore_count }} ({{ stats.blobstore_deleted_count }})</div> </div> </div> </footer> <script src="/bower_components/jquery/dist/jquery.min.js"></script> <script src="/bower_components/bootstrap/dist/js/bootstrap.min.js"></script> {% block js %}{% endblock %} <script src="/js/main.js"></script> </body> </html>
{ "content_hash": "38e47ca97da22f0dec30d136f4ac96eb", "timestamp": "", "source": "github", "line_count": 143, "max_line_length": 146, "avg_line_length": 40.54545454545455, "alnum_prop": 0.612969989651604, "repo_name": "ojonatan/udacity.com-nd004-p2-multi-user-blog", "id": "f175263c152475581be6579b3810a5b49e26c52a", "size": "5799", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "dist/templates/base.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "109" }, { "name": "CSS", "bytes": "34080" }, { "name": "HTML", "bytes": "29936" }, { "name": "JavaScript", "bytes": "2802" }, { "name": "Python", "bytes": "177566" } ], "symlink_target": "" }
ActiveRecord::Schema.define(:version => 20161208092423) do create_table "actions", :force => true do |t| t.string "name" t.text "code" t.integer "vendor_id" t.integer "user_id" t.string "whento" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.string "behavior" t.integer "weight", :default => 0 t.string "afield" t.float "value", :default => 0.0 t.string "field2" t.float "value2" t.integer "hidden_by" t.boolean "hidden" t.datetime "hidden_at" t.integer "company_id" t.string "model_type" t.integer "model_id" t.text "js_code" t.integer "created_by" end add_index "actions", ["user_id"], :name => "index_actions_on_user_id" add_index "actions", ["vendor_id"], :name => "index_actions_on_vendor_id" create_table "broken_items", :force => true do |t| t.string "name" t.string "sku" t.float "quantity" t.integer "vendor_id" t.integer "shipper_id" t.text "note" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.boolean "is_shipment_item" t.integer "hidden_by" t.boolean "hidden" t.datetime "hidden_at" t.integer "company_id" t.integer "user_id" t.integer "price_cents", :default => 0 t.string "currency" end create_table "buttons", :force => true do |t| t.string "name" t.string "sku" t.string "old_category_name" t.integer "weight" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.integer "vendor_id" t.boolean "is_buyback" t.integer "category_id" t.string "color" t.integer "position" t.boolean "hidden" t.integer "hidden_by" t.datetime "hidden_at" t.integer "company_id" t.integer "user_id" end create_table "cash_registers", :force => true do |t| t.string "name" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.integer "vendor_id" t.string "scale" t.string "cash_drawer_path" t.boolean "big_buttons" t.boolean "hide_discounts" t.boolean "no_print" t.string "thermal_printer", :default => "/dev/usb/lp0" t.string "sticker_printer", :default => "/dev/usb/lp1" t.string "a4_printer" t.string "pole_display" t.string "customer_screen_blurb" t.boolean "salor_printer" t.string "color" t.string "ip" t.boolean "hide_buttons", :default => true t.boolean "show_plus_minus", :default => true t.boolean "detailed_edit" t.string "cash_drawer_name" t.string "thermal_printer_name" t.string "sticker_printer_name" t.string "scale_name" t.boolean "always_open_drawer" t.string "pole_display_name" t.boolean "require_password" t.string "locale" t.boolean "hidden" t.integer "hidden_by" t.datetime "hidden_at" t.integer "company_id" t.integer "user_id" t.string "customerscreen_mode" end add_index "cash_registers", ["company_id"], :name => "index_cash_registers_on_company_id" add_index "cash_registers", ["hidden"], :name => "index_cash_registers_on_hidden" add_index "cash_registers", ["vendor_id"], :name => "index_cash_registers_on_vendor_id" create_table "categories", :force => true do |t| t.integer "vendor_id" t.string "name" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.float "quantity_sold", :default => 0.0 t.float "cash_made" t.boolean "button_category" t.integer "position" t.string "color" t.string "sku" t.integer "hidden_by" t.boolean "hidden" t.datetime "hidden_at" t.integer "company_id" t.integer "user_id" end add_index "categories", ["company_id"], :name => "index_categories_on_company_id" add_index "categories", ["hidden"], :name => "index_categories_on_hidden" add_index "categories", ["vendor_id"], :name => "index_categories_on_vendor_id" create_table "companies", :force => true do |t| t.string "name" t.string "identifier" t.string "mode", :default => "local" t.string "subdomain" t.boolean "hidden" t.integer "hidden_by" t.datetime "hidden_at" t.boolean "active", :default => true t.string "email" t.string "auth_user" t.string "full_subdomain" t.string "full_url" t.string "virtualhost_filter" t.integer "auth_https_mode" t.boolean "https" t.boolean "auth" t.string "domain" t.boolean "removal_pending" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end create_table "countries", :force => true do |t| t.string "name" t.integer "vendor_id" t.integer "user_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.integer "hidden_by" t.boolean "hidden" t.datetime "hidden_at" t.integer "company_id" end create_table "cues", :force => true do |t| t.boolean "is_handled", :default => false t.boolean "to_send", :default => false t.boolean "to_receive", :default => false t.text "payload" t.string "url" t.string "source_sku" t.string "destination_sku" t.string "owner_type" t.integer "owner_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end create_table "customers", :force => true do |t| t.string "first_name" t.string "last_name" t.string "street1" t.string "street2" t.string "postalcode" t.string "state" t.string "country" t.string "city" t.string "telephone" t.string "cellphone" t.string "email" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.integer "vendor_id" t.string "company_name" t.string "sku" t.integer "hidden_by" t.string "tax_number" t.boolean "hidden" t.datetime "hidden_at" t.integer "company_id" t.integer "user_id" end add_index "customers", ["company_id"], :name => "index_customers_on_company_id" add_index "customers", ["hidden"], :name => "index_customers_on_hidden" add_index "customers", ["vendor_id"], :name => "index_customers_on_vendor_id" create_table "discounts", :force => true do |t| t.string "name" t.datetime "start_date" t.datetime "end_date" t.integer "vendor_id" t.integer "category_id" t.integer "location_id" t.string "item_sku" t.string "applies_to" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.float "amount" t.string "amount_type" t.string "sku" t.integer "hidden_by" t.boolean "hidden" t.datetime "hidden_at" t.integer "company_id" t.integer "user_id" end add_index "discounts", ["amount_type"], :name => "index_discounts_on_amount_type" add_index "discounts", ["applies_to"], :name => "index_discounts_on_applies_to" add_index "discounts", ["category_id"], :name => "index_discounts_on_category_id" add_index "discounts", ["company_id"], :name => "index_discounts_on_company_id" add_index "discounts", ["hidden"], :name => "index_discounts_on_hidden" add_index "discounts", ["item_sku"], :name => "index_discounts_on_item_sku" add_index "discounts", ["location_id"], :name => "index_discounts_on_location_id" add_index "discounts", ["sku"], :name => "index_discounts_on_sku" add_index "discounts", ["vendor_id"], :name => "index_discounts_on_vendor_id" create_table "discounts_order_items", :id => false, :force => true do |t| t.integer "order_item_id" t.integer "discount_id" end add_index "discounts_order_items", ["order_item_id", "discount_id"], :name => "index_discounts_order_items_on_order_item_id_and_discount_id" create_table "drawer_transactions", :force => true do |t| t.integer "drawer_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.text "notes" t.boolean "refund" t.string "tag" t.integer "cash_register_id" t.integer "order_id" t.integer "order_item_id" t.integer "vendor_id" t.integer "hidden_by" t.boolean "hidden" t.datetime "hidden_at" t.integer "company_id" t.integer "user_id" t.boolean "complete_order" t.integer "nr" t.integer "amount_cents", :default => 0 t.integer "drawer_amount_cents", :default => 0 t.string "currency" end add_index "drawer_transactions", ["company_id"], :name => "index_drawer_transactions_on_company_id" add_index "drawer_transactions", ["complete_order"], :name => "index_drawer_transactions_on_complete_order" add_index "drawer_transactions", ["created_at"], :name => "index_drawer_transactions_on_created_at" add_index "drawer_transactions", ["drawer_id"], :name => "index_drawer_transactions_on_drawer_id" add_index "drawer_transactions", ["hidden"], :name => "index_drawer_transactions_on_hidden" add_index "drawer_transactions", ["order_id"], :name => "index_drawer_transactions_on_order_id" add_index "drawer_transactions", ["refund"], :name => "index_drawer_transactions_on_refund" add_index "drawer_transactions", ["user_id"], :name => "index_drawer_transactions_on_user_id" add_index "drawer_transactions", ["vendor_id"], :name => "index_drawer_transactions_on_vendor_id" create_table "drawers", :force => true do |t| t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.boolean "hidden" t.integer "hidden_by" t.datetime "hidden_at" t.integer "vendor_id" t.integer "company_id" t.integer "amount_cents", :default => 0 t.string "currency" end create_table "emails", :force => true do |t| t.string "sender" t.string "receipient" t.string "subject" t.text "body" t.boolean "technician" t.integer "vendor_id" t.integer "company_id" t.integer "user_id" t.integer "model_id" t.integer "model_type" t.boolean "hidden" t.integer "hidden_by" t.datetime "hidden_at" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end create_table "histories", :force => true do |t| t.string "url" t.string "action_taken" t.string "model_type" t.string "ip" t.integer "sensitivity" t.integer "model_id" t.text "changes_made" t.text "params" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.boolean "hidden" t.integer "hidden_by" t.datetime "hidden_at" t.integer "vendor_id" t.integer "company_id" t.integer "user_id" end create_table "images", :force => true do |t| t.string "name" t.string "imageable_type" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.integer "imageable_id" t.integer "company_id" t.integer "vendor_id" t.string "image_type" t.boolean "hidden" t.integer "hidden_by" t.datetime "hidden_at" end create_table "inventory_report_items", :force => true do |t| t.integer "inventory_report_id" t.integer "item_id" t.float "real_quantity" t.float "quantity" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.integer "vendor_id" t.boolean "hidden" t.integer "hidden_by" t.datetime "hidden_at" t.integer "company_id" t.integer "user_id" t.integer "category_id" t.integer "purchase_price_cents" t.integer "price_cents" t.string "name" t.string "sku" t.string "currency" t.integer "tax_profile_id" end add_index "inventory_report_items", ["inventory_report_id"], :name => "index_inventory_report_items_on_inventory_report_id" add_index "inventory_report_items", ["item_id"], :name => "index_inventory_report_items_on_item_id" add_index "inventory_report_items", ["vendor_id"], :name => "index_inventory_report_items_on_vendor_id" create_table "inventory_reports", :force => true do |t| t.string "name" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.integer "vendor_id" t.boolean "hidden" t.integer "hidden_by" t.datetime "hidden_at" t.integer "company_id" t.integer "user_id" end add_index "inventory_reports", ["vendor_id"], :name => "index_inventory_reports_on_vendor_id" create_table "invoice_blurbs", :force => true do |t| t.string "lang" t.text "body" t.boolean "is_header" t.integer "vendor_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.text "body_receipt" t.boolean "hidden" t.integer "hidden_by" t.datetime "hidden_at" t.integer "company_id" t.integer "user_id" end create_table "invoice_notes", :force => true do |t| t.string "name" t.text "note_header" t.text "note_footer" t.integer "origin_country_id" t.integer "destination_country_id" t.integer "vendor_id" t.integer "user_id" t.integer "sale_type_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.boolean "hidden" t.integer "hidden_by" t.datetime "hidden_at" t.integer "company_id" end create_table "item_shippers", :force => true do |t| t.integer "shipper_id" t.integer "item_id" t.float "purchase_price" t.float "list_price" t.string "item_sku" t.string "shipper_sku" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.boolean "hidden" t.integer "hidden_by" t.datetime "hidden_at" t.integer "vendor_id" t.integer "company_id" t.integer "user_id" end add_index "item_shippers", ["company_id"], :name => "index_item_shippers_on_company_id" add_index "item_shippers", ["hidden"], :name => "index_item_shippers_on_hidden" add_index "item_shippers", ["item_id"], :name => "index_item_shippers_on_item_id" add_index "item_shippers", ["shipper_id"], :name => "index_item_shippers_on_shipper_id" add_index "item_shippers", ["vendor_id"], :name => "index_item_shippers_on_vendor_id" create_table "item_stocks", :force => true do |t| t.integer "item_id" t.float "quantity", :default => 0.0 t.integer "location_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.integer "vendor_id" t.boolean "hidden" t.integer "hidden_by" t.datetime "hidden_at" t.integer "company_id" t.integer "user_id" t.string "location_type" end add_index "item_stocks", ["company_id"], :name => "index_item_stocks_on_company_id" add_index "item_stocks", ["hidden"], :name => "index_item_stocks_on_hidden" add_index "item_stocks", ["item_id"], :name => "index_item_stocks_on_item_id" add_index "item_stocks", ["location_id"], :name => "index_item_stocks_on_location_id" add_index "item_stocks", ["vendor_id"], :name => "index_item_stocks_on_vendor_id" create_table "item_types", :force => true do |t| t.string "name" t.string "behavior" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.integer "vendor_id" t.boolean "hidden" t.integer "hidden_by" t.datetime "hidden_at" t.integer "company_id" t.integer "user_id" end create_table "items", :force => true do |t| t.string "name" t.text "description" t.string "sku" t.string "image" t.integer "vendor_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.integer "location_id" t.integer "category_id" t.integer "tax_profile_id" t.integer "item_type_id" t.boolean "activated" t.integer "void" t.integer "coupon_type" t.string "coupon_applies" t.float "quantity", :default => 0.0 t.float "quantity_sold", :default => 0.0 t.integer "part_id" t.boolean "calculate_part_price" t.float "height", :default => 0.0 t.float "weight", :default => 0.0 t.string "height_metric" t.string "weight_metric", :default => "g" t.float "length", :default => 0.0 t.float "width", :default => 0.0 t.string "length_metric" t.string "width_metric" t.boolean "is_gs1" t.boolean "price_by_qty" t.float "part_quantity", :default => 0.0 t.string "behavior" t.string "sales_metric" t.date "expires_on" t.integer "quantity_buyback", :default => 0 t.boolean "default_buyback" t.float "real_quantity", :default => 0.0 t.boolean "weigh_compulsory" t.float "min_quantity", :default => 0.0 t.boolean "active", :default => true t.integer "shipper_id" t.string "shipper_sku" t.float "packaging_unit", :default => 1.0 t.boolean "ignore_qty" t.integer "child_id" t.boolean "must_change_price" t.boolean "hidden_by_distiller" t.boolean "track_expiry" t.string "customs_code" t.string "origin_country" t.text "name_translations" t.integer "hidden_by" t.boolean "real_quantity_updated" t.boolean "hidden" t.datetime "hidden_at" t.integer "company_id" t.integer "user_id" t.boolean "is_part" t.string "gs1_format", :default => "2,3" t.integer "price_cents", :default => 0 t.integer "gift_card_amount_cents", :default => 0 t.integer "purchase_price_cents", :default => 0 t.integer "buy_price_cents", :default => 0 t.integer "manufacturer_price_cents", :default => 0 t.string "currency" t.integer "created_by" t.string "longname" t.string "shortname" t.date "expiry_date" end add_index "items", ["category_id"], :name => "index_items_on_category_id" add_index "items", ["child_id"], :name => "index_items_on_child_id" add_index "items", ["company_id"], :name => "index_items_on_company_id" add_index "items", ["coupon_applies"], :name => "index_items_on_coupon_applies" add_index "items", ["coupon_type"], :name => "index_items_on_coupon_type" add_index "items", ["hidden"], :name => "index_items_on_hidden" add_index "items", ["item_type_id"], :name => "index_items_on_item_type_id" add_index "items", ["location_id"], :name => "index_items_on_location_id" add_index "items", ["name"], :name => "index_items_on_name" add_index "items", ["part_id"], :name => "index_items_on_part_id" add_index "items", ["sku"], :name => "index_items_on_sku" add_index "items", ["tax_profile_id"], :name => "index_items_on_tax_profile_id" add_index "items", ["vendor_id"], :name => "index_items_on_vendor_id" create_table "list_items", :force => true do |t| t.string "name" t.integer "quantity" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.integer "purchase_item_id" t.string "sku" t.integer "stock" end create_table "locations", :force => true do |t| t.string "name" t.float "x" t.float "y" t.string "shape" t.integer "vendor_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.string "applies_to" t.float "quantity_sold", :default => 0.0 t.float "cash_made", :default => 0.0 t.string "sku", :default => "" t.integer "hidden_by" t.boolean "hidden" t.datetime "hidden_at" t.integer "company_id" t.integer "user_id" end add_index "locations", ["company_id"], :name => "index_locations_on_company_id" add_index "locations", ["hidden"], :name => "index_locations_on_hidden" add_index "locations", ["vendor_id"], :name => "index_locations_on_vendor_id" create_table "loyalty_cards", :force => true do |t| t.integer "points" t.integer "num_swipes" t.integer "num_used" t.integer "customer_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.string "sku" t.string "customer_sku" t.integer "vendor_id" t.boolean "hidden" t.integer "hidden_by" t.datetime "hidden_at" t.integer "company_id" t.integer "user_id" end add_index "loyalty_cards", ["company_id"], :name => "index_loyalty_cards_on_company_id" add_index "loyalty_cards", ["customer_id"], :name => "index_loyalty_cards_on_customer_id" add_index "loyalty_cards", ["hidden"], :name => "index_loyalty_cards_on_hidden" add_index "loyalty_cards", ["sku"], :name => "index_loyalty_cards_on_sku" add_index "loyalty_cards", ["vendor_id"], :name => "index_loyalty_cards_on_vendor_id" create_table "node_messages", :force => true do |t| t.string "source_sku" t.string "dest_sku" t.string "mdhash" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end create_table "node_queues", :force => true do |t| t.boolean "handled", :default => false t.boolean "send", :default => false t.boolean "receive", :default => false t.text "payload" t.string "url" t.string "source_sku" t.string "destination_sku" t.string "owner_type" t.integer "owner_ir" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end create_table "nodes", :force => true do |t| t.string "name" t.string "sku" t.string "token" t.string "node_type" t.string "url" t.boolean "is_self" t.text "accepted_ips" t.integer "vendor_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.string "status" t.boolean "is_busy", :default => false t.integer "hidden", :default => 0 t.boolean "accepts_tax_profiles", :default => true t.boolean "accepts_buttons", :default => true t.boolean "accepts_categories", :default => true t.boolean "accepts_items", :default => true t.boolean "accepts_customers", :default => true t.boolean "accepts_loyalty_cards", :default => true t.boolean "accepts_discounts", :default => true end create_table "notes", :force => true do |t| t.string "title" t.text "body" t.integer "notable_id" t.string "notable_type" t.integer "user_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.boolean "hidden" t.integer "hidden_by" t.datetime "hidden_at" t.integer "vendor_id" t.integer "company_id" end add_index "notes", ["notable_id"], :name => "index_notes_on_notable_id" add_index "notes", ["user_id"], :name => "index_notes_on_user_id" create_table "order_items", :force => true do |t| t.integer "order_id" t.integer "item_id" t.float "quantity" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.integer "tax_profile_id" t.integer "item_type_id" t.boolean "activated" t.string "behavior" t.float "tax" t.integer "category_id" t.integer "location_id" t.boolean "refunded" t.datetime "refunded_at" t.integer "refunded_by" t.float "rebate" t.integer "coupon_id" t.boolean "is_buyback" t.string "sku" t.boolean "weigh_compulsory" t.boolean "no_inc" t.boolean "action_applied" t.integer "vendor_id" t.integer "hidden_by" t.boolean "hidden" t.datetime "hidden_at" t.integer "company_id" t.integer "user_id" t.float "discount" t.boolean "calculate_part_price" t.integer "drawer_id" t.integer "price_cents", :default => 0 t.integer "gift_card_amount_cents", :default => 0 t.integer "tax_amount_cents", :default => 0 t.integer "coupon_amount_cents", :default => 0 t.integer "discount_amount_cents", :default => 0 t.integer "rebate_amount_cents", :default => 0 t.integer "total_cents", :default => 0 t.datetime "completed_at" t.string "currency" t.boolean "is_proforma" t.boolean "is_quote" t.boolean "is_unpaid" t.boolean "paid" t.datetime "paid_at" t.integer "refund_payment_method_item_id" end add_index "order_items", ["activated"], :name => "index_order_items_on_activated" add_index "order_items", ["behavior"], :name => "index_order_items_on_behavior" add_index "order_items", ["category_id"], :name => "index_order_items_on_category_id" add_index "order_items", ["company_id"], :name => "index_order_items_on_company_id" add_index "order_items", ["completed_at"], :name => "index_order_items_on_completed_at" add_index "order_items", ["coupon_id"], :name => "index_order_items_on_coupon_id" add_index "order_items", ["drawer_id"], :name => "index_order_items_on_drawer_id" add_index "order_items", ["hidden"], :name => "index_order_items_on_hidden" add_index "order_items", ["is_buyback"], :name => "index_order_items_on_is_buyback" add_index "order_items", ["is_proforma"], :name => "index_order_items_on_is_proforma" add_index "order_items", ["is_quote"], :name => "index_order_items_on_is_quote" add_index "order_items", ["item_id"], :name => "index_order_items_on_item_id" add_index "order_items", ["item_type_id"], :name => "index_order_items_on_item_type_id" add_index "order_items", ["location_id"], :name => "index_order_items_on_location_id" add_index "order_items", ["no_inc"], :name => "index_order_items_on_no_inc" add_index "order_items", ["order_id"], :name => "index_order_items_on_order_id" add_index "order_items", ["refunded"], :name => "index_order_items_on_refunded" add_index "order_items", ["sku"], :name => "index_order_items_on_sku" add_index "order_items", ["tax"], :name => "index_order_items_on_tax" add_index "order_items", ["tax_profile_id"], :name => "index_order_items_on_tax_profile_id" add_index "order_items", ["total_cents"], :name => "index_order_items_on_total_cents" add_index "order_items", ["user_id"], :name => "index_order_items_on_user_id" add_index "order_items", ["vendor_id"], :name => "index_order_items_on_vendor_id" create_table "orders", :force => true do |t| t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.integer "vendor_id" t.integer "user_id" t.integer "location_id" t.integer "cash_register_id" t.integer "customer_id" t.float "rebate" t.integer "lc_points" t.string "tag" t.boolean "buy_order" t.boolean "was_printed" t.string "sku" t.integer "drawer_id" t.integer "origin_country_id" t.integer "destination_country_id" t.integer "sale_type_id" t.text "invoice_comment" t.text "delivery_note_comment" t.integer "nr" t.boolean "is_proforma" t.integer "hidden_by" t.boolean "is_unpaid" t.integer "qnr" t.boolean "is_quote" t.boolean "hidden" t.datetime "hidden_at" t.integer "company_id" t.boolean "paid" t.datetime "paid_at" t.float "tax" t.integer "tax_profile_id" t.integer "total_cents", :default => 0 t.integer "tax_amount_cents", :default => 0 t.integer "cash_cents", :default => 0 t.integer "lc_amount_cents", :default => 0 t.integer "change_cents", :default => 0 t.integer "payment_total_cents", :default => 0 t.integer "noncash_cents", :default => 0 t.integer "rebate_amount_cents", :default => 0 t.datetime "completed_at" t.string "currency" t.integer "proforma_order_id" t.datetime "payment_due" t.boolean "subscription" t.integer "subscription_interval" t.integer "subscription_order_id" t.datetime "subscription_start" t.datetime "subscription_next" t.datetime "subscription_last" end add_index "orders", ["cash_register_id"], :name => "index_orders_on_cash_register_id" add_index "orders", ["company_id"], :name => "index_orders_on_company_id" add_index "orders", ["customer_id"], :name => "index_orders_on_customer_id" add_index "orders", ["drawer_id"], :name => "index_orders_on_drawer_id" add_index "orders", ["hidden"], :name => "index_orders_on_hidden" add_index "orders", ["location_id"], :name => "index_orders_on_location_id" add_index "orders", ["paid"], :name => "index_orders_on_paid" add_index "orders", ["user_id"], :name => "index_orders_on_user_id" add_index "orders", ["vendor_id"], :name => "index_orders_on_vendor_id" create_table "payment_method_items", :force => true do |t| t.integer "order_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.integer "vendor_id" t.boolean "hidden" t.integer "hidden_by" t.datetime "hidden_at" t.integer "company_id" t.integer "user_id" t.integer "drawer_id" t.integer "payment_method_id" t.boolean "cash" t.boolean "change" t.integer "cash_register_id" t.boolean "unpaid" t.boolean "quote" t.boolean "refund" t.integer "amount_cents", :default => 0 t.string "currency" t.integer "order_item_id" t.boolean "is_proforma" t.boolean "is_quote" t.boolean "is_unpaid" t.boolean "paid" t.datetime "paid_at" t.datetime "completed_at" end add_index "payment_method_items", ["cash"], :name => "index_payment_method_items_on_cash" add_index "payment_method_items", ["cash_register_id"], :name => "index_payment_method_items_on_cash_register_id" add_index "payment_method_items", ["change"], :name => "index_payment_method_items_on_change" add_index "payment_method_items", ["company_id"], :name => "index_payment_method_items_on_company_id" add_index "payment_method_items", ["completed_at"], :name => "index_payment_method_items_on_completed_at" add_index "payment_method_items", ["drawer_id"], :name => "index_payment_method_items_on_drawer_id" add_index "payment_method_items", ["hidden"], :name => "index_payment_method_items_on_hidden" add_index "payment_method_items", ["is_proforma"], :name => "index_payment_method_items_on_is_proforma" add_index "payment_method_items", ["is_quote"], :name => "index_payment_method_items_on_is_quote" add_index "payment_method_items", ["order_id"], :name => "index_payment_methods_on_order_id" add_index "payment_method_items", ["payment_method_id"], :name => "index_payment_method_items_on_payment_method_id" add_index "payment_method_items", ["refund"], :name => "index_payment_method_items_on_refund" add_index "payment_method_items", ["user_id"], :name => "index_payment_method_items_on_user_id" add_index "payment_method_items", ["vendor_id"], :name => "index_payment_method_items_on_vendor_id" create_table "payment_methods", :force => true do |t| t.string "name" t.string "internal_type" t.integer "vendor_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.integer "hidden", :default => 0 t.boolean "cash" t.boolean "change" t.boolean "unpaid" t.boolean "quote" t.integer "position" t.integer "company_id" t.datetime "hidden_at" t.integer "hidden_by" end create_table "plugins", :force => true do |t| t.string "name" t.string "filename" t.string "base_path" t.integer "company_id" t.integer "vendor_id" t.boolean "hidden" t.integer "hidden_by" t.datetime "hidden_at" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.text "files" t.text "meta" end add_index "plugins", ["company_id"], :name => "index_plugins_on_company_id" add_index "plugins", ["hidden_by"], :name => "index_plugins_on_hidden_by" add_index "plugins", ["vendor_id"], :name => "index_plugins_on_vendor_id" create_table "purchase_items", :force => true do |t| t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.string "name" end create_table "receipts", :force => true do |t| t.string "ip" t.integer "cash_register_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.integer "vendor_id" t.integer "order_id" t.binary "content" t.boolean "hidden" t.integer "hidden_by" t.datetime "hidden_at" t.integer "company_id" t.integer "user_id" t.integer "drawer_id" end create_table "reminders", :force => true do |t| t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end create_table "roles", :force => true do |t| t.string "name" t.integer "vendor_id" t.integer "company_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.boolean "hidden" t.integer "hidden_by" t.datetime "hidden_at" t.integer "user_id" end create_table "roles_users", :id => false, :force => true do |t| t.integer "user_id" t.integer "role_id" end create_table "sale_types", :force => true do |t| t.string "name" t.integer "vendor_id" t.integer "user_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.integer "hidden_by" t.boolean "hidden" t.datetime "hidden_at" t.integer "company_id" end create_table "shipment_items", :force => true do |t| t.string "name" t.integer "category_id" t.integer "location_id" t.integer "item_type_id" t.string "sku" t.integer "shipment_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.boolean "in_stock" t.float "quantity" t.integer "hidden_by" t.integer "vendor_id" t.boolean "hidden" t.datetime "hidden_at" t.integer "company_id" t.integer "user_id" t.integer "price_cents", :default => 0 t.integer "purchase_price_cents", :default => 0 t.string "currency" t.integer "total_cents" t.integer "purchase_price_total_cents" t.integer "tax_profile_id" t.float "in_stock_quantity" end add_index "shipment_items", ["category_id"], :name => "index_shipment_items_on_category_id" add_index "shipment_items", ["company_id"], :name => "index_shipment_items_on_company_id" add_index "shipment_items", ["hidden"], :name => "index_shipment_items_on_hidden" add_index "shipment_items", ["item_type_id"], :name => "index_shipment_items_on_item_type_id" add_index "shipment_items", ["location_id"], :name => "index_shipment_items_on_location_id" add_index "shipment_items", ["shipment_id"], :name => "index_shipment_items_on_shipment_id" add_index "shipment_items", ["vendor_id"], :name => "index_shipment_items_on_vendor_id" create_table "shipment_items_stock_locations", :id => false, :force => true do |t| t.integer "shipment_item_id" t.integer "stock_location_id" end add_index "shipment_items_stock_locations", ["shipment_item_id", "stock_location_id"], :name => "shipment_items_stock" create_table "shipment_types", :force => true do |t| t.string "name" t.integer "user_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.integer "vendor_id" t.integer "hidden_by" t.boolean "hidden" t.datetime "hidden_at" t.integer "company_id" end add_index "shipment_types", ["name"], :name => "index_shipment_types_on_name" add_index "shipment_types", ["user_id"], :name => "index_shipment_types_on_user_id" create_table "shipments", :force => true do |t| t.string "receiver_id" t.string "shipper_id" t.string "shipper_type" t.string "receiver_type" t.boolean "paid" t.integer "user_id" t.string "status" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.string "name" t.integer "vendor_id" t.integer "shipment_type_id" t.string "sku" t.integer "hidden_by" t.boolean "hidden" t.datetime "hidden_at" t.integer "company_id" t.integer "price_cents", :default => 0 t.string "currency" t.integer "total_cents" t.integer "purchase_price_total_cents" end add_index "shipments", ["company_id"], :name => "index_shipments_on_company_id" add_index "shipments", ["hidden"], :name => "index_shipments_on_hidden" add_index "shipments", ["receiver_id"], :name => "index_shipments_on_receiver_id" add_index "shipments", ["shipper_id"], :name => "index_shipments_on_shipper_id" add_index "shipments", ["user_id"], :name => "index_shipments_on_user_id" add_index "shipments", ["vendor_id"], :name => "index_shipments_on_vendor_id" create_table "shippers", :force => true do |t| t.string "name" t.string "contact_person" t.string "contact_phone" t.string "contact_fax" t.string "contact_email" t.integer "user_id" t.text "contact_address" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.string "reorder_type" t.string "sku" t.integer "vendor_id" t.integer "hidden_by" t.boolean "hidden" t.datetime "hidden_at" t.integer "company_id" t.string "import_format" t.string "csv_url" end add_index "shippers", ["user_id"], :name => "index_shippers_on_user_id" create_table "stock_locations", :force => true do |t| t.string "name" t.integer "vendor_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.integer "hidden_by" t.boolean "hidden" t.datetime "hidden_at" t.integer "company_id" t.integer "user_id" end add_index "stock_locations", ["vendor_id"], :name => "index_stock_locations_on_vendor_id" create_table "stock_transactions", :force => true do |t| t.integer "company_id" t.integer "vendor_id" t.integer "user_id" t.integer "cash_register_id" t.integer "order_id" t.integer "from_id" t.string "from_type" t.integer "to_id" t.string "to_type" t.float "from_quantity" t.float "to_quantity" t.float "quantity" t.boolean "hidden" t.integer "hidden_by" t.datetime "hidden_at" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end create_table "tax_profiles", :force => true do |t| t.string "name" t.float "value" t.integer "default" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.integer "user_id" t.string "sku" t.integer "vendor_id" t.string "letter" t.integer "hidden_by" t.boolean "hidden" t.datetime "hidden_at" t.integer "company_id" t.string "color" end add_index "tax_profiles", ["user_id"], :name => "index_tax_profiles_on_user_id" create_table "transaction_tags", :force => true do |t| t.string "name" t.integer "vendor_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.integer "hidden_by" t.boolean "hidden" t.datetime "hidden_at" t.integer "company_id" t.integer "user_id" end create_table "user_logins", :force => true do |t| t.datetime "login" t.datetime "logout" t.float "hourly_rate" t.integer "user_id" t.integer "vendor_id" t.integer "shift_seconds" t.float "amount_due" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.integer "company_id" t.boolean "hidden" t.integer "hidden_by" t.datetime "hidden_at" end add_index "user_logins", ["user_id"], :name => "index_employee_logins_on_employee_id" create_table "user_meta", :force => true do |t| t.integer "user_id" t.string "key" t.text "value" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end add_index "user_meta", ["user_id"], :name => "index_user_meta_on_user_id" create_table "users", :force => true do |t| t.string "email", :default => "", :null => false t.string "encrypted_password", :limit => 128, :default => "", :null => false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.integer "sign_in_count", :default => 0 t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.string "current_sign_in_ip" t.string "last_sign_in_ip" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.string "username" t.integer "vendor_id" t.string "first_name" t.string "last_name" t.string "language" t.string "theme" t.boolean "js_keyboard" t.string "apitoken" t.integer "uses_drawer_id" t.integer "auth_code" t.string "last_path" t.string "role_cache" t.float "hourly_rate" t.string "telephone" t.string "cellphone" t.text "address" t.integer "current_order_id" t.integer "company_id" t.boolean "hidden" t.datetime "hidden_at" t.integer "hidden_by" t.integer "drawer_id" t.string "id_hash" end create_table "users_vendors", :id => false, :force => true do |t| t.integer "user_id" t.integer "vendor_id" end create_table "vendors", :force => true do |t| t.string "name" t.integer "user_id" t.text "description" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.boolean "multi_currency" t.string "sku" t.string "token" t.string "email" t.boolean "use_order_numbers", :default => true t.string "unused_order_numbers", :default => "--- []\n" t.integer "largest_order_number", :default => 0 t.integer "hidden_by" t.binary "receipt_logo_header" t.binary "receipt_logo_footer" t.boolean "use_quote_numbers", :default => true t.string "unused_quote_numbers", :default => "--- []\n" t.integer "largest_quote_number", :default => 0 t.string "time_zone" t.string "hash_id" t.boolean "hidden" t.datetime "hidden_at" t.integer "vendor_id" t.integer "company_id" t.float "lp_per_dollar" t.float "dollar_per_lp" t.text "address" t.string "telephone" t.text "receipt_blurb" t.integer "pagination", :default => 10 t.string "stylesheets" t.string "cash_drawer" t.boolean "open_cash_drawer" t.datetime "last_wholesaler_check" t.text "csv_imports" t.string "csv_imports_url" t.boolean "items_view_list" t.boolean "salor_printer" t.text "receipt_blurb_footer" t.boolean "license_accepted" t.boolean "csv_categories" t.boolean "csv_buttons" t.boolean "csv_discounts" t.boolean "csv_customers" t.boolean "csv_loyalty_cards" t.text "invoice_blurb" t.text "invoice_blurb_footer" t.string "gs1_format", :default => "2,5,5" t.string "country", :default => "us" t.integer "largest_drawer_transaction_number", :default => 0 t.boolean "enable_technician_emails" t.string "technician_email" t.string "identifier" t.string "full_subdomain" t.string "full_url" t.string "virtualhost_filter" t.integer "auth_https_mode" t.boolean "https" t.boolean "auth" t.string "domain" t.string "subdomain" t.string "currency", :default => "USD" t.integer "pagination_invoice_one", :default => 20 t.integer "pagination_invoice_other", :default => 30 end add_index "vendors", ["user_id"], :name => "index_vendors_on_user_id" end
{ "content_hash": "7b1bf87ac94eb681aadcaf512ad5eb4b", "timestamp": "", "source": "github", "line_count": 1263, "max_line_length": 142, "avg_line_length": 36.612826603325416, "alnum_prop": 0.5872367112149128, "repo_name": "faisal-bhatti/pos", "id": "a33c7ebe99fa3fdc8089b95445273d06dab37051", "size": "46977", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/schema.rb", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "87409" }, { "name": "CoffeeScript", "bytes": "916" }, { "name": "HTML", "bytes": "240148" }, { "name": "JavaScript", "bytes": "423152" }, { "name": "PostScript", "bytes": "9398" }, { "name": "Ruby", "bytes": "729069" } ], "symlink_target": "" }
from bokeh.sampledata.iris import flowers from bokeh.plotting import * colormap = {'setosa': 'red', 'versicolor': 'green', 'virginica': 'blue'} flowers['color'] = flowers['species'].map(lambda x: colormap[x]) output_file("iris.html", title="iris.py example") p = figure(title = "Iris Morphology") p.xaxis.axis_label = 'Petal Length' p.yaxis.axis_label = 'Petal Width' p.circle(flowers["petal_length"], flowers["petal_width"], color=flowers["color"], fill_alpha=0.2, size=10, ) show(p)
{ "content_hash": "40fa176df909d3b8836d789867526c8d", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 72, "avg_line_length": 31.125, "alnum_prop": 0.6887550200803213, "repo_name": "almarklein/bokeh", "id": "ca7e7aacc9041d9e98e693fb7d29382c5be765a5", "size": "498", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "examples/plotting/file/iris.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "410607" }, { "name": "CoffeeScript", "bytes": "2138603" }, { "name": "JavaScript", "bytes": "349966" }, { "name": "Makefile", "bytes": "6253" }, { "name": "Python", "bytes": "1543731" }, { "name": "Scala", "bytes": "28963" }, { "name": "Shell", "bytes": "20366" } ], "symlink_target": "" }
''' This is a tool to help fiction writers generate ideas for unique characters. The user inputs the first and last name, gender and an archetype and a unique character is generated. ''' import traits from classes import Character import archetypes as arch def characterize( first='Jane', last='Doe', gender='Female', archetype=arch.standard): '''Generate a fictional character based on user arguments.''' my_char = Character(first, last, gender, archetype) # Create a character. my_char.sample_traits(archetype) # Sample some personality traits. my_char.export_markdown() # Serialize character sheet in Markdown. characterize('Example', 'Character', 'Female', archetype=arch.standard)
{ "content_hash": "efeb25901b1ec9de8b5d94934850106d", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 78, "avg_line_length": 34.38095238095238, "alnum_prop": 0.7382271468144044, "repo_name": "darth-platypus/characterizer", "id": "a3900a6749e67103c7cdd853406743bcd4a6209f", "size": "722", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "main.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "18795" } ], "symlink_target": "" }
package org.apache.accumulo.core; import static java.nio.charset.StandardCharsets.UTF_8; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import org.apache.accumulo.core.security.Authorizations; public class Constants { public static final String VERSION = FilteredConstants.VERSION; // Zookeeper locations public static final String ZROOT = "/accumulo"; public static final String ZINSTANCES = "/instances"; public static final String ZTABLES = "/tables"; public static final byte[] ZTABLES_INITIAL_ID = new byte[] {'0'}; public static final String ZTABLE_NAME = "/name"; public static final String ZTABLE_CONF = "/conf"; public static final String ZTABLE_STATE = "/state"; public static final String ZTABLE_FLUSH_ID = "/flush-id"; public static final String ZTABLE_COMPACT_ID = "/compact-id"; public static final String ZTABLE_COMPACT_CANCEL_ID = "/compact-cancel-id"; public static final String ZTABLE_NAMESPACE = "/namespace"; public static final String ZNAMESPACES = "/namespaces"; public static final String ZNAMESPACE_NAME = "/name"; public static final String ZNAMESPACE_CONF = "/conf"; public static final String ZMASTERS = "/masters"; public static final String ZMASTER_LOCK = ZMASTERS + "/lock"; public static final String ZMASTER_GOAL_STATE = ZMASTERS + "/goal_state"; public static final String ZMASTER_REPLICATION_COORDINATOR_ADDR = ZMASTERS + "/repl_coord_addr"; public static final String ZGC = "/gc"; public static final String ZGC_LOCK = ZGC + "/lock"; public static final String ZMONITOR = "/monitor"; public static final String ZMONITOR_LOCK = ZMONITOR + "/lock"; public static final String ZMONITOR_HTTP_ADDR = ZMONITOR + "/http_addr"; public static final String ZMONITOR_LOG4J_ADDR = ZMONITOR + "/log4j_addr"; public static final String ZCONFIG = "/config"; public static final String ZTSERVERS = "/tservers"; public static final String ZDEAD = "/dead"; public static final String ZDEADTSERVERS = ZDEAD + "/tservers"; public static final String ZTRACERS = "/tracers"; public static final String ZPROBLEMS = "/problems"; public static final String BULK_ARBITRATOR_TYPE = "bulkTx"; public static final String ZFATE = "/fate"; public static final String ZNEXT_FILE = "/next_file"; public static final String ZBULK_FAILED_COPYQ = "/bulk_failed_copyq"; public static final String ZHDFS_RESERVATIONS = "/hdfs_reservations"; public static final String ZRECOVERY = "/recovery"; /** * Base znode for storing secret keys that back delegation tokens */ public static final String ZDELEGATION_TOKEN_KEYS = "/delegation_token_keys"; /** * Initial tablet directory name for the default tablet in all tables */ public static final String DEFAULT_TABLET_LOCATION = "/default_tablet"; public static final String ZTABLE_LOCKS = "/table_locks"; public static final String BULK_PREFIX = "b-"; public static final String CLONE_PREFIX = "c-"; public static final byte[] CLONE_PREFIX_BYTES = CLONE_PREFIX.getBytes(UTF_8); // this affects the table client caching of metadata public static final int SCAN_BATCH_SIZE = 1000; // Scanners will default to fetching 3 batches of Key/Value pairs before asynchronously // fetching the next batch. public static final long SCANNER_DEFAULT_READAHEAD_THRESHOLD = 3l; // Security configuration public static final String PW_HASH_ALGORITHM = "SHA-256"; /** * @deprecated since 1.6.0; Use {@link Authorizations#EMPTY} instead */ @Deprecated public static final Authorizations NO_AUTHS = Authorizations.EMPTY; public static final int MAX_DATA_TO_PRINT = 64; public static final String CORE_PACKAGE_NAME = "org.apache.accumulo.core"; public static final String MAPFILE_EXTENSION = "map"; public static final String GENERATED_TABLET_DIRECTORY_PREFIX = "t-"; public static final String EXPORT_METADATA_FILE = "metadata.bin"; public static final String EXPORT_TABLE_CONFIG_FILE = "table_config.txt"; public static final String EXPORT_FILE = "exportMetadata.zip"; public static final String EXPORT_INFO_FILE = "accumulo_export_info.txt"; // Variables that will be substituted with environment vars in PropertyType.PATH values public static final Collection<String> PATH_PROPERTY_ENV_VARS = Collections.unmodifiableCollection(Arrays.asList("ACCUMULO_HOME", "ACCUMULO_CONF_DIR")); public static final String HDFS_TABLES_DIR = "/tables"; public static final int DEFAULT_VISIBILITY_CACHE_SIZE = 1000; }
{ "content_hash": "4a51e74f5af9dad0f9e01e7926e1420e", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 154, "avg_line_length": 38.58474576271186, "alnum_prop": 0.73995168021085, "repo_name": "dhutchis/accumulo", "id": "94ada7a3d6fd24a163e907248518614b5a1acda6", "size": "5354", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "core/src/main/java/org/apache/accumulo/core/Constants.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2423" }, { "name": "C++", "bytes": "2274937" }, { "name": "CSS", "bytes": "5933" }, { "name": "Groovy", "bytes": "1385" }, { "name": "HTML", "bytes": "11698" }, { "name": "Java", "bytes": "22224331" }, { "name": "JavaScript", "bytes": "249600" }, { "name": "Makefile", "bytes": "2560" }, { "name": "Perl", "bytes": "28190" }, { "name": "Protocol Buffer", "bytes": "1325" }, { "name": "Python", "bytes": "1005923" }, { "name": "Ruby", "bytes": "272223" }, { "name": "Shell", "bytes": "201208" }, { "name": "Thrift", "bytes": "62455" } ], "symlink_target": "" }
select class from ( select class, student from courses c0 group by student, class ) c1 group by class having count(class) >=5
{ "content_hash": "df2a59ad6fd81581eba07c4bef538c51", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 25, "avg_line_length": 14.666666666666666, "alnum_prop": 0.7272727272727273, "repo_name": "punkieL/proCom", "id": "19df55226aa290ab89cea7b2f3db58e121eea347", "size": "173", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "leetcode/200-/596-classes-more-than-5-students/596.sql", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "39582" }, { "name": "Java", "bytes": "2399" }, { "name": "Python", "bytes": "373" } ], "symlink_target": "" }
ACCEPTED #### According to IRMNG Homonym List #### Published in Ber. Vers. Dtsch. Naturf. , 37, 1862, 162. #### Original name null ### Remarks null
{ "content_hash": "ade3f053ba32b85d082da9eab19a170e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 42, "avg_line_length": 11.615384615384615, "alnum_prop": 0.6622516556291391, "repo_name": "mdoering/backbone", "id": "46a9b9b679557871befd4e2c6e6d53ada1ce37a7", "size": "195", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/incertae sedis/Epiclintes/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/** * This file is part of the CernVM File System. */ #ifndef CVMFS_RECEIVER_REACTOR_H_ #define CVMFS_RECEIVER_REACTOR_H_ #include <cstdlib> #include <map> #include <string> #include "json_document.h" #include "statistics.h" namespace receiver { class CommitProcessor; class PayloadProcessor; /** * This is the main event loop of the `cvmfs_receiver` program. * * It implements a synchronous protocol, reading JSON requests from the fdin_ * file descriptor and writing JSON responses to fdout_. It handles the framing * of the protocol and the dispatching of the different types of events to * specific handler methods. */ class Reactor { public: enum Request { kQuit = 0, kEcho, kGenerateToken, kGetTokenId, kCheckToken, kSubmitPayload, kCommit, kError, kTestCrash // use to test the gateway }; static Request ReadRequest(int fd, std::string* data); static bool WriteRequest(int fd, Request req, const std::string& data); static bool ReadReply(int fd, std::string* data); static bool WriteReply(int fd, const std::string& data); static bool ExtractStatsFromReq(JsonDocument *req, perf::Statistics *stats, std::string *start_time); Reactor(int fdin, int fdout); virtual ~Reactor(); bool Run(); protected: // NOTE: These methods are virtual such that they can be mocked for the // purpose of unit testing virtual bool HandleGenerateToken(const std::string& req, std::string* reply); virtual bool HandleGetTokenId(const std::string& req, std::string* reply); virtual bool HandleCheckToken(const std::string& req, std::string* reply); virtual bool HandleSubmitPayload(int fdin, const std::string& req, std::string* reply); virtual bool HandleCommit(const std::string& req, std::string* reply); virtual PayloadProcessor* MakePayloadProcessor(); virtual CommitProcessor* MakeCommitProcessor(); private: bool HandleRequest(Request req, const std::string& data); int fdin_; int fdout_; std::map<std::string, perf::Statistics*> statistics_map_; }; } // namespace receiver #endif // CVMFS_RECEIVER_REACTOR_H_
{ "content_hash": "576bffca77574789a1cdd0eae178e356", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 79, "avg_line_length": 27.382716049382715, "alnum_prop": 0.6884580703336339, "repo_name": "cvmfs/cvmfs", "id": "1e0562c699cc62b2440867371250a60727867d71", "size": "2218", "binary": false, "copies": "2", "ref": "refs/heads/devel", "path": "cvmfs/receiver/reactor.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "72102" }, { "name": "C++", "bytes": "5202057" }, { "name": "CMake", "bytes": "160263" }, { "name": "Dockerfile", "bytes": "4438" }, { "name": "Go", "bytes": "351590" }, { "name": "Makefile", "bytes": "10701" }, { "name": "Perl", "bytes": "408977" }, { "name": "Python", "bytes": "143016" }, { "name": "Rich Text Format", "bytes": "4619" }, { "name": "Ruby", "bytes": "514" }, { "name": "Shell", "bytes": "693232" }, { "name": "Smarty", "bytes": "6811" } ], "symlink_target": "" }
module MH_Typechecker where import MH_Parse type TypeEnv = String -> Type updatetenv :: TypeEnv -> String -> Type -> TypeEnv updatetenv tenv x t y = if x == y then t else tenv y hastype :: TypeEnv -> Exp -> Type -> Bool hastype tenv (Var x) t = (t == tenv x) hastype tenv (Num n) t = (t == TypeConst "Integer") hastype tenv (Boolean b) t = (t == TypeConst "Bool") hastype tenv (Cond(exp0, exp1, exp2)) t = (hastype tenv exp0 (TypeConst "Bool")) && (hastype tenv exp1 t) && (hastype tenv exp2 t) hastype tenv (Op("==", exp1, exp2)) t = hastype tenv exp1 (TypeConst "Integer") && hastype tenv exp2 (TypeConst "Integer") && t == TypeConst "Bool" hastype tenv (Op("<", exp1, exp2)) t = hastype tenv exp1 (TypeConst "Integer") && hastype tenv exp2 (TypeConst "Integer") && t == TypeConst "Bool" hastype tenv (Op("+", exp1, exp2)) t = hastype tenv exp1 (TypeConst "Integer") && hastype tenv exp2 (TypeConst "Integer") && t == TypeConst "Integer" hastype tenv (Op("-", exp1, exp2)) t = hastype tenv exp1 (TypeConst "Integer") && hastype tenv exp2 (TypeConst "Integer") && t == TypeConst "Integer" hastype tenv (Op("appl", exp1, exp2)) t = case (typeof tenv exp2) of Just t' -> hastype tenv exp1 (TypeOp ("->", t', t)) Nothing -> error "Static type error" hastype tenv (Lam (x, exp)) (TypeOp ("->", t1, t2)) = hastype (updatetenv tenv x t1) exp t2 hastype tenv (Op (",", exp1, exp2)) (TypeOp (",", t1, t2)) = hastype tenv exp1 t1 && hastype tenv exp2 t2 typeof :: TypeEnv -> Exp -> Maybe Type typeof tenv (Var x) = Just (tenv x) typeof tenv (Num n) = Just (TypeConst "Integer") typeof tenv (Boolean b) = Just (TypeConst "Bool") typeof tenv (Cond(exp0, exp1, exp2)) = if hastype tenv exp0 (TypeConst "Bool") then case typeof tenv exp1 of (Just t) -> if (hastype tenv exp2 t) then Just t else Nothing Nothing -> Nothing else Nothing typeof tenv (Op("==", exp1, exp2)) = if hastype tenv exp1 (TypeConst "Integer") && hastype tenv exp2 (TypeConst "Integer") then Just (TypeConst "Bool") else Nothing typeof tenv (Op("<", exp1, exp2)) = if hastype tenv exp1 (TypeConst "Integer") && hastype tenv exp2 (TypeConst "Integer") then Just (TypeConst "Bool") else Nothing typeof tenv (Op("+", exp1, exp2)) = if hastype tenv exp1 (TypeConst "Integer") && hastype tenv exp2 (TypeConst "Integer") then Just (TypeConst "Integer") else Nothing typeof tenv (Op("-", exp1, exp2)) = if hastype tenv exp1 (TypeConst "Integer") && hastype tenv exp2 (TypeConst "Integer") then Just (TypeConst "Integer") else Nothing typeof tenv (Op("appl", exp1, exp2)) = case (typeof tenv exp1) of (Just (TypeOp ("->", t1, t2))) -> if hastype tenv exp2 t1 then Just t2 else Nothing _ -> Nothing typeof tenv (Lam (x, exp)) = Nothing typeof tenv (Op (",", exp1, exp2)) = case (typeof tenv exp1, typeof tenv exp2) of (Just t1, Just t2) -> Just (TypeOp (",", t1, t2)) _ -> Nothing
{ "content_hash": "fc066ca26232afe4077c24bb2893cb19", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 72, "avg_line_length": 28.757009345794394, "alnum_prop": 0.617809554761131, "repo_name": "jaanos/TPJ-2015-16", "id": "e7996cae86db863f95d398e159eafae55918cc8e", "size": "3078", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "microhaskell/MH_Typechecker.hs", "mode": "33188", "license": "mit", "language": [ { "name": "Haskell", "bytes": "49293" }, { "name": "Logos", "bytes": "3411" }, { "name": "Yacc", "bytes": "8475" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>shuffle: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.13.0 / shuffle - 8.8.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> shuffle <small> 8.8.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-05-12 14:04:55 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-05-12 14:04:55 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.13.0 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.11.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.11.2 Official release 4.11.2 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/shuffle&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Shuffle&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.9~&quot;} ] tags: [ &quot;keyword: Gilbreath&#39;s card trick&quot; &quot;keyword: binary sequences&quot; &quot;category: Miscellaneous/Logical Puzzles and Entertainment&quot; ] authors: [ &quot;Gérard Huet&quot; ] bug-reports: &quot;https://github.com/coq-contribs/shuffle/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/shuffle.git&quot; synopsis: &quot;Gilbreath&#39;s card trick&quot; description: &quot;A full axiomatization and proof development of a non-trivial property of binary sequences, inspired from a card trick of N. Gilbreath.&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/shuffle/archive/v8.8.0.tar.gz&quot; checksum: &quot;md5=c1547f50942d7da552ff1f1f1ea94a7f&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-shuffle.8.8.0 coq.8.13.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.13.0). The following dependencies couldn&#39;t be met: - coq-shuffle -&gt; coq &lt; 8.9~ -&gt; ocaml &lt; 4.10 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-shuffle.8.8.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "e7c51b72019ceba9cba57f99ba5e8835", "timestamp": "", "source": "github", "line_count": 163, "max_line_length": 165, "avg_line_length": 42.214723926380366, "alnum_prop": 0.5412004069175992, "repo_name": "coq-bench/coq-bench.github.io", "id": "b305afae796f8978a1e5a3e3db771dfb2f3ece9f", "size": "6907", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.11.2-2.0.7/released/8.13.0/shuffle/8.8.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build LABEL stage=build WORKDIR /src COPY ./__tmp__ . # Install node.js RUN apt-get update -yq \ && apt-get install curl gnupg -yq \ && curl -sL https://deb.nodesource.com/setup_12.x | bash \ && apt-get install nodejs -yq RUN dotnet publish ./Portal/Portal.csproj -c Release -o /app FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 WORKDIR /app COPY --from=build /app . ARG aspnetenv=Production ENV ASPNETCORE_ENVIRONMENT ${aspnetenv} CMD ASPNETCORE_URLS=http://*:$PORT dotnet Portal.dll
{ "content_hash": "d43f656c2bf70cb04664f795538c6c58", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 62, "avg_line_length": 27.5, "alnum_prop": 0.7109090909090909, "repo_name": "dsuryd/dotnetify-react-demo-vs2017", "id": "475c0ae40d1e3344c13d8686af963fdf8ae33261", "size": "550", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MicrofrontendTemplate/heroku-deploy/Portal/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "56991" }, { "name": "CSS", "bytes": "865" }, { "name": "HTML", "bytes": "3621" }, { "name": "JavaScript", "bytes": "71177" }, { "name": "TypeScript", "bytes": "37781" } ], "symlink_target": "" }
module Main where import Tail import Control.Monad import Options.Applicative tailParser = runTail' <$> argument str (metavar "FILE") <*> lineP where runTail' a b = runTail a b >>= showTail lineP :: Parser Integer lineP = option auto $ long "lines" <> short 'n' <> metavar "N" <> help "lines to read from EOF" argParser :: Parser (IO ()) argParser = subparser ( command "tail" (info tailParser idm ) ) main :: IO () main = join $ execParser (info argParser idm)
{ "content_hash": "806966862ee7a6b5dc74f7fa5230232c", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 46, "avg_line_length": 20.285714285714285, "alnum_prop": 0.5686619718309859, "repo_name": "agrafix/haskell-playground", "id": "10c9044663c8cfe173352d53609f2be82c2ba809", "size": "568", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Main.hs", "mode": "33188", "license": "mit", "language": [ { "name": "Haskell", "bytes": "2005" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE service-builder PUBLIC "-//Liferay//DTD Service Builder 6.2.0//EN" "http://www.liferay.com/dtd/liferay-service-builder_6_2_0.dtd"> <service-builder package-path="org.oep.core.datamgt.dictionary"> <author>TrungDK</author> <namespace>oep_datamgt</namespace> <entity name="DictCollection" table="oep_datamgt_dictcollection" local-service="true" human-name="dictionary collection"> <column name="dictCollectionId" db-name="dictCollectionId" type="long" primary="true"></column> <column name="companyId" db-name="companyId" type="long"></column> <column name="createDate" db-name="createDate" type="Date"></column> <column name="modifiedDate" db-name="modifiedDate" type="Date"></column> <column name="name" db-name="name" type="String"></column> <column name="version" db-name="version" type="String"></column> <column name="title" db-name="title" type="String"></column> <column name="validatedFrom" db-name="validatedFrom" type="Date"></column> <column name="validatedTo" db-name="validatedTo" type="Date"></column> <column name="status" db-name="status" type="int"></column> <column name="dictDatas" type="Collection" entity="DictData" mapping-table="dictdata2collection"></column> <finder name="C_N" return-type="Collection"> <finder-column name="companyId"></finder-column> <finder-column name="name"></finder-column> </finder> <finder name="C_LikeN" return-type="Collection"> <finder-column name="companyId"></finder-column> <finder-column name="name" comparator="LIKE"></finder-column> </finder> <finder name="C_N_V" return-type="DictCollection"> <finder-column name="companyId"></finder-column> <finder-column name="name"></finder-column> <finder-column name="version"></finder-column> </finder> <finder name="C_LikeN_V" return-type="Collection"> <finder-column name="companyId"></finder-column> <finder-column name="name" comparator="LIKE"></finder-column> <finder-column name="version"></finder-column> </finder> <finder name="C_N_S" return-type="DictCollection"> <finder-column name="companyId"></finder-column> <finder-column name="name"></finder-column> <finder-column name="status"></finder-column> </finder> <finder name="C" return-type="Collection"> <finder-column name="companyId"></finder-column> </finder> </entity> <entity name="DictData" table="oep_datamgt_dictdata" local-service="true" human-name="dictionary data"> <column name="dictDataId" db-name="dictDataId" type="long" primary="true"></column> <column name="companyId" db-name="companyId" type="long"></column> <column name="createDate" db-name="createDate" type="Date"></column> <column name="modifiedDate" db-name="modifiedDate" type="Date"></column> <column name="collectionName" db-name="collectionName" type="String"></column> <column name="dataCode" db-name="dataCode" type="String"></column> <column name="node_1" db-name="node_1" type="String"></column> <column name="node_2" db-name="node_2" type="String"></column> <column name="node_3" db-name="node_3" type="String"></column> <column name="node_4" db-name="node_4" type="String"></column> <column name="node_5" db-name="node_5" type="String"></column> <column name="dataLevel" db-name="dataLevel" type="int"></column> <column name="title" db-name="title" type="String"></column> <column name="description" db-name="description" type="String"></column> <column name="validatedFrom" db-name="validatedFrom" type="Date"></column> <column name="validatedTo" db-name="validatedTo" type="Date"></column> <column name="status" db-name="status" type="int"></column> <column name="dictCollections" type="Collection" entity="DictCollection" mapping-table="dictdata2collection"></column> <finder name="C_DC" return-type="Collection"> <finder-column name="dataCode"></finder-column> <finder-column name="companyId"></finder-column> </finder> <finder name="C_CN_DL" return-type="Collection"> <finder-column name="companyId"></finder-column> <finder-column name="collectionName"></finder-column> <finder-column name="dataLevel"></finder-column> </finder> <finder name="C_CN" return-type="Collection"> <finder-column name="companyId"></finder-column> <finder-column name="collectionName"></finder-column> </finder> <finder name="C_DC_CN" return-type="Collection"> <finder-column name="companyId"></finder-column> <finder-column name="dataCode"></finder-column> <finder-column name="collectionName"></finder-column> </finder> <finder name="C_DL" return-type="Collection"> <finder-column name="companyId"></finder-column> <finder-column name="dataLevel"></finder-column> </finder> <finder name="C_DC_CN_S" return-type="DictData"> <finder-column name="companyId"></finder-column> <finder-column name="dataCode"></finder-column> <finder-column name="status"></finder-column> <finder-column name="collectionName"></finder-column> </finder> </entity> <entity name="DictAttribute" table="oep_datamgt_dictattribute" local-service="true" human-name="dictionary attribute"> <column name="dictAttributeId" db-name="dictAttributeId" type="long" primary="true"></column> <column name="companyId" db-name="companyId" type="long"></column> <column name="createDate" db-name="createDate" type="Date"></column> <column name="modifiedDate" db-name="modifiedDate" type="Date"></column> <column name="collectionName" db-name="collectionName" type="String"></column> <column name="name" db-name="name" type="String"></column> <column name="title" db-name="title" type="String"></column> <column name="dataType" db-name="dataType" type="String"></column> <finder name="C" return-type="Collection"> <finder-column name="companyId"></finder-column> </finder> <finder name="C_CN" return-type="Collection"> <finder-column name="companyId"></finder-column> <finder-column name="collectionName"></finder-column> </finder> <finder name="C_CN_DT" return-type="Collection"> <finder-column name="companyId"></finder-column> <finder-column name="collectionName"></finder-column> <finder-column name="dataType"></finder-column> </finder> <finder name="C_DT" return-type="Collection"> <finder-column name="companyId"></finder-column> <finder-column name="dataType"></finder-column> </finder> </entity> <entity name="DictMetaData" table="oep_datamgt_dictmetadata" local-service="true" human-name="dictionary meta data"> <column name="dictMetaDataId" db-name="dictMetaDataId" type="long" primary="true"></column> <column name="companyId" db-name="companyId" type="long"></column> <column name="createDate" db-name="createDate" type="Date"></column> <column name="modifiedDate" db-name="modifiedDate" type="Date"></column> <column name="dictDataId" db-name="dictDataId" type="long"></column> <column name="attributeName" db-name="attributeName" type="String"></column> <column name="attributeValue" db-name="attributeValue" type="String"></column> <finder name="C_DI" return-type="Collection"> <finder-column name="companyId"></finder-column> <finder-column name="dictDataId"></finder-column> </finder> <finder name="C_DI_N" return-type="DictMetaData"> <finder-column name="companyId"></finder-column> <finder-column name="dictDataId"></finder-column> <finder-column name="attributeName"></finder-column> </finder> </entity> <exceptions> <exception>DictCollectionName</exception> <exception>DictCollectionVersion</exception> <exception>DictDataDataCode</exception> <exception>DictAttributeName</exception> <exception>DictCollectionTitle</exception> <exception>DictCollectionStatus</exception> </exceptions> </service-builder>
{ "content_hash": "c55083c3ade65c91d6658a3314587926", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 140, "avg_line_length": 60.0551724137931, "alnum_prop": 0.6329811667432246, "repo_name": "thongdv/OEPv2", "id": "ab40acbc075d6cc177a5fd40c791e708948c364f", "size": "8708", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "portlets/oep-core-datamgt-portlet/docroot/WEB-INF/src/org/oep/core/datamgt/dictionary/service.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3742" }, { "name": "Java", "bytes": "9945598" }, { "name": "Shell", "bytes": "3152" } ], "symlink_target": "" }
<?php namespace Myapp\Models; use Silex\Application; /* Las imágenes que muestren al principio los productos deben ser siempre las más recientes */ class Product{ protected $app; protected $idProduct; public function __construct(Application $app, $idProduct = null){ $this->app = $app; $this->idProduct = $idProduct; } public function getDetails(){ $query = "SELECT p.title, p.description, p.created_at, p.id, s.status, i.path as image_path FROM productos as p LEFT JOIN estados_cosecha as s ON (p.idstatus = s.id) LEFT JOIN images as i ON (p.id = i.idProduct) WHERE p.id = :idProduct ORDER BY i.id DESC LIMIT 1"; $stmt = $this->app["db"]->prepare($query); $stmt->bindValue(":idProduct", $this->idProduct, "integer"); $stmt->execute(); $product = $stmt->fetch(); $product["image_path"] = Product::formatImagePath($product["image_path"]); return $product; } public static function formatImagePath($path){ if(is_null($path)){ return $path; } return "uploads/images/".$path; } }
{ "content_hash": "aa51e11a4eec7111a5662415535f638a", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 94, "avg_line_length": 21.470588235294116, "alnum_prop": 0.6383561643835617, "repo_name": "apachejack/ecological-agrarian-web", "id": "5865d31266b5b8c7b4907f0207fab4e70512b6e9", "size": "1097", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Myapp/Models/Product.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "234" }, { "name": "CSS", "bytes": "1009148" }, { "name": "HTML", "bytes": "589357" }, { "name": "JavaScript", "bytes": "245088" }, { "name": "PHP", "bytes": "13719" } ], "symlink_target": "" }
<!-- 2017-03-23 --> Welcome to Haskell Weekly! [Haskell](https://www.haskell.org) is an advanced, purely functional programming language. This is a weekly summary of what's going on in its community. You can subscribe to [the email newsletter](https://news.us10.list-manage.com/subscribe?u=49a6a2e17b12be2c5c4dcb232&id=ffbbbbd930) or [the Atom feed](/haskell-weekly.atom). Want to contribute to Haskell Weekly? Send us a message [on Twitter](https://twitter.com/haskellweekly) or open an issue [on GitHub](https://github.com/haskellweekly/haskellweekly.github.io). ## News from the Haskell community - [Inlining and specialization](https://mpickering.github.io/posts/2017-03-20-inlining-and-specialisation.html) > The inliner's job is to replace a function with its definition. This removes one layer of indirection and most importantly allows other optimisations to fire. The specialiser is important for optimising code which uses type classes. Type classes are desugared into dictionary passing style but the specialiser removes a layer of indirection by creating new functions with the relevant dictionaries already supplied. - [Applicative sorting](https://elvishjerricco.github.io/2017/03/23/applicative-sorting.html) > Continuing my unending train of thoughts on static analysis of effects, in this post I'm going to talk about using `Applicative` to sort any collection. The `Traversable` typeclass is one of my favorites because it generalizes the idea of a collection so elegantly. I will show how to use `traverse` to sort any such collection safely using a special applicative. - [Proposal: Suggest explicit type application for Foldable length and friends](http://blog.ezyang.com/2017/03/proposal-suggest-explicit-type-application-for-foldable-length/) > If you use a Foldable function like length or null, where instance selection is solely determined by the input argument, you should make your code more robust by introducing an explicit type application specifying which instance you want. This isn't necessary for a function like fold, where the return type can cross-check if you've gotten it right or not. - [Automating static analysis for Haskell projects](https://lwm.github.io/static-analysis-with-haskell/) > As a maintainer, I need to have confidence that new patches are appropriate both in terms of logic and style. Especially when I did not write those patches. Naturally, I spend the majority of my time on the former. Static analysis tools can greatly reduce the manual work necessary for the latter. - [Haskell for Mac 1.4.0 is out](http://blog.haskellformac.com/blog/haskell-for-mac-140-is-out) > This release comes with a range of improvements, but the outstanding feature is the ability to install packages from within the app. - [Obey the (type) laws](https://medium.com/@james_32022/obey-the-type-laws-ffb2fa4e5fe2) > We've discussed three major type classes: functors, applicative functors, and monads. They all have particular laws their instances should follow. Other programmers who use your code will expect any instances you make to follow these laws. Once you are familiar with the types, you will likely create instances that follow the laws. But if you are unsure, you can use the QuickCheck utility to verify them. - [A specification for dependently-typed Haskell](http://www.seas.upenn.edu/~sweirich/papers/systemd-submission.pdf) > Our goal is to design Dependent Haskell, an extension of Haskell with full-spectrum dependent types. The main feature of Dependent Haskell is that, unlike current Haskell, it makes no distinction between types and terms; both compile-time and runtime computation share the same syntax and semantics ## Package of the week This week's package of the week is [eve](https://hackage.haskell.org/package/eve), an extensible event framework. Send us a message [on Twitter](https://twitter.com/haskellweekly) to nominate next week's package!
{ "content_hash": "aa4feb9e87b6ee8bcd5aefa807b611de", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 421, "avg_line_length": 82.85416666666667, "alnum_prop": 0.7860196127734473, "repo_name": "haskellweekly/haskellweekly.github.io", "id": "8a30e52714e56f8430376a5c8b2adb12ac54d44b", "size": "3977", "binary": false, "copies": "1", "ref": "refs/heads/base", "path": "content/issues/47.markdown", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "72647" }, { "name": "Haskell", "bytes": "24633" }, { "name": "Shell", "bytes": "458" } ], "symlink_target": "" }
package me.dablakbandit.customentitiesapi.entities; import ja.ClassClassPath; import ja.CtClass; import ja.CtField; import ja.CtNewMethod; import me.dablakbandit.customentitiesapi.CustomEntitiesAPI; import me.dablakbandit.customentitiesapi.NMSUtils; import org.bukkit.Location; import org.bukkit.entity.Entity; public class CustomEntityGhast extends CustomEntityFlying { public CustomEntityGhast() { super("CustomEntityGhast"); if (ctClass == null) return; register(); } public CustomEntityGhast(Location location) { this(); a(); spawnEntity(location); } public CustomEntityGhast(Entity e) { this(); a(); try { entity = customentity.cast(NMSUtils.getHandle(e)); } catch (Exception e1) { } } public CustomEntityGhast(Object o) { this(); a(); entity = o; } public static Class<?> getCustomEntityGhastClass() { try { return Class.forName("temp.CustomEntityGhast"); } catch (Exception e) { return null; } } public void a() { try { customentity = Class.forName("temp.CustomEntityGhast"); helper = Class.forName("temp.CustomEntityGhastHelper"); } catch (Exception e) { e.printStackTrace(); } } private void register() { try { customentity = Class.forName("temp.CustomEntityGhast"); } catch (Exception e1) { try { cp.insertClassPath(new ClassClassPath( new CustomEntityGhastHelper().getClass())); CtClass ces = cp .getAndRename( "me.dablakbandit.customentitiesapi.entities.CustomEntityGhastHelper", "temp.CustomEntityGhastHelper"); ces.setSuperclass(cp.get("temp.CustomEntityFlyingHelper")); ces.toClass(); CtClass EntityGhast = cp.getCtClass("net.minecraft.server." + NMSUtils.getVersion() + "EntityGhast"); cp.importPackage("net.minecraft.server." + NMSUtils.getVersion() + "EntityGhast"); cp.importPackage("net.minecraft.server." + NMSUtils.getVersion() + "EntityFlying"); for (CtField f : fields) { ctClass.addField(f); } fields.clear(); ctClass.setSuperclass(EntityGhast); methods.add("public void setUnableToMove(){" + "CustomEntityGhastHelper.setUnableToMove(this);" + "}"); methods.add("public void setAbleToMove(){" + "CustomEntityGhastHelper.setAbleToMove(this);" + "}"); methods.add("public void setAbleToMove(double d){" + "CustomEntityGhastHelper.setAbleToMove(this, d);" + "}"); for (String m : methods) { ctClass.addMethod(CtNewMethod.make(m, ctClass)); } methods.clear(); customentity = ctClass.toClass(); } catch (Exception e2) { e2.printStackTrace(); } } if (customentity != null) CustomEntitiesAPI.getInstance().registerEntity("EntityGhast", 56, customentity); } public void setGoalSelectorDefaultPathfinderGoals() { try { helper.getMethod("setGoalSelectorDefaultPathfinderGoals", Object.class).invoke(null, entity); } catch (Exception e) { e.printStackTrace(); } } }
{ "content_hash": "7622c5fea9912bbc6eef115aa383ea18", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 77, "avg_line_length": 26.31858407079646, "alnum_prop": 0.6859448554135844, "repo_name": "Dablakbandit/CustomEntitiesAPI1.8", "id": "5d0f715ecf17874a5791f8f2d8d9c0a608e5b733", "size": "2974", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/me/dablakbandit/customentitiesapi/entities/CustomEntityGhast.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "4585" }, { "name": "Java", "bytes": "2226054" } ], "symlink_target": "" }
**************** Guild Wars 2 API **************** gw2api is a Python library to interface with the `Guild Wars 2 API`_. It aims to have an almost one-to-one mapping to the JSON API, with only some minor differences. Usage Example ------------- .. code-block:: python import gw2api.v2 for item in gw2api.v2.items.get(range(30684, 30705)): link = gw2api.encode_item_link(item["id"]) print "%-26s %-9s %-10s %s" % (item["name"], item["rarity"], item["details"]["type"], link) gw2api is available from the `Python Package Index`_ and is hosted on GitHub_. .. _Guild Wars 2 API: http://wiki.guildwars2.com/wiki/API:Main .. _Python Package Index: https://pypi.python.org/pypi/gw2api .. _GitHub: https://github.com/hackedd/gw2api
{ "content_hash": "1c5e4a435b4de184cb722d524135fdee", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 78, "avg_line_length": 31.76, "alnum_prop": 0.6146095717884131, "repo_name": "hackedd/gw2api", "id": "6f89c9adde992d896fcb054e471aa64f10ca4fce", "size": "794", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.rst", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "112459" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "e7f03afac7c5c846aadb11df3f305d69", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "7aea9982f3383f1a341cd5fae7cd19b75cfef3e5", "size": "175", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Ibidium/Ibidium incurvum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package middleware import ( "net/http" "time" "github.com/go-chi/chi/v5/middleware" "github.com/rs/zerolog" "github.com/rs/zerolog/log" ) // LogRequest returns a middleware to log requests. func LogRequest() func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor) t1 := time.Now() defer func() { ctx := r.Context() logger := log.Ctx(ctx) logger.Info().Dict("response", zerolog.Dict(). Int("status", ww.Status()). Int("sent_bytes", ww.BytesWritten()). Int64("elapsed", time.Since(t1).Microseconds()), ).Msgf("") }() next.ServeHTTP(ww, r) } return http.HandlerFunc(fn) } }
{ "content_hash": "c70c42abb04a17775ea12a060f0df20a", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 58, "avg_line_length": 23.272727272727273, "alnum_prop": 0.6497395833333334, "repo_name": "GoogleCloudPlatform/appengine-cloud-demo-portal", "id": "4b567c2b0996e116c748274069b374574fdf8824", "size": "1357", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "api/pkg/middleware/log_request.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "848" }, { "name": "Go", "bytes": "49913" }, { "name": "HCL", "bytes": "6864" }, { "name": "JavaScript", "bytes": "2543" }, { "name": "Shell", "bytes": "181" }, { "name": "TypeScript", "bytes": "134015" } ], "symlink_target": "" }
<?php namespace Ivoba\AssetVersion\Version; /** * Interface AssetVersionInterface * @package Ivoba\AssetVersion\Version */ interface AssetVersionInterface { /** * @param $file filesystem file path * @return string the version of this file */ public function getVersion($file); }
{ "content_hash": "e4f414e9a122bb13d25062f183927971", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 46, "avg_line_length": 18.058823529411764, "alnum_prop": 0.6970684039087948, "repo_name": "ivoba/twig-asset-version-extension", "id": "d46244d13a8357276b824949fef030422086d31b", "size": "307", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Version/AssetVersionInterface.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "6454" } ], "symlink_target": "" }
namespace Ra { namespace Core { namespace Utils { /// Simple observable implementation with void observer(Args...) notification. /// Typical usage is to derive from Observer with the intended \p Args as in /// \code{.cpp} /// class MyClass : public Oberservable<int> [...] /// MyClass c; /// c.attach(functor) /// \endcode /// Also a class can have Observable members, than act as slots /// \code{.cpp} /// class MyClass { /// public : /// Oberservable<int> slot0; /// Oberservable<> slot1; /// void f(){ slot0.notify(10); } /// }; /// MyClass c; /// c.slot0.attach(functor) /// c.slot1.attach(functor) /// \endcode template <typename... Args> class Observable { public: /// Observer functor type using Observer = std::function<void( Args... )>; /// Default constructor ... do nothing ;) Observable() = default; Observable( const Observable& ) = delete; Observable& operator=( const Observable& ) = delete; virtual ~Observable() = default; /// explicit copy of all attached observers the \p other Observable void copyObserversTo( Observable& other ) const { for ( const auto& o : m_observers ) { other.attach( o.second ); } } /// Attach an \p observer that will be call on subsecant call to notify() /// \return An unique int to identify the observer, could be used to pass to Obeservable::detach inline int attach( Observer observer ) { m_observers.insert( {++m_currentId, observer} ); return m_currentId; } /// Utility function that extract the observer from a class member. /// Attach an \p observer that will be call on subsecant call to notify() /// \return An unique int to identify the observer, could be used to pass to Obeservable::detach template <typename T> int attachMember( T* object, void ( T::*observer )( Args... ) ) { return attach( bind( observer, object ) ); } /// Notify (i.e. call) each attached observer with argument \p p inline void notify( Args... p ) const { for ( const auto& o : m_observers ) o.second( std::forward<Args>( p )... ); } /// Detach all observers inline void detachAll() { m_observers.clear(); } /// Detach the \p observerId, observerId must have been saved from a /// previous call to attach inline void detach( int observerId ) { m_observers.erase( observerId ); } private: // from https://stackoverflow.com/questions/21192659/variadic-templates-and-stdbind template <typename R, typename T, typename U> std::function<R( Args... )> bind( R ( T::*f )( Args... ), U p ) { return [p, f]( Args... args ) -> R { return ( p->*f )( args... ); }; } std::map<int, Observer> m_observers; int m_currentId {0}; }; class RA_CORE_API ObservableVoid : public Observable<> {}; } // namespace Utils } // namespace Core } // namespace Ra
{ "content_hash": "c7a9ae37e0db95119398e252979c4363", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 100, "avg_line_length": 33.146067415730336, "alnum_prop": 0.6216949152542373, "repo_name": "Zouch/Radium-Engine", "id": "9229e2b74f3bed05ea7e76e04a33908ac98a8b73", "size": "3033", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Core/Utils/Observable.hpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "942403" }, { "name": "C++", "bytes": "4163415" }, { "name": "CMake", "bytes": "26942" }, { "name": "GLSL", "bytes": "24748" } ], "symlink_target": "" }
import logging import queue import time from typing import Any, Callable, List, Sequence import uuid __all__ = ("QueueCallbackWorker", "STOP") _LOGGER = logging.getLogger(__name__) # Helper thread stop indicator. This could be a sentinel object or None, # but the sentinel object's ID can change if the process is forked, and # None has the possibility of a user accidentally killing the helper # thread. STOP = uuid.uuid4() def _get_many( queue_: queue.Queue, max_items: int = None, max_latency: float = 0 ) -> List[Any]: """Get multiple items from a Queue. Gets at least one (blocking) and at most ``max_items`` items (non-blocking) from a given Queue. Does not mark the items as done. Args: queue_: The Queue to get items from. max_items: The maximum number of items to get. If ``None``, then all available items in the queue are returned. max_latency: The maximum number of seconds to wait for more than one item from a queue. This number includes the time required to retrieve the first item. Returns: A sequence of items retrieved from the queue. """ start = time.time() # Always return at least one item. items = [queue_.get()] while max_items is None or len(items) < max_items: try: elapsed = time.time() - start timeout = max(0, max_latency - elapsed) items.append(queue_.get(timeout=timeout)) except queue.Empty: break return items class QueueCallbackWorker(object): """A helper that executes a callback for items sent in a queue. Calls a blocking ``get()`` on the ``queue`` until it encounters :attr:`STOP`. Args: queue: A Queue instance, appropriate for crossing the concurrency boundary implemented by ``executor``. Items will be popped off (with a blocking ``get()``) until :attr:`STOP` is encountered. callback: A callback that can process items pulled off of the queue. Multiple items will be passed to the callback in batches. max_items: The maximum amount of items that will be passed to the callback at a time. max_latency: The maximum amount of time in seconds to wait for additional items before executing the callback. """ def __init__( self, queue: queue.Queue, callback: Callable[[Sequence[Any]], Any], max_items: int = 100, max_latency: float = 0, ): self.queue = queue self._callback = callback self.max_items = max_items self.max_latency = max_latency def __call__(self) -> None: continue_ = True while continue_: items = _get_many( self.queue, max_items=self.max_items, max_latency=self.max_latency ) # If stop is in the items, process all items up to STOP and then # exit. try: items = items[: items.index(STOP)] continue_ = False except ValueError: pass # Run the callback. If any exceptions occur, log them and # continue. try: self._callback(items) except Exception as exc: _LOGGER.exception("Error in queue callback worker: %s", exc) _LOGGER.debug("Exiting the QueueCallbackWorker.")
{ "content_hash": "d53f5b8e8d9b1140ecac94902ffe23c7", "timestamp": "", "source": "github", "line_count": 108, "max_line_length": 86, "avg_line_length": 32.407407407407405, "alnum_prop": 0.5977142857142858, "repo_name": "googleapis/python-pubsub", "id": "fbcab781df844ca0d3c8f0482113fc2e0f73973f", "size": "4097", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "google/cloud/pubsub_v1/subscriber/_protocol/helper_threads.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "2050" }, { "name": "Python", "bytes": "1857078" }, { "name": "Shell", "bytes": "34068" } ], "symlink_target": "" }
#ifndef ALIANALYSISTASKSEEFFICIENCY_H #define ALIANALYSISTASKSEEFFICIENCY_H /* $Id$ */ class TString; class TTree; class TH1F; class TF1; class TH2F; class TRandom3; class AliESDEvent; class TNtuple; class AliITSPIDResponse; class THnSparse;//per la vettorizzazione class AliESDtrackCuts; class AliPPVsMultUtils; class AliAnalysisUtils; #include "AliAnalysisTaskSE.h" class AliAnalysisTaskSEEfficiency : public AliAnalysisTaskSE { public: AliAnalysisTaskSEEfficiency(); virtual ~AliAnalysisTaskSEEfficiency(); virtual void UserCreateOutputObjects(); virtual void Init(); virtual void LocalInit() {Init();} virtual void UserExec(Option_t *); virtual void Terminate(Option_t *); private: ClassDef(AliAnalysisTaskSEITSsaSpectra, 1); }; #endif
{ "content_hash": "fe8a01cc533d580416b8b9f68250182d", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 62, "avg_line_length": 19.35, "alnum_prop": 0.7751937984496124, "repo_name": "njacazio/AliAnalysisTaskEfficiency", "id": "e0f6fbf1c51fd20f2c14438a5e033a6dc780fde3", "size": "774", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AliAnalysisTaskSEEfficiency.h", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "777" } ], "symlink_target": "" }
<?php namespace Magento\SalesSequence\Test\Unit\Model; /** * Class BuilderTest */ class BuilderTest extends \PHPUnit_Framework_TestCase { /** * @var \Magento\SalesSequence\Model\Builder */ private $sequenceBuilder; /** * @var \Magento\SalesSequence\Model\ResourceModel\Meta | \PHPUnit_Framework_MockObject_MockObject */ private $resourceSequenceMeta; /** * @var \Magento\SalesSequence\Model\Meta | \PHPUnit_Framework_MockObject_MockObject */ private $meta; /** * @var \Magento\SalesSequence\Model\Profile | \PHPUnit_Framework_MockObject_MockObject */ private $profile; /** * @var \Magento\SalesSequence\Model\MetaFactory | \PHPUnit_Framework_MockObject_MockObject */ private $metaFactory; /** * @var \Magento\SalesSequence\Model\ProfileFactory | \PHPUnit_Framework_MockObject_MockObject */ private $profileFactory; /** * @var \Magento\Framework\DB\Adapter\AdapterInterface | \PHPUnit_Framework_MockObject_MockObject */ private $connectionMock; /** * @var \Magento\Framework\DB\Ddl\Sequence | \PHPUnit_Framework_MockObject_MockObject */ private $sequence; /** * @var \Magento\Framework\App\ResourceConnection | \PHPUnit_Framework_MockObject_MockObject */ private $resourceMock; protected function setUp() { $this->connectionMock = $this->getMockForAbstractClass( 'Magento\Framework\DB\Adapter\AdapterInterface', [], '', false, false, true, ['query'] ); $this->resourceSequenceMeta = $this->getMock( 'Magento\SalesSequence\Model\ResourceModel\Meta', ['loadByEntityTypeAndStore', 'save', 'createSequence'], [], '', false ); $this->meta = $this->getMock( 'Magento\SalesSequence\Model\Meta', ['getId', 'setData', 'save', 'getSequenceTable'], [], '', false ); $this->sequence = $this->getMock( 'Magento\Framework\DB\Ddl\Sequence', [], [], '', false ); $this->resourceMock = $this->getMock( 'Magento\Framework\App\ResourceConnection', [], [], '', false ); $this->profile = $this->getMock( 'Magento\SalesSequence\Model\Profile', ['getId', 'setData', 'getStartValue'], [], '', false ); $this->metaFactory = $this->getMock( 'Magento\SalesSequence\Model\MetaFactory', ['create'], [], '', false ); $this->metaFactory->expects($this->any())->method('create')->willReturn($this->meta); $this->profileFactory = $this->getMock( 'Magento\SalesSequence\Model\ProfileFactory', ['create'], [], '', false ); $this->profileFactory->expects($this->any())->method('create')->willReturn($this->profile); $this->resourceMock->expects($this->atLeastOnce()) ->method('getTableName') ->willReturn('sequence_lalalka_1'); $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->sequenceBuilder = $helper->getObject( 'Magento\SalesSequence\Model\Builder', [ 'resourceMetadata' => $this->resourceSequenceMeta, 'metaFactory' => $this->metaFactory, 'profileFactory' => $this->profileFactory, 'appResource' => $this->resourceMock, 'ddlSequence' => $this->sequence ] ); } public function testAddSequenceExistMeta() { $entityType = 'lalalka'; $storeId = 1; $this->resourceSequenceMeta->expects($this->once()) ->method('loadByEntityTypeAndStore') ->with($entityType, $storeId) ->willReturn($this->meta); $this->meta->expects($this->once()) ->method('getSequenceTable') ->willReturn('sequence_lalalka_1'); $this->profileFactory->expects($this->never()) ->method('create'); $this->sequenceBuilder->setEntityType($entityType) ->setStoreId($storeId) ->setSuffix('SUFF') ->setPrefix('PREF') ->setStartValue(1) ->setStep(1) ->setWarningValue(9999999) ->setMaxValue(912992192) ->create(); } public function testAddSequence() { $entityType = 'lalalka'; $storeId = 1; $prefix = 'PRE'; $suffix = 'SUF'; $startValue = 1; $step = 1; $maxValue = 120000; $warningValue = 110000; $this->resourceSequenceMeta->expects($this->once()) ->method('loadByEntityTypeAndStore') ->with($entityType, $storeId) ->willReturn($this->meta); $this->meta->expects($this->once()) ->method('getSequenceTable') ->willReturn(null); $this->profileFactory->expects($this->once()) ->method('create') ->with([ 'data' => [ 'prefix' => $prefix, 'suffix' => $suffix, 'start_value' => $startValue, 'step' => $step, 'max_value' => $maxValue, 'warning_value' => $warningValue, 'is_active' => 1 ] ])->willReturn($this->profile); $sequenceTable = sprintf('sequence_%s_%s', $entityType, $storeId); $this->metaFactory->expects($this->once()) ->method('create') ->with([ 'data' => [ 'entity_type' => $entityType, 'store_id' => $storeId, 'sequence_table' => $sequenceTable, 'active_profile' => $this->profile ] ])->willReturn($this->meta); $this->resourceSequenceMeta->expects($this->once())->method('save')->willReturn($this->meta); $this->stepCreateSequence($sequenceTable, $startValue); $this->sequenceBuilder->setEntityType($entityType) ->setStoreId($storeId) ->setPrefix($prefix) ->setSuffix($suffix) ->setStartValue($startValue) ->setStep($step) ->setMaxValue($maxValue) ->setWarningValue($warningValue) ->create(); } /** * Step create sequence * * @param $sequenceName * @param $startNumber */ private function stepCreateSequence($sequenceName, $startNumber) { $sql = "some sql"; $this->resourceMock->expects($this->atLeastOnce()) ->method('getTableName'); $this->resourceMock->expects($this->any()) ->method('getConnection') ->with('sales') ->willReturn($this->connectionMock); $this->sequence->expects($this->once()) ->method('getCreateSequenceDdl') ->with($sequenceName, $startNumber) ->willReturn($sql); $this->connectionMock->expects($this->once())->method('query')->with($sql); } }
{ "content_hash": "e31c3b99d1be140d8dd904bcd545ca1a", "timestamp": "", "source": "github", "line_count": 233, "max_line_length": 102, "avg_line_length": 32.15450643776824, "alnum_prop": 0.5185531233315537, "repo_name": "j-froehlich/magento2_wk", "id": "3eae19b0215699e7320a4032bbb3e1592e9696d0", "size": "7600", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vendor/magento/module-sales-sequence/Test/Unit/Model/BuilderTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "13636" }, { "name": "CSS", "bytes": "2076720" }, { "name": "HTML", "bytes": "6151072" }, { "name": "JavaScript", "bytes": "2488727" }, { "name": "PHP", "bytes": "12466046" }, { "name": "Shell", "bytes": "6088" }, { "name": "XSLT", "bytes": "19979" } ], "symlink_target": "" }
package org.springframework.security.oauth.provider.attributes; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.access.AccessDecisionVoter; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.oauth.provider.OAuthAuthenticationDetails; import java.util.List; import java.util.Collection; /** * @author Ryan Heaton * @author Andrew McCall */ public class ConsumerSecurityVoter implements AccessDecisionVoter<Object> { /** * The config attribute is supported if it's an instance of {@link org.springframework.security.oauth.provider.attributes.ConsumerSecurityConfig}. * * @param attribute The attribute. * @return Whether the attribute is an instance of {@link org.springframework.security.oauth.provider.attributes.ConsumerSecurityConfig}. */ public boolean supports(ConfigAttribute attribute) { return attribute instanceof ConsumerSecurityConfig; } /** * All classes are supported. * * @param clazz The class. * @return true. */ public boolean supports(Class<?> clazz) { return true; } /** * Votes on giving access to the specified authentication based on the security attributes. * * @param authentication The authentication. * @param object The object. * @param configAttributes the ConfigAttributes. * @return The vote. */ public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) { int result = ACCESS_ABSTAIN; if (authentication.getDetails() instanceof OAuthAuthenticationDetails) { OAuthAuthenticationDetails details = (OAuthAuthenticationDetails) authentication.getDetails(); for (Object configAttribute : configAttributes) { ConfigAttribute attribute = (ConfigAttribute) configAttribute; if (ConsumerSecurityConfig.PERMIT_ALL_ATTRIBUTE.equals(attribute)) { return ACCESS_GRANTED; } else if (ConsumerSecurityConfig.DENY_ALL_ATTRIBUTE.equals(attribute)) { return ACCESS_DENIED; } else if (supports(attribute)) { ConsumerSecurityConfig config = (ConsumerSecurityConfig) attribute; if ((config.getSecurityType() == ConsumerSecurityConfig.ConsumerSecurityType.CONSUMER_KEY) && (config.getAttribute().equals(details.getConsumerDetails().getConsumerKey()))) { return ACCESS_GRANTED; } else if (config.getSecurityType() == ConsumerSecurityConfig.ConsumerSecurityType.CONSUMER_ROLE) { List<GrantedAuthority> authorities = details.getConsumerDetails().getAuthorities(); if (authorities != null) { for (GrantedAuthority authority : authorities) { if (authority.getAuthority().equals(config.getAttribute())) { return ACCESS_GRANTED; } } } } } } } return result; } }
{ "content_hash": "be50758364e4a4cdc47f040ed0f81353", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 148, "avg_line_length": 36.29761904761905, "alnum_prop": 0.702853394555592, "repo_name": "jgrandja/spring-security-oauth", "id": "fc26ba7c166308ab5f39a653a73c00f83120c45c", "size": "3643", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "spring-security-oauth/src/main/java/org/springframework/security/oauth/provider/attributes/ConsumerSecurityVoter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2437099" } ], "symlink_target": "" }
using System; using System.Linq; using System.Reactive.Disposables; using System.Threading.Tasks; using Microsoft.Its.Domain.Sql.CommandScheduler; using Microsoft.Its.Recipes; namespace Microsoft.Its.Domain.Testing { public static class CommandScheduler { /// <summary> /// Allows awaiting delivery of all commands that are currently due on the command scheduler. /// </summary> /// <param name="scheduler">The command scheduler.</param> /// <param name="clockName">The name of the clock on which the commands are scheduled.</param> [Obsolete("This method will be removed in a future version. Use CommandScheduler.CommandSchedulerDone instead.")] public static async Task Done( this ISchedulerClockTrigger scheduler, string clockName = null) { clockName = clockName ?? SqlCommandScheduler.DefaultClockName; using (var db = new CommandSchedulerDbContext()) { var now = Clock.Latest(Clock.Current, db.Clocks.Single(c => c.Name == clockName)).Now(); await scheduler.AdvanceClock(clockName, now); } } /// <summary> /// Returns a <see cref="Task" /> that allows awaiting the completion of commands currently scheduled and due on the configured command scheduler. /// </summary> /// <param name="configuration">The configuration.</param> /// <param name="timeoutInMilliseconds">The timeout in milliseconds to wait for the scheduler to complete. If it hasn't completed by the specified time, a <see cref="TimeoutException" /> is thrown.</param> /// <returns></returns> public static Task CommandSchedulerDone( this Configuration configuration, int timeoutInMilliseconds = 5000) { var virtualClockDone = Clock.Current.IfTypeIs<VirtualClock>() .Then(c => c.Done()) .Else(() => Task.FromResult(Unit.Default)); var noCommandsInPipeline = configuration.Container .Resolve<CommandsInPipeline>() .Done(); return Task.WhenAll(virtualClockDone, noCommandsInPipeline) .TimeoutAfter(TimeSpan.FromMilliseconds(timeoutInMilliseconds)); } internal static ScheduledCommandInterceptor<TAggregate> WithInMemoryDeferredScheduling<TAggregate>(Configuration configuration) where TAggregate : class { return async (command, next) => { var etagStore = configuration.Container.Resolve<InMemoryCommandETagStore>(); if (!etagStore.TryAdd(scope: command.TargetId, etag: command.Command.ETag)) { command.Result = new CommandDeduplicated(command, "Schedule"); } else if (command.Result == null) { var clock = Clock.Current; command.Result = new CommandScheduled(command, clock); VirtualClock.Schedule( command, command.DueTime ?? Clock.Now().AddTicks(1), (s, c) => { Domain.CommandScheduler.DeliverImmediatelyOnConfiguredScheduler(c, configuration).Wait(); return Disposable.Empty; }); } await next(command); }; } } }
{ "content_hash": "e08265ee36d8995aced2fe01811d197f", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 213, "avg_line_length": 44.23529411764706, "alnum_prop": 0.5545212765957447, "repo_name": "commonsensesoftware/Its.Cqrs", "id": "9cad7a12fd8206b9dbc038705a20a828dbf39048", "size": "3914", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Domain.Testing/CommandScheduler.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "111" }, { "name": "Batchfile", "bytes": "534" }, { "name": "C#", "bytes": "2116942" }, { "name": "CSS", "bytes": "13188" }, { "name": "JavaScript", "bytes": "572" }, { "name": "PowerShell", "bytes": "342" }, { "name": "Shell", "bytes": "197" } ], "symlink_target": "" }
from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Snippet' db.create_table(u'snippets_snippet', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), ('title', self.gf('django.db.models.fields.CharField')(default='', max_length=100, blank=True)), ('code', self.gf('django.db.models.fields.TextField')()), ('linenos', self.gf('django.db.models.fields.BooleanField')(default=False)), ('language', self.gf('django.db.models.fields.CharField')(default='python', max_length=100)), ('style', self.gf('django.db.models.fields.CharField')(default='friendly', max_length=100)), ('owner', self.gf('django.db.models.fields.related.ForeignKey')(related_name='snippets', to=orm['auth.User'])), ('highlighted', self.gf('django.db.models.fields.TextField')()), )) db.send_create_signal(u'snippets', ['Snippet']) def backwards(self, orm): # Deleting model 'Snippet' db.delete_table(u'snippets_snippet') models = { u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'snippets.snippet': { 'Meta': {'ordering': "('created',)", 'object_name': 'Snippet'}, 'code': ('django.db.models.fields.TextField', [], {}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'highlighted': ('django.db.models.fields.TextField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'default': "'python'", 'max_length': '100'}), 'linenos': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'snippets'", 'to': u"orm['auth.User']"}), 'style': ('django.db.models.fields.CharField', [], {'default': "'friendly'", 'max_length': '100'}), 'title': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '100', 'blank': 'True'}) } } complete_apps = ['snippets']
{ "content_hash": "a13c20d1b6e28613fd784891a6557b34", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 195, "avg_line_length": 68.98765432098766, "alnum_prop": 0.5676449534717252, "repo_name": "rohanarora/Framework", "id": "52c9e82cdb46bc2bbedc4522fac19c97aae89c84", "size": "5612", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Django/project/snippets/migrations/0001_initial.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1411" }, { "name": "JavaScript", "bytes": "12560" }, { "name": "Python", "bytes": "26709" } ], "symlink_target": "" }
Python wrapper for accessing [Mxit's public APIs](https://dev.mxit.com/docs/restapi) ## Installation pip install mxit ## Usage ### [Authentication](https://dev.mxit.com/docs/authentication) In order to use the Mxit APIs, one needs a *client ID* and *client secret*, which can be obtained by registering your app at [dev.mxit.com](https://dev.mxit.com). With these credentials a client object can be created: ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET) ``` Certain *Mxit API* calls are publically available, and thus only require app authentication. It is not necessary to specify *scope* when making these calls through this *API wrapper*, since it is already done in the respective functions. Certain *Mxit API* calls require user authentication. The user would thus need to be redirected to *Mxit's* auth site, where permission will be granted by the user for the requested *scope(s)*. The auth site will then redirect the user back to a specified url with a *code* attached in the query string. This code is then used to obtain the auth token for the following *API* calls. For this flow the url where the auth site needs to redirect back to needs to be specified when instantiating the client: ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET, redirect_url='http://example.org') client.oauth.get_user_token(SCOPE, RECEIVED_CODE) ``` The auth site url to redirect the user to can be obtained with the following call (where *SCOPE* is the required scope(s) for the API calls to be made): ```python client.oauth.auth_url(SCOPE) ``` After the user has granted the desired permissions and the user redirected back the the url as specified, the auth token can be fetched as follows: ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET, redirect_url='http://example.org') client.oauth.get_user_token(SCOPE, RECEIVED_CODE) ``` From here the client has access to the api calls allowed by the specified *scope*. ### [Messaging API](https://dev.mxit.com/docs/restapi/messaging) #### [send_message](https://dev.mxit.com/docs/restapi/messaging/post-message-send) Send a message (from a Mxit app) to a list of Mxit users *User authentication required*: **NO** *Required scope*: **message/send** ##### Parameters * *app_mxit_id* (**required**) * *target_user_ids* (**required**) * *message* (**required**) * *contains_markup* (**optional**) * *scope* (**optional**) ##### Example ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET) client.messaging.send_message("example_app_mxit_id", ["mxit_user_id_1", "mxit_user_id_2" ], "This is a test message") ``` #### [send_user_to_user_message](https://dev.mxit.com/docs/restapi/messaging/post-message-send) Send a message (from a Mxit user) to a list of Mxit users *User authentication required*: **YES** *Required scope*: **message/user** ##### Parameters * *from_user_id* (**required**) * *target_user_ids* (**required**) * *message* (**required**) * *contains_markup* (**optional**) * *scope* (**optional**) ##### Example ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET, redirect_uri="http://example.org") client.oauth.get_user_token("message/user", RECEIVED_AUTH_CODE) client.messaging.send_user_to_user_message("example_mxit_user_id", ["mxit_user_id_1", "mxit_user_id_2" ], "This is a test user to user message") ``` ### [User API](https://dev.mxit.com/docs/restapi/user]) #### [get_user_id](https://dev.mxit.com/docs/restapi/user/get-user-lookup-mxitid) Retrieve the Mxit user's internal "user ID" *User authentication required*: **NO** *Required scope*: **profile/public** ##### Parameters * *mxit_id* (**required**) * *scope* (**optional**) ##### Example ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET) user_id = client.users.get_user_id("example_mxit_id") ``` #### [get_status](https://dev.mxit.com/docs/restapi/user/get-user-statusmessage) Retrieve the Mxit user's current status *User authentication required*: **NO** *Required scope*: **profile/public** ##### Parameters * *mxit_id* (**required**) * *scope* (**optional**) ##### Example ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET) status = client.users.get_status("example_mxit_id") ``` #### [set_status](https://dev.mxit.com/docs/restapi/user/put-user-statusmessage) Set the Mxit user's status *User authentication required*: **YES** *Required scope*: **status/write** ##### Parameters * *message* (**required**) * *scope* (**optional**) ##### Example ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET, redirect_uri="http://example.org") client.oauth.get_user_token("status/write", RECEIVED_AUTH_CODE) client.users.set_status("Some awesome status") ``` #### [get_display_name](https://dev.mxit.com/docs/restapi/user/get-user-public-displayname-mxitid) Retrieve the Mxit user's display name *User authentication required*: **NO** *Required scope*: **profile/public** ##### Parameters * *mxit_id* (**required**) * *scope* (**optional**) ##### Example ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET) display_name = client.users.get_display_name("example_mxit_id") ``` #### [get_avatar](https://dev.mxit.com/docs/restapi/user/get-user-avatar) Retrieve the Mxit user's avatar *User authentication required*: **NO** *Required scope*: **profile/public** ##### Parameters If *output_file_path* is set, the file will be saved at that path, otherwise the file data will be returned. * *mxit_id* (**required**) * *output_file_path* (**optional**) * *scope* (**optional**) ##### Example ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET) client.users.get_avatar("example_mxit_id", output_file_path="/path/to/avatar.png") data = client.users.get_avatar("example_mxit_id") ``` #### [set_avatar](https://dev.mxit.com/docs/restapi/user/post-user-avatar) Set the Mxit user's avatar *User authentication required*: **YES** *Required scope*: **avatar/write** ##### Parameters The avatar can either be sent as a bytestream in *data* or as a filepath in *input_file_path*. * *data* (**optional**) * *input_file_path* (**optional**) * *content_type* (**optional**) * *scope* (**optional**) ##### Example ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET, redirect_uri="http://example.org") client.oauth.get_user_token("avatar/write", RECEIVED_AUTH_CODE) client.users.set_avatar(input_file_path="/path/to/avatar.png") ``` #### [delete_avatar](https://dev.mxit.com/docs/restapi/user/delete-user-avatar) Delete the Mxit user's avatar *User authentication required*: **YES** *Required scope*: **avatar/write** ##### Parameters * *scope* (**optional**) ##### Example ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET, redirect_uri="http://example.org") client.oauth.get_user_token("avatar/write", RECEIVED_AUTH_CODE) client.users.delete_avatar() ``` #### [get_basic_profile](https://dev.mxit.com/docs/restapi/user/get-user-profile-userid) Retrieve the Mxit user's basic profile *User authentication required*: **NO** *Required scope*: **profile/public** ##### Parameters * *user_id* (**required**) * *scope* (**optional**) ##### Example ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET) basic_profile = client.users.get_basic_profile("example_user_id") ``` #### [get_full_profile](https://dev.mxit.com/docs/restapi/user/get-user-profile) Retrieve the Mxit user's full profile *User authentication required*: **YES** *Required scope*: **profile/private** ##### Parameters * *scope* (**optional**) ##### Example ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET, redirect_uri="http://example.org") client.oauth.get_user_token("profile/private", RECEIVED_AUTH_CODE) full_profile = client.users.get_full_profile() ``` #### [update_profile](https://dev.mxit.com/docs/restapi/user/put-user-profile) Update the Mxit user's profile *User authentication required*: **YES** *Required scope*: **profile/write** ##### Parameters * *about_me* (**optional**) * *display_name* (**optional**) * *email* (**optional**) * *first_name* (**optional**) * *gender* (**optional**) * *last_name* (**optional**) * *mobile_number* (**optional**) * *relationship_status* (**optional**) * *title* (**optional**) * *where_am_i* (**optional**) * *scope* (**optional**) ##### Example ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET, redirect_uri="http://example.org") client.oauth.get_user_token("profile/write", RECEIVED_AUTH_CODE) client.users.update_profile(email="test@test.com", relationship_status=3) ``` #### [add_contact](https://dev.mxit.com/docs/restapi/user/put-user-socialgraph-contact-contact) Add a contact on Mxit *User authentication required*: **YES** *Required scope*: **contact/invite** ##### Parameters *contact_id* can either be the mxit ID of a service or a Mxit user * *contact_id* (**required**) * *scope* (**optional**) ##### Example ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET, redirect_uri="http://example.org") client.oauth.get_user_token("contact/invite", RECEIVED_AUTH_CODE) client.users.add_contact("example_contact_id") ``` #### [get_contact_list](https://dev.mxit.com/docs/restapi/user/get-user-socialgraph-contactlist) Retrieve the Mxit user's full contact list *User authentication required*: **YES** *Required scope*: **graph/read** ##### Parameters *list_filter* options can be found in ``mxit.CONTACT_LIST_FILTER``. The following options are available: **"all", "friends", "apps", "invites", "connections", "rejected", "pending", "deleted", "blocked"** * *list_filter* (**required**) * *skip* (**optional**) * *count* (**optional**) * *scope* (**optional**) ##### Example ```python from mxit import Mxit, CONTACT_LIST_FILTER client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET, redirect_uri="http://example.org") client.oauth.get_user_token("graph/read", RECEIVED_AUTH_CODE) client.users.get_contact_list(CONTACT_LIST_FILTER['all']) ``` #### [get_friend_suggestions](https://dev.mxit.com/docs/restapi/user/get-user-socialgraph-suggestions) Retrieve the Mxit user's full profile *User authentication required*: **YES** *Required scope*: **graph/read** ##### Parameters * *scope* (**optional**) ##### Example ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET, redirect_uri="http://example.org") client.oauth.get_user_token("graph/read", RECEIVED_AUTH_CODE) client.users.get_friend_suggestions() ``` #### [get_gallery_folder_list](https://dev.mxit.com/docs/restapi/user/get-user-media) Retrieve a list of the Mxit user's gallery folders *User authentication required*: **YES** *Required scope*: **content/read** ##### Parameters * *scope* (**optional**) ##### Example ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET, redirect_uri="http://example.org") client.oauth.get_user_token("content/read", RECEIVED_AUTH_CODE) client.users.get_gallery_folder_list() ``` #### [create_gallery_folder](https://dev.mxit.com/docs/restapi/user/post-user-media-foldername) Create a new folder in the Mxit user's gallery *User authentication required*: **YES** *Required scope*: **content/write** ##### Parameters * *folder_name* (**required**) * *scope* (**optional**) ##### Example ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET, redirect_uri="http://example.org") client.oauth.get_user_token("content/write", RECEIVED_AUTH_CODE) client.users.create_gallery_folder("example folder name") ``` #### [delete_gallery_folder](https://dev.mxit.com/docs/restapi/user/delete-user-media-foldername) Delete a folder in the Mxit user's gallery *User authentication required*: **YES** *Required scope*: **content/write** ##### Parameters * *folder_name* (**required**) * *scope* (**optional**) ##### Example ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET, redirect_uri="http://example.org") client.oauth.get_user_token("content/write", RECEIVED_AUTH_CODE) client.users.delete_gallery_folder("example folder name") ``` #### [rename_gallery_folder](https://dev.mxit.com/docs/restapi/user/put-user-media-foldername) Rename a folder in the Mxit user's gallery *User authentication required*: **YES** *Required scope*: **content/write** ##### Parameters * *old_folder_name* (**required**) * *new_folder_name* (**required**) * *scope* (**optional**) ##### Example ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET, redirect_uri="http://example.org") client.oauth.get_user_token("content/write", RECEIVED_AUTH_CODE) client.users.rename_gallery_folder("old example folder name", "new example folder name") ``` #### [delete_gallery_file](https://dev.mxit.com/docs/restapi/user/delete-user-media-file-fileid) Delete a file in the Mxit user's gallery *User authentication required*: **YES** *Required scope*: **content/write** ##### Parameters * *file_id* (**required**) * *scope* (**optional**) ##### Example ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET, redirect_uri="http://example.org") client.oauth.get_user_token("content/write", RECEIVED_AUTH_CODE) client.users.delete_gallery_file("example_file_id") ``` #### [rename_gallery_file](https://dev.mxit.com/docs/restapi/user/put-user-media-file-fileid) Rename a file in the Mxit user's gallery *User authentication required*: **YES** *Required scope*: **content/write** ##### Parameters * *file_id* (**required**) * *new_file_name* (**required**) * *scope* (**optional**) ##### Example ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET, redirect_uri="http://example.org") client.oauth.get_user_token("content/write", RECEIVED_AUTH_CODE) client.users.rename_gallery_file("example_file_id", "new file name") ``` #### [upload_gallery_file](https://dev.mxit.com/docs/restapi/user/post-user-media-file-foldername) Upload a file to a folder in the Mxit user's gallery *User authentication required*: **YES** *Required scope*: **content/write** ##### Parameters The file can either be sent as a bytestream in *data* or as a filepath in *input_file_path*. * *folder_name* (**required**) * *file_name* (**required**) * *data* (**optional**) * *input_file_path* (**optional**) * *prevent_share* (**optional**) * *content_type* (**optional**) * *scope* (**optional**) ##### Example ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET, redirect_uri="http://example.org") client.oauth.get_user_token("content/write", RECEIVED_AUTH_CODE) client.users.upload_gallery_file("example folder name", "example file name", input_file_path="/path/to/image.png", content_type="image/png") ``` #### [get_gallery_item_list](https://dev.mxit.com/docs/restapi/user/get-user-media-list-foldername) Get the item listing in a given folder in the Mxit user's gallery *User authentication required*: **YES** *Required scope*: **content/read** ##### Parameters * *folder_name* (**required**) * *skip* (**optional**) * *count* (**optional**) * *scope* (**optional**) ##### Example ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET, redirect_uri="http://example.org") client.oauth.get_user_token("content/read", RECEIVED_AUTH_CODE) client.users.get_gallery_item_list("example folder name") ``` #### [get_gallery_file](https://dev.mxit.com/docs/restapi/user/get-user-media-content-fileid) Get a file in the Mxit user's gallery *User authentication required*: **YES** *Required scope*: **content/read** ##### Parameters If *output_file_path* is set, the file will be saved at that path, otherwise the file data will be returned. * *file_id* (**required**) * *output_file_path* (**optional**) * *scope* (**optional**) ##### Example ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET, redirect_uri="http://example.org") client.oauth.get_user_token("content/read", RECEIVED_AUTH_CODE) client.users.get_gallery_file("example_file_id", output_file_path="/path/to/image.png") data = client.users.get_avatar("example_file_id") ``` #### upload_file_and_send_file_offer Upload a file of any type to store and return a FileId once file offer has been sent. *User authentication required*: **NO** *Required scope*: **content/send** ##### Parameters The file can either be sent as a bytestream in *data* or as a filepath in *input_file_path*. * *file_name* (**required**) * *user_id* (**required**) * *data* (**optional**) * *input_file_path* (**optional**) * *auto_open* (**optional**) * *prevent_share* (**optional**) * *scope* (**optional**) ##### Example ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET) user_id = client.users.get_user_id("example_mxit_id") client.users.upload_file_and_send_file_offer("example_file_name", user_id, input_file_path="/path/to/image.png") ``` #### send_file_offer Upload a file of any type to store and return a FileId once file offer has been sent. *User authentication required*: **NO** *Required scope*: **content/send** ##### Parameters * *file_id* (**required**) * *user_id* (**required**) * *scope* (**optional**) ##### Example ```python from mxit import Mxit client = Mxit(MXIT_CLIENT_ID, MXIT_CLIENT_SECRET) user_id = client.users.get_user_id("example_mxit_id") client.users.send_file_offer("example_file_id", user_id) ```
{ "content_hash": "b3fd8e4dbcd1bafd7828ad64cfc1bc57", "timestamp": "", "source": "github", "line_count": 713, "max_line_length": 503, "avg_line_length": 24.994389901823283, "alnum_prop": 0.6951910667190393, "repo_name": "Mxit/python-mxit", "id": "410e4bba1bed855ead700f284dd9b3d6d0344956", "size": "17836", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "39237" }, { "name": "Shell", "bytes": "50" } ], "symlink_target": "" }
package com.rocko.wwv; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebSettings; import android.webkit.WebView; import com.rocko.wwv.widget.HorizontalSlideWebView; /** * @author: Rocko */ public class WebViewsFragment extends Fragment { private static final String TAG = WebViewsFragment.class.getSimpleName(); protected HorizontalSlideWebView mWebView; private int index; public WebViewsFragment() { } public WebViewsFragment(int index) { this.index = index; } public static WebViewsFragment newInstance(int index) { return new WebViewsFragment(index); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View contentView = inflater.inflate(R.layout.webview_horizontalslide, container, false); initWidget(contentView); initData(); return contentView; } private void initWidget(View contentView) { mWebView = (HorizontalSlideWebView) contentView.findViewById(R.id.webview_horizontal); setWebViewDefault(mWebView); switch (index) { case 1: mWebView.setTopContentHeightPercent(1f/3); mWebView.setSlideGalleryHeightPercent(1f/3); break; case 2: mWebView.setTopContentHeightPercent(1f/7); mWebView.setSlideGalleryHeightPercent(2.8f/7); break; case 3: mWebView.setTopContentHeightPercent(1f/7); mWebView.setSlideGalleryHeightPercent(2.8f/7); break; } } private void initData() { String url = ""; switch (index) { case 1: url = "http://i.ifeng.com/"; break; case 2: url = "http://i.ifeng.com/"; break; case 3: url = "http://i.ifeng.com/"; break; } mWebView.loadUrl(url); } /** * WebView 默认设置 */ private void setWebViewDefault(WebView webView) { WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true); } }
{ "content_hash": "8b8a8b630baaf3abeb8f8093eee8ac12", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 100, "avg_line_length": 23.288888888888888, "alnum_prop": 0.7352099236641222, "repo_name": "zhengxiaopeng/Rocko-Android-Demos", "id": "0476a7e6164b97b05a9b7b23c6260441dd38ed2a", "size": "2104", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "webview-with-viewpager/src/main/java/com/rocko/wwv/WebViewsFragment.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "700261" } ], "symlink_target": "" }
 #pragma once #include <aws/ec2/EC2_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSStreamFwd.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/ec2/model/GroupIdentifier.h> #include <aws/ec2/model/Tag.h> #include <utility> namespace Aws { namespace Utils { namespace Xml { class XmlNode; } // namespace Xml } // namespace Utils namespace EC2 { namespace Model { /** * <p>Describes a linked EC2-Classic instance.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ClassicLinkInstance">AWS * API Reference</a></p> */ class AWS_EC2_API ClassicLinkInstance { public: ClassicLinkInstance(); ClassicLinkInstance(const Aws::Utils::Xml::XmlNode& xmlNode); ClassicLinkInstance& operator=(const Aws::Utils::Xml::XmlNode& xmlNode); void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const; void OutputToStream(Aws::OStream& oStream, const char* location) const; /** * <p>A list of security groups.</p> */ inline const Aws::Vector<GroupIdentifier>& GetGroups() const{ return m_groups; } /** * <p>A list of security groups.</p> */ inline void SetGroups(const Aws::Vector<GroupIdentifier>& value) { m_groupsHasBeenSet = true; m_groups = value; } /** * <p>A list of security groups.</p> */ inline void SetGroups(Aws::Vector<GroupIdentifier>&& value) { m_groupsHasBeenSet = true; m_groups = std::move(value); } /** * <p>A list of security groups.</p> */ inline ClassicLinkInstance& WithGroups(const Aws::Vector<GroupIdentifier>& value) { SetGroups(value); return *this;} /** * <p>A list of security groups.</p> */ inline ClassicLinkInstance& WithGroups(Aws::Vector<GroupIdentifier>&& value) { SetGroups(std::move(value)); return *this;} /** * <p>A list of security groups.</p> */ inline ClassicLinkInstance& AddGroups(const GroupIdentifier& value) { m_groupsHasBeenSet = true; m_groups.push_back(value); return *this; } /** * <p>A list of security groups.</p> */ inline ClassicLinkInstance& AddGroups(GroupIdentifier&& value) { m_groupsHasBeenSet = true; m_groups.push_back(std::move(value)); return *this; } /** * <p>The ID of the instance.</p> */ inline const Aws::String& GetInstanceId() const{ return m_instanceId; } /** * <p>The ID of the instance.</p> */ inline void SetInstanceId(const Aws::String& value) { m_instanceIdHasBeenSet = true; m_instanceId = value; } /** * <p>The ID of the instance.</p> */ inline void SetInstanceId(Aws::String&& value) { m_instanceIdHasBeenSet = true; m_instanceId = std::move(value); } /** * <p>The ID of the instance.</p> */ inline void SetInstanceId(const char* value) { m_instanceIdHasBeenSet = true; m_instanceId.assign(value); } /** * <p>The ID of the instance.</p> */ inline ClassicLinkInstance& WithInstanceId(const Aws::String& value) { SetInstanceId(value); return *this;} /** * <p>The ID of the instance.</p> */ inline ClassicLinkInstance& WithInstanceId(Aws::String&& value) { SetInstanceId(std::move(value)); return *this;} /** * <p>The ID of the instance.</p> */ inline ClassicLinkInstance& WithInstanceId(const char* value) { SetInstanceId(value); return *this;} /** * <p>Any tags assigned to the instance.</p> */ inline const Aws::Vector<Tag>& GetTags() const{ return m_tags; } /** * <p>Any tags assigned to the instance.</p> */ inline void SetTags(const Aws::Vector<Tag>& value) { m_tagsHasBeenSet = true; m_tags = value; } /** * <p>Any tags assigned to the instance.</p> */ inline void SetTags(Aws::Vector<Tag>&& value) { m_tagsHasBeenSet = true; m_tags = std::move(value); } /** * <p>Any tags assigned to the instance.</p> */ inline ClassicLinkInstance& WithTags(const Aws::Vector<Tag>& value) { SetTags(value); return *this;} /** * <p>Any tags assigned to the instance.</p> */ inline ClassicLinkInstance& WithTags(Aws::Vector<Tag>&& value) { SetTags(std::move(value)); return *this;} /** * <p>Any tags assigned to the instance.</p> */ inline ClassicLinkInstance& AddTags(const Tag& value) { m_tagsHasBeenSet = true; m_tags.push_back(value); return *this; } /** * <p>Any tags assigned to the instance.</p> */ inline ClassicLinkInstance& AddTags(Tag&& value) { m_tagsHasBeenSet = true; m_tags.push_back(std::move(value)); return *this; } /** * <p>The ID of the VPC.</p> */ inline const Aws::String& GetVpcId() const{ return m_vpcId; } /** * <p>The ID of the VPC.</p> */ inline void SetVpcId(const Aws::String& value) { m_vpcIdHasBeenSet = true; m_vpcId = value; } /** * <p>The ID of the VPC.</p> */ inline void SetVpcId(Aws::String&& value) { m_vpcIdHasBeenSet = true; m_vpcId = std::move(value); } /** * <p>The ID of the VPC.</p> */ inline void SetVpcId(const char* value) { m_vpcIdHasBeenSet = true; m_vpcId.assign(value); } /** * <p>The ID of the VPC.</p> */ inline ClassicLinkInstance& WithVpcId(const Aws::String& value) { SetVpcId(value); return *this;} /** * <p>The ID of the VPC.</p> */ inline ClassicLinkInstance& WithVpcId(Aws::String&& value) { SetVpcId(std::move(value)); return *this;} /** * <p>The ID of the VPC.</p> */ inline ClassicLinkInstance& WithVpcId(const char* value) { SetVpcId(value); return *this;} private: Aws::Vector<GroupIdentifier> m_groups; bool m_groupsHasBeenSet; Aws::String m_instanceId; bool m_instanceIdHasBeenSet; Aws::Vector<Tag> m_tags; bool m_tagsHasBeenSet; Aws::String m_vpcId; bool m_vpcIdHasBeenSet; }; } // namespace Model } // namespace EC2 } // namespace Aws
{ "content_hash": "a0babeaada97c4cecbb9802430f5b4f2", "timestamp": "", "source": "github", "line_count": 202, "max_line_length": 149, "avg_line_length": 29.89108910891089, "alnum_prop": 0.6303411725736999, "repo_name": "JoyIfBam5/aws-sdk-cpp", "id": "4570c4e7a040faf49482822bf9c3e35f9e6cdfd8", "size": "6611", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-cpp-sdk-ec2/include/aws/ec2/model/ClassicLinkInstance.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "11868" }, { "name": "C++", "bytes": "167818064" }, { "name": "CMake", "bytes": "591577" }, { "name": "HTML", "bytes": "4471" }, { "name": "Java", "bytes": "271801" }, { "name": "Python", "bytes": "85650" }, { "name": "Shell", "bytes": "5277" } ], "symlink_target": "" }
package org.deri.iris.evaluation.forewriting; import java.util.ArrayList; import java.util.List; import org.deri.iris.Configuration; import org.deri.iris.EvaluationException; import org.deri.iris.api.basics.IQuery; import org.deri.iris.api.basics.IRule; import org.deri.iris.evaluation.IEvaluationStrategy; import org.deri.iris.evaluation.IEvaluationStrategyFactory; import org.deri.iris.facts.IFacts; /** * @author Giorgio Orsi <orsi AT elet DOT polimi DOT it> * ICT Institute - Politecnico di Milano. * @version 0.1b * */ public class SQLRewritingEvaluationStrategyFactory extends FORewritingEvaluationStrategyFactory implements IEvaluationStrategyFactory { public IEvaluationStrategy createEvaluator(IFacts facts, List<IRule> rules, Configuration configuration) throws EvaluationException { return createEvaluator(facts, rules, new ArrayList<IQuery>(), configuration); } /* (non-Javadoc) * @see org.deri.iris.evaluation.IEvaluationStrategyFactory#createEvaluator(org.deri.iris.facts.IFacts, java.util.List, java.util.List, org.deri.iris.Configuration) */ @Override public IEvaluationStrategy createEvaluator(IFacts facts, List<IRule> rules, List<IQuery> queries, Configuration configuration) throws EvaluationException { return new SQLRewritingEvaluationStrategy(facts, rules, queries, configuration); } }
{ "content_hash": "07d25151eaf056c2cfb914d4133cbfb7", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 168, "avg_line_length": 33.68292682926829, "alnum_prop": 0.78059377262853, "repo_name": "personalised-semantic-search/JoDS_IRIS--", "id": "f6c12fbfffead70ce9d40c34ed5b456e0816f4f0", "size": "2284", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "JoDS_IRIS+-/src/org/deri/iris/evaluation/forewriting/SQLRewritingEvaluationStrategyFactory.java", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "374" }, { "name": "CSS", "bytes": "4880" }, { "name": "HTML", "bytes": "4634" }, { "name": "Java", "bytes": "5099393" }, { "name": "PHP", "bytes": "132535" }, { "name": "Shell", "bytes": "2532" } ], "symlink_target": "" }
<html> <head> <title>Daniel Wild's panel show appearances</title> <script type="text/javascript" src="../common.js"></script> <link rel="stylesheet" media="all" href="../style.css" type="text/css"/> <script type="text/javascript" src="../people.js"></script> <!--#include virtual="head.txt" --> </head> <body> <!--#include virtual="nav.txt" --> <div class="page"> <h1>Daniel Wild's panel show appearances</h1> <p>Daniel Wild has appeared in <span class="total">1</span> episodes between 2018-2018. Note that these appearances may be for more than one person if multiple people have the same name.</p> <div class="performerholder"> <table class="performer"> <tr style="vertical-align:bottom;"> <td><div style="height:100px;" class="performances male" title="1"></div><span class="year">2018</span></td> </tr> </table> </div> <ol class="episodes"> <li><strong>2018-03-16</strong> / <a href="../shows/the-drum.html">The Drum</a></li> </ol> </div> </body> </html>
{ "content_hash": "08aed4feaf774f00c84891a1a2a35608", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 191, "avg_line_length": 32.833333333333336, "alnum_prop": 0.6649746192893401, "repo_name": "slowe/panelshows", "id": "6dd18480e5e96d9301a0cb2d66a1cf3b077a4e51", "size": "985", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "people/k7z73d8i.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8431" }, { "name": "HTML", "bytes": "25483901" }, { "name": "JavaScript", "bytes": "95028" }, { "name": "Perl", "bytes": "19899" } ], "symlink_target": "" }
package com.itellity.comp.type.communication; import com.itellity.sys.type.AbstractImmutableValue; import com.itellity.sys.type.PrimitiveValue; import com.itellity.sys.util.StringUtilities; import com.itellity.comp.type.communication.EmailAddress; /** * This Primitive value defines the data type <code>EmailAddress</code>. * * @author Goetz Perry * @version $Id: EmailAddress.java 12355 2009-02-20 13:11:58Z erik $ */ public final class EmailAddress extends AbstractImmutableValue { private static final long serialVersionUID = -6369643101971029136L; public static final int EMAIL_ADDRESS_MAX_LENGTH = 100; public final static EmailAddress UNDEFINED = new EmailAddress(); private volatile int hashCode = 0; private final String emailAddress; /** * No-arg constructor. used to define an undefined value. */ private EmailAddress() { this.emailAddress = ""; } /** * Creates a new EmailAddress object. * * @param emailAddress the email address. */ public EmailAddress(String emailAddress) { // check email address. checkMaxStringLength(emailAddress, EMAIL_ADDRESS_MAX_LENGTH, "email address"); if (!isValidFormat(emailAddress)) { throw new IllegalArgumentException("A valid email address must contain at least one . and @. This doesn't comply:" + emailAddress); } this.emailAddress = emailAddress; } public static boolean isValidFormat(String emailAddress) { return !StringUtilities.isNullOrEmpty(emailAddress) && (emailAddress.indexOf("@") > -1 && emailAddress.indexOf(".") > -1); } /** * Returns the email address as a string. * * @return the email address. */ public String getEmailAddress() { return emailAddress; } /** * @see java.lang.Object#hashCode() */ public int hashCode() { if (hashCode == 0) { hashCode = emailAddress.hashCode(); } return hashCode; } /** * @see com.transmobility.sys.type.Value#isUndefined() */ public boolean isUndefined() { return UNDEFINED.equals(this); } public String toString() { return isUndefined() ? UNDEFINED_STRING : getEmailAddress(); } /** * @see com.transmobility.sys.type.PrimitiveValue#doEquals(PrimitiveValue) */ public boolean doEquals(PrimitiveValue value) { EmailAddress other = (EmailAddress) value; return (emailAddress.equals(other.emailAddress)); } public static EmailAddress valueOf(String string) { return new EmailAddress(string); } }
{ "content_hash": "ad26f2014c14ea1608466b796a549baf", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 140, "avg_line_length": 27.14851485148515, "alnum_prop": 0.6382202771699489, "repo_name": "schmiegelow/BaseFramework", "id": "b3e813fbee28f7a445c2d28c6eb339f0f288ee0a", "size": "2906", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/itellity/comp/type/communication/EmailAddress.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1032250" } ], "symlink_target": "" }
namespace Neo.Gui.Base.Dialogs.Results.Wallets { public class ImportPrivateKeyDialogResult { } }
{ "content_hash": "0157ccac6ad6a9790637f27f8a6ce589", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 47, "avg_line_length": 18.333333333333332, "alnum_prop": 0.7181818181818181, "repo_name": "jlgaffney/neo-gui-wpf", "id": "9212bb94fb7c51f6fd2463aac78300eb687c81d3", "size": "112", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Neo.Gui.Base/Dialogs/Results/Wallets/ImportPrivateKeyDialogResult.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "275" }, { "name": "C#", "bytes": "469051" } ], "symlink_target": "" }
 #pragma once #include <aws/iotevents-data/IoTEventsData_EXPORTS.h> #include <aws/iotevents-data/IoTEventsDataRequest.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/iotevents-data/model/SnoozeAlarmActionRequest.h> #include <utility> namespace Aws { namespace IoTEventsData { namespace Model { /** */ class AWS_IOTEVENTSDATA_API BatchSnoozeAlarmRequest : public IoTEventsDataRequest { public: BatchSnoozeAlarmRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "BatchSnoozeAlarm"; } Aws::String SerializePayload() const override; /** * <p>The list of snooze action requests. You can specify up to 10 requests per * operation.</p> */ inline const Aws::Vector<SnoozeAlarmActionRequest>& GetSnoozeActionRequests() const{ return m_snoozeActionRequests; } /** * <p>The list of snooze action requests. You can specify up to 10 requests per * operation.</p> */ inline bool SnoozeActionRequestsHasBeenSet() const { return m_snoozeActionRequestsHasBeenSet; } /** * <p>The list of snooze action requests. You can specify up to 10 requests per * operation.</p> */ inline void SetSnoozeActionRequests(const Aws::Vector<SnoozeAlarmActionRequest>& value) { m_snoozeActionRequestsHasBeenSet = true; m_snoozeActionRequests = value; } /** * <p>The list of snooze action requests. You can specify up to 10 requests per * operation.</p> */ inline void SetSnoozeActionRequests(Aws::Vector<SnoozeAlarmActionRequest>&& value) { m_snoozeActionRequestsHasBeenSet = true; m_snoozeActionRequests = std::move(value); } /** * <p>The list of snooze action requests. You can specify up to 10 requests per * operation.</p> */ inline BatchSnoozeAlarmRequest& WithSnoozeActionRequests(const Aws::Vector<SnoozeAlarmActionRequest>& value) { SetSnoozeActionRequests(value); return *this;} /** * <p>The list of snooze action requests. You can specify up to 10 requests per * operation.</p> */ inline BatchSnoozeAlarmRequest& WithSnoozeActionRequests(Aws::Vector<SnoozeAlarmActionRequest>&& value) { SetSnoozeActionRequests(std::move(value)); return *this;} /** * <p>The list of snooze action requests. You can specify up to 10 requests per * operation.</p> */ inline BatchSnoozeAlarmRequest& AddSnoozeActionRequests(const SnoozeAlarmActionRequest& value) { m_snoozeActionRequestsHasBeenSet = true; m_snoozeActionRequests.push_back(value); return *this; } /** * <p>The list of snooze action requests. You can specify up to 10 requests per * operation.</p> */ inline BatchSnoozeAlarmRequest& AddSnoozeActionRequests(SnoozeAlarmActionRequest&& value) { m_snoozeActionRequestsHasBeenSet = true; m_snoozeActionRequests.push_back(std::move(value)); return *this; } private: Aws::Vector<SnoozeAlarmActionRequest> m_snoozeActionRequests; bool m_snoozeActionRequestsHasBeenSet = false; }; } // namespace Model } // namespace IoTEventsData } // namespace Aws
{ "content_hash": "9ce4c6a2b772c2129754893ae93dd169", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 204, "avg_line_length": 38.741573033707866, "alnum_prop": 0.7230278422273781, "repo_name": "aws/aws-sdk-cpp", "id": "ee881521cfbae6c46b615e298eb68af0c0635b1d", "size": "3567", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "aws-cpp-sdk-iotevents-data/include/aws/iotevents-data/model/BatchSnoozeAlarmRequest.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "309797" }, { "name": "C++", "bytes": "476866144" }, { "name": "CMake", "bytes": "1245180" }, { "name": "Dockerfile", "bytes": "11688" }, { "name": "HTML", "bytes": "8056" }, { "name": "Java", "bytes": "413602" }, { "name": "Python", "bytes": "79245" }, { "name": "Shell", "bytes": "9246" } ], "symlink_target": "" }
import React from 'react'; import {mount} from 'enzyme'; import sinon from 'sinon'; import FauxtonAPI from '../../../core/api'; import AddOptionButton from '../components/AddOptionButton'; import ConfigOption from '../components/ConfigOption'; import ConfigOptionValue from '../components/ConfigOptionValue'; import ConfigOptionTrash from '../components/ConfigOptionTrash'; import ConfigTableScreen from '../components/ConfigTableScreen'; import utils from '../../../../test/mocha/testUtils'; FauxtonAPI.router = new FauxtonAPI.Router([]); const assert = utils.assert; describe('Config Components', () => { describe('ConfigTableScreen', () => { const options = [ {editing: false, header:true, sectionName: 'sec1', optionName: 'opt1', value: 'value1'}, {editing: false, header:false, sectionName: 'sec1', optionName: 'opt2', value: 'value2'} ]; const node = 'test_node'; const defaultProps = { saving: false, loading: false, deleteOption: () => {}, saveOption: () => {}, editOption: () => {}, cancelEdit: () => {}, fetchAndEditConfig: () => {}, node, options }; it('deletes options', () => { const spy = sinon.stub(); const wrapper = mount(<ConfigTableScreen {...defaultProps} deleteOption={spy}/> ); wrapper.instance().deleteOption({}); sinon.assert.called(spy); }); it('saves options', () => { const spy = sinon.stub(); const wrapper = mount(<ConfigTableScreen {...defaultProps} saveOption={spy}/> ); wrapper.instance().saveOption({}); sinon.assert.called(spy); }); it('edits options', () => { const spy = sinon.stub(); const wrapper = mount(<ConfigTableScreen {...defaultProps} editOption={spy}/> ); wrapper.instance().editOption({}); sinon.assert.called(spy); }); it('cancels editing', () => { const spy = sinon.stub(); const wrapper = mount(<ConfigTableScreen {...defaultProps} cancelEdit={spy}/> ); wrapper.instance().cancelEdit(); sinon.assert.called(spy); }); }); describe('ConfigOption', () => { const defaultProps = { option: {}, saving: false, onEdit: () => {}, onCancelEdit: () => {}, onSave: () => {}, onDelete: () => {} }; it('renders section name if the option is a header', () => { const option = { sectionName: 'test_section', optionName: 'test_option', value: 'test_value', header: true, editing: true }; const el = mount(<table><tbody><ConfigOption {...defaultProps} option={option}/></tbody></table>); assert.equal(el.find('th').text(), 'test_section'); }); }); describe('ConfigOptionValue', () => { const defaultProps = { value: '', editing: false, onEdit: () => {}, onCancelEdit: () => {}, onSave: () => {} }; it('displays the value prop', () => { const el = mount( <table><tbody><tr> <ConfigOptionValue {...defaultProps} value={'test_value'}/> </tr></tbody></table> ); assert.equal(el.text(), 'test_value'); }); it('starts editing when clicked', () => { const spy = sinon.spy(); const el = mount( <table><tbody><tr> <ConfigOptionValue {...defaultProps} value={'test_value'} onEdit={spy}/> </tr></tbody></table> ); el.find(ConfigOptionValue).simulate('click'); assert.ok(spy.calledOnce); }); it('displays editing controls if editing', () => { const el = mount( <table><tbody><tr> <ConfigOptionValue {...defaultProps} value={'test_value'} editing/> </tr></tbody></table> ); assert.equal(el.find('input.config-value-input').length, 1); assert.equal(el.find('button.btn-config-cancel').length, 1); assert.equal(el.find('button.btn-config-save').length, 1); }); it('disables input when saving is set to true', () => { const el = mount( <table><tbody><tr> <ConfigOptionValue {...defaultProps} value={'test_value'} editing={true} saving={true}/> </tr></tbody></table> ); assert.ok(el.find('input.config-value-input').prop('disabled')); }); it('saves changed value of input when save clicked', () => { var change = { target: { value: 'new_value' } }; const spy = sinon.spy(); const el = mount( <table><tbody><tr> <ConfigOptionValue {...defaultProps} value={'test_value'} editing onSave={spy}/> </tr></tbody></table> ); el.find('input.config-value-input').simulate('change', change); el.find('button.btn-config-save').simulate('click'); assert.ok(spy.calledWith('new_value')); }); it('cancels edit if save clicked with unchanged value', () => { const spy = sinon.spy(); const el = mount( <table><tbody><tr> <ConfigOptionValue {...defaultProps} value={'test_value'} editing onCancelEdit={spy}/> </tr></tbody></table> ); el.find('button.btn-config-save').simulate('click'); assert.ok(spy.calledOnce); }); }); describe('ConfigOptionTrash', () => { it.skip('displays delete modal when clicked', () => { const el = mount( <ConfigOptionTrash sectionName='test_section' optionName='test_option'/> ); el.simulate('click'); // assert.equal($('div.confirmation-modal').length, 1); }); it.skip('calls on delete when confirmation modal Okay button clicked', () => { const spy = sinon.spy(); const el = mount( <ConfigOptionTrash onDelete={spy}/> ); el.simulate('click'); // TestUtils.Simulate.click($('div.confirmation-modal button.btn-primary')[0]); assert.ok(spy.calledOnce); }); }); //we need enzyme to support portals for this describe.skip('AddOptionButton', () => { it('adds options', () => { const spy = sinon.stub(); const wrapper = mount( <AddOptionButton onAdd={spy}/> ); wrapper.instance().onAdd(); assert.ok(spy.calledOnce); }); }); //we need enzyme to support portals for this describe.skip('AddOptionButton', () => { it('displays add option controls when clicked', () => { const el = mount( <AddOptionButton/> ); el.find('button#add-option-button').simulate('click'); assert.equal($('div#add-option-popover .input-section-name').length, 1); assert.equal($('div#add-option-popover .input-option-name').length, 1); assert.equal($('div#add-option-popover .input-value').length, 1); assert.equal($('div#add-option-popover .btn-create').length, 1); }); it('does not hide popover if create clicked with invalid input', () => { const el = mount( <AddOptionButton/> ); el.find('button#add-option-button').simulate('click'); // TestUtils.Simulate.click($('div#add-option-popover .btn-create')[0]); assert.equal($('div#add-option-popover').length, 1); }); it('does not add option if create clicked with invalid input', () => { const el = mount( <AddOptionButton/> ); el.find('button#add-option-button').simulate('click'); // TestUtils.Simulate.click($('div#add-option-popover .btn-create')[0]); assert.equal($('div#add-option-popover').length, 1); }); it('does adds option if create clicked with valid input', () => { const el = mount( <AddOptionButton/> ); el.find('button#add-option-button').simulate('click'); // TestUtils.Simulate.click($('div#add-option-popover .btn-create')[0]); assert.equal($('div#add-option-popover').length, 1); }); it('adds option when create clicked with valid input', () => { const spy = sinon.spy(); const el = mount( <AddOptionButton onAdd={spy}/> ); el.find('button#add-option-button').simulate('click'); // TestUtils.Simulate.change($('div#add-option-popover .input-section-name')[0], { target: { value: 'test_section' } }); // TestUtils.Simulate.change($('div#add-option-popover .input-option-name')[0], { target: { value: 'test_option' } }); // TestUtils.Simulate.change($('div#add-option-popover .input-value')[0], { target: { value: 'test_value' } }); // TestUtils.Simulate.click($('div#add-option-popover .btn-create')[0]); assert.ok(spy.calledWith(sinon.match({ sectionName: 'test_section', optionName: 'test_option', value: 'test_value' }))); }); }); });
{ "content_hash": "752c9bc16b2bf11394a8f81205c881b2", "timestamp": "", "source": "github", "line_count": 276, "max_line_length": 126, "avg_line_length": 31.6231884057971, "alnum_prop": 0.5734417965169569, "repo_name": "michellephung/couchdb-fauxton", "id": "a250e3e356eaff45c3c56fdd7664792b0a0d5d50", "size": "9282", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/addons/config/__tests__/components.test.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "151383" }, { "name": "HTML", "bytes": "254979" }, { "name": "JavaScript", "bytes": "1616857" }, { "name": "Ruby", "bytes": "124" }, { "name": "Shell", "bytes": "3030" }, { "name": "TypeScript", "bytes": "1241" } ], "symlink_target": "" }
import moment from 'moment'; import base from './apiBase'; export default class extends base { async getAction(){ let data; if (this.id) { data = await this.modelInstance.where({id: this.id}).find(); data.category = await this.model('category').where({id: data.category_id}).getField('name', true); } else { let page = this.get('page') || 1; let pageCount = this.get('page_count') || 20; data = await this.modelInstance .alias('post') .field('`post`.*, `category`.`name` as "category", `user`.`username` as "user"') .join([{ table: 'category', as: 'category', on: ['`post`.`category_id`', '`category`.`id`'] }, { table: 'user', as: 'user', on: ['`post`.`user_id`', '`user`.`id`'] }]) .order('`date` DESC') .limit((page - 1) * pageCount, pageCount) .select(); } return this.success(data); } async postAction() { let data = this.post(); if(think.isEmpty(data)){ return this.fail('data is empty'); } let category_id = data.category; if (data.newCategory) { let categoryModel = this.model('category'); category_id = categoryModel.add({name: data.newCategory}); } let date = moment().format(); let author = this.userInfo.id; let insertId = await this.modelInstance.add({ category_id, date, author, title: data.title, content: data.content, modify_date: date, modify_user: author }); return this.success({id: insertId}); } async putAction() { if (!this.id) { return this.fail('params error'); } let data = this.post(); if (think.isEmpty(data)) { return this.fail('data is empty'); } delete data.id; Object.assign(data, { modify_date: moment().format(), modify_user: this.userInfo.id }); let rows = await this.modelInstance.where({id: this.id}).update(data); return this.success({affectedRows: rows}); } async deleteAction() { if (!this.id) { return this.fail('params error'); } let ids = this.id.toString().split(','); let rows = await this.modelInstance.where({id: ['in', ids]}).delete(); return this.success({affectedRows: rows}); } }
{ "content_hash": "d297c657434c3c640834df1752a4bd77", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 104, "avg_line_length": 25.619565217391305, "alnum_prop": 0.5536699193890539, "repo_name": "songguangyu/firekylin", "id": "12f0024181ffa1c6d452434c0f31aa59c8f675e2", "size": "2357", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/admin/controller/post.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "296257" }, { "name": "HTML", "bytes": "10576" }, { "name": "JavaScript", "bytes": "118262" } ], "symlink_target": "" }
import { PerformAction } from '@redux-devtools/core'; import { Action } from 'redux'; import { UPDATE_STATE, SET_STATE, LIFTED_ACTION, SELECT_INSTANCE, REMOVE_INSTANCE, TOGGLE_PERSIST, TOGGLE_SYNC, } from '../constants/actionTypes'; import { DISCONNECTED } from '../constants/socketActionTypes'; import parseJSON from '../utils/parseJSON'; import { recompute } from '../utils/updateState'; import { ActionCreator, LiftedActionDispatchAction, Request, StoreAction, } from '../actions'; export interface Features { lock?: boolean; export?: string | boolean; import?: string | boolean; persist?: boolean; pause?: boolean; reorder?: boolean; jump?: boolean; skip?: boolean; dispatch?: boolean; sync?: boolean; test?: boolean; } export interface Options { name?: string; connectionId?: string; explicitLib?: string; lib?: string; actionCreators?: ActionCreator[]; features: Features; serialize?: boolean; } export interface State { actionsById: { [actionId: number]: PerformAction<Action<unknown>> }; computedStates: { state: unknown; error?: string }[]; currentStateIndex: number; nextActionId: number; skippedActionIds: number[]; stagedActionIds: number[]; committedState?: unknown; isLocked?: boolean; isPaused?: boolean; } export interface InstancesState { selected: string | null; current: string; sync: boolean; connections: { [id: string]: string[] }; options: { [id: string]: Options }; states: { [id: string]: State }; persisted?: boolean; } export const initialState: InstancesState = { selected: null, current: 'default', sync: false, connections: {}, options: { default: { features: {} } }, states: { default: { actionsById: {}, computedStates: [], currentStateIndex: -1, nextActionId: 0, skippedActionIds: [], stagedActionIds: [], }, }, }; function updateState( state: { [id: string]: State }, request: Request, id: string, serialize: boolean | undefined ) { let payload: State = request.payload as State; const actionsById = request.actionsById; if (actionsById) { payload = { // eslint-disable-next-line @typescript-eslint/ban-types ...payload, actionsById: parseJSON(actionsById, serialize), computedStates: parseJSON(request.computedStates, serialize), } as State; if (request.type === 'STATE' && request.committedState) { payload.committedState = payload.computedStates[0].state; } } else { payload = parseJSON(payload as unknown as string, serialize) as State; } let newState; const liftedState = state[id] || state.default; const action = ((request.action && parseJSON(request.action, serialize)) || {}) as PerformAction<Action<unknown>>; switch (request.type) { case 'INIT': newState = recompute(state.default, payload, { action: { type: '@@INIT' }, timestamp: (action as { timestamp?: number }).timestamp || Date.now(), }); break; case 'ACTION': { const isExcess = request.isExcess; const nextActionId = request.nextActionId || liftedState.nextActionId + 1; const maxAge = request.maxAge; if (Array.isArray(action)) { // Batched actions newState = liftedState; for (let i = 0; i < action.length; i++) { newState = recompute( newState, request.batched ? payload : (payload as unknown as State[])[i], action[i], newState.nextActionId + 1, maxAge, isExcess ); } } else { newState = recompute( liftedState, payload, action, nextActionId, maxAge, isExcess ); } break; } case 'STATE': newState = payload; if (newState.computedStates.length <= newState.currentStateIndex) { newState.currentStateIndex = newState.computedStates.length - 1; } break; case 'PARTIAL_STATE': { const maxAge = request.maxAge; const nextActionId = payload.nextActionId; const stagedActionIds = payload.stagedActionIds; let computedStates = payload.computedStates; let oldActionsById; let oldComputedStates; let committedState; if (nextActionId > maxAge) { const oldStagedActionIds = liftedState.stagedActionIds; const excess = oldStagedActionIds.indexOf(stagedActionIds[1]); let key; if (excess > 0) { oldComputedStates = liftedState.computedStates.slice(excess - 1); oldActionsById = { ...liftedState.actionsById }; for (let i = 1; i < excess; i++) { key = oldStagedActionIds[i]; if (key) delete oldActionsById[key]; } committedState = computedStates[0].state; } else { oldActionsById = liftedState.actionsById; oldComputedStates = liftedState.computedStates; committedState = liftedState.committedState; } } else { oldActionsById = liftedState.actionsById; oldComputedStates = liftedState.computedStates; committedState = liftedState.committedState; } computedStates = [...oldComputedStates, ...computedStates]; const statesCount = computedStates.length; let currentStateIndex = payload.currentStateIndex; if (statesCount <= currentStateIndex) currentStateIndex = statesCount - 1; newState = { ...liftedState, actionsById: { ...oldActionsById, ...payload.actionsById }, computedStates, currentStateIndex, nextActionId, stagedActionIds, committedState, }; break; } case 'LIFTED': newState = liftedState; break; default: return state; } if (request.liftedState) newState = { ...newState, ...request.liftedState }; return { ...state, [id]: newState }; } export function dispatchAction( state: InstancesState, { action }: LiftedActionDispatchAction ) { if (action.type === 'JUMP_TO_STATE' || action.type === 'JUMP_TO_ACTION') { const id = state.selected || state.current; const liftedState = state.states[id]; let currentStateIndex = action.index; if (typeof currentStateIndex === 'undefined' && action.actionId) { currentStateIndex = liftedState.stagedActionIds.indexOf(action.actionId); } return { ...state, states: { ...state.states, [id]: { ...liftedState, currentStateIndex }, }, }; } return state; } function removeState(state: InstancesState, connectionId: string) { const instanceIds = state.connections[connectionId]; if (!instanceIds) return state; const connections = { ...state.connections }; const options = { ...state.options }; const states = { ...state.states }; let selected = state.selected; let current = state.current; let sync = state.sync; delete connections[connectionId]; instanceIds.forEach((id) => { if (id === selected) { selected = null; sync = false; } if (id === current) { const inst = Object.keys(connections)[0]; if (inst) current = connections[inst][0]; else current = 'default'; } delete options[id]; delete states[id]; }); return { selected, current, sync, connections, options, states, }; } function init( { type, action, name, libConfig = {} }: Request, connectionId: string, current: string ): Options { let lib; let actionCreators; let creators = libConfig.actionCreators || action; if (typeof creators === 'string') creators = JSON.parse(creators); if (Array.isArray(creators)) actionCreators = creators; if (type === 'STATE') lib = 'redux'; return { name: libConfig.name || name || current, connectionId, explicitLib: libConfig.type, lib, actionCreators, features: libConfig.features ? libConfig.features : { lock: lib === 'redux', export: libConfig.type === 'redux' ? 'custom' : true, import: 'custom', persist: true, pause: true, reorder: true, jump: true, skip: true, dispatch: true, sync: true, test: true, }, serialize: libConfig.serialize, }; } export default function instances( state = initialState, action: StoreAction ): InstancesState { switch (action.type) { case UPDATE_STATE: { const { request } = action; if (!request) return state; const connectionId = action.id || request.id; const current = request.instanceId || connectionId; let connections = state.connections; let options = state.options; if (typeof state.options[current] === 'undefined') { connections = { ...state.connections, [connectionId]: [...(connections[connectionId] || []), current], }; options = { ...options, [current]: init(request, connectionId, current), }; } return { ...state, current, connections, options, states: updateState( state.states, request, current, options[current].serialize ), }; } case SET_STATE: return { ...state, states: { ...state.states, [getActiveInstance(state)]: action.newState, }, }; case TOGGLE_PERSIST: return { ...state, persisted: !state.persisted }; case TOGGLE_SYNC: return { ...state, sync: !state.sync }; case SELECT_INSTANCE: return { ...state, selected: action.selected, sync: false }; case REMOVE_INSTANCE: return removeState(state, action.id); case LIFTED_ACTION: { if (action.message === 'DISPATCH') return dispatchAction(state, action); if (action.message === 'IMPORT') { const id = state.selected || state.current; if (state.options[id].features.import === true) { return { ...state, states: { ...state.states, [id]: parseJSON(action.state) as State, }, }; } } return state; } case DISCONNECTED: return initialState; default: return state; } } export const getActiveInstance = (instances: InstancesState) => instances.selected || instances.current;
{ "content_hash": "ae77078d41d0f05fe189811a395a7256", "timestamp": "", "source": "github", "line_count": 382, "max_line_length": 80, "avg_line_length": 27.515706806282722, "alnum_prop": 0.6058414993816003, "repo_name": "gaearon/redux-devtools", "id": "9b2aa01e03a000a47281aa5e019a96a3ffaa9c9a", "size": "10511", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/redux-devtools-app/src/reducers/instances.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "7194" } ], "symlink_target": "" }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet.h" #include "base58.h" #include "coincontrol.h" #include "kernel.h" #include "net.h" #include "timedata.h" #include "txdb.h" #include "ui_interface.h" #include "walletdb.h" #include "crypter.h" #include "key.h" #include "spork.h" #include "darksend.h" #include "instantx.h" #include "masternode.h" #include "chainparams.h" #include "smessage.h" #include <boost/algorithm/string/replace.hpp> #include <boost/range/algorithm.hpp> #include <boost/numeric/ublas/matrix.hpp> using namespace std; // Settings int64_t nTransactionFee = MIN_TX_FEE; int64_t nReserveBalance = 0; int64_t nMinimumInputValue = 0; static unsigned int GetStakeSplitAge() { return 9 * 24 * 60 * 60; } static int64_t GetStakeCombineThreshold() { return 100 * COIN; } int64_t gcd(int64_t n,int64_t m) { return m == 0 ? n : gcd(m, n % m); } static uint64_t CoinWeightCost(const COutput &out) { int64_t nTimeWeight = (int64_t)GetTime() - (int64_t)out.tx->nTime; CBigNum bnCoinDayWeight = CBigNum(out.tx->vout[out.i].nValue) * nTimeWeight / (24 * 60 * 60); return bnCoinDayWeight.getuint64(); } ////////////////////////////////////////////////////////////////////////////// // // mapWallet // struct CompareValueOnly { bool operator()(const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t1, const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t2) const { return t1.first < t2.first; } }; CPubKey CWallet::GenerateNewKey() { AssertLockHeld(cs_wallet); // mapKeyMetadata bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets RandAddSeedPerfmon(); CKey secret; secret.MakeNewKey(fCompressed); // Compressed public keys were introduced in version 0.6.0 if (fCompressed) SetMinVersion(FEATURE_COMPRPUBKEY); CPubKey pubkey = secret.GetPubKey(); // Create new metadata int64_t nCreationTime = GetTime(); mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime); if (!nTimeFirstKey || nCreationTime < nTimeFirstKey) nTimeFirstKey = nCreationTime; if (!AddKeyPubKey(secret, pubkey)) throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed"); return pubkey; } bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey) { AssertLockHeld(cs_wallet); // mapKeyMetadata if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) return false; if (!fFileBacked) return true; if (!IsCrypted()) { return CWalletDB(strWalletFile).WriteKey(pubkey, secret.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]); } return true; } bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret) { if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret)) return false; if (!fFileBacked) return true; { LOCK(cs_wallet); if (pwalletdbEncryption) return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]); else return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]); } return false; } bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta) { AssertLockHeld(cs_wallet); // mapKeyMetadata if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey)) nTimeFirstKey = meta.nCreateTime; mapKeyMetadata[pubkey.GetID()] = meta; return true; } bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); } bool CWallet::AddCScript(const CScript& redeemScript) { if (!CCryptoKeyStore::AddCScript(redeemScript)) return false; if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript); } // optional setting to unlock wallet for staking only // serves to disable the trivial sendmoney when OS account compromised // provides no real security bool fWalletUnlockStakingOnly = false; bool CWallet::LoadCScript(const CScript& redeemScript) { /* A sanity check was added in pull #3843 to avoid adding redeemScripts * that never can be redeemed. However, old wallets may still contain * these. Do not add them to the wallet and warn. */ if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE) { std::string strAddr = CBitcoinAddress(redeemScript.GetID()).ToString(); LogPrintf("%s: Warning: This wallet contains a redeemScript of size %u which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n", __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr); return true; } return CCryptoKeyStore::AddCScript(redeemScript); } bool CWallet::Lock() { if (IsLocked()) return true; if (fDebug) printf("Locking wallet.\n"); { LOCK(cs_wallet); CWalletDB wdb(strWalletFile); // -- load encrypted spend_secret of stealth addresses CStealthAddress sxAddrTemp; std::set<CStealthAddress>::iterator it; for (it = stealthAddresses.begin(); it != stealthAddresses.end(); ++it) { if (it->scan_secret.size() < 32) continue; // stealth address is not owned // -- CStealthAddress are only sorted on spend_pubkey CStealthAddress &sxAddr = const_cast<CStealthAddress&>(*it); if (fDebug) printf("Recrypting stealth key %s\n", sxAddr.Encoded().c_str()); sxAddrTemp.scan_pubkey = sxAddr.scan_pubkey; if (!wdb.ReadStealthAddress(sxAddrTemp)) { printf("Error: Failed to read stealth key from db %s\n", sxAddr.Encoded().c_str()); continue; } sxAddr.spend_secret = sxAddrTemp.spend_secret; }; } return LockKeyStore(); }; bool CWallet::Unlock(const SecureString& strWalletPassphrase, bool anonymizeOnly) { SecureString strWalletPassphraseFinal; if(!IsLocked()) { fWalletUnlockAnonymizeOnly = anonymizeOnly; return true; } strWalletPassphraseFinal = strWalletPassphrase; CCrypter crypter; CKeyingMaterial vMasterKey; { LOCK(cs_wallet); BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if(!crypter.SetKeyFromPassphrase(strWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) return false; if (!CCryptoKeyStore::Unlock(vMasterKey)) return false; break; } fWalletUnlockAnonymizeOnly = anonymizeOnly; UnlockStealthAddresses(vMasterKey); return true; } return false; } bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase) { bool fWasLocked = IsLocked(); SecureString strOldWalletPassphraseFinal; strOldWalletPassphraseFinal = strOldWalletPassphrase; { LOCK(cs_wallet); Lock(); CCrypter crypter; CKeyingMaterial vMasterKey; BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if(!crypter.SetKeyFromPassphrase(strOldWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) return false; if (CCryptoKeyStore::Unlock(vMasterKey) && UnlockStealthAddresses(vMasterKey)) { int64_t nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))); nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; if (pMasterKey.second.nDeriveIterations < 25000) pMasterKey.second.nDeriveIterations = 25000; LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations); if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey)) return false; CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second); if (fWasLocked) Lock(); return true; } } } return false; } void CWallet::SetBestChain(const CBlockLocator& loc) { CWalletDB walletdb(strWalletFile); walletdb.WriteBestBlock(loc); } bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit) { LOCK(cs_wallet); // nWalletVersion if (nWalletVersion >= nVersion) return true; // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way if (fExplicit && nVersion > nWalletMaxVersion) nVersion = FEATURE_LATEST; nWalletVersion = nVersion; if (nVersion > nWalletMaxVersion) nWalletMaxVersion = nVersion; if (fFileBacked) { CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile); if (nWalletVersion > 40000) pwalletdb->WriteMinVersion(nWalletVersion); if (!pwalletdbIn) delete pwalletdb; } return true; } bool CWallet::SetMaxVersion(int nVersion) { LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion // cannot downgrade below current version if (nWalletVersion > nVersion) return false; nWalletMaxVersion = nVersion; return true; } bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase) { if (IsCrypted()) return false; CKeyingMaterial vMasterKey; RandAddSeedPerfmon(); vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE); RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE); CMasterKey kMasterKey(nDerivationMethodIndex); RandAddSeedPerfmon(); kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE); RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE); CCrypter crypter; int64_t nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime)); nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; if (kMasterKey.nDeriveIterations < 25000) kMasterKey.nDeriveIterations = 25000; LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations); if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod)) return false; if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey)) return false; { LOCK(cs_wallet); mapMasterKeys[++nMasterKeyMaxID] = kMasterKey; if (fFileBacked) { pwalletdbEncryption = new CWalletDB(strWalletFile); if (!pwalletdbEncryption->TxnBegin()) return false; pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey); } if (!EncryptKeys(vMasterKey)) { if (fFileBacked) pwalletdbEncryption->TxnAbort(); exit(1); //We now probably have half of our keys encrypted in memory, and half not...die and let the user reload their unencrypted wallet. } std::set<CStealthAddress>::iterator it; for (it = stealthAddresses.begin(); it != stealthAddresses.end(); ++it) { if (it->scan_secret.size() < 32) continue; // stealth address is not owned // -- CStealthAddress is only sorted on spend_pubkey CStealthAddress &sxAddr = const_cast<CStealthAddress&>(*it); if (fDebug) printf("Encrypting stealth key %s\n", sxAddr.Encoded().c_str()); std::vector<unsigned char> vchCryptedSecret; CSecret vchSecret; vchSecret.resize(32); memcpy(&vchSecret[0], &sxAddr.spend_secret[0], 32); uint256 iv = Hash(sxAddr.spend_pubkey.begin(), sxAddr.spend_pubkey.end()); if (!EncryptSecret(vMasterKey, vchSecret, iv, vchCryptedSecret)) { printf("Error: Failed encrypting stealth key %s\n", sxAddr.Encoded().c_str()); continue; }; sxAddr.spend_secret = vchCryptedSecret; pwalletdbEncryption->WriteStealthAddress(sxAddr); }; // Encryption was introduced in version 0.4.0 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true); if (fFileBacked) { if (!pwalletdbEncryption->TxnCommit()) exit(1); //We now have keys encrypted in memory, but no on disk...die to avoid confusion and let the user reload their unencrypted wallet. delete pwalletdbEncryption; pwalletdbEncryption = NULL; } Lock(); Unlock(strWalletPassphrase); NewKeyPool(); Lock(); // Need to completely rewrite the wallet file; if we don't, bdb might keep // bits of the unencrypted private key in slack space in the database file. CDB::Rewrite(strWalletFile); } NotifyStatusChanged(this); return true; } int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb) { AssertLockHeld(cs_wallet); // nOrderPosNext int64_t nRet = nOrderPosNext++; if (pwalletdb) { pwalletdb->WriteOrderPosNext(nOrderPosNext); } else { CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext); } return nRet; } CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount) { AssertLockHeld(cs_wallet); // mapWallet CWalletDB walletdb(strWalletFile); // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap. TxItems txOrdered; // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry // would make this much faster for applications that do this a lot. for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { CWalletTx* wtx = &((*it).second); txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0))); } acentries.clear(); walletdb.ListAccountCreditDebit(strAccount, acentries); BOOST_FOREACH(CAccountingEntry& entry, acentries) { txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry))); } return txOrdered; } void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock) { // Anytime a signature is successfully verified, it's proof the outpoint is spent. // Update the wallet spent flag if it doesn't know due to wallet.dat being // restored from backup or the user making copies of wallet.dat. { LOCK(cs_wallet); BOOST_FOREACH(const CTxIn& txin, tx.vin) { map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { CWalletTx& wtx = (*mi).second; if (txin.prevout.n >= wtx.vout.size()) LogPrintf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString()); else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n])) { LogPrintf("WalletUpdateSpent found spent coin %s BC %s\n", FormatMoney(wtx.GetCredit()), wtx.GetHash().ToString()); wtx.MarkSpent(txin.prevout.n); wtx.WriteToDisk(); NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED); } } } if (fBlock) { uint256 hash = tx.GetHash(); map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash); CWalletTx& wtx = (*mi).second; BOOST_FOREACH(const CTxOut& txout, tx.vout) { if (IsMine(txout)) { wtx.MarkUnspent(&txout - &tx.vout[0]); wtx.WriteToDisk(); NotifyTransactionChanged(this, hash, CT_UPDATED); } } } } } void CWallet::MarkDirty() { { LOCK(cs_wallet); BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) item.second.MarkDirty(); } } bool CWallet::AddToWallet(const CWalletTx& wtxIn) { uint256 hash = wtxIn.GetHash(); { LOCK(cs_wallet); // Inserts only if not already there, returns tx inserted or tx found pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn)); CWalletTx& wtx = (*ret.first).second; wtx.BindWallet(this); bool fInsertedNew = ret.second; if (fInsertedNew) { wtx.nTimeReceived = GetAdjustedTime(); wtx.nOrderPos = IncOrderPosNext(); wtx.nTimeSmart = wtx.nTimeReceived; if (wtxIn.hashBlock != 0) { if (mapBlockIndex.count(wtxIn.hashBlock)) { unsigned int latestNow = wtx.nTimeReceived; unsigned int latestEntry = 0; { // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future int64_t latestTolerated = latestNow + 300; std::list<CAccountingEntry> acentries; TxItems txOrdered = OrderedTxItems(acentries); for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) { CWalletTx *const pwtx = (*it).second.first; if (pwtx == &wtx) continue; CAccountingEntry *const pacentry = (*it).second.second; int64_t nSmartTime; if (pwtx) { nSmartTime = pwtx->nTimeSmart; if (!nSmartTime) nSmartTime = pwtx->nTimeReceived; } else nSmartTime = pacentry->nTime; if (nSmartTime <= latestTolerated) { latestEntry = nSmartTime; if (nSmartTime > latestNow) latestNow = nSmartTime; break; } } } unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime; wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow)); } else LogPrintf("AddToWallet() : found %s in block %s not in index\n", wtxIn.GetHash().ToString(), wtxIn.hashBlock.ToString()); } } bool fUpdated = false; if (!fInsertedNew) { // Merge if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock) { wtx.hashBlock = wtxIn.hashBlock; fUpdated = true; } if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex)) { wtx.vMerkleBranch = wtxIn.vMerkleBranch; wtx.nIndex = wtxIn.nIndex; fUpdated = true; } if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe) { wtx.fFromMe = wtxIn.fFromMe; fUpdated = true; } fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent); } //// debug print LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : "")); // Write to disk if (fInsertedNew || fUpdated) if (!wtx.WriteToDisk()) return false; if (!fHaveGUI) { // If default receiving address gets used, replace it with a new one if (vchDefaultKey.IsValid()) { CScript scriptDefaultKey; scriptDefaultKey.SetDestination(vchDefaultKey.GetID()); BOOST_FOREACH(const CTxOut& txout, wtx.vout) { if (txout.scriptPubKey == scriptDefaultKey) { CPubKey newDefaultKey; if (GetKeyFromPool(newDefaultKey)) { SetDefaultKey(newDefaultKey); SetAddressBookName(vchDefaultKey.GetID(), ""); } } } } } // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0)); // Notify UI of new or updated transaction NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED); // notify an external script when a wallet transaction comes in or is updated std::string strCmd = GetArg("-walletnotify", ""); if ( !strCmd.empty()) { boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex()); boost::thread t(runCommand, strCmd); // thread runs free } } return true; } // Add a transaction to the wallet, or update it. // pblock is optional, but should be provided if the transaction is known to be in a block. // If fUpdate is true, existing transactions will be updated. bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate) { uint256 hash = tx.GetHash(); { LOCK(cs_wallet); bool fExisted = mapWallet.count(hash); if (fExisted && !fUpdate) return false; mapValue_t mapNarr; FindStealthTransactions(tx, mapNarr); if (fExisted || IsMine(tx) || IsFromMe(tx)) { CWalletTx wtx(this,tx); if (!mapNarr.empty()) wtx.mapValue.insert(mapNarr.begin(), mapNarr.end()); // Get merkle branch if transaction was found in a block if (pblock) wtx.SetMerkleBranch(pblock); return AddToWallet(wtx); } else WalletUpdateSpent(tx); } return false; } void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock, bool fConnect) { if (!fConnect) { // wallets need to refund inputs when disconnecting coinstake if (tx.IsCoinStake()) { if (IsFromMe(tx)) DisableTransaction(tx); } return; } AddToWalletIfInvolvingMe(tx, pblock, true); } void CWallet::EraseFromWallet(const uint256 &hash) { if (!fFileBacked) return; { LOCK(cs_wallet); if (mapWallet.erase(hash)) CWalletDB(strWalletFile).EraseTx(hash); } return; } bool CWallet::IsMine(const CTxIn &txin) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) if (IsMine(prev.vout[txin.prevout.n])) return true; } } return false; } int64_t CWallet::GetDebit(const CTxIn &txin) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) if (IsMine(prev.vout[txin.prevout.n])) return prev.vout[txin.prevout.n].nValue; } } return 0; } bool CWallet::IsDenominated(const CTxIn &txin) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) return IsDenominatedAmount(prev.vout[txin.prevout.n].nValue); } } return false; } bool CWallet::IsDenominatedAmount(int64_t nInputAmount) const { BOOST_FOREACH(int64_t d, darkSendDenominations) if(nInputAmount == d) return true; return false; } bool CWallet::IsChange(const CTxOut& txout) const { CTxDestination address; // TODO: fix handling of 'change' outputs. The assumption is that any // payment to a TX_PUBKEYHASH that is mine but isn't in the address book // is change. That assumption is likely to break when we implement multisignature // wallets that return change back into a multi-signature-protected address; // a better way of identifying which outputs are 'the send' and which are // 'the change' will need to be implemented (maybe extend CWalletTx to remember // which output, if any, was change). if (ExtractDestination(txout.scriptPubKey, address) && ::IsMine(*this, address)) { LOCK(cs_wallet); if (!mapAddressBook.count(address)) return true; } return false; } int64_t CWalletTx::GetTxTime() const { int64_t n = nTimeSmart; return n ? n : nTimeReceived; } int CWalletTx::GetRequestCount() const { // Returns -1 if it wasn't being tracked int nRequests = -1; { LOCK(pwallet->cs_wallet); if (IsCoinBase() || IsCoinStake()) { // Generated block if (hashBlock != 0) { map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; } } else { // Did anyone request this transaction? map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash()); if (mi != pwallet->mapRequestCount.end()) { nRequests = (*mi).second; // How about the block it's in? if (nRequests == 0 && hashBlock != 0) { map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; else nRequests = 1; // If it's in someone else's block it must have got out } } } } return nRequests; } void CWalletTx::GetAmounts(list<pair<CTxDestination, int64_t> >& listReceived, list<pair<CTxDestination, int64_t> >& listSent, int64_t& nFee, string& strSentAccount) const { LOCK(pwallet->cs_wallet); nFee = 0; listReceived.clear(); listSent.clear(); strSentAccount = strFromAccount; // Compute fee: int64_t nDebit = GetDebit(); if (nDebit > 0) // debit>0 means we signed/sent this transaction { int64_t nValueOut = GetValueOut(); nFee = nDebit - nValueOut; } // Sent/received. BOOST_FOREACH(const CTxOut& txout, vout) { // Skip special stake out if (txout.scriptPubKey.empty()) continue; bool fIsMine; // Only need to handle txouts if AT LEAST one of these is true: // 1) they debit from us (sent) // 2) the output is to us (received) if (nDebit > 0) { // Don't report 'change' txouts // GRAVITONNOTE: CoinControl possible fix related... with HD wallet we need to report change? //if (pwallet->IsChange(txout)) // continue; fIsMine = pwallet->IsMine(txout); } else if (!(fIsMine = pwallet->IsMine(txout))) continue; // In either case, we need to get the destination address CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address)) { LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n", this->GetHash().ToString()); address = CNoDestination(); } // If we are debited by the transaction, add the output as a "sent" entry if (nDebit > 0) listSent.push_back(make_pair(address, txout.nValue)); // If we are receiving the output, add it as a "received" entry if (fIsMine) listReceived.push_back(make_pair(address, txout.nValue)); } } void CWalletTx::GetAccountAmounts(const string& strAccount, int64_t& nReceived, int64_t& nSent, int64_t& nFee) const { LOCK(pwallet->cs_wallet); nReceived = nSent = nFee = 0; int64_t allFee; string strSentAccount; list<pair<CTxDestination, int64_t> > listReceived; list<pair<CTxDestination, int64_t> > listSent; GetAmounts(listReceived, listSent, allFee, strSentAccount); if (strAccount == strSentAccount) { BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& s, listSent) nSent += s.second; nFee = allFee; } { BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listReceived) { if (pwallet->mapAddressBook.count(r.first)) { map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first); if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount) nReceived += r.second; } else if (strAccount.empty()) { nReceived += r.second; } } } } void CWalletTx::AddSupportingTransactions(CTxDB& txdb) { vtxPrev.clear(); const int COPY_DEPTH = 3; if (SetMerkleBranch() < COPY_DEPTH) { vector<uint256> vWorkQueue; BOOST_FOREACH(const CTxIn& txin, vin) vWorkQueue.push_back(txin.prevout.hash); // This critsect is OK because txdb is already open { LOCK(pwallet->cs_wallet); map<uint256, const CMerkleTx*> mapWalletPrev; set<uint256> setAlreadyDone; for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hash = vWorkQueue[i]; if (setAlreadyDone.count(hash)) continue; setAlreadyDone.insert(hash); CMerkleTx tx; map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash); if (mi != pwallet->mapWallet.end()) { tx = (*mi).second; BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev) mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev; } else if (mapWalletPrev.count(hash)) { tx = *mapWalletPrev[hash]; } else if (txdb.ReadDiskTx(hash, tx)) { ; } else { LogPrintf("ERROR: AddSupportingTransactions() : unsupported transaction\n"); continue; } int nDepth = tx.SetMerkleBranch(); vtxPrev.push_back(tx); if (nDepth < COPY_DEPTH) { BOOST_FOREACH(const CTxIn& txin, tx.vin) vWorkQueue.push_back(txin.prevout.hash); } } } } reverse(vtxPrev.begin(), vtxPrev.end()); } bool CWalletTx::WriteToDisk() { return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this); } // Scan the block chain (starting in pindexStart) for transactions // from or to us. If fUpdate is true, found transactions that already // exist in the wallet will be updated. int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) { int ret = 0; CBlockIndex* pindex = pindexStart; { LOCK2(cs_main, cs_wallet); while (pindex) { // no need to read and scan block, if block was created before // our wallet birthday (as adjusted for block time variability) if (nTimeFirstKey && (pindex->nTime < (nTimeFirstKey - 7200))) { pindex = pindex->pnext; continue; } CBlock block; block.ReadFromDisk(pindex, true); BOOST_FOREACH(CTransaction& tx, block.vtx) { if (AddToWalletIfInvolvingMe(tx, &block, fUpdate)) ret++; } pindex = pindex->pnext; } } return ret; } void CWallet::ReacceptWalletTransactions() { CTxDB txdb("r"); bool fRepeat = true; while (fRepeat) { LOCK2(cs_main, cs_wallet); fRepeat = false; vector<CDiskTxPos> vMissingTx; BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) { CWalletTx& wtx = item.second; if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1))) continue; CTxIndex txindex; bool fUpdated = false; if (txdb.ReadTxIndex(wtx.GetHash(), txindex)) { // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat if (txindex.vSpent.size() != wtx.vout.size()) { LogPrintf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %u != wtx.vout.size() %u\n", txindex.vSpent.size(), wtx.vout.size()); continue; } for (unsigned int i = 0; i < txindex.vSpent.size(); i++) { if (wtx.IsSpent(i)) continue; if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i])) { wtx.MarkSpent(i); fUpdated = true; vMissingTx.push_back(txindex.vSpent[i]); } } if (fUpdated) { LogPrintf("ReacceptWalletTransactions found spent coin %s BC %s\n", FormatMoney(wtx.GetCredit()), wtx.GetHash().ToString()); wtx.MarkDirty(); wtx.WriteToDisk(); } } else { // Re-accept any txes of ours that aren't already in a block if (!(wtx.IsCoinBase() || wtx.IsCoinStake())) wtx.AcceptWalletTransaction(txdb); } } if (!vMissingTx.empty()) { // TODO: optimize this to scan just part of the block chain? if (ScanForWalletTransactions(pindexGenesisBlock)) fRepeat = true; // Found missing transactions: re-do re-accept. } } } void CWalletTx::RelayWalletTransaction(CTxDB& txdb) { BOOST_FOREACH(const CMerkleTx& tx, vtxPrev) { if (!(tx.IsCoinBase() || tx.IsCoinStake())) { uint256 hash = tx.GetHash(); if (!txdb.ContainsTx(hash)) RelayTransaction((CTransaction)tx, hash); } } if (!(IsCoinBase() || IsCoinStake())) { uint256 hash = GetHash(); if (!txdb.ContainsTx(hash)) { LogPrintf("Relaying wtx %s\n", hash.ToString()); RelayTransaction((CTransaction)*this, hash); } } } void CWalletTx::RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); } void CWallet::ResendWalletTransactions(bool fForce) { if (!fForce) { // Do this infrequently and randomly to avoid giving away // that these are our transactions. static int64_t nNextTime; if (GetTime() < nNextTime) return; bool fFirst = (nNextTime == 0); nNextTime = GetTime() + GetRand(30 * 60); if (fFirst) return; // Only do it if there's been a new block since last time static int64_t nLastTime; if (nTimeBestReceived < nLastTime) return; nLastTime = GetTime(); } // Rebroadcast any of our txes that aren't in a block yet LogPrintf("ResendWalletTransactions()\n"); CTxDB txdb("r"); { LOCK(cs_wallet); // Sort them in chronological order multimap<unsigned int, CWalletTx*> mapSorted; BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) { CWalletTx& wtx = item.second; // Don't rebroadcast until it's had plenty of time that // it should have gotten in already by now. if (fForce || nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60) mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx)); } BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted) { CWalletTx& wtx = *item.second; if (wtx.CheckTransaction()) wtx.RelayWalletTransaction(txdb); else LogPrintf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString()); } } } ////////////////////////////////////////////////////////////////////////////// // // Actions // int64_t CWallet::GetBalance() const { int64_t nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) nTotal += pcoin->GetAvailableCredit(); } } return nTotal; } int64_t CWallet::GetBalanceNoLocks() const { int64_t nTotal = 0; { for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) nTotal += pcoin->GetAvailableCredit(); } } return nTotal; } CAmount CWallet::GetAnonymizedBalance() const { int64_t nTotal = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) { int nDepth = pcoin->GetDepthInMainChain(); for (unsigned int i = 0; i < pcoin->vout.size(); i++) { //isminetype mine = IsMine(pcoin->vout[i]); bool mine = IsMine(pcoin->vout[i]); //COutput out = COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO); COutput out = COutput(pcoin, i, nDepth, mine); CTxIn vin = CTxIn(out.tx->GetHash(), out.i); //if(IsSpent(out.tx->GetHash(), i) || !IsMine(pcoin->vout[i]) || !IsDenominated(vin)) continue; if(pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]) || !IsDenominated(vin)) continue; int rounds = GetInputDarksendRounds(vin); if(rounds >= nDarksendRounds){ nTotal += pcoin->vout[i].nValue; } } } } } return nTotal; } double CWallet::GetAverageAnonymizedRounds() const { double fTotal = 0; double fCount = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) { int nDepth = pcoin->GetDepthInMainChain(); for (unsigned int i = 0; i < pcoin->vout.size(); i++) { //isminetype mine = IsMine(pcoin->vout[i]); bool mine = IsMine(pcoin->vout[i]); //COutput out = COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO); COutput out = COutput(pcoin, i, nDepth, mine); CTxIn vin = CTxIn(out.tx->GetHash(), out.i); //if(IsSpent(out.tx->GetHash(), i) || !IsMine(pcoin->vout[i]) || !IsDenominated(vin)) continue; if(pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]) || !IsDenominated(vin)) continue; int rounds = GetInputDarksendRounds(vin); fTotal += (float)rounds; fCount += 1; } } } } if(fCount == 0) return 0; return fTotal/fCount; } CAmount CWallet::GetNormalizedAnonymizedBalance() const { int64_t nTotal = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) { int nDepth = pcoin->GetDepthInMainChain(); for (unsigned int i = 0; i < pcoin->vout.size(); i++) { //isminetype mine = IsMine(pcoin->vout[i]); bool mine = IsMine(pcoin->vout[i]); //COutput out = COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO); COutput out = COutput(pcoin, i, nDepth, mine); CTxIn vin = CTxIn(out.tx->GetHash(), out.i); //if(IsSpent(out.tx->GetHash(), i) || !IsMine(pcoin->vout[i]) || !IsDenominated(vin)) continue; if(pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]) || !IsDenominated(vin)) continue; int rounds = GetInputDarksendRounds(vin); nTotal += pcoin->vout[i].nValue * rounds / nDarksendRounds; } } } } return nTotal; } CAmount CWallet::GetDenominatedBalance(bool onlyDenom, bool onlyUnconfirmed) const { int64_t nTotal = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; int nDepth = pcoin->GetDepthInMainChain(); // skip conflicted if(nDepth < 0) continue; bool unconfirmed = (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && nDepth == 0)); if(onlyUnconfirmed != unconfirmed) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { //isminetype mine = IsMine(pcoin->vout[i]); //bool mine = IsMine(pcoin->vout[i]); //COutput out = COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO); //COutput out = COutput(pcoin, i, nDepth, mine); //if(IsSpent(out.tx->GetHash(), i)) continue; if(pcoin->IsSpent(i)) continue; if(!IsMine(pcoin->vout[i])) continue; if(onlyDenom != IsDenominatedAmount(pcoin->vout[i].nValue)) continue; nTotal += pcoin->vout[i].nValue; } } } return nTotal; } int64_t CWallet::GetUnconfirmedBalance() const { int64_t nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0)) nTotal += pcoin->GetAvailableCredit(); } } return nTotal; } int64_t CWallet::GetImmatureBalance() const { int64_t nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx& pcoin = (*it).second; if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.IsInMainChain()) nTotal += GetCredit(pcoin); } } return nTotal; } // populate vCoins with vector of spendable COutputs void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl, AvailableCoinsType coin_type, bool useIX) const { vCoins.clear(); { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!IsFinalTx(*pcoin)) continue; if (fOnlyConfirmed && !pcoin->IsTrusted()) continue; if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0) continue; if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0) continue; int nDepth = pcoin->GetDepthInMainChain(); if (nDepth <= 0) // GRAVITONNOTE: coincontrol fix / ignore 0 confirm continue; /* for (unsigned int i = 0; i < pcoin->vout.size(); i++) if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue && (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i))) vCoins.push_back(COutput(pcoin, i, nDepth));*/ // do not use IX for inputs that have less then 6 blockchain confirmations if (useIX && nDepth < 6) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { bool found = false; if(coin_type == ONLY_DENOMINATED) { //should make this a vector found = IsDenominatedAmount(pcoin->vout[i].nValue); } else if(coin_type == ONLY_NONDENOMINATED || coin_type == ONLY_NONDENOMINATED_NOTMN) { found = true; if (IsCollateralAmount(pcoin->vout[i].nValue)) continue; // do not use collateral amounts found = !IsDenominatedAmount(pcoin->vout[i].nValue); if(found && coin_type == ONLY_NONDENOMINATED_NOTMN) found = (pcoin->vout[i].nValue != 25000*COIN); // do not use MN funds } else { found = true; } if(!found) continue; //isminetype mine = IsMine(pcoin->vout[i]); bool mine = IsMine(pcoin->vout[i]); //if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO && // !IsLockedCoin((*it).first, i) && pcoin->vout[i].nValue > 0 && // (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i))) // vCoins.push_back(COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO)); //if (!(IsSpent(wtxid, i)) && mine && if (!(pcoin->IsSpent(i)) && mine && !IsLockedCoin((*it).first, i) && pcoin->vout[i].nValue > 0 && (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i))) vCoins.push_back(COutput(pcoin, i, nDepth, mine)); } } } } void CWallet::AvailableCoinsMN(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl, AvailableCoinsType coin_type, bool useIX) const { vCoins.clear(); { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!IsFinalTx(*pcoin)) continue; if (fOnlyConfirmed && !pcoin->IsTrusted()) continue; if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0) continue; if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0) continue; int nDepth = pcoin->GetDepthInMainChain(); if (nDepth <= 0) // GRAVITONNOTE: coincontrol fix / ignore 0 confirm continue; /* for (unsigned int i = 0; i < pcoin->vout.size(); i++) if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue && (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i))) vCoins.push_back(COutput(pcoin, i, nDepth));*/ // do not use IX for inputs that have less then 6 blockchain confirmations if (useIX && nDepth < 6) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { bool found = false; if(coin_type == ONLY_DENOMINATED) { //should make this a vector found = IsDenominatedAmount(pcoin->vout[i].nValue); } else if(coin_type == ONLY_NONDENOMINATED || coin_type == ONLY_NONDENOMINATED_NOTMN) { found = true; if (IsCollateralAmount(pcoin->vout[i].nValue)) continue; // do not use collateral amounts found = !IsDenominatedAmount(pcoin->vout[i].nValue); if(found && coin_type == ONLY_NONDENOMINATED_NOTMN) found = (pcoin->vout[i].nValue != 25000*COIN); // do not use MN funds } else { found = true; } if(!found) continue; //isminetype mine = IsMine(pcoin->vout[i]); bool mine = IsMine(pcoin->vout[i]); //if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO && // !IsLockedCoin((*it).first, i) && pcoin->vout[i].nValue > 0 && // (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i))) // vCoins.push_back(COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO)); //if (!(IsSpent(wtxid, i)) && mine && if (!(pcoin->IsSpent(i)) && !IsLockedCoin((*it).first, i) && pcoin->vout[i].nValue > 0 && (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i))) vCoins.push_back(COutput(pcoin, i, nDepth, mine)); } } } } void CWallet::AvailableCoinsForStaking(vector<COutput>& vCoins, unsigned int nSpendTime) const { vCoins.clear(); { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; // Filtering by tx timestamp instead of block timestamp may give false positives but never false negatives if (pcoin->nTime + nStakeMinAge > nSpendTime) continue; if (pcoin->GetBlocksToMaturity() > 0) continue; int nDepth = pcoin->GetDepthInMainChain(); if (nDepth < 1) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue) vCoins.push_back(COutput(pcoin, i, nDepth, true)); } } } static void ApproximateBestSubset(vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > >vValue, int64_t nTotalLower, int64_t nTargetValue, vector<char>& vfBest, int64_t& nBest, int iterations = 1000) { vector<char> vfIncluded; vfBest.assign(vValue.size(), true); nBest = nTotalLower; seed_insecure_rand(); for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++) { vfIncluded.assign(vValue.size(), false); int64_t nTotal = 0; bool fReachedTarget = false; for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++) { for (unsigned int i = 0; i < vValue.size(); i++) { //The solver here uses a randomized algorithm, //the randomness serves no real security purpose but is just //needed to prevent degenerate behavior and it is important //that the rng fast. We do not use a constant random sequence, //because there may be some privacy improvement by making //the selection random. if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i]) { nTotal += vValue[i].first; vfIncluded[i] = true; if (nTotal >= nTargetValue) { fReachedTarget = true; if (nTotal < nBest) { nBest = nTotal; vfBest = vfIncluded; } nTotal -= vValue[i].first; vfIncluded[i] = false; } } } } } } // ppcoin: total coins staked (non-spendable until maturity) int64_t CWallet::GetStake() const { int64_t nTotal = 0; LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0) nTotal += CWallet::GetCredit(*pcoin); } return nTotal; } int64_t CWallet::GetNewMint() const { int64_t nTotal = 0; LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0) nTotal += CWallet::GetCredit(*pcoin); } return nTotal; } struct LargerOrEqualThanThreshold { int64_t threshold; LargerOrEqualThanThreshold(int64_t threshold) : threshold(threshold) {} bool operator()(pair<pair<int64_t,int64_t>,pair<const CWalletTx*,unsigned int> > const &v) const { return v.first.first >= threshold; } }; bool CWallet::SelectCoinsMinConfByCoinAge(int64_t nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const { setCoinsRet.clear(); nValueRet = 0; vector<pair<COutput, uint64_t> > mCoins; BOOST_FOREACH(const COutput& out, vCoins) { mCoins.push_back(std::make_pair(out, CoinWeightCost(out))); } // List of values less than target pair<pair<int64_t,int64_t>, pair<const CWalletTx*,unsigned int> > coinLowestLarger; coinLowestLarger.first.second = std::numeric_limits<int64_t>::max(); coinLowestLarger.second.first = NULL; vector<pair<pair<int64_t,int64_t>,pair<const CWalletTx*,unsigned int> > > vValue; int64_t nTotalLower = 0; boost::sort(mCoins, boost::bind(&std::pair<COutput, uint64_t>::second, _1) < boost::bind(&std::pair<COutput, uint64_t>::second, _2)); BOOST_FOREACH(const PAIRTYPE(COutput, uint64_t)& output, mCoins) { const CWalletTx *pcoin = output.first.tx; if (output.first.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs)) continue; int i = output.first.i; // Follow the timestamp rules if (pcoin->nTime > nSpendTime) continue; int64_t n = pcoin->vout[i].nValue; pair<pair<int64_t,int64_t>,pair<const CWalletTx*,unsigned int> > coin = make_pair(make_pair(n,output.second),make_pair(pcoin, i)); if (n < nTargetValue + CENT) { vValue.push_back(coin); nTotalLower += n; } else if (output.second < (uint64_t)coinLowestLarger.first.second) { coinLowestLarger = coin; } } if (nTotalLower < nTargetValue) { if (coinLowestLarger.second.first == NULL) return false; setCoinsRet.insert(coinLowestLarger.second); nValueRet += coinLowestLarger.first.first; return true; } // Calculate dynamic programming matrix int64_t nTotalValue = vValue[0].first.first; int64_t nGCD = vValue[0].first.first; for (unsigned int i = 1; i < vValue.size(); ++i) { nGCD = gcd(vValue[i].first.first, nGCD); nTotalValue += vValue[i].first.first; } nGCD = gcd(nTargetValue, nGCD); int64_t denom = nGCD; const int64_t k = 25; const int64_t approx = int64_t(vValue.size() * (nTotalValue - nTargetValue)) / k; if (approx > nGCD) { denom = approx; // apply approximation } if (fDebug) cerr << "nGCD " << nGCD << " denom " << denom << " k " << k << endl; if (nTotalValue == nTargetValue) { for (unsigned int i = 0; i < vValue.size(); ++i) { setCoinsRet.insert(vValue[i].second); } nValueRet = nTotalValue; return true; } size_t nBeginBundles = vValue.size(); size_t nTotalCoinValues = vValue.size(); size_t nBeginCoinValues = 0; int64_t costsum = 0; vector<vector<pair<pair<int64_t,int64_t>,pair<const CWalletTx*,unsigned int> > >::iterator> vZeroValueBundles; if (denom != nGCD) { // All coin outputs that with zero value will always be added by the dynamic programming routine // So we collect them into bundles of value denom vector<pair<pair<int64_t,int64_t>,pair<const CWalletTx*,unsigned int> > >::iterator itZeroValue = std::stable_partition(vValue.begin(), vValue.end(), LargerOrEqualThanThreshold(denom)); vZeroValueBundles.push_back(itZeroValue); pair<int64_t, int64_t> pBundle = make_pair(0, 0); nBeginBundles = itZeroValue - vValue.begin(); nTotalCoinValues = nBeginBundles; while (itZeroValue != vValue.end()) { pBundle.first += itZeroValue->first.first; pBundle.second += itZeroValue->first.second; itZeroValue++; if (pBundle.first >= denom) { vZeroValueBundles.push_back(itZeroValue); vValue[nTotalCoinValues].first = pBundle; pBundle = make_pair(0, 0); nTotalCoinValues++; } } // We need to recalculate the total coin value due to truncation of integer division nTotalValue = 0; for (unsigned int i = 0; i < nTotalCoinValues; ++i) { nTotalValue += vValue[i].first.first / denom; } // Check if dynamic programming is still applicable with the approximation if (nTargetValue/denom >= nTotalValue) { // We lose too much coin value through the approximation, i.e. the residual of the previous recalculation is too large // Since the partitioning of the previously sorted list is stable, we can just pick the first coin outputs in the list until we have a valid target value for (; nBeginCoinValues < nTotalCoinValues && (nTargetValue - nValueRet)/denom >= nTotalValue; ++nBeginCoinValues) { if (nBeginCoinValues >= nBeginBundles) { if (fDebug) cerr << "prepick bundle item " << FormatMoney(vValue[nBeginCoinValues].first.first) << " normalized " << vValue[nBeginCoinValues].first.first / denom << " cost " << vValue[nBeginCoinValues].first.second << endl; const size_t nBundle = nBeginCoinValues - nBeginBundles; for (vector<pair<pair<int64_t,int64_t>,pair<const CWalletTx*,unsigned int> > >::iterator it = vZeroValueBundles[nBundle]; it != vZeroValueBundles[nBundle + 1]; ++it) { setCoinsRet.insert(it->second); } } else { if (fDebug) cerr << "prepicking " << FormatMoney(vValue[nBeginCoinValues].first.first) << " normalized " << vValue[nBeginCoinValues].first.first / denom << " cost " << vValue[nBeginCoinValues].first.second << endl; setCoinsRet.insert(vValue[nBeginCoinValues].second); } nTotalValue -= vValue[nBeginCoinValues].first.first / denom; nValueRet += vValue[nBeginCoinValues].first.first; costsum += vValue[nBeginCoinValues].first.second; } if (nValueRet >= nTargetValue) { if (fDebug) cerr << "Done without dynprog: " << "requested " << FormatMoney(nTargetValue) << "\tnormalized " << nTargetValue/denom + (nTargetValue % denom != 0 ? 1 : 0) << "\tgot " << FormatMoney(nValueRet) << "\tcost " << costsum << endl; return true; } } } else { nTotalValue /= denom; } uint64_t nAppend = 1; if ((nTargetValue - nValueRet) % denom != 0) { // We need to decrease the capacity because of integer truncation nAppend--; } // The capacity (number of columns) corresponds to the amount of coin value we are allowed to discard boost::numeric::ublas::matrix<uint64_t> M((nTotalCoinValues - nBeginCoinValues) + 1, (nTotalValue - (nTargetValue - nValueRet)/denom) + nAppend, std::numeric_limits<int64_t>::max()); boost::numeric::ublas::matrix<unsigned int> B((nTotalCoinValues - nBeginCoinValues) + 1, (nTotalValue - (nTargetValue - nValueRet)/denom) + nAppend); for (unsigned int j = 0; j < M.size2(); ++j) { M(0,j) = 0; } for (unsigned int i = 1; i < M.size1(); ++i) { uint64_t nWeight = vValue[nBeginCoinValues + i - 1].first.first / denom; uint64_t nValue = vValue[nBeginCoinValues + i - 1].first.second; //cerr << "Weight " << nWeight << " Value " << nValue << endl; for (unsigned int j = 0; j < M.size2(); ++j) { B(i, j) = j; if (nWeight <= j) { uint64_t nStep = M(i - 1, j - nWeight) + nValue; if (M(i - 1, j) >= nStep) { M(i, j) = M(i - 1, j); } else { M(i, j) = nStep; B(i, j) = j - nWeight; } } else { M(i, j) = M(i - 1, j); } } } // Trace back optimal solution int64_t nPrev = M.size2() - 1; for (unsigned int i = M.size1() - 1; i > 0; --i) { //cerr << i - 1 << " " << vValue[i - 1].second.second << " " << vValue[i - 1].first.first << " " << vValue[i - 1].first.second << " " << nTargetValue << " " << nPrev << " " << (nPrev == B(i, nPrev) ? "XXXXXXXXXXXXXXX" : "") << endl; if (nPrev == B(i, nPrev)) { const size_t nValue = nBeginCoinValues + i - 1; // Check if this is a bundle if (nValue >= nBeginBundles) { if (fDebug) cerr << "pick bundle item " << FormatMoney(vValue[nValue].first.first) << " normalized " << vValue[nValue].first.first / denom << " cost " << vValue[nValue].first.second << endl; const size_t nBundle = nValue - nBeginBundles; for (vector<pair<pair<int64_t,int64_t>,pair<const CWalletTx*,unsigned int> > >::iterator it = vZeroValueBundles[nBundle]; it != vZeroValueBundles[nBundle + 1]; ++it) { setCoinsRet.insert(it->second); } } else { if (fDebug) cerr << "pick " << nValue << " value " << FormatMoney(vValue[nValue].first.first) << " normalized " << vValue[nValue].first.first / denom << " cost " << vValue[nValue].first.second << endl; setCoinsRet.insert(vValue[nValue].second); } nValueRet += vValue[nValue].first.first; costsum += vValue[nValue].first.second; } nPrev = B(i, nPrev); } if (nValueRet < nTargetValue && !vZeroValueBundles.empty()) { // If we get here it means that there are either not sufficient funds to pay the transaction or that there are small coin outputs left that couldn't be bundled // We try to fulfill the request by adding these small coin outputs for (vector<pair<pair<int64_t,int64_t>,pair<const CWalletTx*,unsigned int> > >::iterator it = vZeroValueBundles.back(); it != vValue.end() && nValueRet < nTargetValue; ++it) { setCoinsRet.insert(it->second); nValueRet += it->first.first; } } if (fDebug) cerr << "requested " << FormatMoney(nTargetValue) << "\tnormalized " << nTargetValue/denom + (nTargetValue % denom != 0 ? 1 : 0) << "\tgot " << FormatMoney(nValueRet) << "\tcost " << costsum << endl; if (fDebug) cerr << "M " << M.size1() << "x" << M.size2() << "; vValue.size() = " << vValue.size() << endl; return true; } // TODO: find appropriate place for this sort function // move denoms down bool less_then_denom (const COutput& out1, const COutput& out2) { const CWalletTx *pcoin1 = out1.tx; const CWalletTx *pcoin2 = out2.tx; bool found1 = false; bool found2 = false; BOOST_FOREACH(int64_t d, darkSendDenominations) // loop through predefined denoms { if(pcoin1->vout[out1.i].nValue == d) found1 = true; if(pcoin2->vout[out2.i].nValue == d) found2 = true; } return (!found1 && found2); } bool CWallet::SelectCoinsMinConf(int64_t nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const { setCoinsRet.clear(); nValueRet = 0; // List of values less than target pair<int64_t, pair<const CWalletTx*,unsigned int> > coinLowestLarger; coinLowestLarger.first = std::numeric_limits<int64_t>::max(); coinLowestLarger.second.first = NULL; vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > > vValue; int64_t nTotalLower = 0; random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt); // move denoms down on the list sort(vCoins.begin(), vCoins.end(), less_then_denom); // try to find nondenom first to prevent unneeded spending of mixed coins for (unsigned int tryDenom = 0; tryDenom < 2; tryDenom++) { if (fDebug) LogPrint("selectcoins", "tryDenom: %d\n", tryDenom); vValue.clear(); nTotalLower = 0; BOOST_FOREACH(COutput output, vCoins) { const CWalletTx *pcoin = output.tx; if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs)) continue; int i = output.i; // Follow the timestamp rules if (pcoin->nTime > nSpendTime) continue; int64_t n = pcoin->vout[i].nValue; if (tryDenom == 0 && IsDenominatedAmount(n)) continue; // we don't want denom values on first run pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i)); if (n == nTargetValue) { setCoinsRet.insert(coin.second); nValueRet += coin.first; return true; } else if (n < nTargetValue + CENT) { vValue.push_back(coin); nTotalLower += n; } else if (n < coinLowestLarger.first) { coinLowestLarger = coin; } } if (nTotalLower == nTargetValue) { for (unsigned int i = 0; i < vValue.size(); ++i) { setCoinsRet.insert(vValue[i].second); nValueRet += vValue[i].first; } return true; } if (nTotalLower < nTargetValue) { if (coinLowestLarger.second.first == NULL) return false; setCoinsRet.insert(coinLowestLarger.second); nValueRet += coinLowestLarger.first; return true; } // Solve subset sum by stochastic approximation sort(vValue.rbegin(), vValue.rend(), CompareValueOnly()); vector<char> vfBest; int64_t nBest; ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000); if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT) ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000); // If we have a bigger coin and (either the stochastic approximation didn't find a good solution, // or the next bigger coin is closer), return the bigger coin if (coinLowestLarger.second.first && ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest)) { setCoinsRet.insert(coinLowestLarger.second); nValueRet += coinLowestLarger.first; } else { for (unsigned int i = 0; i < vValue.size(); i++) if (vfBest[i]) { setCoinsRet.insert(vValue[i].second); nValueRet += vValue[i].first; } LogPrint("selectcoins", "SelectCoins() best subset: "); for (unsigned int i = 0; i < vValue.size(); i++) if (vfBest[i]) LogPrint("selectcoins", "%s ", FormatMoney(vValue[i].first)); LogPrint("selectcoins", "total %s\n", FormatMoney(nBest)); } return true; } return false; } bool CWallet::SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX) const { vector<COutput> vCoins; AvailableCoins(vCoins, true, coinControl); //if we're doing only denominated, we need to round up to the nearest .1GRAVITON if(coin_type == ONLY_DENOMINATED){ // Make outputs by looping through denominations, from large to small BOOST_FOREACH(int64_t v, darkSendDenominations) { int added = 0; BOOST_FOREACH(const COutput& out, vCoins) { if(out.tx->vout[out.i].nValue == v //make sure it's the denom we're looking for && nValueRet + out.tx->vout[out.i].nValue < nTargetValue + (0.1*COIN)+100 //round the amount up to .1GRAVITON over && added <= 100){ //don't add more than 100 of one denom type CTxIn vin = CTxIn(out.tx->GetHash(),out.i); int rounds = GetInputDarksendRounds(vin); // make sure it's actually anonymized if(rounds < nDarksendRounds) continue; nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.insert(make_pair(out.tx, out.i)); added++; } } } return (nValueRet >= nTargetValue); } // coin control -> return all selected outputs (we want all selected to go into the transaction for sure) if (coinControl && coinControl->HasSelected()) { BOOST_FOREACH(const COutput& out, vCoins) { if(!out.fSpendable) continue; nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.insert(make_pair(out.tx, out.i)); } return (nValueRet >= nTargetValue); } boost::function<bool (const CWallet*, int64_t, unsigned int, int, int, std::vector<COutput>, std::set<std::pair<const CWalletTx*,unsigned int> >&, int64_t&)> f = fMinimizeCoinAge ? &CWallet::SelectCoinsMinConfByCoinAge : &CWallet::SelectCoinsMinConf; return (f(this, nTargetValue, nSpendTime, 1, 10, vCoins, setCoinsRet, nValueRet) || f(this, nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) || f(this, nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet)); } // Select some coins without random shuffle or best subset approximation bool CWallet::SelectCoinsForStaking(int64_t nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const { vector<COutput> vCoins; AvailableCoinsForStaking(vCoins, nSpendTime); setCoinsRet.clear(); nValueRet = 0; BOOST_FOREACH(COutput output, vCoins) { const CWalletTx *pcoin = output.tx; int i = output.i; // Stop if we've chosen enough inputs if (nValueRet >= nTargetValue) break; int64_t n = pcoin->vout[i].nValue; pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i)); if (n >= nTargetValue) { // If input value is greater or equal to target then simply insert // it into the current subset and exit setCoinsRet.insert(coin.second); nValueRet += coin.first; break; } else if (n < nTargetValue + CENT) { setCoinsRet.insert(coin.second); nValueRet += coin.first; } } return true; } struct CompareByPriority { bool operator()(const COutput& t1, const COutput& t2) const { return t1.Priority() > t2.Priority(); } }; bool CWallet::SelectCoinsByDenominations(int nDenom, int64_t nValueMin, int64_t nValueMax, std::vector<CTxIn>& setCoinsRet, vector<COutput>& setCoinsRet2, int64_t& nValueRet, int nDarksendRoundsMin, int nDarksendRoundsMax) { setCoinsRet.clear(); nValueRet = 0; setCoinsRet2.clear(); vector<COutput> vCoins; AvailableCoins(vCoins); //order the array so fees are first, then denominated money, then the rest. std::random_shuffle(vCoins.rbegin(), vCoins.rend()); //keep track of each denomination that we have bool fFound100000 = false; bool fFound10000 = false; bool fFound1000 = false; bool fFound100 = false; bool fFound10 = false; bool fFound1 = false; bool fFoundDot1 = false; //Check to see if any of the denomination are off, in that case mark them as fulfilled if(!(nDenom & (1 << 0))) fFound100000 = true; if(!(nDenom & (1 << 1))) fFound10000 = true; if(!(nDenom & (1 << 2))) fFound1000 = true; if(!(nDenom & (1 << 3))) fFound100 = true; if(!(nDenom & (1 << 4))) fFound10 = true; if(!(nDenom & (1 << 5))) fFound1 = true; if(!(nDenom & (1 << 6))) fFoundDot1 = true; BOOST_FOREACH(const COutput& out, vCoins) { //there's no reason to allow inputs less than 1 COIN into DS (other than denominations smaller than that amount) if(out.tx->vout[out.i].nValue < 1*COIN && out.tx->vout[out.i].nValue != (.1*COIN)+100) continue; if(fMasterNode && out.tx->vout[out.i].nValue == 25000*COIN) continue; //masternode input if(nValueRet + out.tx->vout[out.i].nValue <= nValueMax){ bool fAccepted = false; // Function returns as follows: // // bit 0 - 100GRAVITON+1 ( bit on if present ) // bit 1 - 10GRAVITON+1 // bit 2 - 1GRAVITON+1 // bit 3 - .1GRAVITON+1 CTxIn vin = CTxIn(out.tx->GetHash(),out.i); int rounds = GetInputDarksendRounds(vin); if(rounds >= nDarksendRoundsMax) continue; if(rounds < nDarksendRoundsMin) continue; if(fFound100000 && fFound10000 && fFound1000 && fFound100 && fFound10 && fFound1 && fFoundDot1){ //if fulfilled //we can return this for submission if(nValueRet >= nValueMin){ //random reduce the max amount we'll submit for anonymity nValueMax -= (rand() % (nValueMax/5)); //on average use 50% of the inputs or less int r = (rand() % (int)vCoins.size()); if((int)setCoinsRet.size() > r) return true; } //Denomination criterion has been met, we can take any matching denominations if((nDenom & (1 << 0)) && out.tx->vout[out.i].nValue == ((100000*COIN) +100000000)) {fAccepted = true;} else if((nDenom & (1 << 1)) && out.tx->vout[out.i].nValue == ((10000*COIN) +10000000)) {fAccepted = true;} else if((nDenom & (1 << 2)) && out.tx->vout[out.i].nValue == ((1000*COIN) +1000000)) {fAccepted = true;} else if((nDenom & (1 << 3)) && out.tx->vout[out.i].nValue == ((100*COIN) +100000)) {fAccepted = true;} else if((nDenom & (1 << 4)) && out.tx->vout[out.i].nValue == ((10*COIN) +10000)) {fAccepted = true;} else if((nDenom & (1 << 5)) && out.tx->vout[out.i].nValue == ((1*COIN) +1000)) {fAccepted = true;} else if((nDenom & (1 << 6)) && out.tx->vout[out.i].nValue == ((.1*COIN) +100)) {fAccepted = true;} } else { //Criterion has not been satisfied, we will only take 1 of each until it is. if((nDenom & (1 << 0)) && out.tx->vout[out.i].nValue == ((100000*COIN) +100000000)) {fAccepted = true; fFound100000 = true;} else if((nDenom & (1 << 1)) && out.tx->vout[out.i].nValue == ((10000*COIN) +10000000)) {fAccepted = true; fFound10000 = true;} else if((nDenom & (1 << 1)) && out.tx->vout[out.i].nValue == ((1000*COIN) +1000000)) {fAccepted = true; fFound1000 = true;} else if((nDenom & (1 << 1)) && out.tx->vout[out.i].nValue == ((100*COIN) +100000)) {fAccepted = true; fFound100 = true;} else if((nDenom & (1 << 1)) && out.tx->vout[out.i].nValue == ((10*COIN) +10000)) {fAccepted = true; fFound10 = true;} else if((nDenom & (1 << 2)) && out.tx->vout[out.i].nValue == ((1*COIN) +1000)) {fAccepted = true; fFound1 = true;} else if((nDenom & (1 << 3)) && out.tx->vout[out.i].nValue == ((.1*COIN) +100)) {fAccepted = true; fFoundDot1 = true;} } if(!fAccepted) continue; vin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.push_back(vin); setCoinsRet2.push_back(out); } } return (nValueRet >= nValueMin && fFound100000 && fFound10000 && fFound1000 && fFound100 && fFound10 && fFound1 && fFoundDot1); } bool CWallet::SelectCoinsDark(int64_t nValueMin, int64_t nValueMax, std::vector<CTxIn>& setCoinsRet, int64_t& nValueRet, int nDarksendRoundsMin, int nDarksendRoundsMax) const { CCoinControl *coinControl=NULL; setCoinsRet.clear(); nValueRet = 0; vector<COutput> vCoins; AvailableCoins(vCoins, true, coinControl, nDarksendRoundsMin < 0 ? ONLY_NONDENOMINATED_NOTMN : ONLY_DENOMINATED); set<pair<const CWalletTx*,unsigned int> > setCoinsRet2; //order the array so fees are first, then denominated money, then the rest. sort(vCoins.rbegin(), vCoins.rend(), CompareByPriority()); //the first thing we get is a fee input, then we'll use as many denominated as possible. then the rest BOOST_FOREACH(const COutput& out, vCoins) { //there's no reason to allow inputs less than 1 COIN into DS (other than denominations smaller than that amount) if(out.tx->vout[out.i].nValue < 1*COIN && out.tx->vout[out.i].nValue != (.1*COIN)+100) continue; if(fMasterNode && out.tx->vout[out.i].nValue == 25000*COIN) continue; //masternode input if(nValueRet + out.tx->vout[out.i].nValue <= nValueMax){ CTxIn vin = CTxIn(out.tx->GetHash(),out.i); int rounds = GetInputDarksendRounds(vin); if(rounds >= nDarksendRoundsMax) continue; if(rounds < nDarksendRoundsMin) continue; vin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.push_back(vin); setCoinsRet2.insert(make_pair(out.tx, out.i)); } } // if it's more than min, we're good to return if(nValueRet >= nValueMin) return true; return false; } bool CWallet::SelectCoinsCollateral(std::vector<CTxIn>& setCoinsRet, int64_t& nValueRet) const { vector<COutput> vCoins; //printf(" selecting coins for collateral\n"); AvailableCoins(vCoins); //printf("found coins %d\n", (int)vCoins.size()); set<pair<const CWalletTx*,unsigned int> > setCoinsRet2; BOOST_FOREACH(const COutput& out, vCoins) { // collateral inputs will always be a multiple of DARSEND_COLLATERAL, up to five if(IsCollateralAmount(out.tx->vout[out.i].nValue)) { CTxIn vin = CTxIn(out.tx->GetHash(),out.i); vin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.push_back(vin); setCoinsRet2.insert(make_pair(out.tx, out.i)); return true; } } return false; } int CWallet::CountInputsWithAmount(int64_t nInputAmount) { int64_t nTotal = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()){ int nDepth = pcoin->GetDepthInMainChain(); for (unsigned int i = 0; i < pcoin->vout.size(); i++) { //isminetype mine = IsMine(pcoin->vout[i]); bool mine = IsMine(pcoin->vout[i]); //COutput out = COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO); COutput out = COutput(pcoin, i, nDepth, mine); CTxIn vin = CTxIn(out.tx->GetHash(), out.i); if(out.tx->vout[out.i].nValue != nInputAmount) continue; if(!IsDenominatedAmount(pcoin->vout[i].nValue)) continue; //if(IsSpent(out.tx->GetHash(), i) || !IsMine(pcoin->vout[i]) || !IsDenominated(vin)) continue; if(pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]) || !IsDenominated(vin)) continue; nTotal++; } } } } return nTotal; } bool CWallet::HasCollateralInputs() const { vector<COutput> vCoins; AvailableCoins(vCoins); int nFound = 0; BOOST_FOREACH(const COutput& out, vCoins) if(IsCollateralAmount(out.tx->vout[out.i].nValue)) nFound++; return nFound > 1; // should have more than one just in case } bool CWallet::IsCollateralAmount(int64_t nInputAmount) const { return nInputAmount == (DARKSEND_COLLATERAL * 5)+DARKSEND_FEE || nInputAmount == (DARKSEND_COLLATERAL * 4)+DARKSEND_FEE || nInputAmount == (DARKSEND_COLLATERAL * 3)+DARKSEND_FEE || nInputAmount == (DARKSEND_COLLATERAL * 2)+DARKSEND_FEE || nInputAmount == (DARKSEND_COLLATERAL * 1)+DARKSEND_FEE; } bool CWallet::SelectCoinsWithoutDenomination(int64_t nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const { CCoinControl *coinControl=NULL; vector<COutput> vCoins; AvailableCoins(vCoins, true, coinControl, ONLY_NONDENOMINATED); BOOST_FOREACH(const COutput& out, vCoins) { nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.insert(make_pair(out.tx, out.i)); } return (nValueRet >= nTargetValue); } bool CWallet::CreateCollateralTransaction(CTransaction& txCollateral, std::string strReason) { /* To doublespend a collateral transaction, it will require a fee higher than this. So there's still a significant cost. */ int64_t nFeeRet = 0.001*COIN; txCollateral.vin.clear(); txCollateral.vout.clear(); CReserveKey reservekey(this); int64_t nValueIn2 = 0; std::vector<CTxIn> vCoinsCollateral; if (!SelectCoinsCollateral(vCoinsCollateral, nValueIn2)) { strReason = "Error: Darksend requires a collateral transaction and could not locate an acceptable input!"; return false; } // make our change address CScript scriptChange; CPubKey vchPubKey; assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptChange =GetScriptForDestination(vchPubKey.GetID()); reservekey.KeepKey(); BOOST_FOREACH(CTxIn v, vCoinsCollateral) txCollateral.vin.push_back(v); if(nValueIn2 - DARKSEND_COLLATERAL - nFeeRet > 0) { //pay collateral charge in fees CTxOut vout3 = CTxOut(nValueIn2 - DARKSEND_COLLATERAL, scriptChange); txCollateral.vout.push_back(vout3); } int vinNumber = 0; BOOST_FOREACH(CTxIn v, txCollateral.vin) { if(!SignSignature(*this, v.prevPubKey, txCollateral, vinNumber, int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))) { BOOST_FOREACH(CTxIn v, vCoinsCollateral) UnlockCoin(v.prevout); strReason = "CDarkSendPool::Sign - Unable to sign collateral transaction! \n"; return false; } vinNumber++; } return true; } bool CWallet::ConvertList(std::vector<CTxIn> vCoins, std::vector<int64_t>& vecAmounts) { BOOST_FOREACH(CTxIn i, vCoins){ if (mapWallet.count(i.prevout.hash)) { CWalletTx& wtx = mapWallet[i.prevout.hash]; if(i.prevout.n < wtx.vout.size()){ vecAmounts.push_back(wtx.vout[i.prevout.n].nValue); } } else { LogPrintf("ConvertList -- Couldn't find transaction\n"); } } return true; } bool CWallet::CreateTransaction(const vector<pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, int32_t& nChangePos, std::string& strFailReason, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX) { int64_t nValue = 0; BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend) { if (nValue < 0) return false; nValue += s.second; } if (vecSend.empty() || nValue < 0) return false; wtxNew.BindWallet(this); CTransaction txNew; { LOCK2(cs_main, cs_wallet); // txdb must be opened before the mapWallet lock CTxDB txdb("r"); { nFeeRet = nTransactionFee; while (true) { wtxNew.vin.clear(); wtxNew.vout.clear(); wtxNew.fFromMe = true; int64_t nTotalValue = nValue + nFeeRet; double dPriority = 0; // vouts to the payees BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend) wtxNew.vout.push_back(CTxOut(s.second, s.first)); // Choose coins to use set<pair<const CWalletTx*,unsigned int> > setCoins; int64_t nValueIn = 0; if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl)) { if(coin_type == ALL_COINS) { strFailReason = _("Insufficient funds."); } else if (coin_type == ONLY_NONDENOMINATED) { strFailReason = _("Unable to locate enough Darksend non-denominated funds for this transaction."); } else if (coin_type == ONLY_NONDENOMINATED_NOTMN) { strFailReason = _("Unable to locate enough Darksend non-denominated funds for this transaction that are not equal 1000 GRAVITON."); } else { strFailReason = _("Unable to locate enough Darksend denominated funds for this transaction."); strFailReason += _("Darksend uses exact denominated amounts to send funds, you might simply need to anonymize some more coins."); } if(useIX){ strFailReason += _("InstantX requires inputs with at least 6 confirmations, you might need to wait a few minutes and try again."); } return false; } BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { int64_t nCredit = pcoin.first->vout[pcoin.second].nValue; dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain(); } int64_t nChange = nValueIn - nValue - nFeeRet; if (nChange > 0) { // Fill a vout to ourself // TODO: pass in scriptChange instead of reservekey so // change transaction isn't always pay-to-bitcoin-address CScript scriptChange; // coin control: send change to custom address if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange)) scriptChange.SetDestination(coinControl->destChange); // no coin control: send change to newly generated address else { // Note: We use a new key here to keep it from being obvious which side is the change. // The drawback is that by not reusing a previous key, the change may be lost if a // backup is restored, if the backup doesn't have the new private key for the change. // If we reused the old key, it would be possible to add code to look for and // rediscover unknown transactions that were written with keys of ours to recover // post-backup change. // Reserve a new key pair from key pool CPubKey vchPubKey; assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptChange.SetDestination(vchPubKey.GetID()); } // Insert change txn at random position: vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size()); // -- don't put change output between value and narration outputs if (position > wtxNew.vout.begin() && position < wtxNew.vout.end()) { while (position > wtxNew.vout.begin()) { if (position->nValue != 0) break; position--; }; }; wtxNew.vout.insert(position, CTxOut(nChange, scriptChange)); nChangePos = std::distance(wtxNew.vout.begin(), position); } else reservekey.ReturnKey(); // Fill vin BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second)); // Sign int nIn = 0; BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) if (!SignSignature(*this, *coin.first, wtxNew, nIn++)) return false; // Limit size unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= MAX_STANDARD_TX_SIZE) return false; dPriority /= nBytes; // Check that enough fee is included int64_t nPayFee = nTransactionFee * (1 + (int64_t)nBytes / 1000); int64_t nMinFee = GetMinFee(wtxNew, 1, GMF_SEND, nBytes); if (nFeeRet < max(nPayFee, nMinFee)) { nFeeRet = max(nPayFee, nMinFee); continue; } // Fill vtxPrev by copying from previous transactions vtxPrev wtxNew.AddSupportingTransactions(txdb); wtxNew.fTimeReceivedIsTxTime = true; break; } } } return true; } bool CWallet::CreateTransaction(CScript scriptPubKey, int64_t nValue, std::string& sNarr, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl) { vector< pair<CScript, int64_t> > vecSend; vecSend.push_back(make_pair(scriptPubKey, nValue)); if (sNarr.length() > 0) { std::vector<uint8_t> vNarr(sNarr.c_str(), sNarr.c_str() + sNarr.length()); std::vector<uint8_t> vNDesc; vNDesc.resize(2); vNDesc[0] = 'n'; vNDesc[1] = 'p'; CScript scriptN = CScript() << OP_RETURN << vNDesc << OP_RETURN << vNarr; vecSend.push_back(make_pair(scriptN, 0)); } // -- CreateTransaction won't place change between value and narr output. // narration output will be for preceding output int nChangePos; std::string strFailReason; bool rv = CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, nChangePos, strFailReason, coinControl); // -- narration will be added to mapValue later in FindStealthTransactions From CommitTransaction return rv; } bool CWallet::NewStealthAddress(std::string& sError, std::string& sLabel, CStealthAddress& sxAddr) { ec_secret scan_secret; ec_secret spend_secret; if (GenerateRandomSecret(scan_secret) != 0 || GenerateRandomSecret(spend_secret) != 0) { sError = "GenerateRandomSecret failed."; printf("Error CWallet::NewStealthAddress - %s\n", sError.c_str()); return false; }; ec_point scan_pubkey, spend_pubkey; if (SecretToPublicKey(scan_secret, scan_pubkey) != 0) { sError = "Could not get scan public key."; printf("Error CWallet::NewStealthAddress - %s\n", sError.c_str()); return false; }; if (SecretToPublicKey(spend_secret, spend_pubkey) != 0) { sError = "Could not get spend public key."; printf("Error CWallet::NewStealthAddress - %s\n", sError.c_str()); return false; }; if (fDebug) { printf("getnewstealthaddress: "); printf("scan_pubkey "); for (uint32_t i = 0; i < scan_pubkey.size(); ++i) printf("%02x", scan_pubkey[i]); printf("\n"); printf("spend_pubkey "); for (uint32_t i = 0; i < spend_pubkey.size(); ++i) printf("%02x", spend_pubkey[i]); printf("\n"); }; sxAddr.label = sLabel; sxAddr.scan_pubkey = scan_pubkey; sxAddr.spend_pubkey = spend_pubkey; sxAddr.scan_secret.resize(32); memcpy(&sxAddr.scan_secret[0], &scan_secret.e[0], 32); sxAddr.spend_secret.resize(32); memcpy(&sxAddr.spend_secret[0], &spend_secret.e[0], 32); return true; } bool CWallet::AddStealthAddress(CStealthAddress& sxAddr) { LOCK(cs_wallet); // must add before changing spend_secret stealthAddresses.insert(sxAddr); bool fOwned = sxAddr.scan_secret.size() == ec_secret_size; if (fOwned) { // -- owned addresses can only be added when wallet is unlocked if (IsLocked()) { printf("Error: CWallet::AddStealthAddress wallet must be unlocked.\n"); stealthAddresses.erase(sxAddr); return false; }; if (IsCrypted()) { std::vector<unsigned char> vchCryptedSecret; CSecret vchSecret; vchSecret.resize(32); memcpy(&vchSecret[0], &sxAddr.spend_secret[0], 32); uint256 iv = Hash(sxAddr.spend_pubkey.begin(), sxAddr.spend_pubkey.end()); if (!EncryptSecret(vMasterKey, vchSecret, iv, vchCryptedSecret)) { printf("Error: Failed encrypting stealth key %s\n", sxAddr.Encoded().c_str()); stealthAddresses.erase(sxAddr); return false; }; sxAddr.spend_secret = vchCryptedSecret; }; }; bool rv = CWalletDB(strWalletFile).WriteStealthAddress(sxAddr); if (rv) NotifyAddressBookChanged(this, sxAddr, sxAddr.label, fOwned, CT_NEW); return rv; } bool CWallet::UnlockStealthAddresses(const CKeyingMaterial& vMasterKeyIn) { // -- decrypt spend_secret of stealth addresses std::set<CStealthAddress>::iterator it; for (it = stealthAddresses.begin(); it != stealthAddresses.end(); ++it) { if (it->scan_secret.size() < 32) continue; // stealth address is not owned // -- CStealthAddress are only sorted on spend_pubkey CStealthAddress &sxAddr = const_cast<CStealthAddress&>(*it); if (fDebug) printf("Decrypting stealth key %s\n", sxAddr.Encoded().c_str()); CSecret vchSecret; uint256 iv = Hash(sxAddr.spend_pubkey.begin(), sxAddr.spend_pubkey.end()); if(!DecryptSecret(vMasterKeyIn, sxAddr.spend_secret, iv, vchSecret) || vchSecret.size() != 32) { printf("Error: Failed decrypting stealth key %s\n", sxAddr.Encoded().c_str()); continue; }; ec_secret testSecret; memcpy(&testSecret.e[0], &vchSecret[0], 32); ec_point pkSpendTest; if (SecretToPublicKey(testSecret, pkSpendTest) != 0 || pkSpendTest != sxAddr.spend_pubkey) { printf("Error: Failed decrypting stealth key, public key mismatch %s\n", sxAddr.Encoded().c_str()); continue; }; sxAddr.spend_secret.resize(32); memcpy(&sxAddr.spend_secret[0], &vchSecret[0], 32); }; CryptedKeyMap::iterator mi = mapCryptedKeys.begin(); for (; mi != mapCryptedKeys.end(); ++mi) { CPubKey &pubKey = (*mi).second.first; std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second; if (vchCryptedSecret.size() != 0) continue; CKeyID ckid = pubKey.GetID(); CBitcoinAddress addr(ckid); StealthKeyMetaMap::iterator mi = mapStealthKeyMeta.find(ckid); if (mi == mapStealthKeyMeta.end()) { printf("Error: No metadata found to add secret for %s\n", addr.ToString().c_str()); continue; }; CStealthKeyMetadata& sxKeyMeta = mi->second; CStealthAddress sxFind; sxFind.scan_pubkey = sxKeyMeta.pkScan.Raw(); std::set<CStealthAddress>::iterator si = stealthAddresses.find(sxFind); if (si == stealthAddresses.end()) { printf("No stealth key found to add secret for %s\n", addr.ToString().c_str()); continue; }; if (fDebug) printf("Expanding secret for %s\n", addr.ToString().c_str()); ec_secret sSpendR; ec_secret sSpend; ec_secret sScan; if (si->spend_secret.size() != ec_secret_size || si->scan_secret.size() != ec_secret_size) { printf("Stealth address has no secret key for %s\n", addr.ToString().c_str()); continue; } memcpy(&sScan.e[0], &si->scan_secret[0], ec_secret_size); memcpy(&sSpend.e[0], &si->spend_secret[0], ec_secret_size); ec_point pkEphem = sxKeyMeta.pkEphem.Raw(); if (StealthSecretSpend(sScan, pkEphem, sSpend, sSpendR) != 0) { printf("StealthSecretSpend() failed.\n"); continue; }; ec_point pkTestSpendR; if (SecretToPublicKey(sSpendR, pkTestSpendR) != 0) { printf("SecretToPublicKey() failed.\n"); continue; }; CSecret vchSecret; vchSecret.resize(ec_secret_size); memcpy(&vchSecret[0], &sSpendR.e[0], ec_secret_size); CKey ckey; try { ckey.Set(vchSecret.begin(), vchSecret.end(), true); //ckey.SetSecret(vchSecret, true); } catch (std::exception& e) { printf("ckey.SetSecret() threw: %s.\n", e.what()); continue; }; CPubKey cpkT = ckey.GetPubKey(); if (!cpkT.IsValid()) { printf("cpkT is invalid.\n"); continue; }; if (cpkT != pubKey) { printf("Error: Generated secret does not match.\n"); continue; }; if (!ckey.IsValid()) { printf("Reconstructed key is invalid.\n"); continue; }; if (fDebug) { CKeyID keyID = cpkT.GetID(); CBitcoinAddress coinAddress(keyID); printf("Adding secret to key %s.\n", coinAddress.ToString().c_str()); }; if (!AddKey(ckey)) { printf("AddKey failed.\n"); continue; }; if (!CWalletDB(strWalletFile).EraseStealthKeyMeta(ckid)) printf("EraseStealthKeyMeta failed for %s\n", addr.ToString().c_str()); }; return true; } bool CWallet::UpdateStealthAddress(std::string &addr, std::string &label, bool addIfNotExist) { if (fDebug) printf("UpdateStealthAddress %s\n", addr.c_str()); CStealthAddress sxAddr; if (!sxAddr.SetEncoded(addr)) return false; std::set<CStealthAddress>::iterator it; it = stealthAddresses.find(sxAddr); ChangeType nMode = CT_UPDATED; CStealthAddress sxFound; if (it == stealthAddresses.end()) { if (addIfNotExist) { sxFound = sxAddr; sxFound.label = label; stealthAddresses.insert(sxFound); nMode = CT_NEW; } else { printf("UpdateStealthAddress %s, not in set\n", addr.c_str()); return false; }; } else { sxFound = const_cast<CStealthAddress&>(*it); if (sxFound.label == label) { // no change return true; }; it->label = label; // update in .stealthAddresses if (sxFound.scan_secret.size() == ec_secret_size) { printf("UpdateStealthAddress: todo - update owned stealth address.\n"); return false; }; }; sxFound.label = label; if (!CWalletDB(strWalletFile).WriteStealthAddress(sxFound)) { printf("UpdateStealthAddress(%s) Write to db failed.\n", addr.c_str()); return false; }; bool fOwned = sxFound.scan_secret.size() == ec_secret_size; NotifyAddressBookChanged(this, sxFound, sxFound.label, fOwned, nMode); return true; } bool CWallet::CreateStealthTransaction(CScript scriptPubKey, int64_t nValue, std::vector<uint8_t>& P, std::vector<uint8_t>& narr, std::string& sNarr, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl) { vector< pair<CScript, int64_t> > vecSend; vecSend.push_back(make_pair(scriptPubKey, nValue)); CScript scriptP = CScript() << OP_RETURN << P; if (narr.size() > 0) scriptP = scriptP << OP_RETURN << narr; vecSend.push_back(make_pair(scriptP, 1)); // -- shuffle inputs, change output won't mix enough as it must be not fully random for plantext narrations std::random_shuffle(vecSend.begin(), vecSend.end()); int nChangePos; std::string strFailReason; bool rv = CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, nChangePos, strFailReason, coinControl); // -- the change txn is inserted in a random pos, check here to match narr to output if (rv && narr.size() > 0) { for (unsigned int k = 0; k < wtxNew.vout.size(); ++k) { if (wtxNew.vout[k].scriptPubKey != scriptPubKey || wtxNew.vout[k].nValue != nValue) continue; char key[64]; if (snprintf(key, sizeof(key), "n_%u", k) < 1) { printf("CreateStealthTransaction(): Error creating narration key."); break; }; wtxNew.mapValue[key] = sNarr; break; }; }; return rv; } string CWallet::SendStealthMoney(CScript scriptPubKey, int64_t nValue, std::vector<uint8_t>& P, std::vector<uint8_t>& narr, std::string& sNarr, CWalletTx& wtxNew, bool fAskFee) { CReserveKey reservekey(this); int64_t nFeeRequired; if (IsLocked()) { string strError = _("Error: Wallet locked, unable to create transaction "); printf("SendStealthMoney() : %s", strError.c_str()); return strError; } if (fWalletUnlockStakingOnly) { string strError = _("Error: Wallet unlocked for staking only, unable to create transaction."); printf("SendStealthMoney() : %s", strError.c_str()); return strError; } if (!CreateStealthTransaction(scriptPubKey, nValue, P, narr, sNarr, wtxNew, reservekey, nFeeRequired)) { string strError; if (nValue + nFeeRequired > GetBalance()) strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds "), FormatMoney(nFeeRequired).c_str()); else strError = _("Error: Transaction creation failed "); printf("SendStealthMoney() : %s", strError.c_str()); return strError; } if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending..."))) return "ABORTED"; if (!CommitTransaction(wtxNew, reservekey)) return _("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."); return ""; } bool CWallet::SendStealthMoneyToDestination(CStealthAddress& sxAddress, int64_t nValue, std::string& sNarr, CWalletTx& wtxNew, std::string& sError, bool fAskFee) { // -- Check amount if (nValue <= 0) { sError = "Invalid amount"; return false; }; if (nValue + nTransactionFee + (1) > GetBalance()) { sError = "Insufficient funds"; return false; }; ec_secret ephem_secret; ec_secret secretShared; ec_point pkSendTo; ec_point ephem_pubkey; if (GenerateRandomSecret(ephem_secret) != 0) { sError = "GenerateRandomSecret failed."; return false; }; if (StealthSecret(ephem_secret, sxAddress.scan_pubkey, sxAddress.spend_pubkey, secretShared, pkSendTo) != 0) { sError = "Could not generate receiving public key."; return false; }; CPubKey cpkTo(pkSendTo); if (!cpkTo.IsValid()) { sError = "Invalid public key generated."; return false; }; CKeyID ckidTo = cpkTo.GetID(); CBitcoinAddress addrTo(ckidTo); if (SecretToPublicKey(ephem_secret, ephem_pubkey) != 0) { sError = "Could not generate ephem public key."; return false; }; if (fDebug) { printf("Stealth send to generated pubkey %"PRIszu": %s\n", pkSendTo.size(), HexStr(pkSendTo).c_str()); printf("hash %s\n", addrTo.ToString().c_str()); printf("ephem_pubkey %"PRIszu": %s\n", ephem_pubkey.size(), HexStr(ephem_pubkey).c_str()); }; std::vector<unsigned char> vchNarr; if (sNarr.length() > 0) { SecMsgCrypter crypter; crypter.SetKey(&secretShared.e[0], &ephem_pubkey[0]); if (!crypter.Encrypt((uint8_t*)&sNarr[0], sNarr.length(), vchNarr)) { sError = "Narration encryption failed."; return false; }; if (vchNarr.size() > 48) { sError = "Encrypted narration is too long."; return false; }; }; // -- Parse Bitcoin address CScript scriptPubKey; scriptPubKey.SetDestination(addrTo.Get()); if ((sError = SendStealthMoney(scriptPubKey, nValue, ephem_pubkey, vchNarr, sNarr, wtxNew, fAskFee)) != "") return false; return true; } bool CWallet::FindStealthTransactions(const CTransaction& tx, mapValue_t& mapNarr) { if (fDebug) LogPrintf("FindStealthTransactions() tx: %s\n", tx.GetHash().GetHex().c_str()); mapNarr.clear(); LOCK(cs_wallet); ec_secret sSpendR; ec_secret sSpend; ec_secret sScan; ec_secret sShared; ec_point pkExtracted; std::vector<uint8_t> vchEphemPK; std::vector<uint8_t> vchDataB; std::vector<uint8_t> vchENarr; opcodetype opCode; char cbuf[256]; int32_t nOutputIdOuter = -1; BOOST_FOREACH(const CTxOut& txout, tx.vout) { nOutputIdOuter++; // -- for each OP_RETURN need to check all other valid outputs //printf("txout scriptPubKey %s\n", txout.scriptPubKey.ToString().c_str()); CScript::const_iterator itTxA = txout.scriptPubKey.begin(); if (!txout.scriptPubKey.GetOp(itTxA, opCode, vchEphemPK) || opCode != OP_RETURN) continue; else if (!txout.scriptPubKey.GetOp(itTxA, opCode, vchEphemPK) || vchEphemPK.size() != 33) { // -- look for plaintext narrations if (vchEphemPK.size() > 1 && vchEphemPK[0] == 'n' && vchEphemPK[1] == 'p') { if (txout.scriptPubKey.GetOp(itTxA, opCode, vchENarr) && opCode == OP_RETURN && txout.scriptPubKey.GetOp(itTxA, opCode, vchENarr) && vchENarr.size() > 0) { std::string sNarr = std::string(vchENarr.begin(), vchENarr.end()); snprintf(cbuf, sizeof(cbuf), "n_%d", nOutputIdOuter-1); // plaintext narration always matches preceding value output mapNarr[cbuf] = sNarr; } else { printf("Warning: FindStealthTransactions() tx: %s, Could not extract plaintext narration.\n", tx.GetHash().GetHex().c_str()); }; } continue; } int32_t nOutputId = -1; nStealth++; BOOST_FOREACH(const CTxOut& txoutB, tx.vout) { nOutputId++; if (&txoutB == &txout) continue; bool txnMatch = false; // only 1 txn will match an ephem pk //printf("txoutB scriptPubKey %s\n", txoutB.scriptPubKey.ToString().c_str()); CTxDestination address; if (!ExtractDestination(txoutB.scriptPubKey, address)) continue; if (address.type() != typeid(CKeyID)) continue; CKeyID ckidMatch = boost::get<CKeyID>(address); if (HaveKey(ckidMatch)) // no point checking if already have key continue; std::set<CStealthAddress>::iterator it; for (it = stealthAddresses.begin(); it != stealthAddresses.end(); ++it) { if (it->scan_secret.size() != ec_secret_size) continue; // stealth address is not owned //printf("it->Encodeded() %s\n", it->Encoded().c_str()); memcpy(&sScan.e[0], &it->scan_secret[0], ec_secret_size); if (StealthSecret(sScan, vchEphemPK, it->spend_pubkey, sShared, pkExtracted) != 0) { printf("StealthSecret failed.\n"); continue; }; //printf("pkExtracted %"PRIszu": %s\n", pkExtracted.size(), HexStr(pkExtracted).c_str()); CPubKey cpkE(pkExtracted); if (!cpkE.IsValid()) continue; CKeyID ckidE = cpkE.GetID(); if (ckidMatch != ckidE) continue; if (fDebug) printf("Found stealth txn to address %s\n", it->Encoded().c_str()); if (IsLocked()) { if (fDebug) printf("Wallet is locked, adding key without secret.\n"); // -- add key without secret std::vector<uint8_t> vchEmpty; AddCryptedKey(cpkE, vchEmpty); CKeyID keyId = cpkE.GetID(); CBitcoinAddress coinAddress(keyId); std::string sLabel = it->Encoded(); SetAddressBookName(keyId, sLabel); CPubKey cpkEphem(vchEphemPK); CPubKey cpkScan(it->scan_pubkey); CStealthKeyMetadata lockedSkMeta(cpkEphem, cpkScan); if (!CWalletDB(strWalletFile).WriteStealthKeyMeta(keyId, lockedSkMeta)) printf("WriteStealthKeyMeta failed for %s\n", coinAddress.ToString().c_str()); mapStealthKeyMeta[keyId] = lockedSkMeta; nFoundStealth++; } else { if (it->spend_secret.size() != ec_secret_size) continue; memcpy(&sSpend.e[0], &it->spend_secret[0], ec_secret_size); if (StealthSharedToSecretSpend(sShared, sSpend, sSpendR) != 0) { printf("StealthSharedToSecretSpend() failed.\n"); continue; }; ec_point pkTestSpendR; if (SecretToPublicKey(sSpendR, pkTestSpendR) != 0) { printf("SecretToPublicKey() failed.\n"); continue; }; CSecret vchSecret; vchSecret.resize(ec_secret_size); memcpy(&vchSecret[0], &sSpendR.e[0], ec_secret_size); CKey ckey; try { ckey.Set(vchSecret.begin(), vchSecret.end(), true); //ckey.SetSecret(vchSecret, true); } catch (std::exception& e) { printf("ckey.SetSecret() threw: %s.\n", e.what()); continue; }; CPubKey cpkT = ckey.GetPubKey(); if (!cpkT.IsValid()) { printf("cpkT is invalid.\n"); continue; }; if (!ckey.IsValid()) { printf("Reconstructed key is invalid.\n"); continue; }; CKeyID keyID = cpkT.GetID(); if (fDebug) { CBitcoinAddress coinAddress(keyID); printf("Adding key %s.\n", coinAddress.ToString().c_str()); }; if (!AddKey(ckey)) { printf("AddKey failed.\n"); continue; }; std::string sLabel = it->Encoded(); SetAddressBookName(keyID, sLabel); nFoundStealth++; }; if (txout.scriptPubKey.GetOp(itTxA, opCode, vchENarr) && opCode == OP_RETURN && txout.scriptPubKey.GetOp(itTxA, opCode, vchENarr) && vchENarr.size() > 0) { SecMsgCrypter crypter; crypter.SetKey(&sShared.e[0], &vchEphemPK[0]); std::vector<uint8_t> vchNarr; if (!crypter.Decrypt(&vchENarr[0], vchENarr.size(), vchNarr)) { printf("Decrypt narration failed.\n"); continue; }; std::string sNarr = std::string(vchNarr.begin(), vchNarr.end()); snprintf(cbuf, sizeof(cbuf), "n_%d", nOutputId); mapNarr[cbuf] = sNarr; }; txnMatch = true; break; }; if (txnMatch) break; }; }; return true; }; uint64_t CWallet::GetStakeWeight() const { // Choose coins to use int64_t nBalance = GetBalance(); if (nBalance <= nReserveBalance) return 0; vector<const CWalletTx*> vwtxPrev; set<pair<const CWalletTx*,unsigned int> > setCoins; int64_t nValueIn = 0; if (!SelectCoinsForStaking(nBalance - nReserveBalance, GetTime(), setCoins, nValueIn)) return 0; if (setCoins.empty()) return 0; uint64_t nWeight = 0; int64_t nCurrentTime = GetTime(); CTxDB txdb("r"); LOCK2(cs_main, cs_wallet); BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { CTxIndex txindex; if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex)) continue; if (nCurrentTime - pcoin.first->nTime > nStakeMinAge) nWeight += pcoin.first->vout[pcoin.second].nValue; } return nWeight; } bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64_t nSearchInterval, int64_t nFees, CTransaction& txNew, CKey& key) { CBlockIndex* pindexPrev = pindexBest; CBigNum bnTargetPerCoinDay; bnTargetPerCoinDay.SetCompact(nBits); txNew.vin.clear(); txNew.vout.clear(); // Mark coin stake transaction CScript scriptEmpty; scriptEmpty.clear(); txNew.vout.push_back(CTxOut(0, scriptEmpty)); // Choose coins to use int64_t nBalance = GetBalance(); if (nBalance <= nReserveBalance) return false; vector<const CWalletTx*> vwtxPrev; set<pair<const CWalletTx*,unsigned int> > setCoins; int64_t nValueIn = 0; // Select coins with suitable depth if (!SelectCoinsForStaking(nBalance - nReserveBalance, txNew.nTime, setCoins, nValueIn)) return false; if (setCoins.empty()) return false; int64_t nCredit = 0; CScript scriptPubKeyKernel; CTxDB txdb("r"); BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { static int nMaxStakeSearchInterval = 60; bool fKernelFound = false; for (unsigned int n=0; n<min(nSearchInterval,(int64_t)nMaxStakeSearchInterval) && !fKernelFound && pindexPrev == pindexBest; n++) { boost::this_thread::interruption_point(); // Search backward in time from the given txNew timestamp // Search nSearchInterval seconds back up to nMaxStakeSearchInterval COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second); int64_t nBlockTime; if (CheckKernel(pindexPrev, nBits, txNew.nTime - n, prevoutStake, &nBlockTime)) { // Found a kernel LogPrint("coinstake", "CreateCoinStake : kernel found\n"); vector<valtype> vSolutions; txnouttype whichType; CScript scriptPubKeyOut; scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey; if (!Solver(scriptPubKeyKernel, whichType, vSolutions)) { LogPrint("coinstake", "CreateCoinStake : failed to parse kernel\n"); break; } LogPrint("coinstake", "CreateCoinStake : parsed kernel type=%d\n", whichType); if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH) { LogPrint("coinstake", "CreateCoinStake : no support for kernel type=%d\n", whichType); break; // only support pay to public key and pay to address } if (whichType == TX_PUBKEYHASH) // pay to address type { // convert to pay to public key type if (!keystore.GetKey(uint160(vSolutions[0]), key)) { LogPrint("coinstake", "CreateCoinStake : failed to get key for kernel type=%d\n", whichType); break; // unable to find corresponding public key } scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG; } if (whichType == TX_PUBKEY) { valtype& vchPubKey = vSolutions[0]; if (!keystore.GetKey(Hash160(vchPubKey), key)) { LogPrint("coinstake", "CreateCoinStake : failed to get key for kernel type=%d\n", whichType); break; // unable to find corresponding public key } if (key.GetPubKey() != vchPubKey) { LogPrint("coinstake", "CreateCoinStake : invalid key for kernel type=%d\n", whichType); break; // keys mismatch } scriptPubKeyOut = scriptPubKeyKernel; } txNew.nTime -= n; txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second)); nCredit += pcoin.first->vout[pcoin.second].nValue; vwtxPrev.push_back(pcoin.first); txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); if(nCredit > 100 * COIN) txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake LogPrint("coinstake", "CreateCoinStake : added kernel type=%d\n", whichType); fKernelFound = true; break; } } if (fKernelFound) break; // if kernel is found stop searching } if (nCredit == 0 || nCredit > nBalance - nReserveBalance) return false; BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { // Attempt to add more inputs // Only add coins of the same key/address as kernel if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey)) && pcoin.first->GetHash() != txNew.vin[0].prevout.hash) { int64_t nTimeWeight = GetWeight((int64_t)pcoin.first->nTime, (int64_t)txNew.nTime); // Stop adding more inputs if already too many inputs if (txNew.vin.size() >= 100) break; // Stop adding more inputs if value is already pretty significant if (nCredit >= GetStakeCombineThreshold()) break; // Stop adding inputs if reached reserve limit if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance) break; // Do not add additional significant input if (pcoin.first->vout[pcoin.second].nValue >= GetStakeCombineThreshold()) continue; // Do not add input that is still too young if (nTimeWeight < nStakeMinAge) continue; txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second)); nCredit += pcoin.first->vout[pcoin.second].nValue; vwtxPrev.push_back(pcoin.first); } } // Calculate coin age reward int64_t nReward; { uint64_t nCoinAge; CTxDB txdb("r"); if (!txNew.GetCoinAge(txdb, nCoinAge)) return error("CreateCoinStake : failed to calculate coin age"); nReward = GetProofOfStakeReward(pindexPrev->nHeight + 1, nCoinAge, nFees); if (nReward <= 0) return false; nCredit += nReward; } // Masternode Payments int payments = 1; // start masternode payments bool bMasterNodePayment = true; // note was false, set true to test if ( Params().NetworkID() == CChainParams::TESTNET ){ if (GetTime() > START_MASTERNODE_PAYMENTS_TESTNET ){ bMasterNodePayment = true; } }else{ if (GetTime() > START_MASTERNODE_PAYMENTS){ bMasterNodePayment = true; } } CScript payee; bool hasPayment = true; if(bMasterNodePayment) { //spork if(!masternodePayments.GetBlockPayee(pindexPrev->nHeight+1, payee)){ int winningNode = GetCurrentMasterNode(1); if(winningNode >= 0){ payee =GetScriptForDestination(vecMasternodes[winningNode].pubkey.GetID()); } else { LogPrintf("CreateCoinStake: Failed to detect masternode to pay\n"); hasPayment = false; } } } if(hasPayment){ payments = txNew.vout.size() + 1; txNew.vout.resize(payments); txNew.vout[payments-1].scriptPubKey = payee; txNew.vout[payments-1].nValue = 0; CTxDestination address1; ExtractDestination(payee, address1); CBitcoinAddress address2(address1); LogPrintf("Masternode payment to %s\n", address2.ToString().c_str()); } int64_t blockValue = nCredit; int64_t masternodePayment = GetMasternodePayment(pindexPrev->nHeight+1, nReward); // Set output amount if (!hasPayment && txNew.vout.size() == 3) // 2 stake outputs, stake was split, no masternode payment { txNew.vout[1].nValue = (blockValue / 2 / CENT) * CENT; txNew.vout[2].nValue = blockValue - txNew.vout[1].nValue; } else if(hasPayment && txNew.vout.size() == 4) // 2 stake outputs, stake was split, plus a masternode payment { txNew.vout[payments-1].nValue = masternodePayment; blockValue -= masternodePayment; txNew.vout[1].nValue = (blockValue / 2 / CENT) * CENT; txNew.vout[2].nValue = blockValue - txNew.vout[1].nValue; } else if(!hasPayment && txNew.vout.size() == 2) // only 1 stake output, was not split, no masternode payment txNew.vout[1].nValue = blockValue; else if(hasPayment && txNew.vout.size() == 3) // only 1 stake output, was not split, plus a masternode payment { txNew.vout[payments-1].nValue = masternodePayment; blockValue -= masternodePayment; txNew.vout[1].nValue = blockValue; } // Sign int nIn = 0; BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev) { if (!SignSignature(*this, *pcoin, txNew, nIn++)) return error("CreateCoinStake : failed to sign coinstake"); } // Limit size unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= MAX_BLOCK_SIZE_GEN/5) return error("CreateCoinStake : exceeded coinstake size limit"); // Successfully generated coinstake return true; } // Call after CreateTransaction unless you want to abort bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey) { mapValue_t mapNarr; FindStealthTransactions(wtxNew, mapNarr); if (!mapNarr.empty()) { BOOST_FOREACH(const PAIRTYPE(string,string)& item, mapNarr) wtxNew.mapValue[item.first] = item.second; }; { LOCK2(cs_main, cs_wallet); LogPrintf("CommitTransaction:\n%s", wtxNew.ToString()); { // This is only to keep the database open to defeat the auto-flush for the // duration of this scope. This is the only place where this optimization // maybe makes sense; please don't do it anywhere else. CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL; // Take key pair from key pool so it won't be used again reservekey.KeepKey(); // Add tx to wallet, because if it has change it's also ours, // otherwise just for transaction history. AddToWallet(wtxNew); // Mark old coins as spent set<CWalletTx*> setCoins; BOOST_FOREACH(const CTxIn& txin, wtxNew.vin) { CWalletTx &coin = mapWallet[txin.prevout.hash]; coin.BindWallet(this); coin.MarkSpent(txin.prevout.n); coin.WriteToDisk(); NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED); } if (fFileBacked) delete pwalletdb; } // Track how many getdata requests our transaction gets mapRequestCount[wtxNew.GetHash()] = 0; // Broadcast if (!wtxNew.AcceptToMemoryPool(true)) { // This must not fail. The transaction has already been signed and recorded. LogPrintf("CommitTransaction() : Error: Transaction not valid\n"); return false; } wtxNew.RelayWalletTransaction(); } return true; } string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, std::string& sNarr, CWalletTx& wtxNew, bool fAskFee) { CReserveKey reservekey(this); int64_t nFeeRequired; if (IsLocked()) { string strError = _("Error: Wallet locked, unable to create transaction!"); LogPrintf("SendMoney() : %s", strError); return strError; } if (fWalletUnlockStakingOnly) { string strError = _("Error: Wallet unlocked for staking only, unable to create transaction."); LogPrintf("SendMoney() : %s", strError); return strError; } if (!CreateTransaction(scriptPubKey, nValue, sNarr, wtxNew, reservekey, nFeeRequired)) { string strError; if (nValue + nFeeRequired > GetBalance()) strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!"), FormatMoney(nFeeRequired)); else strError = _("Error: Transaction creation failed!"); LogPrintf("SendMoney() : %s\n", strError); return strError; } if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending..."))) return "ABORTED"; if (!CommitTransaction(wtxNew, reservekey)) return _("Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."); return ""; } string CWallet::SendMoneyToDestination(const CTxDestination& address, int64_t nValue, std::string& sNarr, CWalletTx& wtxNew, bool fAskFee) { // Check amount if (nValue <= 0) return _("Invalid amount"); if (nValue + nTransactionFee > GetBalance()) return _("Insufficient funds"); if (sNarr.length() > 24) return _("Narration must be 24 characters or less."); // Parse Bitcoin address CScript scriptPubKey; scriptPubKey.SetDestination(address); return SendMoney(scriptPubKey, nValue, sNarr, wtxNew, fAskFee); } string CWallet::PrepareDarksendDenominate(int minRounds, int maxRounds) { if (IsLocked()) return _("Error: Wallet locked, unable to create transaction!"); if(darkSendPool.GetState() != POOL_STATUS_ERROR && darkSendPool.GetState() != POOL_STATUS_SUCCESS) if(darkSendPool.GetMyTransactionCount() > 0) return _("Error: You already have pending entries in the Darksend pool"); // ** find the coins we'll use std::vector<CTxIn> vCoins; std::vector<COutput> vCoins2; int64_t nValueIn = 0; CReserveKey reservekey(this); /* Select the coins we'll use if minRounds >= 0 it means only denominated inputs are going in and coming out */ if(minRounds >= 0){ if (!SelectCoinsByDenominations(darkSendPool.sessionDenom, 0.1*COIN, DARKSEND_POOL_MAX, vCoins, vCoins2, nValueIn, minRounds, maxRounds)) return _("Insufficient funds"); } // calculate total value out int64_t nTotalValue = GetTotalValue(vCoins); LogPrintf("PrepareDarksendDenominate - preparing darksend denominate . Got: %d \n", nTotalValue); //-------------- BOOST_FOREACH(CTxIn v, vCoins) LockCoin(v.prevout); // denominate our funds int64_t nValueLeft = nTotalValue; std::vector<CTxOut> vOut; std::vector<int64_t> vDenoms; /* TODO: Front load with needed denominations (e.g. .1, 1 ) */ /* Add all denominations once The beginning of the list is front loaded with each possible denomination in random order. This means we'll at least get 1 of each that is required as outputs. */ BOOST_FOREACH(int64_t d, darkSendDenominations){ vDenoms.push_back(d); vDenoms.push_back(d); } //randomize the order of these denominations std::random_shuffle (vDenoms.begin(), vDenoms.end()); /* Build a long list of denominations Next we'll build a long random list of denominations to add. Eventually as the algorithm goes through these it'll find the ones it nees to get exact change. */ for(int i = 0; i <= 500; i++) BOOST_FOREACH(int64_t d, darkSendDenominations) vDenoms.push_back(d); //randomize the order of inputs we get back std::random_shuffle (vDenoms.begin() + (int)darkSendDenominations.size() + 1, vDenoms.end()); // Make outputs by looping through denominations randomly BOOST_REVERSE_FOREACH(int64_t v, vDenoms){ //only use the ones that are approved bool fAccepted = false; if((darkSendPool.sessionDenom & (1 << 0)) && v == ((100000*COIN) +100000000)) {fAccepted = true;} else if((darkSendPool.sessionDenom & (1 << 1)) && v == ((10000*COIN) +10000000)) {fAccepted = true;} else if((darkSendPool.sessionDenom & (1 << 2)) && v == ((1000*COIN) +1000000)) {fAccepted = true;} else if((darkSendPool.sessionDenom & (1 << 3)) && v == ((100*COIN) +100000)) {fAccepted = true;} else if((darkSendPool.sessionDenom & (1 << 4)) && v == ((10*COIN) +10000)) {fAccepted = true;} else if((darkSendPool.sessionDenom & (1 << 5)) && v == ((1*COIN) +1000)) {fAccepted = true;} else if((darkSendPool.sessionDenom & (1 << 6)) && v == ((.1*COIN) +100)) {fAccepted = true;} if(!fAccepted) continue; int nOutputs = 0; // add each output up to 10 times until it can't be added again if(nValueLeft - v >= 0 && nOutputs <= 10) { CScript scriptChange; CPubKey vchPubKey; //use a unique change address assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptChange =GetScriptForDestination(vchPubKey.GetID()); reservekey.KeepKey(); CTxOut o(v, scriptChange); vOut.push_back(o); //increment outputs and subtract denomination amount nOutputs++; nValueLeft -= v; } if(nValueLeft == 0) break; } //back up mode , incase we couldn't successfully make the outputs for some reason if(vOut.size() > 40 || darkSendPool.GetDenominations(vOut) != darkSendPool.sessionDenom || nValueLeft != 0){ vOut.clear(); nValueLeft = nTotalValue; // Make outputs by looping through denominations, from small to large BOOST_FOREACH(const COutput& out, vCoins2){ CScript scriptChange; CPubKey vchPubKey; //use a unique change address assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptChange =GetScriptForDestination(vchPubKey.GetID()); reservekey.KeepKey(); CTxOut o(out.tx->vout[out.i].nValue, scriptChange); vOut.push_back(o); //increment outputs and subtract denomination amount nValueLeft -= out.tx->vout[out.i].nValue; if(nValueLeft == 0) break; } } if(darkSendPool.GetDenominations(vOut) != darkSendPool.sessionDenom) return "Error: can't make current denominated outputs"; // we don't support change at all if(nValueLeft != 0) return "Error: change left-over in pool. Must use denominations only"; //randomize the output order std::random_shuffle (vOut.begin(), vOut.end()); darkSendPool.SendDarksendDenominate(vCoins, vOut, nValueIn); return ""; } int64_t CWallet::GetTotalValue(std::vector<CTxIn> vCoins) { int64_t nTotalValue = 0; CWalletTx wtx; BOOST_FOREACH(CTxIn i, vCoins){ if (mapWallet.count(i.prevout.hash)) { CWalletTx& wtx = mapWallet[i.prevout.hash]; if(i.prevout.n < wtx.vout.size()){ nTotalValue += wtx.vout[i.prevout.n].nValue; } } else { LogPrintf("GetTotalValue -- Couldn't find transaction\n"); } } return nTotalValue; } DBErrors CWallet::LoadWallet(bool& fFirstRunRet) { if (!fFileBacked) return DB_LOAD_OK; fFirstRunRet = false; DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this); if (nLoadWalletRet == DB_NEED_REWRITE) { if (CDB::Rewrite(strWalletFile, "\x04pool")) { LOCK(cs_wallet); setKeyPool.clear(); // Note: can't top-up keypool here, because wallet is locked. // User will be prompted to unlock wallet the next operation // the requires a new key. } } if (nLoadWalletRet != DB_LOAD_OK) return nLoadWalletRet; fFirstRunRet = !vchDefaultKey.IsValid(); return DB_LOAD_OK; } bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName) { bool fUpdated = false; { LOCK(cs_wallet); // mapAddressBook std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address); fUpdated = mi != mapAddressBook.end(); mapAddressBook[address] = strName; } NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (fUpdated ? CT_UPDATED : CT_NEW) ); if (!fFileBacked) return false; return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName); } bool CWallet::DelAddressBookName(const CTxDestination& address) { { LOCK(cs_wallet); // mapAddressBook mapAddressBook.erase(address); } NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED); if (!fFileBacked) return false; return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString()); } bool CWallet::SetDefaultKey(const CPubKey &vchPubKey) { if (fFileBacked) { if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey)) return false; } vchDefaultKey = vchPubKey; return true; } // // Mark old keypool keys as used, // and generate all new keys // bool CWallet::NewKeyPool() { { LOCK(cs_wallet); CWalletDB walletdb(strWalletFile); BOOST_FOREACH(int64_t nIndex, setKeyPool) walletdb.ErasePool(nIndex); setKeyPool.clear(); if (IsLocked()) return false; int64_t nKeys = max(GetArg("-keypool", 100), (int64_t)0); for (int i = 0; i < nKeys; i++) { int64_t nIndex = i+1; walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey())); setKeyPool.insert(nIndex); } LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys); } return true; } bool CWallet::TopUpKeyPool(unsigned int nSize) { { LOCK(cs_wallet); if (IsLocked()) return false; CWalletDB walletdb(strWalletFile); // Top up key pool unsigned int nTargetSize; if (nSize > 0) nTargetSize = nSize; else nTargetSize = max(GetArg("-keypool", 100), (int64_t)0); while (setKeyPool.size() < (nTargetSize + 1)) { int64_t nEnd = 1; if (!setKeyPool.empty()) nEnd = *(--setKeyPool.end()) + 1; if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey()))) throw runtime_error("TopUpKeyPool() : writing generated key failed"); setKeyPool.insert(nEnd); LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size()); } } return true; } void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool) { nIndex = -1; keypool.vchPubKey = CPubKey(); { LOCK(cs_wallet); if (!IsLocked()) TopUpKeyPool(); // Get the oldest key if(setKeyPool.empty()) return; CWalletDB walletdb(strWalletFile); nIndex = *(setKeyPool.begin()); setKeyPool.erase(setKeyPool.begin()); if (!walletdb.ReadPool(nIndex, keypool)) throw runtime_error("ReserveKeyFromKeyPool() : read failed"); if (!HaveKey(keypool.vchPubKey.GetID())) throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool"); assert(keypool.vchPubKey.IsValid()); LogPrintf("keypool reserve %d\n", nIndex); } } int64_t CWallet::AddReserveKey(const CKeyPool& keypool) { { LOCK2(cs_main, cs_wallet); CWalletDB walletdb(strWalletFile); int64_t nIndex = 1 + *(--setKeyPool.end()); if (!walletdb.WritePool(nIndex, keypool)) throw runtime_error("AddReserveKey() : writing added key failed"); setKeyPool.insert(nIndex); return nIndex; } return -1; } void CWallet::KeepKey(int64_t nIndex) { // Remove from key pool if (fFileBacked) { CWalletDB walletdb(strWalletFile); walletdb.ErasePool(nIndex); } LogPrintf("keypool keep %d\n", nIndex); } void CWallet::ReturnKey(int64_t nIndex) { // Return to key pool { LOCK(cs_wallet); setKeyPool.insert(nIndex); } LogPrintf("keypool return %d\n", nIndex); } bool CWallet::GetKeyFromPool(CPubKey& result) { int64_t nIndex = 0; CKeyPool keypool; { LOCK(cs_wallet); ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex == -1) { if (IsLocked()) return false; result = GenerateNewKey(); return true; } KeepKey(nIndex); result = keypool.vchPubKey; } return true; } int64_t CWallet::GetOldestKeyPoolTime() { int64_t nIndex = 0; CKeyPool keypool; ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex == -1) return GetTime(); ReturnKey(nIndex); return keypool.nTime; } std::map<CTxDestination, int64_t> CWallet::GetAddressBalances() { map<CTxDestination, int64_t> balances; { LOCK(cs_wallet); BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) { CWalletTx *pcoin = &walletEntry.second; if (!IsFinalTx(*pcoin) || !pcoin->IsTrusted()) continue; if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0) continue; int nDepth = pcoin->GetDepthInMainChain(); if (nDepth < (pcoin->IsFromMe() ? 0 : 1)) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { CTxDestination addr; if (!IsMine(pcoin->vout[i])) continue; if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr)) continue; int64_t n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue; if (!balances.count(addr)) balances[addr] = 0; balances[addr] += n; } } } return balances; } set< set<CTxDestination> > CWallet::GetAddressGroupings() { AssertLockHeld(cs_wallet); // mapWallet set< set<CTxDestination> > groupings; set<CTxDestination> grouping; BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) { CWalletTx *pcoin = &walletEntry.second; if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0])) { // group all input addresses with each other BOOST_FOREACH(CTxIn txin, pcoin->vin) { CTxDestination address; if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address)) continue; grouping.insert(address); } // group change with input addresses BOOST_FOREACH(CTxOut txout, pcoin->vout) if (IsChange(txout)) { CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash]; CTxDestination txoutAddr; if(!ExtractDestination(txout.scriptPubKey, txoutAddr)) continue; grouping.insert(txoutAddr); } groupings.insert(grouping); grouping.clear(); } // group lone addrs by themselves for (unsigned int i = 0; i < pcoin->vout.size(); i++) if (IsMine(pcoin->vout[i])) { CTxDestination address; if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address)) continue; grouping.insert(address); groupings.insert(grouping); grouping.clear(); } } set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it BOOST_FOREACH(set<CTxDestination> grouping, groupings) { // make a set of all the groups hit by this new group set< set<CTxDestination>* > hits; map< CTxDestination, set<CTxDestination>* >::iterator it; BOOST_FOREACH(CTxDestination address, grouping) if ((it = setmap.find(address)) != setmap.end()) hits.insert((*it).second); // merge all hit groups into a new single group and delete old groups set<CTxDestination>* merged = new set<CTxDestination>(grouping); BOOST_FOREACH(set<CTxDestination>* hit, hits) { merged->insert(hit->begin(), hit->end()); uniqueGroupings.erase(hit); delete hit; } uniqueGroupings.insert(merged); // update setmap BOOST_FOREACH(CTxDestination element, *merged) setmap[element] = merged; } set< set<CTxDestination> > ret; BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings) { ret.insert(*uniqueGrouping); delete uniqueGrouping; } return ret; } // ppcoin: check 'spent' consistency between wallet and txindex // ppcoin: fix wallet spent state according to txindex void CWallet::FixSpentCoins(int& nMismatchFound, int64_t& nBalanceInQuestion, bool fCheckOnly) { nMismatchFound = 0; nBalanceInQuestion = 0; LOCK(cs_wallet); vector<CWalletTx*> vCoins; vCoins.reserve(mapWallet.size()); for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) vCoins.push_back(&(*it).second); CTxDB txdb("r"); BOOST_FOREACH(CWalletTx* pcoin, vCoins) { // Find the corresponding transaction index CTxIndex txindex; if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex)) continue; for (unsigned int n=0; n < pcoin->vout.size(); n++) { if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull())) { LogPrintf("FixSpentCoins found lost coin %s BC %s[%d], %s\n", FormatMoney(pcoin->vout[n].nValue), pcoin->GetHash().ToString(), n, fCheckOnly? "repair not attempted" : "repairing"); nMismatchFound++; nBalanceInQuestion += pcoin->vout[n].nValue; if (!fCheckOnly) { pcoin->MarkUnspent(n); pcoin->WriteToDisk(); } } else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull())) { LogPrintf("FixSpentCoins found spent coin %s BC %s[%d], %s\n", FormatMoney(pcoin->vout[n].nValue), pcoin->GetHash().ToString(), n, fCheckOnly? "repair not attempted" : "repairing"); nMismatchFound++; nBalanceInQuestion += pcoin->vout[n].nValue; if (!fCheckOnly) { pcoin->MarkSpent(n); pcoin->WriteToDisk(); } } } } } // ppcoin: disable transaction (only for coinstake) void CWallet::DisableTransaction(const CTransaction &tx) { if (!tx.IsCoinStake() || !IsFromMe(tx)) return; // only disconnecting coinstake requires marking input unspent LOCK(cs_wallet); BOOST_FOREACH(const CTxIn& txin, tx.vin) { map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n])) { prev.MarkUnspent(txin.prevout.n); prev.WriteToDisk(); } } } } bool CReserveKey::GetReservedKey(CPubKey& pubkey) { if (nIndex == -1) { CKeyPool keypool; pwallet->ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex != -1) vchPubKey = keypool.vchPubKey; else { if (pwallet->vchDefaultKey.IsValid()) { LogPrintf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!"); vchPubKey = pwallet->vchDefaultKey; } else return false; } } assert(vchPubKey.IsValid()); pubkey = vchPubKey; return true; } void CReserveKey::KeepKey() { if (nIndex != -1) pwallet->KeepKey(nIndex); nIndex = -1; vchPubKey = CPubKey(); } void CReserveKey::ReturnKey() { if (nIndex != -1) pwallet->ReturnKey(nIndex); nIndex = -1; vchPubKey = CPubKey(); } void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const { setAddress.clear(); CWalletDB walletdb(strWalletFile); LOCK2(cs_main, cs_wallet); BOOST_FOREACH(const int64_t& id, setKeyPool) { CKeyPool keypool; if (!walletdb.ReadPool(id, keypool)) throw runtime_error("GetAllReserveKeyHashes() : read failed"); assert(keypool.vchPubKey.IsValid()); CKeyID keyID = keypool.vchPubKey.GetID(); if (!HaveKey(keyID)) throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool"); setAddress.insert(keyID); } } void CWallet::UpdatedTransaction(const uint256 &hashTx) { { LOCK(cs_wallet); // Only notify UI if this transaction is in this wallet map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx); if (mi != mapWallet.end()) NotifyTransactionChanged(this, hashTx, CT_UPDATED); } } void CWallet::LockCoin(COutPoint& output) { AssertLockHeld(cs_wallet); // setLockedCoins setLockedCoins.insert(output); } void CWallet::UnlockCoin(COutPoint& output) { AssertLockHeld(cs_wallet); // setLockedCoins setLockedCoins.erase(output); } void CWallet::UnlockAllCoins() { AssertLockHeld(cs_wallet); // setLockedCoins setLockedCoins.clear(); } bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const { AssertLockHeld(cs_wallet); // setLockedCoins COutPoint outpt(hash, n); return (setLockedCoins.count(outpt) > 0); } void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) { AssertLockHeld(cs_wallet); // setLockedCoins for (std::set<COutPoint>::iterator it = setLockedCoins.begin(); it != setLockedCoins.end(); it++) { COutPoint outpt = (*it); vOutpts.push_back(outpt); } } void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const { AssertLockHeld(cs_wallet); // mapKeyMetadata mapKeyBirth.clear(); // get birth times for keys with metadata for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++) if (it->second.nCreateTime) mapKeyBirth[it->first] = it->second.nCreateTime; // map in which we'll infer heights of other keys CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock; std::set<CKeyID> setKeys; GetKeys(setKeys); BOOST_FOREACH(const CKeyID &keyid, setKeys) { if (mapKeyBirth.count(keyid) == 0) mapKeyFirstBlock[keyid] = pindexMax; } setKeys.clear(); // if there are no such keys, we're done if (mapKeyFirstBlock.empty()) return; // find first block that affects those keys, if there are any left std::vector<CKeyID> vAffected; for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) { // iterate over all wallet transactions... const CWalletTx &wtx = (*it).second; std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock); if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) { // ... which are already in a block int nHeight = blit->second->nHeight; BOOST_FOREACH(const CTxOut &txout, wtx.vout) { // iterate over all their outputs ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected); BOOST_FOREACH(const CKeyID &keyid, vAffected) { // ... and all their affected keys std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid); if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight) rit->second = blit->second; } vAffected.clear(); } } } // Extract block timestamps for those keys for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++) mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off } bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx) { { LOCK(cs_wallet); map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx); if (mi != mapWallet.end()) { wtx = (*mi).second; return true; } } return false; } int CMerkleTx::GetTransactionLockSignatures() const { if(!IsSporkActive(SPORK_1_MASTERNODE_PAYMENTS_ENFORCEMENT)) return -3; if(nInstantXDepth == 0) return -1; //compile consessus vote std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(GetHash()); if (i != mapTxLocks.end()){ return (*i).second.CountSignatures(); } return -1; } bool CMerkleTx::IsTransactionLockTimedOut() const { if(nInstantXDepth == 0) return 0; //compile consessus vote std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(GetHash()); if (i != mapTxLocks.end()){ return GetTime() > (*i).second.nTimeout; } return false; } bool CWallet::AddAdrenalineNodeConfig(CAdrenalineNodeConfig nodeConfig) { bool rv = CWalletDB(strWalletFile).WriteAdrenalineNodeConfig(nodeConfig.sAlias, nodeConfig); if(rv) uiInterface.NotifyAdrenalineNodeChanged(nodeConfig); return rv; }
{ "content_hash": "21c9868d2be34c174d59e1c32748e558", "timestamp": "", "source": "github", "line_count": 4486, "max_line_length": 265, "avg_line_length": 35.72759696834596, "alnum_prop": 0.5668542620761945, "repo_name": "gravitondev/graviton", "id": "deb1b0d150d2c619b058b544989480f6a705d1c9", "size": "160274", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/wallet.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "104261" }, { "name": "C++", "bytes": "4361931" }, { "name": "CSS", "bytes": "1127" }, { "name": "HTML", "bytes": "50620" }, { "name": "Makefile", "bytes": "11748" }, { "name": "NSIS", "bytes": "6077" }, { "name": "Objective-C", "bytes": "858" }, { "name": "Objective-C++", "bytes": "3517" }, { "name": "Python", "bytes": "54355" }, { "name": "QMake", "bytes": "16023" }, { "name": "Shell", "bytes": "8509" } ], "symlink_target": "" }
package cn.cerc.mis.excel.output; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import cn.cerc.db.core.DataSet; import jxl.Workbook; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; public class DataSetFile { private ExcelTemplate template; private DataSet dataSet; private String fileName; public DataSetFile(DataSet dataSet) { this.dataSet = dataSet; } public void save() throws IOException, WriteException { save(this.fileName); } public void save(String fileName) throws IOException, WriteException { setFileName(fileName); OutputStream os = new FileOutputStream(fileName); ExcelTemplate template = this.getTemplate(); template.setFileName(fileName); template.setDataSet(dataSet); if (template.getColumns().size() == 0) { for (String field : dataSet.fields().names()) { StringColumn column = new StringColumn(); column.setCode(field); column.setName(field); template.addColumn(column); } } // 创建工作薄 WritableWorkbook workbook = Workbook.createWorkbook(os); // 创建新的一页 WritableSheet sheet = workbook.createSheet("Sheet1", 0); template.output(sheet); // 把创建的内容写入到输出流中,并关闭输出流 workbook.write(); workbook.close(); os.close(); } public ExcelTemplate getTemplate() { if (template == null) { template = new ExcelTemplate(); template.setColumns(new ArrayList<>()); } return template; } public void setTemplate(ExcelTemplate template) { this.template = template; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } }
{ "content_hash": "c851c0623e117b7021bf39e54dff9a36", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 74, "avg_line_length": 27.943661971830984, "alnum_prop": 0.6300403225806451, "repo_name": "cn-cerc/summer-mis", "id": "f489e915d597eaafbe90f9829152cec3325ffcb0", "size": "2046", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/main/java/cn/cerc/mis/excel/output/DataSetFile.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "23851" }, { "name": "Java", "bytes": "519967" }, { "name": "JavaScript", "bytes": "398" } ], "symlink_target": "" }
<!DOCTYPE html> <html ng-app="BabaOmoApp"> <head> <title>Paternity Test - Baba Omo</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" /> <script src="https://use.fontawesome.com/6e40765922.js"></script> <base href="/babaomo/"> <link rel="icon" href="img/dna.png" /> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css"> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-material-datetimepicker/2.7.1/css/bootstrap-material-datetimepicker.min.css" /> <link rel="stylesheet" href="css/style.css" /> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div ui-view></div> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <!-- Angular --> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script> <!-- Custom --> <script src="js/app.js"></script> <script src="js/babaomo.factory.js"></script> <script src="js/alleles.ctrl.js"></script> <script src="js/info.ctrl.js"></script> <script src="js/result.ctrl.js"></script> <script src="js/models/config.model.js"></script> <script src="js/models/allele-frequency.model.js"></script> <script src="js/models/constants.model.js"></script> <script src="js/models/locus.model.js"></script> <script src="js/models/paternity.model.js"></script> <script src="js/models/population.model.js"></script> <script src="js/models/report.model.js"></script> <script src="js/directives/allele-pair.dir.js"></script> <script src="js/directives/load-allele-test.dir.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.2/angular-ui-router.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-material-datetimepicker/2.7.1/js/bootstrap-material-datetimepicker.min.js"></script> <script src="https://rawgit.com/notifyjs/notifyjs/master/dist/notify.js"></script> <script src="js/prototypes/array.prototype.js"></script> <script src="js/prototypes/string.prototype.js"></script> <script src="js/modules/doc.module.js"></script> </body> </html>
{ "content_hash": "10be241b1e537175df17df8ef83bb777", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 158, "avg_line_length": 54.55, "alnum_prop": 0.665139016193095, "repo_name": "sharonikechi/babaomo", "id": "5cc52434bb33438835e73d653d72370b611943b3", "size": "3275", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "App/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "106" }, { "name": "Batchfile", "bytes": "45" }, { "name": "C#", "bytes": "166508" }, { "name": "CSS", "bytes": "7921" }, { "name": "HTML", "bytes": "35612" }, { "name": "JavaScript", "bytes": "85614" } ], "symlink_target": "" }
/* * 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. */ /* * This code was generated by https://github.com/google/apis-client-generator/ * (build: 2021-08-24 11:56:07 EDT) * on 2021-08-24 at 15:56:28 UTC * Modify at your own risk. */ package com.google.api.services.rcsbusinessmessaging.v1.model; /** * Request to check if users are RBM-reachable. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the RCS Business Messaging API. For a detailed * explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class BatchGetUsersRequest extends com.google.api.client.json.GenericJson { /** * Optional. The agent's unique identifier. Defined by RCS Business Messaging. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String agentId; /** * List of users' phone numbers in E.164 format. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> users; /** * Optional. The agent's unique identifier. Defined by RCS Business Messaging. * @return value or {@code null} for none */ public java.lang.String getAgentId() { return agentId; } /** * Optional. The agent's unique identifier. Defined by RCS Business Messaging. * @param agentId agentId or {@code null} for none */ public BatchGetUsersRequest setAgentId(java.lang.String agentId) { this.agentId = agentId; return this; } /** * List of users' phone numbers in E.164 format. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getUsers() { return users; } /** * List of users' phone numbers in E.164 format. * @param users users or {@code null} for none */ public BatchGetUsersRequest setUsers(java.util.List<java.lang.String> users) { this.users = users; return this; } @Override public BatchGetUsersRequest set(String fieldName, Object value) { return (BatchGetUsersRequest) super.set(fieldName, value); } @Override public BatchGetUsersRequest clone() { return (BatchGetUsersRequest) super.clone(); } }
{ "content_hash": "334049b558eb4c2730aca30447902417", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 182, "avg_line_length": 31.612903225806452, "alnum_prop": 0.7061224489795919, "repo_name": "google-business-communications/java-rcsbusinessmessaging", "id": "3ca6fa984bf1a05d6f9d9bfa93c9ebf46fefda5f", "size": "2940", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "com/google/api/services/rcsbusinessmessaging/v1/model/BatchGetUsersRequest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "364857" } ], "symlink_target": "" }
Ember.libraries.register('Ember Simple Auth', '1.0.1');
{ "content_hash": "5df6c0bc37fa2b934484970646810bce", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 55, "avg_line_length": 56, "alnum_prop": 0.7142857142857143, "repo_name": "mdehoog/ember-simple-auth", "id": "9b85f1a28d2f950d9f3de5012e5ee27dd9fa824e", "size": "56", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vendor/ember-simple-auth/register-version.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "196" }, { "name": "HTML", "bytes": "4959" }, { "name": "JavaScript", "bytes": "191928" } ], "symlink_target": "" }
#ifdef _MSC_VER #pragma comment(linker, "/SUBSYSTEM:CONSOLE") #endif #include <inviwo/core/common/inviwo.h> #include <inviwo/core/common/inviwoapplication.h> #include <inviwo/core/util/logcentral.h> #include <inviwo/core/util/consolelogger.h> #include <inviwo/core/common/coremodulesharedlibrary.h> #include <inviwo/core/util/settings/systemsettings.h> #include <inviwo/testutil/configurablegtesteventlistener.h> #include <warn/push> #include <warn/ignore/all> #include <gtest/gtest.h> #include <warn/pop> using namespace inviwo; int main(int argc, char** argv) { LogCentral::init(); auto logger = std::make_shared<ConsoleLogger>(); LogCentral::getPtr()->setVerbosity(LogVerbosity::Error); LogCentral::getPtr()->registerLogger(logger); InviwoApplication app(argc, argv, "Inviwo-Unittests-Core"); app.getSystemSettings().stackTraceInException_.set(true); { std::vector<std::unique_ptr<InviwoModuleFactoryObject>> modules; modules.emplace_back(createInviwoCore()); app.registerModules(std::move(modules)); } app.processFront(); int ret = -1; { #ifdef IVW_ENABLE_MSVC_MEM_LEAK_TEST VLDDisable(); ::testing::InitGoogleTest(&argc, argv); VLDEnable(); #else ::testing::InitGoogleTest(&argc, argv); #endif ConfigurableGTestEventListener::setup(); ret = RUN_ALL_TESTS(); } return ret; }
{ "content_hash": "71e1682aebbea0e45b14efd4d5b0af6e", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 72, "avg_line_length": 26.660377358490567, "alnum_prop": 0.6942675159235668, "repo_name": "Sparkier/inviwo", "id": "3baa2e99cba2c6a785c098137d9a6104f1397ec1", "size": "2996", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/core/tests/unittests/inviwo-core-unittest-main.cpp", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "146426" }, { "name": "C++", "bytes": "11871087" }, { "name": "CMake", "bytes": "574616" }, { "name": "CSS", "bytes": "18058" }, { "name": "GLSL", "bytes": "504032" }, { "name": "Groovy", "bytes": "11430" }, { "name": "HTML", "bytes": "79818" }, { "name": "JavaScript", "bytes": "173791" }, { "name": "Mathematica", "bytes": "109319" }, { "name": "Python", "bytes": "1817954" }, { "name": "QMake", "bytes": "172" }, { "name": "TeX", "bytes": "5813" } ], "symlink_target": "" }
<?php /* * * @author Vee W. * @license http://opensource.org/licenses/MIT * */ namespace Modules\Dbt\Models; class Test extends \Phalcon\Mvc\Model { /** * @Primary * @Identity * @Column(type="integer", nullable=false) */ public $id; /** * @Column(type="string", length=255, nullable=true) */ public $name; /** * @Column(type="string", length=1000, nullable=true) */ public $address; public function getSource() { $config = $this->_dependencyInjector->getShared('config'); return $config->database->tablePrefix.'test'; }// getSource public function initialize() { // $this->belongsTo();// more info about relations, see the document. }// initialize }
{ "content_hash": "2c64a6db143b4bee1647e9ef53cda519", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 77, "avg_line_length": 16.638297872340427, "alnum_prop": 0.5728900255754475, "repo_name": "lukesUbuntu/phalcon-begins", "id": "d7274e0196272e6950b6841ee72c021f2fac22e4", "size": "782", "binary": false, "copies": "1", "ref": "refs/heads/simple-test", "path": "modules/dbt/models/Test.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "212" }, { "name": "HTML", "bytes": "2328" }, { "name": "PHP", "bytes": "60493" }, { "name": "Volt", "bytes": "1673" } ], "symlink_target": "" }
package pl.sw.project.tests; import org.junit.Test; /** * Created by nishi on 2017-03-07. */ public class NumberOfStickersTest extends TestBase { @Test public void testNumberOfStickers() { app.goTo().mainPage(); app.article().checkNumberOfStickers(); } }
{ "content_hash": "6cbf9285f5b1646e9fe1d33c561cf1bc", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 52, "avg_line_length": 18.266666666666666, "alnum_prop": 0.6970802919708029, "repo_name": "maciekp85/selenium-webdriver", "id": "432c3eac914e6659857f11085b7e172883baea28", "size": "274", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "java-example/src/test/java/pl/sw/project/tests/NumberOfStickersTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "27142" } ], "symlink_target": "" }
package com.amazonaws.services.quicksight.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.quicksight.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * CreateDashboardRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class CreateDashboardRequestProtocolMarshaller implements Marshaller<Request<CreateDashboardRequest>, CreateDashboardRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON) .requestUri("/accounts/{AwsAccountId}/dashboards/{DashboardId}").httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false) .hasPayloadMembers(true).serviceName("AmazonQuickSight").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public CreateDashboardRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<CreateDashboardRequest> marshall(CreateDashboardRequest createDashboardRequest) { if (createDashboardRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<CreateDashboardRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, createDashboardRequest); protocolMarshaller.startMarshalling(); CreateDashboardRequestMarshaller.getInstance().marshall(createDashboardRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
{ "content_hash": "2ee7109f73e83b3ad2870dbf6bda8771", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 152, "avg_line_length": 40.73076923076923, "alnum_prop": 0.7629839471199245, "repo_name": "aws/aws-sdk-java", "id": "9d9a9da1d372cfe49dcf71377382235537cd1466", "size": "2698", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-quicksight/src/main/java/com/amazonaws/services/quicksight/model/transform/CreateDashboardRequestProtocolMarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!-- A basic index.html file served from the "/" URL. --> <html> <body> <p>Enqueue a value, to be processed by a worker.</p> <form action="/enqueue" method="post"> <input type="text" name="value"> <input type="text" name="name"> <input type="submit"> </form> </body> </html>
{ "content_hash": "7489265de00e6b02c656bd5b8abcb679", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 57, "avg_line_length": 25.833333333333332, "alnum_prop": 0.5709677419354838, "repo_name": "hessenh/CS263Project", "id": "34f67a653ab59d1bf4533337059d856ba3a1a869", "size": "310", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/webapp/other/task.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "152368" }, { "name": "Java", "bytes": "69037" } ], "symlink_target": "" }
/* * 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. * */ package net.rptools.parser.jsapi; import net.rptools.lib.datavalue.DataType; import net.rptools.lib.permissions.PermissionLevel; import net.rptools.lib.permissions.PlayerPermissions; import net.rptools.parser.dice.DicePattern; import net.rptools.parser.dice.JavaScriptDice; import net.rptools.parser.functions.FunctionDefinitionBuilder; import net.rptools.parser.functions.javascript.JavaScriptFunction; import java.util.*; /** * Class used for JavaScript API call to export JavaScript functions. * */ public class ExportJS { /** The temporary list of exported functions */ private static final List<ExportedFunction> exportedFunctions = new ArrayList<>(); /** The temporary list of exported dice rolls. */ private static final List<JavaScriptDice> exportedDice = new ArrayList<>(); private ExportJS() { // Stop instantiation. } /** * Clear the currently exported functions. This should be run before calling a new JavaScript * script so that you can record which functions were defined in the script. */ public static void clearExportedFunctions() { exportedFunctions.clear(); } /** * Returns the exported functions since the last {@code clearExportedFunctions()} call. * * @return the exported functions. */ public static Collection<ExportedFunction> getExportedFunctions() { return Collections.unmodifiableCollection(exportedFunctions); } /** * Callback to export a JavaScript function. * * @param name The name of the scripting language function. * @param params The parameter list for the function. * @param returnType The return type of the function. * @param jsFunctionName The name of the JavaScript function. * @param perm The default permissions required to run the function. */ public static void exportFunction(String name, Object params, String returnType, String jsFunctionName, String perm) { FunctionDefinitionBuilder fdBuilder = new FunctionDefinitionBuilder(); fdBuilder.setReturnType(DataType.valueOf(returnType.toUpperCase())); fdBuilder.setName(name); fdBuilder.setDefaultPermission(PermissionLevel.valueOf(perm.toUpperCase())); ExportedFunction ef = new ExportedFunction(name, DataType.valueOf(returnType.toUpperCase()), params, jsFunctionName, PermissionLevel.valueOf(perm.toUpperCase())); exportedFunctions.add(ef); } /** * Clear the list of currently exported dice. This should be run before calling a new JavaScript script * so that cou can record which dice were defined in the script. */ public static void clearExportedDice() { exportedDice.clear(); } /** * Returns a list of the exported dice. * * @return the exported dice. */ public static Collection<JavaScriptDice> getExportedDice() { return Collections.unmodifiableCollection(exportedDice); } /** * Call back to export JavaScript dice. * * @param name The name of the dice. * @param diceString The dice pattern string. * @param jsFunctionName The name of the JavaScript function to call. * @param caseInsensitive Is the the dice pattern to be exported case insensitive. * */ public static void exportDice(String name, String diceString, String jsFunctionName, boolean caseInsensitive) { FunctionDefinitionBuilder fdBuilder = new FunctionDefinitionBuilder(); fdBuilder.setReturnType(DataType.RESULT); fdBuilder.setName("Dice Roll(" + name + ")"); fdBuilder.setDefaultPermission(PlayerPermissions.getUnspecifiedPlayerPermissions().getPermissionLevel()); DicePattern dicePattern; if (caseInsensitive) { dicePattern = DicePattern.getCaseInsenstiveDicePattern(diceString); } else { dicePattern = DicePattern.getDicePattern(diceString); } // Add all of the arguments. for (String argName : dicePattern.getArgNames()) { fdBuilder.addParameter(argName, DataType.DOUBLE); } JavaScriptFunction jsf = new JavaScriptFunction(jsFunctionName, fdBuilder.toFunctionDefinition()); JavaScriptDice jsd = new JavaScriptDice(dicePattern, name, jsf); exportedDice.add(jsd); } }
{ "content_hash": "5c4bb9760919ee064451f6541542d82c", "timestamp": "", "source": "github", "line_count": 142, "max_line_length": 120, "avg_line_length": 35.24647887323944, "alnum_prop": 0.6947052947052947, "repo_name": "RPTools/zz-old-rptools-common", "id": "248e25b75acb414eaf73d9718d666153576bd2d3", "size": "5005", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "parser/src/main/java/net/rptools/parser/jsapi/ExportJS.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "430122" }, { "name": "JavaScript", "bytes": "20068" } ], "symlink_target": "" }
This project uses AngularJS, JSHint, BrowserSync, Less, Karma, Jasmine, PhantomJS, GulpJS. Node.JS 5 is required. ## What is it? This is simple single page responsive application showing usage of common Javascript technologies. Main page state is a listing of repositories. When someone clicks on one of them state switch to details of this repository. In current version the application uses two directives for rv-list for list of the repositories and rv-number-span for number-image pair element. It is very likely that this two components will be highly reusable. RvList could be placed in many different contexts other views. RvNumberImage would be used probably in all occurrences of numer-image pairs for views, stars and shares. When more mockups would be provided we could consider adding directive for list row. I used angular-ui-router for controlling application state changes. Configuration is in config.js. Services: * logger - for events logging. In current version in just uses angular $log service under covers. * rest - service for making REST calls for getting data from the server. Views: * Listing - show a list of repositories in tabular form. Default view. * Details - shows details of the selected record. Required recordId parameter. Application is build using GulpJS. Current version runs on BrowserSync. Gulp tasks: * gulp lint - runs lint checker. * gulp less - compiles less sources and put them into /public/css * gulp serve - starts HTTP server and open Firefox. Default. Views are prepared with heavily use of flex boxes. It makes a lot easier to make responsive web designs using flex boxes. I used autoprefixer to add browser specific prefixes to CSS formulas. Tested on: Firefox 40.0.2, Chrome 48.0.+, Opera 35.0. ## How to install npm install && bower install ## How to run npm start or gulp serve ## How to run tests npm test Tests will be run in auto-watch-mode. When changes in code occur the tests will rerun. # TODO - what I will do next * Test on IE9+. * Create directive for list record. * Add sending logs to server in logger service. * Add e2e tests. * Unit tests for controllers. * Prepare gulp configuration for production build (minify, uglify). # Licence This project is licensed under the [MIT licence](LICENSE.md). # Enjoy!
{ "content_hash": "54d51eed491e0f3cbd399b8a58b77523", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 467, "avg_line_length": 34.343283582089555, "alnum_prop": 0.7740112994350282, "repo_name": "adamfaryna/repository-viewer", "id": "88a475831f8156a22fd64c97cf731d8a79793049", "size": "2322", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2585" }, { "name": "HTML", "bytes": "4014" }, { "name": "JavaScript", "bytes": "8998" } ], "symlink_target": "" }
set -o verbose soname=heater.so SOURCE=heater.c # gcc -c -Wall ./$SOURCE # Create SO gcc -Wall -shared -Wl,-soname,$soname -o ./$soname -fPIC ./$SOURCE
{ "content_hash": "cf761175cb5fd37dcc4f03b57f140f5c", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 66, "avg_line_length": 19.25, "alnum_prop": 0.6753246753246753, "repo_name": "zutshi/S3CAMX", "id": "c2ed2dbc5a4c544e91f4b942d8cd9f3866423cda", "size": "174", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/heater/compile.sh", "mode": "33261", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "6988" }, { "name": "Matlab", "bytes": "41830" }, { "name": "Python", "bytes": "621726" }, { "name": "Shell", "bytes": "11798" } ], "symlink_target": "" }
package com.microsoft.azure.management.network.v2018_08_01.implementation; import com.microsoft.azure.arm.resources.models.implementation.GroupableResourceCoreImpl; import com.microsoft.azure.management.network.v2018_08_01.BgpServiceCommunity; import rx.Observable; import java.util.List; import com.microsoft.azure.management.network.v2018_08_01.BGPCommunity; class BgpServiceCommunityImpl extends GroupableResourceCoreImpl<BgpServiceCommunity, BgpServiceCommunityInner, BgpServiceCommunityImpl, NetworkManager> implements BgpServiceCommunity { BgpServiceCommunityImpl(String name, BgpServiceCommunityInner inner, NetworkManager manager) { super(name, inner, manager); } @Override public Observable<BgpServiceCommunity> createResourceAsync() { BgpServiceCommunitiesInner client = this.manager().inner().bgpServiceCommunities(); return null; // NOP createResourceAsync implementation as create is not supported } @Override public Observable<BgpServiceCommunity> updateResourceAsync() { BgpServiceCommunitiesInner client = this.manager().inner().bgpServiceCommunities(); return null; // NOP updateResourceAsync implementation as update is not supported } @Override protected Observable<BgpServiceCommunityInner> getInnerAsync() { BgpServiceCommunitiesInner client = this.manager().inner().bgpServiceCommunities(); return null; // NOP getInnerAsync implementation as get is not supported } @Override public List<BGPCommunity> bgpCommunities() { return this.inner().bgpCommunities(); } @Override public String serviceName() { return this.inner().serviceName(); } }
{ "content_hash": "9d4b88f2b071db61cd9dc3eed79cee6b", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 184, "avg_line_length": 37.26086956521739, "alnum_prop": 0.7596266044340724, "repo_name": "selvasingh/azure-sdk-for-java", "id": "0329fcd588eda6b2f6769d8ea68576c134723c68", "size": "1944", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sdk/network/mgmt-v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/BgpServiceCommunityImpl.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "29891970" }, { "name": "JavaScript", "bytes": "6198" }, { "name": "PowerShell", "bytes": "160" }, { "name": "Shell", "bytes": "609" } ], "symlink_target": "" }
USE :schemaName; --peptide-- CREATE INDEX idx_peptide_id ON peptide(peptide_id); CREATE INDEX idx_sequence_id ON peptide(sequence_id); --CREATE INDEX idx_start_pos ON peptide(start_pos); --CREATE INDEX idx_end_pos ON peptide(end_pos); CREATE INDEX idx_peptide_mass ON peptide(mass); --protein2sequence CREATE INDEX idx_protein2sequence_protein_id ON protein2sequence(protein_id); CREATE INDEX idx_protein2sequence_sequence_id ON protein2sequence(sequence_id);
{ "content_hash": "57623f199bf29fb1bdaf5ce379a3229b", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 79, "avg_line_length": 39.5, "alnum_prop": 0.7721518987341772, "repo_name": "compomics/compomics-sigpep", "id": "9f9807869c559af01f90684a2baa123351bec9e0", "size": "474", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sigpep-persistence/src/main/resources/sql/create_indices.sql", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "22665" }, { "name": "Java", "bytes": "1292609" }, { "name": "R", "bytes": "17950" }, { "name": "Shell", "bytes": "568" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="it"> <head> <!-- Generated by javadoc (1.8.0_222) on Thu Jan 23 18:46:06 CET 2020 --> <title>it.unical.mat.embasp.base Class Hierarchy</title> <meta name="date" content="2020-01-23"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="it.unical.mat.embasp.base Class Hierarchy"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li><a href="../../../../../it/unical/mat/embasp/languages/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?it/unical/mat/embasp/base/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 class="title">Hierarchy For Package it.unical.mat.embasp.base</h1> <span class="packageHierarchyLabel">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="../../../../../overview-tree.html">All Packages</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.Object <ul> <li type="circle">it.unical.mat.embasp.base.<a href="../../../../../it/unical/mat/embasp/base/Handler.html" title="class in it.unical.mat.embasp.base"><span class="typeNameLink">Handler</span></a></li> <li type="circle">it.unical.mat.embasp.base.<a href="../../../../../it/unical/mat/embasp/base/InputProgram.html" title="class in it.unical.mat.embasp.base"><span class="typeNameLink">InputProgram</span></a></li> <li type="circle">it.unical.mat.embasp.base.<a href="../../../../../it/unical/mat/embasp/base/OptionDescriptor.html" title="class in it.unical.mat.embasp.base"><span class="typeNameLink">OptionDescriptor</span></a></li> <li type="circle">it.unical.mat.embasp.base.<a href="../../../../../it/unical/mat/embasp/base/Output.html" title="class in it.unical.mat.embasp.base"><span class="typeNameLink">Output</span></a> (implements java.lang.Cloneable)</li> </ul> </li> </ul> <h2 title="Interface Hierarchy">Interface Hierarchy</h2> <ul> <li type="circle">it.unical.mat.embasp.base.<a href="../../../../../it/unical/mat/embasp/base/Callback.html" title="interface in it.unical.mat.embasp.base"><span class="typeNameLink">Callback</span></a></li> <li type="circle">it.unical.mat.embasp.base.<a href="../../../../../it/unical/mat/embasp/base/Service.html" title="interface in it.unical.mat.embasp.base"><span class="typeNameLink">Service</span></a></li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li><a href="../../../../../it/unical/mat/embasp/languages/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?it/unical/mat/embasp/base/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "58f6b9919c04ff1a4ed7428c669ab2f4", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 232, "avg_line_length": 39.38620689655173, "alnum_prop": 0.6242339345123445, "repo_name": "DeMaCS-UNICAL/embasp_website", "id": "d64ec687bd5143ecfb9a4423337a839db8808628", "size": "5711", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "javadoc/it/unical/mat/embasp/base/package-tree.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "532404" }, { "name": "JavaScript", "bytes": "6121" } ], "symlink_target": "" }
<?php /** * Variance * * @phpstub * * @param array $real * @param integer $timePeriod * @param float $nbDev * * @return array Returns an array with calculated data or false on failure. */ function trader_var($real, $timePeriod = NULL, $nbDev = NULL) { }
{ "content_hash": "cb9d6d472afcdc9dae8ae62f921ad975", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 75, "avg_line_length": 16.5, "alnum_prop": 0.6515151515151515, "repo_name": "schmittjoh/php-stubs", "id": "bba3403159c4efb9e8cf732371e8c6ca650d1e2d", "size": "264", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "res/php/trader/functions/trader-var.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "2203628" } ], "symlink_target": "" }
import { Component } from '@angular/core'; @Component({ selector: 'code-editor-demo', styleUrls: ['./code-editor-demo.component.scss'], templateUrl: './code-editor-demo.component.html', }) export class CodeEditorDemoComponent {}
{ "content_hash": "73224ca63e0a422cfb0605d8679c95ae", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 51, "avg_line_length": 29.5, "alnum_prop": 0.7161016949152542, "repo_name": "Teradata/covalent", "id": "8a449433bd2052d1777b6728603c6ebd498fff35", "size": "236", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "apps/docs-app/src/app/content/components/component-demos/code-editor/demos/code-editor-demo.component.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "25936" }, { "name": "HTML", "bytes": "400615" }, { "name": "JavaScript", "bytes": "142209" }, { "name": "SCSS", "bytes": "375607" }, { "name": "Shell", "bytes": "1377" }, { "name": "TypeScript", "bytes": "1653078" } ], "symlink_target": "" }
package service import ( "reflect" "testing" "k8s.io/dashboard/api/pkg/resource/endpoint" "k8s.io/dashboard/api/pkg/resource/pod" v1 "k8s.io/api/core/v1" metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes/fake" "k8s.io/dashboard/api/pkg/api" "k8s.io/dashboard/api/pkg/resource/common" "k8s.io/dashboard/api/pkg/resource/dataselect" ) func TestGetServiceList(t *testing.T) { cases := []struct { serviceList *v1.ServiceList expectedActions []string expected *ServiceList }{ { serviceList: &v1.ServiceList{ Items: []v1.Service{ {ObjectMeta: metaV1.ObjectMeta{ Name: "svc-1", Namespace: "ns-1", Labels: map[string]string{}, }}, }}, expectedActions: []string{"list"}, expected: &ServiceList{ ListMeta: api.ListMeta{TotalItems: 1}, Services: []Service{ { ObjectMeta: api.ObjectMeta{ Name: "svc-1", Namespace: "ns-1", Labels: map[string]string{}, }, TypeMeta: api.TypeMeta{Kind: api.ResourceKindService}, InternalEndpoint: common.Endpoint{Host: "svc-1.ns-1"}, ExternalEndpoints: []common.Endpoint{}, }, }, Errors: []error{}, }, }, } for _, c := range cases { fakeClient := fake.NewSimpleClientset(c.serviceList) actual, _ := GetServiceList(fakeClient, common.NewNamespaceQuery(nil), dataselect.NoDataSelect) actions := fakeClient.Actions() if len(actions) != len(c.expectedActions) { t.Errorf("Unexpected actions: %v, expected %d actions got %d", actions, len(c.expectedActions), len(actions)) continue } for i, verb := range c.expectedActions { if actions[i].GetVerb() != verb { t.Errorf("Unexpected action: %+v, expected %s", actions[i], verb) } } if !reflect.DeepEqual(actual, c.expected) { t.Errorf("GetServiceList(client) == got\n%#v, expected\n %#v", actual, c.expected) } } } func TestToServiceDetail(t *testing.T) { cases := []struct { service *v1.Service eventList common.EventList podList pod.PodList endpointList endpoint.EndpointList expected ServiceDetail }{ { service: &v1.Service{}, eventList: common.EventList{}, podList: pod.PodList{}, endpointList: endpoint.EndpointList{}, expected: ServiceDetail{ Service: Service{ TypeMeta: api.TypeMeta{Kind: api.ResourceKindService}, ExternalEndpoints: []common.Endpoint{}, }, }, }, { service: &v1.Service{ ObjectMeta: metaV1.ObjectMeta{ Name: "test-service", Namespace: "test-namespace", }}, expected: ServiceDetail{ Service: Service{ ObjectMeta: api.ObjectMeta{ Name: "test-service", Namespace: "test-namespace", }, TypeMeta: api.TypeMeta{Kind: api.ResourceKindService}, InternalEndpoint: common.Endpoint{Host: "test-service.test-namespace"}, ExternalEndpoints: []common.Endpoint{}, }, }, }, } for _, c := range cases { actual := toServiceDetail(c.service, c.endpointList, nil) if !reflect.DeepEqual(actual, c.expected) { t.Errorf("ToServiceDetail(%#v) == \ngot %#v, \nexpected %#v", c.service, actual, c.expected) } } } func TestToService(t *testing.T) { cases := []struct { service *v1.Service expected Service }{ { service: &v1.Service{}, expected: Service{ TypeMeta: api.TypeMeta{Kind: api.ResourceKindService}, ExternalEndpoints: []common.Endpoint{}, }, }, { service: &v1.Service{ ObjectMeta: metaV1.ObjectMeta{ Name: "test-service", Namespace: "test-namespace", }}, expected: Service{ ObjectMeta: api.ObjectMeta{ Name: "test-service", Namespace: "test-namespace", }, TypeMeta: api.TypeMeta{Kind: api.ResourceKindService}, InternalEndpoint: common.Endpoint{Host: "test-service.test-namespace"}, ExternalEndpoints: []common.Endpoint{}, }, }, } for _, c := range cases { actual := toService(c.service) if !reflect.DeepEqual(actual, c.expected) { t.Errorf("ToService(%#v) == \ngot %#v, \nexpected %#v", c.service, actual, c.expected) } } }
{ "content_hash": "05b6b040c885190b636430798ac7d8a9", "timestamp": "", "source": "github", "line_count": 159, "max_line_length": 97, "avg_line_length": 26.163522012578618, "alnum_prop": 0.6331730769230769, "repo_name": "kubernetes/dashboard", "id": "255c982a0713f78c1e9de4b30b5583bd3f2276ca", "size": "4761", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "modules/api/pkg/resource/service/list_test.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "7104" }, { "name": "Go", "bytes": "1250542" }, { "name": "HTML", "bytes": "451845" }, { "name": "JavaScript", "bytes": "3927" }, { "name": "Makefile", "bytes": "17988" }, { "name": "SCSS", "bytes": "67993" }, { "name": "Shell", "bytes": "17925" }, { "name": "Smarty", "bytes": "3598" }, { "name": "TypeScript", "bytes": "846357" } ], "symlink_target": "" }
using NetworkSocket.Fast.Attributes; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Server { /// <summary> /// 登录特性 /// </summary> public class LoginAttribute : FilterAttribute { public override bool OnExecuting(NetworkSocket.SocketAsync<NetworkSocket.Fast.FastPacket> client, NetworkSocket.Fast.FastPacket packet) { return client.Tag.IsValidated; } } }
{ "content_hash": "4d799f4e5ddb42bf261ba48120957923", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 143, "avg_line_length": 24.473684210526315, "alnum_prop": 0.6881720430107527, "repo_name": "GISwilson/NetworksSocketDemo", "id": "a80f6e9af38759b14b0ea67f6e96e4cb1bb22b66", "size": "475", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Demo/Server/LoginAttribute.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "141126" } ], "symlink_target": "" }
const path = require('path') const algoliasearch = require('algoliasearch') const glob = require('glob') const client = algoliasearch( process.env.ALGOLIA_APP_ID, process.env.ALGOLIA_ADMIN_API_KEY ) const indexName = process.env.ALGOLIA_INDEX_NAME || 'minimo_site' const publicDir = path.resolve(process.argv[2] || 'public') const objectsPaths = glob.sync('**/search/index.json', { cwd: publicDir, absolute: true }) const indicesInfo = objectsPaths.map(objectsPath => ({ path: objectsPath, name: `${indexName}${objectsPath .slice(publicDir.length, -'/search/index.json'.length) .replace('/', '_')}` })) indicesInfo.forEach(indexInfo => { let objects = require(indexInfo.path) objects.forEach(object => { object.objectID = object.href }) let index = client.initIndex(indexInfo.name) index.addObjects(objects, (err, _content) => { if (err) console.error(err.toString()) else console.log( `Algolia Index Generated for: ${indexInfo.path.replace(publicDir, '')}` ) }) })
{ "content_hash": "53520d98540fda3f84e00f9192d254c4", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 79, "avg_line_length": 24.738095238095237, "alnum_prop": 0.6756496631376323, "repo_name": "MunifTanjim/minimo", "id": "a4c24aba3f883a4f73f73d0a74529bddbeedb6d4", "size": "1039", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "scripts/generate-search-index-algolia.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "17" }, { "name": "HTML", "bytes": "48398" }, { "name": "JavaScript", "bytes": "16983" }, { "name": "SCSS", "bytes": "26827" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.11"/> <title>V8 API Reference Guide for node.js v7.5.0: Class Members</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for node.js v7.5.0 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.11 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li class="current"><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="navrow3" class="tabs2"> <ul class="tablist"> <li class="current"><a href="functions.html"><span>All</span></a></li> <li><a href="functions_func.html"><span>Functions</span></a></li> <li><a href="functions_vars.html"><span>Variables</span></a></li> <li><a href="functions_type.html"><span>Typedefs</span></a></li> <li><a href="functions_enum.html"><span>Enumerations</span></a></li> </ul> </div> <div id="navrow4" class="tabs3"> <ul class="tablist"> <li><a href="functions.html#index_a"><span>a</span></a></li> <li><a href="functions_b.html#index_b"><span>b</span></a></li> <li><a href="functions_c.html#index_c"><span>c</span></a></li> <li><a href="functions_d.html#index_d"><span>d</span></a></li> <li><a href="functions_e.html#index_e"><span>e</span></a></li> <li><a href="functions_f.html#index_f"><span>f</span></a></li> <li><a href="functions_g.html#index_g"><span>g</span></a></li> <li><a href="functions_h.html#index_h"><span>h</span></a></li> <li><a href="functions_i.html#index_i"><span>i</span></a></li> <li><a href="functions_j.html#index_j"><span>j</span></a></li> <li><a href="functions_k.html#index_k"><span>k</span></a></li> <li><a href="functions_l.html#index_l"><span>l</span></a></li> <li><a href="functions_m.html#index_m"><span>m</span></a></li> <li><a href="functions_n.html#index_n"><span>n</span></a></li> <li class="current"><a href="functions_o.html#index_o"><span>o</span></a></li> <li><a href="functions_p.html#index_p"><span>p</span></a></li> <li><a href="functions_r.html#index_r"><span>r</span></a></li> <li><a href="functions_s.html#index_s"><span>s</span></a></li> <li><a href="functions_t.html#index_t"><span>t</span></a></li> <li><a href="functions_u.html#index_u"><span>u</span></a></li> <li><a href="functions_v.html#index_v"><span>v</span></a></li> <li><a href="functions_w.html#index_w"><span>w</span></a></li> <li><a href="functions_0x7e.html#index_0x7e"><span>~</span></a></li> </ul> </div> </div><!-- top --> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> <div class="textblock">Here is a list of all documented class members with links to the class documentation for each member:</div> <h3><a class="anchor" id="index_o"></a>- o -</h3><ul> <li>operator!=() : <a class="el" href="classv8_1_1Local.html#a5739e619db6d06074d02d99a1b1c79d7">v8::Local&lt; T &gt;</a> </li> <li>operator=() : <a class="el" href="classv8_1_1Global.html#a9d3d7d8f10ad23e413f2027cc15ab209">v8::Global&lt; T &gt;</a> </li> <li>operator==() : <a class="el" href="classv8_1_1Local.html#a85570b6ff0a3328627d1b7bc11513a5b">v8::Local&lt; T &gt;</a> </li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.11 </small></address> </body> </html>
{ "content_hash": "821b3cf9a7fd85b18c55f23dd01a2ea8", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 154, "avg_line_length": 45.72222222222222, "alnum_prop": 0.6227217496962333, "repo_name": "v8-dox/v8-dox.github.io", "id": "de2c3b3ca6356d9f19b2fc664165f08a004cb620", "size": "6584", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "da59a57/html/functions_o.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
import React from 'react' import PropTypes from 'prop-types' import { Image, Keyboard, StyleSheet, Text, TouchableOpacity, TouchableWithoutFeedback, View, } from 'react-native' import {Field, reduxForm} from 'redux-form' import axios from 'axios' import {connect} from 'react-redux' import {selectBackend, selectEmail, setCredentials} from '@inab/shared' // eslint-disable-next-line import/named import {LinearGradient} from 'expo' import {TextInputField} from './fields/TextInputField' const mapStateToProps = state => ({ initialValues: { backend: selectBackend(state), email: selectEmail(state), }, }) const mapDispatchToProps = { setCredentials, } @connect( mapStateToProps, mapDispatchToProps ) @reduxForm({form: 'login', enableReinitialize: true}) export class LoginScreen extends React.Component { static propTypes = { setCredentials: PropTypes.func.isRequired, handleSubmit: PropTypes.func.isRequired, } onSubmit = data => { this.props.setCredentials({ backend: data.backend, email: data.email, }) this.performLogin(data.backend, data.email, data.password) } performLogin = (backend, email, password) => { axios({ url: `${backend}/auth/login`, method: 'POST', data: { email, password, }, }) .then(response => { if (response.headers.authorization) { // Dispatch save token this.props.setCredentials({token: response.headers.authorization}) } else { alert('Login error') } }) .catch(err => alert('Login error: ' + err.toString())) } render() { return ( <TouchableWithoutFeedback onPress={Keyboard.dismiss}> <LinearGradient colors={['#ABDCFF', '#0396FF']} style={styles.container} start={[0.25, 0.0]} end={[1.0, 1.0]} > <View style={styles.logoContainer}> <Image source={require('../assets/icons/login.png')} /> </View> <View style={styles.fieldWrapper}> <Field name="backend" component={TextInputField} placeholder="Server" autoCapitalize="none" placeholderTextColor="rgba(255,255,255,0.6)" style={styles.field} /> </View> <View style={styles.fieldWrapper}> <Field name="email" component={TextInputField} placeholder="Email" autoCapitalize="none" keyboardType="email-address" placeholderTextColor="rgba(255,255,255,0.6)" style={styles.field} /> </View> <View style={styles.fieldWrapper}> <Field name="password" component={TextInputField} placeholder="Password" secureTextEntry placeholderTextColor="rgba(255,255,255,0.6)" style={styles.field} /> </View> <TouchableOpacity onPress={this.props.handleSubmit(this.onSubmit)} style={styles.button} > <Text style={styles.buttonText}>Login</Text> </TouchableOpacity> </LinearGradient> </TouchableWithoutFeedback> ) } } const verticalSpacing = 12 const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', }, logoContainer: { alignItems: 'center', marginBottom: 3 * verticalSpacing, }, field: { height: 40, color: 'white', }, fieldWrapper: { marginHorizontal: 24, marginVertical: verticalSpacing, borderBottomColor: 'rgba(255,255,255,.6)', borderBottomWidth: StyleSheet.hairlineWidth, }, button: { alignItems: 'center', backgroundColor: 'rgba(255,255,255,.1)', padding: verticalSpacing, marginHorizontal: 24, marginTop: verticalSpacing, }, buttonText: { fontSize: 18, color: 'white', }, })
{ "content_hash": "2b78ea8d049eea3483176d1f296adaf2", "timestamp": "", "source": "github", "line_count": 166, "max_line_length": 76, "avg_line_length": 24.397590361445783, "alnum_prop": 0.5834567901234567, "repo_name": "hwaterke/inab", "id": "2865b61192b478a22e93dcfc3dbda9ca2ab7e6bb", "size": "4050", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "packages/native/src/components/LoginScreen.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "119" }, { "name": "Dockerfile", "bytes": "505" }, { "name": "HTML", "bytes": "534" }, { "name": "JavaScript", "bytes": "313056" }, { "name": "Shell", "bytes": "890" }, { "name": "TypeScript", "bytes": "2469" } ], "symlink_target": "" }
package com.hazelcast.client.replicatedmap; import com.hazelcast.client.config.ClientConfig; import com.hazelcast.client.config.ClientNetworkConfig; import com.hazelcast.client.test.TestHazelcastFactory; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.ReplicatedMap; import com.hazelcast.nio.Address; import com.hazelcast.test.AssertTask; import com.hazelcast.test.HazelcastParallelClassRunner; import com.hazelcast.test.HazelcastTestSupport; import com.hazelcast.test.annotation.ParallelTest; import com.hazelcast.test.annotation.QuickTest; import org.junit.After; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import java.lang.reflect.Field; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @RunWith(HazelcastParallelClassRunner.class) @Category({QuickTest.class, ParallelTest.class}) public class DummyClientReplicatedMapTest extends HazelcastTestSupport { private TestHazelcastFactory hazelcastFactory = new TestHazelcastFactory(); @After public void cleanup() { hazelcastFactory.terminateAll(); } @Test public void testGet() throws Exception { HazelcastInstance instance1 = hazelcastFactory.newHazelcastInstance(); HazelcastInstance instance2 = hazelcastFactory.newHazelcastInstance(); HazelcastInstance client = hazelcastFactory.newHazelcastClient(getClientConfig(instance1)); ReplicatedMap<String, String> map = client.getReplicatedMap(randomMapName()); String key = generateKeyOwnedBy(instance2); int partitionId = instance2.getPartitionService().getPartition(key).getPartitionId(); setPartitionId(map, partitionId); String value = randomString(); map.put(key, value); assertEquals(value, map.get(key)); } @Test public void testIsEmpty() throws Exception { HazelcastInstance instance1 = hazelcastFactory.newHazelcastInstance(); HazelcastInstance instance2 = hazelcastFactory.newHazelcastInstance(); HazelcastInstance client = hazelcastFactory.newHazelcastClient(getClientConfig(instance1)); final ReplicatedMap<String, String> map = client.getReplicatedMap(randomMapName()); String key = generateKeyOwnedBy(instance2); int partitionId = instance1.getPartitionService().getPartition(key).getPartitionId(); setPartitionId(map, partitionId); String value = randomString(); map.put(key, value); assertTrueEventually(new AssertTask() { @Override public void run() { assertFalse(map.isEmpty()); } }); } @Test public void testKeySet() throws Exception { HazelcastInstance instance1 = hazelcastFactory.newHazelcastInstance(); HazelcastInstance instance2 = hazelcastFactory.newHazelcastInstance(); HazelcastInstance client = hazelcastFactory.newHazelcastClient(getClientConfig(instance1)); final ReplicatedMap<String, String> map = client.getReplicatedMap(randomMapName()); final String key = generateKeyOwnedBy(instance2); final String value = randomString(); int partitionId = instance1.getPartitionService().getPartition(key).getPartitionId(); setPartitionId(map, partitionId); map.put(key, value); assertTrueEventually(new AssertTask() { @Override public void run() { Collection<String> keySet = map.keySet(); assertEquals(1, keySet.size()); assertEquals(key, keySet.iterator().next()); } }); } @Test public void testEntrySet() throws Exception { HazelcastInstance instance1 = hazelcastFactory.newHazelcastInstance(); HazelcastInstance instance2 = hazelcastFactory.newHazelcastInstance(); HazelcastInstance client = hazelcastFactory.newHazelcastClient(getClientConfig(instance1)); final ReplicatedMap<String, String> map = client.getReplicatedMap(randomMapName()); final String key = generateKeyOwnedBy(instance2); final String value = randomString(); int partitionId = instance1.getPartitionService().getPartition(key).getPartitionId(); setPartitionId(map, partitionId); map.put(key, value); assertTrueEventually(new AssertTask() { @Override public void run() { Set<Map.Entry<String, String>> entries = map.entrySet(); assertEquals(1, entries.size()); Map.Entry<String, String> entry = entries.iterator().next(); assertEquals(key, entry.getKey()); assertEquals(value, entry.getValue()); } }); } @Test public void testValues() throws Exception { HazelcastInstance instance1 = hazelcastFactory.newHazelcastInstance(); HazelcastInstance instance2 = hazelcastFactory.newHazelcastInstance(); HazelcastInstance client = hazelcastFactory.newHazelcastClient(getClientConfig(instance1)); final ReplicatedMap<String, String> map = client.getReplicatedMap(randomMapName()); final String key = generateKeyOwnedBy(instance2); final String value = randomString(); int partitionId = instance1.getPartitionService().getPartition(key).getPartitionId(); setPartitionId(map, partitionId); map.put(key, value); assertTrueEventually(new AssertTask() { @Override public void run() { Collection<String> values = map.values(); assertEquals(1, values.size()); assertEquals(value, values.iterator().next()); } }); } @Test public void testContainsKey() throws Exception { HazelcastInstance instance1 = hazelcastFactory.newHazelcastInstance(); HazelcastInstance instance2 = hazelcastFactory.newHazelcastInstance(); HazelcastInstance client = hazelcastFactory.newHazelcastClient(getClientConfig(instance1)); ReplicatedMap<String, String> map = client.getReplicatedMap(randomMapName()); final String key = generateKeyOwnedBy(instance2); int partitionId = instance1.getPartitionService().getPartition(key).getPartitionId(); setPartitionId(map, partitionId); String value = randomString(); map.put(key, value); assertTrue(map.containsKey(key)); } @Test public void testContainsValue() throws Exception { HazelcastInstance instance1 = hazelcastFactory.newHazelcastInstance(); HazelcastInstance instance2 = hazelcastFactory.newHazelcastInstance(); HazelcastInstance client = hazelcastFactory.newHazelcastClient(getClientConfig(instance1)); final ReplicatedMap<String, String> map = client.getReplicatedMap(randomMapName()); final String key = generateKeyOwnedBy(instance2); int partitionId = instance1.getPartitionService().getPartition(key).getPartitionId(); setPartitionId(map, partitionId); final String value = randomString(); map.put(key, value); assertTrueEventually(new AssertTask() { @Override public void run() { assertTrue(map.containsValue(value)); } }); } @Test public void testSize() throws Exception { HazelcastInstance instance1 = hazelcastFactory.newHazelcastInstance(); HazelcastInstance instance2 = hazelcastFactory.newHazelcastInstance(); HazelcastInstance client = hazelcastFactory.newHazelcastClient(getClientConfig(instance1)); final ReplicatedMap<String, String> map = client.getReplicatedMap(randomMapName()); String key = generateKeyOwnedBy(instance2); int partitionId = instance1.getPartitionService().getPartition(key).getPartitionId(); setPartitionId(map, partitionId); String value = randomString(); map.put(key, value); assertTrueEventually(new AssertTask() { @Override public void run() { assertEquals(1, map.size()); } }); } @Test public void testClear() throws Exception { HazelcastInstance instance1 = hazelcastFactory.newHazelcastInstance(); HazelcastInstance instance2 = hazelcastFactory.newHazelcastInstance(); HazelcastInstance client = hazelcastFactory.newHazelcastClient(getClientConfig(instance1)); final ReplicatedMap<String, String> map = client.getReplicatedMap(randomMapName()); String key = generateKeyOwnedBy(instance2); int partitionId = instance1.getPartitionService().getPartition(key).getPartitionId(); setPartitionId(map, partitionId); String value = randomString(); map.put(key, value); map.clear(); assertTrueEventually(new AssertTask() { @Override public void run() { assertEquals(0, map.size()); } }); } @Test public void testRemove() throws Exception { HazelcastInstance instance1 = hazelcastFactory.newHazelcastInstance(); HazelcastInstance instance2 = hazelcastFactory.newHazelcastInstance(); HazelcastInstance client = hazelcastFactory.newHazelcastClient(getClientConfig(instance1)); final ReplicatedMap<String, String> map = client.getReplicatedMap(randomMapName()); String key = generateKeyOwnedBy(instance2); int partitionId = instance1.getPartitionService().getPartition(key).getPartitionId(); setPartitionId(map, partitionId); String value = randomString(); map.put(key, value); map.remove(key); assertTrueEventually(new AssertTask() { @Override public void run() { assertEquals(0, map.size()); } }); } @Test public void testPutAll() throws Exception { HazelcastInstance instance1 = hazelcastFactory.newHazelcastInstance(); HazelcastInstance instance2 = hazelcastFactory.newHazelcastInstance(); HazelcastInstance client = hazelcastFactory.newHazelcastClient(getClientConfig(instance1)); final ReplicatedMap<String, String> map = client.getReplicatedMap(randomMapName()); String key = generateKeyOwnedBy(instance2); int partitionId = instance1.getPartitionService().getPartition(key).getPartitionId(); setPartitionId(map, partitionId); String value = randomString(); HashMap<String, String> m = new HashMap<String, String>(); m.put(key, value); map.putAll(m); assertEquals(value, map.get(key)); } private ClientConfig getClientConfig(HazelcastInstance instance) { Address address = instance.getCluster().getLocalMember().getAddress(); String addressString = address.getHost() + ":" + address.getPort(); ClientConfig dummyClientConfig = new ClientConfig(); ClientNetworkConfig networkConfig = new ClientNetworkConfig(); networkConfig.setSmartRouting(false); networkConfig.addAddress(addressString); dummyClientConfig.setNetworkConfig(networkConfig); return dummyClientConfig; } private void setPartitionId(ReplicatedMap<String, String> map, int partitionId) throws Exception { Class<?> clazz = map.getClass(); Field targetPartitionId = clazz.getDeclaredField("targetPartitionId"); targetPartitionId.setAccessible(true); targetPartitionId.setInt(map, partitionId); } }
{ "content_hash": "dc9b1f62ddc3595a72ac678937c8dc07", "timestamp": "", "source": "github", "line_count": 292, "max_line_length": 102, "avg_line_length": 40.42123287671233, "alnum_prop": 0.6868592730661697, "repo_name": "tombujok/hazelcast", "id": "88f4dc02c5c4a54d94b78bd06d8e9e93dcec4c2c", "size": "12428", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "hazelcast-client/src/test/java/com/hazelcast/client/replicatedmap/DummyClientReplicatedMapTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1449" }, { "name": "Java", "bytes": "33147517" }, { "name": "Shell", "bytes": "12286" } ], "symlink_target": "" }
#include "cytypes.h" #include "LcdRS.h" /* APIs are not generated for P15[7:6] on PSoC 5 */ #if !(CY_PSOC5A &&\ LcdRS__PORT == 15 && ((LcdRS__MASK & 0xC0) != 0)) /******************************************************************************* * Function Name: LcdRS_Write ******************************************************************************** * * Summary: * Assign a new value to the digital port's data output register. * * Parameters: * prtValue: The value to be assigned to the Digital Port. * * Return: * None * *******************************************************************************/ void LcdRS_Write(uint8 value) { uint8 staticBits = (LcdRS_DR & (uint8)(~LcdRS_MASK)); LcdRS_DR = staticBits | ((uint8)(value << LcdRS_SHIFT) & LcdRS_MASK); } /******************************************************************************* * Function Name: LcdRS_SetDriveMode ******************************************************************************** * * Summary: * Change the drive mode on the pins of the port. * * Parameters: * mode: Change the pins to one of the following drive modes. * * LcdRS_DM_STRONG Strong Drive * LcdRS_DM_OD_HI Open Drain, Drives High * LcdRS_DM_OD_LO Open Drain, Drives Low * LcdRS_DM_RES_UP Resistive Pull Up * LcdRS_DM_RES_DWN Resistive Pull Down * LcdRS_DM_RES_UPDWN Resistive Pull Up/Down * LcdRS_DM_DIG_HIZ High Impedance Digital * LcdRS_DM_ALG_HIZ High Impedance Analog * * Return: * None * *******************************************************************************/ void LcdRS_SetDriveMode(uint8 mode) { CyPins_SetPinDriveMode(LcdRS_0, mode); } /******************************************************************************* * Function Name: LcdRS_Read ******************************************************************************** * * Summary: * Read the current value on the pins of the Digital Port in right justified * form. * * Parameters: * None * * Return: * Returns the current value of the Digital Port as a right justified number * * Note: * Macro LcdRS_ReadPS calls this function. * *******************************************************************************/ uint8 LcdRS_Read(void) { return (LcdRS_PS & LcdRS_MASK) >> LcdRS_SHIFT; } /******************************************************************************* * Function Name: LcdRS_ReadDataReg ******************************************************************************** * * Summary: * Read the current value assigned to a Digital Port's data output register * * Parameters: * None * * Return: * Returns the current value assigned to the Digital Port's data output register * *******************************************************************************/ uint8 LcdRS_ReadDataReg(void) { return (LcdRS_DR & LcdRS_MASK) >> LcdRS_SHIFT; } /* If Interrupts Are Enabled for this Pins component */ #if defined(LcdRS_INTSTAT) /******************************************************************************* * Function Name: LcdRS_ClearInterrupt ******************************************************************************** * Summary: * Clears any active interrupts attached to port and returns the value of the * interrupt status register. * * Parameters: * None * * Return: * Returns the value of the interrupt status register * *******************************************************************************/ uint8 LcdRS_ClearInterrupt(void) { return (LcdRS_INTSTAT & LcdRS_MASK) >> LcdRS_SHIFT; } #endif /* If Interrupts Are Enabled for this Pins component */ #endif /* CY_PSOC5A... */ /* [] END OF FILE */
{ "content_hash": "840aa94fe1b49d08285a91bc483c9c04", "timestamp": "", "source": "github", "line_count": 132, "max_line_length": 84, "avg_line_length": 28.507575757575758, "alnum_prop": 0.44220037204358226, "repo_name": "jh247247/ECE3091-chickybot", "id": "9c86b4735eda3fdc8a9751d94faeb92cc7b27c55", "size": "4444", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "chickybot.cydsn/Generated_Source/PSoC5/LcdRS.c", "mode": "33188", "license": "mit", "language": [ { "name": "Arduino", "bytes": "2608" }, { "name": "Assembly", "bytes": "332286" }, { "name": "C", "bytes": "4794063" }, { "name": "C#", "bytes": "54260" }, { "name": "C++", "bytes": "1184711" }, { "name": "HTML", "bytes": "430702" }, { "name": "OpenEdge ABL", "bytes": "199017" }, { "name": "SourcePawn", "bytes": "916896" }, { "name": "Verilog", "bytes": "111722" } ], "symlink_target": "" }
<?php /* Safe sample input : use exec to execute the script /tmp/tainted.php and store the output in $tainted sanitize : cast via + = 0 construction : interpretation */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ $script = "/tmp/tainted.php"; exec($script, $result, $return); $tainted = $result[0]; $tainted += 0 ; $query = "SELECT * FROM COURSE c WHERE c.id IN (SELECT idcourse FROM REGISTRATION WHERE idstudent= $tainted )"; $conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); // Connection to the database (address, user, password) mysql_select_db('dbname') ; echo "query : ". $query ."<br /><br />" ; $res = mysql_query($query); //execution while($data =mysql_fetch_array($res)){ print_r($data) ; echo "<br />" ; } mysql_close($conn); ?>
{ "content_hash": "be3e86a5aa38916279f26f8ca3f264c1", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 123, "avg_line_length": 24.742424242424242, "alnum_prop": 0.7391304347826086, "repo_name": "stivalet/PHP-Vulnerability-test-suite", "id": "a9b4be7e85012993007dc840706687b0c4c9c521", "size": "1633", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Injection/CWE_89/safe/CWE_89__exec__CAST-cast_int_sort_of__multiple_select-interpretation.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "64184004" } ], "symlink_target": "" }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Release notes &#8212; MNE 0.17.1 documentation</title> <link rel="stylesheet" href="../../_static/bootstrap-sphinx.css" type="text/css" /> <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../../_static/gallery.css" /> <link rel="stylesheet" type="text/css" href="../../_static/reset-syntax.css" /> <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script> <script type="text/javascript" src="../../_static/jquery.js"></script> <script type="text/javascript" src="../../_static/underscore.js"></script> <script type="text/javascript" src="../../_static/doctools.js"></script> <script type="text/javascript" src="../../_static/language_data.js"></script> <script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/javascript" src="../../_static/js/jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../../_static/js/jquery-fix.js"></script> <script type="text/javascript" src="../../_static/bootstrap-3.3.7/js/bootstrap.min.js"></script> <script type="text/javascript" src="../../_static/bootstrap-sphinx.js"></script> <link rel="shortcut icon" href="../../_static/favicon.ico"/> <link rel="index" title="Index" href="../../genindex.html" /> <link rel="search" title="Search" href="../../search.html" /> <script type="text/javascript" src="../../_static/copybutton.js"></script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-37225609-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <link rel="stylesheet" href="../../_static/style.css " type="text/css" /> <link rel="stylesheet" href="../../_static/font-awesome.css" type="text/css" /> <link rel="stylesheet" href="../../_static/flag-icon.css" type="text/css" /> <script type="text/javascript"> !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s); js.id=id;js.src="https://platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); </script> <script type="text/javascript"> (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })(); </script> <link rel="canonical" href="https://mne.tools/stable/index.html" /> </head><body> <div id="navbar" class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <!-- .btn-navbar is used as the toggle for collapsed navbar content --> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../../index.html"><span><img src="../../_static/mne_logo_small.png"></span> </a> <span class="navbar-text navbar-version pull-left"><b>0.17.1</b></span> </div> <div class="collapse navbar-collapse nav-collapse"> <ul class="nav navbar-nav"> <li><a href="../../getting_started.html">Install</a></li> <li><a href="../../documentation.html">Documentation</a></li> <li><a href="../../python_reference.html">API</a></li> <li><a href="../../glossary.html">Glossary</a></li> <li><a href="../../auto_examples/index.html">Examples</a></li> <li><a href="../../contributing.html">Contribute</a></li> <li class="dropdown globaltoc-container"> <a role="button" id="dLabelGlobalToc" data-toggle="dropdown" data-target="#" href="../../index.html">Site <b class="caret"></b></a> <ul class="dropdown-menu globaltoc" role="menu" aria-labelledby="dLabelGlobalToc"></ul> </li> <li class="hidden-sm"></li> </ul> <div class="navbar-form navbar-right navbar-btn dropdown btn-group-sm" style="margin-left: 20px; margin-top: 5px; margin-bottom: 5px"> <button type="button" class="btn btn-primary navbar-btn dropdown-toggle" id="dropdownMenu1" data-toggle="dropdown"> v0.17.1 <span class="caret"></span> </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenu1"> <li><a href="https://mne-tools.github.io/dev/index.html">Development</a></li> <li><a href="https://mne-tools.github.io/stable/index.html">v0.17 (stable)</a></li> <li><a href="https://mne-tools.github.io/0.16/index.html">v0.16</a></li> <li><a href="https://mne-tools.github.io/0.15/index.html">v0.15</a></li> <li><a href="https://mne-tools.github.io/0.14/index.html">v0.14</a></li> <li><a href="https://mne-tools.github.io/0.13/index.html">v0.13</a></li> <li><a href="https://mne-tools.github.io/0.12/index.html">v0.12</a></li> <li><a href="https://mne-tools.github.io/0.11/index.html">v0.11</a></li> </ul> </div> <form class="navbar-form navbar-right" action="../../search.html" method="get"> <div class="form-group"> <input type="text" name="q" class="form-control" placeholder="Search" /> </div> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> </div> <div class="container"> <div class="row"> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <p class="logo"><a href="../../index.html"> <img class="logo" src="../../_static/mne_logo_small.png" alt="Logo"/> </a></p><ul> <li><a class="reference internal" href="#">Release notes</a><ul> <li><a class="reference internal" href="#release-notes-for-mne-software-2-4">Release notes for MNE software 2.4</a><ul> <li><a class="reference internal" href="#manual">Manual</a></li> <li><a class="reference internal" href="#general-software-changes">General software changes</a></li> <li><a class="reference internal" href="#file-conversion-utilities">File conversion utilities</a></li> <li><a class="reference internal" href="#mne-browse-raw">mne_browse_raw</a></li> <li><a class="reference internal" href="#mne-analyze">mne_analyze</a></li> <li><a class="reference internal" href="#mne-make-movie">mne_make_movie</a></li> <li><a class="reference internal" href="#averaging">Averaging</a></li> </ul> </li> <li><a class="reference internal" href="#release-notes-for-mne-software-2-5">Release notes for MNE software 2.5</a><ul> <li><a class="reference internal" href="#id2">Manual</a></li> <li><a class="reference internal" href="#id3">mne_browse_raw</a></li> <li><a class="reference internal" href="#mne-epochs2mat">mne_epochs2mat</a></li> <li><a class="reference internal" href="#id4">mne_analyze</a></li> <li><a class="reference internal" href="#mne-ctf2fiff">mne_ctf2fiff</a></li> <li><a class="reference internal" href="#id5">mne_make_movie</a></li> <li><a class="reference internal" href="#mne-surf2bem">mne_surf2bem</a></li> <li><a class="reference internal" href="#mne-forward-solution">mne_forward_solution</a></li> <li><a class="reference internal" href="#mne-inverse-operator">mne_inverse_operator</a></li> <li><a class="reference internal" href="#mne-compute-raw-inverse">mne_compute_raw_inverse</a></li> <li><a class="reference internal" href="#time-range-settings">Time range settings</a></li> <li><a class="reference internal" href="#mne-change-baselines">mne_change_baselines</a></li> <li><a class="reference internal" href="#new-utilities">New utilities</a><ul> <li><a class="reference internal" href="#mne-show-fiff">mne_show_fiff</a></li> <li><a class="reference internal" href="#mne-make-cor-set">mne_make_cor_set</a></li> <li><a class="reference internal" href="#mne-compensate-data">mne_compensate_data</a></li> <li><a class="reference internal" href="#mne-insert-4d-comp">mne_insert_4D_comp</a></li> <li><a class="reference internal" href="#mne-ctf-dig2fiff">mne_ctf_dig2fiff</a></li> <li><a class="reference internal" href="#mne-kit2fiff">mne_kit2fiff</a></li> <li><a class="reference internal" href="#mne-make-derivations">mne_make_derivations</a></li> </ul> </li> <li><a class="reference internal" href="#bem-mesh-generation">BEM mesh generation</a></li> <li><a class="reference internal" href="#matlab-toolbox">Matlab toolbox</a></li> </ul> </li> <li><a class="reference internal" href="#release-notes-for-mne-software-2-6">Release notes for MNE software 2.6</a><ul> <li><a class="reference internal" href="#id6">Manual</a></li> <li><a class="reference internal" href="#command-line-options">Command-line options</a></li> <li><a class="reference internal" href="#changes-to-existing-software">Changes to existing software</a><ul> <li><a class="reference internal" href="#mne-add-patch-info">mne_add_patch_info</a></li> <li><a class="reference internal" href="#id7">mne_analyze</a></li> <li><a class="reference internal" href="#mne-average-forward-solutions">mne_average_forward_solutions</a></li> <li><a class="reference internal" href="#mne-browse-raw-and-mne-process-raw">mne_browse_raw and mne_process_raw</a></li> <li><a class="reference internal" href="#id8">mne_compute_raw_inverse</a></li> <li><a class="reference internal" href="#mne-convert-surface">mne_convert_surface</a></li> <li><a class="reference internal" href="#mne-dump-triggers">mne_dump_triggers</a></li> <li><a class="reference internal" href="#id9">mne_epochs2mat</a></li> <li><a class="reference internal" href="#id10">mne_forward_solution</a></li> <li><a class="reference internal" href="#mne-list-bem">mne_list_bem</a></li> <li><a class="reference internal" href="#id11">mne_make_cor_set</a></li> <li><a class="reference internal" href="#id12">mne_make_movie</a></li> <li><a class="reference internal" href="#mne-make-source-space">mne_make_source_space</a></li> <li><a class="reference internal" href="#mne-mdip2stc">mne_mdip2stc</a></li> <li><a class="reference internal" href="#mne-project-raw">mne_project_raw</a></li> <li><a class="reference internal" href="#mne-rename-channels">mne_rename_channels</a></li> <li><a class="reference internal" href="#mne-setup-forward-model">mne_setup_forward_model</a></li> <li><a class="reference internal" href="#mne-simu">mne_simu</a></li> <li><a class="reference internal" href="#mne-transform-points">mne_transform_points</a></li> <li><a class="reference internal" href="#id13">Matlab toolbox</a></li> </ul> </li> <li><a class="reference internal" href="#id14">New utilities</a><ul> <li><a class="reference internal" href="#mne-collect-transforms">mne_collect_transforms</a></li> <li><a class="reference internal" href="#mne-convert-dig-data">mne_convert_dig_data</a></li> <li><a class="reference internal" href="#mne-edf2fiff">mne_edf2fiff</a></li> <li><a class="reference internal" href="#mne-brain-vision2fiff">mne_brain_vision2fiff</a></li> <li><a class="reference internal" href="#mne-anonymize">mne_anonymize</a></li> <li><a class="reference internal" href="#mne-opengl-test">mne_opengl_test</a></li> <li><a class="reference internal" href="#mne-volume-data2mri">mne_volume_data2mri</a></li> <li><a class="reference internal" href="#mne-volume-source-space">mne_volume_source_space</a></li> <li><a class="reference internal" href="#mne-copy-processing-history">mne_copy_processing_history</a></li> </ul> </li> </ul> </li> <li><a class="reference internal" href="#release-notes-for-mne-software-2-7">Release notes for MNE software 2.7</a><ul> <li><a class="reference internal" href="#software-engineering">Software engineering</a></li> <li><a class="reference internal" href="#matlab-tools">Matlab tools</a></li> <li><a class="reference internal" href="#id15">mne_browse_raw</a></li> <li><a class="reference internal" href="#id16">mne_analyze</a></li> <li><a class="reference internal" href="#miscellaneous">Miscellaneous</a></li> </ul> </li> <li><a class="reference internal" href="#release-notes-for-mne-software-2-7-1">Release notes for MNE software 2.7.1</a><ul> <li><a class="reference internal" href="#id17">mne_analyze</a></li> <li><a class="reference internal" href="#id18">mne_browse_raw</a></li> </ul> </li> <li><a class="reference internal" href="#release-notes-for-mne-software-2-7-2">Release notes for MNE software 2.7.2</a><ul> <li><a class="reference internal" href="#id19">mne_add_patch_info</a></li> <li><a class="reference internal" href="#id20">Matlab toolbox</a></li> <li><a class="reference internal" href="#id21">Miscellaneous</a></li> </ul> </li> <li><a class="reference internal" href="#release-notes-for-mne-software-2-7-3">Release notes for MNE software 2.7.3</a><ul> <li><a class="reference internal" href="#id22">Miscellaneous</a></li> </ul> </li> </ul> </li> </ul> <form action="../../search.html" method="get"> <div class="form-group"> <input type="text" name="q" class="form-control" placeholder="Search" /> </div> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <div class="col-md-12 content"> <div class="section" id="release-notes"> <span id="id1"></span><h1>Release notes<a class="headerlink" href="#release-notes" title="Permalink to this headline">¶</a></h1> <div class="contents local topic" id="contents"> <p class="topic-title first">Contents</p> <ul class="simple"> <li><a class="reference internal" href="#release-notes-for-mne-software-2-4" id="id23">Release notes for MNE software 2.4</a><ul> <li><a class="reference internal" href="#manual" id="id24">Manual</a></li> <li><a class="reference internal" href="#general-software-changes" id="id25">General software changes</a></li> <li><a class="reference internal" href="#file-conversion-utilities" id="id26">File conversion utilities</a></li> <li><a class="reference internal" href="#mne-browse-raw" id="id27">mne_browse_raw</a></li> <li><a class="reference internal" href="#mne-analyze" id="id28">mne_analyze</a></li> <li><a class="reference internal" href="#mne-make-movie" id="id29">mne_make_movie</a></li> <li><a class="reference internal" href="#averaging" id="id30">Averaging</a></li> </ul> </li> <li><a class="reference internal" href="#release-notes-for-mne-software-2-5" id="id31">Release notes for MNE software 2.5</a><ul> <li><a class="reference internal" href="#id2" id="id32">Manual</a></li> <li><a class="reference internal" href="#id3" id="id33">mne_browse_raw</a></li> <li><a class="reference internal" href="#mne-epochs2mat" id="id34">mne_epochs2mat</a></li> <li><a class="reference internal" href="#id4" id="id35">mne_analyze</a></li> <li><a class="reference internal" href="#mne-ctf2fiff" id="id36">mne_ctf2fiff</a></li> <li><a class="reference internal" href="#id5" id="id37">mne_make_movie</a></li> <li><a class="reference internal" href="#mne-surf2bem" id="id38">mne_surf2bem</a></li> <li><a class="reference internal" href="#mne-forward-solution" id="id39">mne_forward_solution</a></li> <li><a class="reference internal" href="#mne-inverse-operator" id="id40">mne_inverse_operator</a></li> <li><a class="reference internal" href="#mne-compute-raw-inverse" id="id41">mne_compute_raw_inverse</a></li> <li><a class="reference internal" href="#time-range-settings" id="id42">Time range settings</a></li> <li><a class="reference internal" href="#mne-change-baselines" id="id43">mne_change_baselines</a></li> <li><a class="reference internal" href="#new-utilities" id="id44">New utilities</a></li> <li><a class="reference internal" href="#bem-mesh-generation" id="id45">BEM mesh generation</a></li> <li><a class="reference internal" href="#matlab-toolbox" id="id46">Matlab toolbox</a></li> </ul> </li> <li><a class="reference internal" href="#release-notes-for-mne-software-2-6" id="id47">Release notes for MNE software 2.6</a><ul> <li><a class="reference internal" href="#id6" id="id48">Manual</a></li> <li><a class="reference internal" href="#command-line-options" id="id49">Command-line options</a></li> <li><a class="reference internal" href="#changes-to-existing-software" id="id50">Changes to existing software</a></li> <li><a class="reference internal" href="#id14" id="id51">New utilities</a></li> </ul> </li> <li><a class="reference internal" href="#release-notes-for-mne-software-2-7" id="id52">Release notes for MNE software 2.7</a><ul> <li><a class="reference internal" href="#software-engineering" id="id53">Software engineering</a></li> <li><a class="reference internal" href="#matlab-tools" id="id54">Matlab tools</a></li> <li><a class="reference internal" href="#id15" id="id55">mne_browse_raw</a></li> <li><a class="reference internal" href="#id16" id="id56">mne_analyze</a></li> <li><a class="reference internal" href="#miscellaneous" id="id57">Miscellaneous</a></li> </ul> </li> <li><a class="reference internal" href="#release-notes-for-mne-software-2-7-1" id="id58">Release notes for MNE software 2.7.1</a><ul> <li><a class="reference internal" href="#id17" id="id59">mne_analyze</a></li> <li><a class="reference internal" href="#id18" id="id60">mne_browse_raw</a></li> </ul> </li> <li><a class="reference internal" href="#release-notes-for-mne-software-2-7-2" id="id61">Release notes for MNE software 2.7.2</a><ul> <li><a class="reference internal" href="#id19" id="id62">mne_add_patch_info</a></li> <li><a class="reference internal" href="#id20" id="id63">Matlab toolbox</a></li> <li><a class="reference internal" href="#id21" id="id64">Miscellaneous</a></li> </ul> </li> <li><a class="reference internal" href="#release-notes-for-mne-software-2-7-3" id="id65">Release notes for MNE software 2.7.3</a><ul> <li><a class="reference internal" href="#id22" id="id66">Miscellaneous</a></li> </ul> </li> </ul> </div> <p>This appendix contains a brief description of the changes in MNE software in each major release.</p> <div class="section" id="release-notes-for-mne-software-2-4"> <h2><a class="toc-backref" href="#id23">Release notes for MNE software 2.4</a><a class="headerlink" href="#release-notes-for-mne-software-2-4" title="Permalink to this headline">¶</a></h2> <div class="section" id="manual"> <h3><a class="toc-backref" href="#id24">Manual</a><a class="headerlink" href="#manual" title="Permalink to this headline">¶</a></h3> <p>The manual has been significantly expanded and reorganized. <a class="reference internal" href="../gui/analyze.html#ch-interactive-analysis"><span class="std std-ref">Interactive analysis with mne_analyze</span></a> describing mne_analyze has been added. <a class="reference internal" href="../sample_dataset.html#ch-sample-data"><span class="std std-ref">The sample data set</span></a> contains instructions for analyzing the sample data set provided with the software. Useful background material is listed in <a class="reference internal" href="../../references.html#ch-reading"><span class="std std-ref">Related publications</span></a>. Almost all utility programs are now covered in the manual.</p> </div> <div class="section" id="general-software-changes"> <h3><a class="toc-backref" href="#id25">General software changes</a><a class="headerlink" href="#general-software-changes" title="Permalink to this headline">¶</a></h3> <p>The following overall changes have been made:</p> <ul class="simple"> <li>A forward solution library independent of Neuromag software was written.</li> <li>The MEG sensor information is now imported from the coil definition file instead of being hardcoded in the software.</li> <li>CTF and 4D Neuroimaging sensors are now supported.</li> <li>The number of Neuromag-based utilities was minimized.</li> <li>The LINUX port of Neuromag software modules was completely separated from the MNE software and now resides under a separate directory tree.</li> <li>Support for topologically connected source spaces was added.</li> <li>A lot of bugs were fixed.</li> </ul> </div> <div class="section" id="file-conversion-utilities"> <h3><a class="toc-backref" href="#id26">File conversion utilities</a><a class="headerlink" href="#file-conversion-utilities" title="Permalink to this headline">¶</a></h3> <p>The following import utilities were added:</p> <ul class="simple"> <li>mne_ctf2fiff to convert CTF data to the fif format.</li> <li>mne_tufts2fiff to convert EEG data from Tufts university to fif format.</li> </ul> <p>The output of the Matlab conversion utilities was changed to use structures.</p> <p>Matlab tools to import and export w and stc files were added.</p> </div> <div class="section" id="mne-browse-raw"> <h3><a class="toc-backref" href="#id27">mne_browse_raw</a><a class="headerlink" href="#mne-browse-raw" title="Permalink to this headline">¶</a></h3> <p>Output of decimated and filtered data is now available. mne_analyze now fully supports 32-bit integer data found in CTF and new Neuromag raw data files.</p> </div> <div class="section" id="mne-analyze"> <h3><a class="toc-backref" href="#id28">mne_analyze</a><a class="headerlink" href="#mne-analyze" title="Permalink to this headline">¶</a></h3> <p>The following changes have been made in mne_analyze :</p> <ul class="simple"> <li>Curved and flat surface patches are now supported.</li> <li>An iterative coordinate alignment procedure was added, see <a class="reference internal" href="../gui/analyze.html#cacehgcd"><span class="std std-ref">Coordinate frame alignment</span></a>.</li> <li>Utility to view continuous HPI information was added.</li> <li>Several small changes and bug fixes were done.</li> </ul> </div> <div class="section" id="mne-make-movie"> <h3><a class="toc-backref" href="#id29">mne_make_movie</a><a class="headerlink" href="#mne-make-movie" title="Permalink to this headline">¶</a></h3> <p>The only major change in mne_make_movie is the addition of support for curved and surface patches.</p> </div> <div class="section" id="averaging"> <h3><a class="toc-backref" href="#id30">Averaging</a><a class="headerlink" href="#averaging" title="Permalink to this headline">¶</a></h3> <p>The highly inefficient program mne_grand_average has been removed from the distribution and replaced with the combined use of mne_make_movie and a new averaging program mne_average_estimates.</p> </div> </div> <div class="section" id="release-notes-for-mne-software-2-5"> <h2><a class="toc-backref" href="#id31">Release notes for MNE software 2.5</a><a class="headerlink" href="#release-notes-for-mne-software-2-5" title="Permalink to this headline">¶</a></h2> <div class="section" id="id2"> <h3><a class="toc-backref" href="#id32">Manual</a><a class="headerlink" href="#id2" title="Permalink to this headline">¶</a></h3> <p>The MNE Matlab toolbox is now covered in a separate chapter. Change bars are employed to indicate changes in the chapters that existed in the previous version of the manual. Note that <a class="reference internal" href="../matlab.html#ch-matlab"><span class="std std-ref">MNE-MATLAB toolbox</span></a> describing the Matlab toolbox is totally new and change bars have not been used there. Furthermore, <a class="reference internal" href="martinos.html#setup-martinos"><span class="std std-ref">Setup at the Martinos Center</span></a> now contains all the information specific to the Martinos Center.</p> </div> <div class="section" id="id3"> <h3><a class="toc-backref" href="#id33">mne_browse_raw</a><a class="headerlink" href="#id3" title="Permalink to this headline">¶</a></h3> <p>There are several improvements in the raw data processor mne_browse_raw/mne_process_raw :</p> <ul class="simple"> <li>Possibility to delete and add channel selections interactively has been added. A nonstandard channel selection file can be now specified on the command line.</li> <li>Handling of CTF software gradient compensation has been added.</li> <li>The vertical scale of the digital trigger channel is now automatically set to accommodate the largest trigger value.</li> <li>It is now possible to load evoked-response data sets from files. Time scales of the evoked-response data and data averaged in mne_browse_raw can be now set from the scales dialog. <a class="reference internal" href="../sample_dataset.html#chdhbggh"><span class="std std-ref">Viewing the off-line average</span></a> has been updated to employ mne_browse_raw in viewing the averages computed from the sample raw data set.</li> <li>It is now possible to create new SSP operators in mne_browse_raw.</li> <li>Listing of amplitude values have been added to both the strip-chart and topographical displays.</li> <li>Text format event files can now be loaded for easy inspection of rejected epochs, for example.</li> <li>Handling of derived channels has been added.</li> <li>SSS information is now transferred to the covariance matrix output files.</li> <li>Neuromag processing history is included with the output files.</li> </ul> </div> <div class="section" id="mne-epochs2mat"> <h3><a class="toc-backref" href="#id34">mne_epochs2mat</a><a class="headerlink" href="#mne-epochs2mat" title="Permalink to this headline">¶</a></h3> <p>This new utility extracts epochs from a raw data file, applies a bandpass filter to them and outputs them in a format convenient for processing in Matlab.</p> </div> <div class="section" id="id4"> <h3><a class="toc-backref" href="#id35">mne_analyze</a><a class="headerlink" href="#id4" title="Permalink to this headline">¶</a></h3> <p>The following new features have been added:</p> <ul class="simple"> <li>Processing of raw data segment and easy switching between multiple evoked data sets (not in the manual yet).</li> <li>Sketchy surface display mode for source spaces with selection triangulation information created with the <code class="docutils literal notranslate"><span class="pre">--ico</span></code> option to mne_setup_source_space.</li> <li>Rotation of the coordinate frame in the coordinate system alignment dialog.</li> <li>Several new graphics output file formats as well as automatic and snapshot output modes.</li> <li>It is now possible to inquire timecourses from stc overlays. Both labels and surface picking are supported.</li> <li>Added an option to include surface vertex numbers to the timecourse output.</li> <li>Overlays matching the scalp surface can now be loaded.</li> <li>The dipole display dialog has now control over the dipole display properties. Multiple dipoles can be now displayed.</li> <li>Time stepping with cursor keys has been added.</li> <li>Dynamic cursors have been added to the full view display.</li> <li>The viewer display now automatically rotates to facilitate fiducial picking from the head surface.</li> </ul> </div> <div class="section" id="mne-ctf2fiff"> <h3><a class="toc-backref" href="#id36">mne_ctf2fiff</a><a class="headerlink" href="#mne-ctf2fiff" title="Permalink to this headline">¶</a></h3> <p>Correct errors in compensation channel information and compensation data output. The transformation between the CTF and Neuromag coordinate frames is now included in the output file.</p> </div> <div class="section" id="id5"> <h3><a class="toc-backref" href="#id37">mne_make_movie</a><a class="headerlink" href="#id5" title="Permalink to this headline">¶</a></h3> <p>Added the <code class="docutils literal notranslate"><span class="pre">--labelverts</span></code> option.</p> </div> <div class="section" id="mne-surf2bem"> <h3><a class="toc-backref" href="#id38">mne_surf2bem</a><a class="headerlink" href="#mne-surf2bem" title="Permalink to this headline">¶</a></h3> <p>Added the <code class="docutils literal notranslate"><span class="pre">--shift</span></code> option to move surface vertices outwards. Fixed some loopholes in topology checks. Also added the <code class="docutils literal notranslate"><span class="pre">--innershift</span></code> option to mne_setup_forward_model.</p> </div> <div class="section" id="mne-forward-solution"> <h3><a class="toc-backref" href="#id39">mne_forward_solution</a><a class="headerlink" href="#mne-forward-solution" title="Permalink to this headline">¶</a></h3> <p>Added code to compute forward solutions for CTF data with software gradient compensation on.</p> </div> <div class="section" id="mne-inverse-operator"> <h3><a class="toc-backref" href="#id40">mne_inverse_operator</a><a class="headerlink" href="#mne-inverse-operator" title="Permalink to this headline">¶</a></h3> <p>The following changes have been made in mne_inverse_operator :</p> <ul class="simple"> <li>Added options to regularize the noise-covariance matrix.</li> <li>Added correct handling of the rank-deficient covariance matrix resulting from the use of SSS.</li> <li>Additional projections cannot be specified if the noise covariance matrix was computed with projections on.</li> <li>Bad channels can be added only in special circumstances if the noise covariance matrix was computed with projections on.</li> </ul> </div> <div class="section" id="mne-compute-raw-inverse"> <h3><a class="toc-backref" href="#id41">mne_compute_raw_inverse</a><a class="headerlink" href="#mne-compute-raw-inverse" title="Permalink to this headline">¶</a></h3> <p>This utility is now documented in <a class="reference internal" href="../source_localization/inverse.html#computing-inverse"><span class="std std-ref">Computing inverse from raw and evoked data</span></a>. The utility mne_make_raw_inverse_operator has been removed from the software.</p> </div> <div class="section" id="time-range-settings"> <h3><a class="toc-backref" href="#id42">Time range settings</a><a class="headerlink" href="#time-range-settings" title="Permalink to this headline">¶</a></h3> <p>The tools mne_compute_raw_inverse , mne_convert_mne_data , and mne_compute_mne no longer have command-line options to restrict the time range of evoked data input.</p> </div> <div class="section" id="mne-change-baselines"> <h3><a class="toc-backref" href="#id43">mne_change_baselines</a><a class="headerlink" href="#mne-change-baselines" title="Permalink to this headline">¶</a></h3> <p>It is now possible to process all data sets in a file at once. All processed data are stored in a single output file.</p> </div> <div class="section" id="new-utilities"> <h3><a class="toc-backref" href="#id44">New utilities</a><a class="headerlink" href="#new-utilities" title="Permalink to this headline">¶</a></h3> <div class="section" id="mne-show-fiff"> <h4>mne_show_fiff<a class="headerlink" href="#mne-show-fiff" title="Permalink to this headline">¶</a></h4> <p>Replacement for the Neuromag utility show_fiff . This utility conforms to the standard command-line option conventions in MNE software.</p> </div> <div class="section" id="mne-make-cor-set"> <h4>mne_make_cor_set<a class="headerlink" href="#mne-make-cor-set" title="Permalink to this headline">¶</a></h4> <p>Replaces the functionality of the Neuromag utility create_mri_set_simple to create a fif format description file for the FreeSurfer MRI data. This utility is called by the mne_setup_mri script.</p> </div> <div class="section" id="mne-compensate-data"> <h4>mne_compensate_data<a class="headerlink" href="#mne-compensate-data" title="Permalink to this headline">¶</a></h4> <p>This utility applies or removes CTF software gradient compensation from evoked-response data.</p> </div> <div class="section" id="mne-insert-4d-comp"> <h4>mne_insert_4D_comp<a class="headerlink" href="#mne-insert-4d-comp" title="Permalink to this headline">¶</a></h4> <p>This utility merges 4D Magnes compensation data from a text file and the main helmet sensor data from a fif file and creates a new fif file <a class="reference internal" href="../c_reference.html#mne-insert-4d-comp"><span class="std std-ref">mne_insert_4D_comp</span></a>.</p> </div> <div class="section" id="mne-ctf-dig2fiff"> <h4>mne_ctf_dig2fiff<a class="headerlink" href="#mne-ctf-dig2fiff" title="Permalink to this headline">¶</a></h4> <p>This utility reads a text format Polhemus data file, transforms the data into the Neuromag head coordinate system, and outputs the data in fif or hpts format.</p> </div> <div class="section" id="mne-kit2fiff"> <h4>mne_kit2fiff<a class="headerlink" href="#mne-kit2fiff" title="Permalink to this headline">¶</a></h4> <p>The purpose of this new utility is to import data from the KIT MEG system.</p> </div> <div class="section" id="mne-make-derivations"> <h4>mne_make_derivations<a class="headerlink" href="#mne-make-derivations" title="Permalink to this headline">¶</a></h4> <p>This new utility will take derivation data from a text file and convert it to fif format for use with mne_browse_raw.</p> </div> </div> <div class="section" id="bem-mesh-generation"> <h3><a class="toc-backref" href="#id45">BEM mesh generation</a><a class="headerlink" href="#bem-mesh-generation" title="Permalink to this headline">¶</a></h3> <p>All information concerning BEM mesh generation has been moved to <a class="reference internal" href="bem_model.html#create-bem-model"><span class="std std-ref">Creating the BEM meshes</span></a>. Utilities for BEM mesh generation using FLASH images have been added.</p> </div> <div class="section" id="matlab-toolbox"> <h3><a class="toc-backref" href="#id46">Matlab toolbox</a><a class="headerlink" href="#matlab-toolbox" title="Permalink to this headline">¶</a></h3> <p>The MNE Matlab toolbox has been significantly enhanced. New features include:</p> <ul class="simple"> <li>Basic routines for reading and writing fif files.</li> <li>High-level functions to read and write evoked-response fif data.</li> <li>High-level functions to read raw data.</li> <li>High-level routines to read source space information, covariance matrices, forward solutions, and inverse operator decompositions directly from fif files.</li> </ul> <p>The Matlab toolbox is documented in <a class="reference internal" href="../matlab.html#ch-matlab"><span class="std std-ref">MNE-MATLAB toolbox</span></a>.</p> <p>The mne_div_w utility has been removed because it is now easy to perform its function and much more using the Matlab Toolbox.</p> </div> </div> <div class="section" id="release-notes-for-mne-software-2-6"> <h2><a class="toc-backref" href="#id47">Release notes for MNE software 2.6</a><a class="headerlink" href="#release-notes-for-mne-software-2-6" title="Permalink to this headline">¶</a></h2> <div class="section" id="id6"> <h3><a class="toc-backref" href="#id48">Manual</a><a class="headerlink" href="#id6" title="Permalink to this headline">¶</a></h3> <p>The changes described below briefly are documented in the relevant sections of the manual. Change bars are employed to indicate changes with respect to manual version 2.5. <a class="reference internal" href="../source_localization/forward.html#ch-forward"><span class="std std-ref">The forward solution</span></a> now contains a comprehensive discussion of the various coordinate systems used in MEG/EEG data.</p> </div> <div class="section" id="command-line-options"> <h3><a class="toc-backref" href="#id49">Command-line options</a><a class="headerlink" href="#command-line-options" title="Permalink to this headline">¶</a></h3> <p>All compiled C programs now check that the command line does not contain any unknown options. Consequently, scripts that have inadvertently specified some options which are invalid will now fail.</p> </div> <div class="section" id="changes-to-existing-software"> <h3><a class="toc-backref" href="#id50">Changes to existing software</a><a class="headerlink" href="#changes-to-existing-software" title="Permalink to this headline">¶</a></h3> <div class="section" id="mne-add-patch-info"> <h4>mne_add_patch_info<a class="headerlink" href="#mne-add-patch-info" title="Permalink to this headline">¶</a></h4> <ul class="simple"> <li>Changed option <code class="docutils literal notranslate"><span class="pre">--in</span></code> to <code class="docutils literal notranslate"><span class="pre">--src</span></code> and <code class="docutils literal notranslate"><span class="pre">--out</span></code> to <code class="docutils literal notranslate"><span class="pre">--srcp</span></code> .</li> <li>Added <code class="docutils literal notranslate"><span class="pre">--labeldir</span></code> option.</li> </ul> </div> <div class="section" id="id7"> <h4>mne_analyze<a class="headerlink" href="#id7" title="Permalink to this headline">¶</a></h4> <p>New features include:</p> <ul class="simple"> <li>The name of the digital trigger channel can be specified with the MNE_TRIGGER_CH_NAME environment variable.</li> <li>Using information from the fif data files, the wall clock time corresponding to the current file position is shown on the status line</li> <li>mne_analyze can now be controlled by mne_browse_raw to facilitate interactive analysis of clinical data.</li> <li>Added compatibility with Elekta-Neuromag Report Composer (cliplab and improved the quality of hardcopies.</li> <li>Both in mne_browse_raw and in mne_analyze , a non-standard default layout can be set on a user-by-user basis.</li> <li>Added the <code class="docutils literal notranslate"><span class="pre">--digtrigmask</span></code> option.</li> <li>Added new image rotation functionality using the mouse wheel or trackball.</li> <li>Added remote control of the FreeSurfer MRI viewer (tkmedit ).</li> <li>Added fitting of single equivalent current dipoles and channel selections.</li> <li>Added loading of FreeSurfer cortical parcellation data as labels.</li> <li>Added support for using the FreeSurfer average brain (fsaverage) as a surrogate.</li> <li>The surface selection dialog was redesigned for faster access to the files and to remove problems with a large number of subjects.</li> <li>A shortcut button to direct a file selector to the appropriate default directory was added to several file loading dialogs.</li> <li>The vertex coordinates can now be displayed.</li> </ul> </div> <div class="section" id="mne-average-forward-solutions"> <h4>mne_average_forward_solutions<a class="headerlink" href="#mne-average-forward-solutions" title="Permalink to this headline">¶</a></h4> <p>EEG forward solutions are now averaged as well.</p> </div> <div class="section" id="mne-browse-raw-and-mne-process-raw"> <h4>mne_browse_raw and mne_process_raw<a class="headerlink" href="#mne-browse-raw-and-mne-process-raw" title="Permalink to this headline">¶</a></h4> <p>Improvements in the raw data processor mne_browse_raw /mne_process_raw include:</p> <ul class="simple"> <li>The name of the digital trigger channel can be specified with the MNE_TRIGGER_CH_NAME environment variable.</li> <li>The format of the text event files was slightly changed. The sample numbers are now “absolute” sample numbers taking into account the initial skip in the event files. The new format is indicated by an additional “pseudoevent” in the beginning of the file. mne_browse_raw and mne_process_raw are still compatible with the old event file format.</li> <li>Using information from the fif data files, the wall clock time corresponding to the current file position is shown on the status line</li> <li>mne_browse_raw can now control mne_analyze to facilitate interactive analysis of clinical data.</li> <li>If the length of an output raw data file exceeds the 2-Gbyte fif file size limit, the output is split into multiple files.</li> <li><code class="docutils literal notranslate"><span class="pre">-split</span></code> and <code class="docutils literal notranslate"><span class="pre">--events</span></code> options was added to mne_process_raw .</li> <li>The <code class="docutils literal notranslate"><span class="pre">--allowmaxshield</span></code> option was added to mne_browse_raw to allow loading of unprocessed data with MaxShield in the Elekta-Neuromag systems. These kind of data should never be used as an input for source localization.</li> <li>The <code class="docutils literal notranslate"><span class="pre">--savehere</span></code> option was added.</li> <li>The stderr parameter was added to the averaging definition files.</li> <li>Added compatibility with Elekta-Neuromag Report Composer (cliplab and improved the quality of hardcopies.</li> <li>Both in mne_browse_raw and in mne_analyze , a non-standard default layout can be set on a user-by-user basis.</li> <li>mne_browse_raw now includes an interactive editor to create derived channels.</li> <li>The menus in mne_browse_raw were reorganized and an time point specification text field was added</li> <li>Possibility to keep the old projection items added to the new projection definition dialog.</li> <li>Added <code class="docutils literal notranslate"><span class="pre">--cd</span></code> option.</li> <li>Added filter buttons for raw files and Maxfilter (TM) output to the open dialog.</li> <li>Added possibility to create a graph-compatible projection to the Save projection dialog</li> <li>Added possibility to compute a projection operator from epochs specified by events.</li> <li>Added the <code class="docutils literal notranslate"><span class="pre">--keepsamplemean</span></code> option to the covariance matrix computation files.</li> <li>Added the <code class="docutils literal notranslate"><span class="pre">--digtrigmask</span></code> option.</li> <li>Added Load channel selections… item to the File menu.</li> <li>Added new browsing functionality using the mouse wheel or trackball.</li> <li>Added optional items to the topographical data displays.</li> <li>Added an event list window.</li> <li>Added an annotator window.</li> <li>Keep events sorted by time.</li> <li>User-defined events are automatically kept in a fif-format annotation file.</li> <li>Added the delay parameter to the averaging and covariance matrix estimation description files.</li> </ul> <p>Detailed information on these changes can be found in <a class="reference internal" href="../gui/browse.html#ch-browse"><span class="std std-ref">Browsing raw data with mne_browse_raw</span></a>.</p> </div> <div class="section" id="id8"> <h4>mne_compute_raw_inverse<a class="headerlink" href="#id8" title="Permalink to this headline">¶</a></h4> <p>The <code class="docutils literal notranslate"><span class="pre">--digtrig</span></code> , <code class="docutils literal notranslate"><span class="pre">--extra</span></code> , <code class="docutils literal notranslate"><span class="pre">--noextra</span></code> , <code class="docutils literal notranslate"><span class="pre">--split</span></code> , <code class="docutils literal notranslate"><span class="pre">--labeldir</span></code> , and <code class="docutils literal notranslate"><span class="pre">--out</span></code> options were added.</p> </div> <div class="section" id="mne-convert-surface"> <h4>mne_convert_surface<a class="headerlink" href="#mne-convert-surface" title="Permalink to this headline">¶</a></h4> <p>The functionality of mne_convert_dfs was integrated into mne_convert_surface . Text output as a triangle file and and file file containing the list of vertex points was added. The Matlab output option was removed. Consequently, mne_convert_dfs , mne_surface2mat , and mne_list_surface_nodes were deleted from the distribution.</p> </div> <div class="section" id="mne-dump-triggers"> <h4>mne_dump_triggers<a class="headerlink" href="#mne-dump-triggers" title="Permalink to this headline">¶</a></h4> <p>This obsolete utility was deleted from the distribution.</p> </div> <div class="section" id="id9"> <h4>mne_epochs2mat<a class="headerlink" href="#id9" title="Permalink to this headline">¶</a></h4> <p>The name of the digital trigger channel can be specified with the MNE_TRIGGER_CH_NAME environment variable. Added the <code class="docutils literal notranslate"><span class="pre">--digtrigmask</span></code> option.</p> </div> <div class="section" id="id10"> <h4>mne_forward_solution<a class="headerlink" href="#id10" title="Permalink to this headline">¶</a></h4> <p>Added code to compute the derivatives of with respect to the dipole position coordinates.</p> </div> <div class="section" id="mne-list-bem"> <h4>mne_list_bem<a class="headerlink" href="#mne-list-bem" title="Permalink to this headline">¶</a></h4> <p>The <code class="docutils literal notranslate"><span class="pre">--surfno</span></code> option is replaced with the <code class="docutils literal notranslate"><span class="pre">--id</span></code> option.</p> </div> <div class="section" id="id11"> <h4>mne_make_cor_set<a class="headerlink" href="#id11" title="Permalink to this headline">¶</a></h4> <p>Include data from mgh/mgz files to the output automatically. Include the Talairach transformations from the FreeSurfer data to the output file if possible.</p> </div> <div class="section" id="id12"> <h4>mne_make_movie<a class="headerlink" href="#id12" title="Permalink to this headline">¶</a></h4> <p>Added the <code class="docutils literal notranslate"><span class="pre">--noscalebar</span></code>, <code class="docutils literal notranslate"><span class="pre">--nocomments</span></code>, <code class="docutils literal notranslate"><span class="pre">--morphgrade</span></code>, <code class="docutils literal notranslate"><span class="pre">--rate</span></code>, and <code class="docutils literal notranslate"><span class="pre">--pickrange</span></code> options.</p> </div> <div class="section" id="mne-make-source-space"> <h4>mne_make_source_space<a class="headerlink" href="#mne-make-source-space" title="Permalink to this headline">¶</a></h4> <p>The <code class="docutils literal notranslate"><span class="pre">--spacing</span></code> option is now implemented in this program, which means mne_mris_trix is now obsolete. The mne_setup_source_space script was modified accordingly. Support for tri, dec, and dip files was dropped.</p> </div> <div class="section" id="mne-mdip2stc"> <h4>mne_mdip2stc<a class="headerlink" href="#mne-mdip2stc" title="Permalink to this headline">¶</a></h4> <p>This utility is obsolete and was removed from the distribution.</p> </div> <div class="section" id="mne-project-raw"> <h4>mne_project_raw<a class="headerlink" href="#mne-project-raw" title="Permalink to this headline">¶</a></h4> <p>This is utility is obsolete and was removed from the distribution. The functionality is included in mne_process_raw .</p> </div> <div class="section" id="mne-rename-channels"> <h4>mne_rename_channels<a class="headerlink" href="#mne-rename-channels" title="Permalink to this headline">¶</a></h4> <p>Added the <code class="docutils literal notranslate"><span class="pre">--revert</span></code> option.</p> </div> <div class="section" id="mne-setup-forward-model"> <h4>mne_setup_forward_model<a class="headerlink" href="#mne-setup-forward-model" title="Permalink to this headline">¶</a></h4> <p>Added the <code class="docutils literal notranslate"><span class="pre">--outershift</span></code> and <code class="docutils literal notranslate"><span class="pre">--scalpshift</span></code> options.</p> </div> <div class="section" id="mne-simu"> <h4>mne_simu<a class="headerlink" href="#mne-simu" title="Permalink to this headline">¶</a></h4> <p>Added source waveform expressions and the <code class="docutils literal notranslate"><span class="pre">--raw</span></code> option.</p> </div> <div class="section" id="mne-transform-points"> <h4>mne_transform_points<a class="headerlink" href="#mne-transform-points" title="Permalink to this headline">¶</a></h4> <p>Removed the <code class="docutils literal notranslate"><span class="pre">--tomrivol</span></code> option.</p> </div> <div class="section" id="id13"> <h4>Matlab toolbox<a class="headerlink" href="#id13" title="Permalink to this headline">¶</a></h4> <p>Several new functions were added, see <a class="reference internal" href="../matlab.html#ch-matlab"><span class="std std-ref">MNE-MATLAB toolbox</span></a>.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">The matlab function fiff_setup_read_raw has a significant change. The sample numbers now take into account possible initial skip in the file, <em>i.e.</em>, the time between the start of the data acquisition and the start of saving the data to disk. The first_samp member of the returned structure indicates the initial skip in samples. If you want your own routines, which assume that initial skip has been removed, perform identically with the previous version, subtract first_samp from the sample numbers you specify to fiff_read_raw_segment . Furthermore, fiff_setup_read_raw has an optional argument to allow reading of unprocessed MaxShield data acquired with the Elekta MEG systems.</p> </div> </div> </div> <div class="section" id="id14"> <h3><a class="toc-backref" href="#id51">New utilities</a><a class="headerlink" href="#id14" title="Permalink to this headline">¶</a></h3> <div class="section" id="mne-collect-transforms"> <h4>mne_collect_transforms<a class="headerlink" href="#mne-collect-transforms" title="Permalink to this headline">¶</a></h4> <p>This utility collects coordinate transformation information from several sources into a single file.</p> </div> <div class="section" id="mne-convert-dig-data"> <h4>mne_convert_dig_data<a class="headerlink" href="#mne-convert-dig-data" title="Permalink to this headline">¶</a></h4> <p>This new utility convertes digitization (Polhemus) data between different file formats.</p> </div> <div class="section" id="mne-edf2fiff"> <h4>mne_edf2fiff<a class="headerlink" href="#mne-edf2fiff" title="Permalink to this headline">¶</a></h4> <p>This is a new utility to convert EEG data from EDF, EDF+, and BDF formats to the fif format.</p> </div> <div class="section" id="mne-brain-vision2fiff"> <h4>mne_brain_vision2fiff<a class="headerlink" href="#mne-brain-vision2fiff" title="Permalink to this headline">¶</a></h4> <p>This is a new utility to convert BrainVision EEG data to the fif format. This utility is also used by the mne_eximia_2fiff script to convert EEG data from the Nexstim eXimia EEG system to the fif format.</p> </div> <div class="section" id="mne-anonymize"> <h4>mne_anonymize<a class="headerlink" href="#mne-anonymize" title="Permalink to this headline">¶</a></h4> <p>New utility to remove subject identifying information from measurement files.</p> </div> <div class="section" id="mne-opengl-test"> <h4>mne_opengl_test<a class="headerlink" href="#mne-opengl-test" title="Permalink to this headline">¶</a></h4> <p>New utility for testing the OpenGL graphics performance.</p> </div> <div class="section" id="mne-volume-data2mri"> <h4>mne_volume_data2mri<a class="headerlink" href="#mne-volume-data2mri" title="Permalink to this headline">¶</a></h4> <p>Convert data defined in a volume created with mne_volume_source_space to an MRI overlay.</p> </div> <div class="section" id="mne-volume-source-space"> <h4>mne_volume_source_space<a class="headerlink" href="#mne-volume-source-space" title="Permalink to this headline">¶</a></h4> <p>Create a a grid of source points within a volume. mne_volume_source_space also optionally creates a trilinear interpolator matrix to facilitate converting values a distribution in the volume grid into an MRI overlay using mne_volume_data2mri.</p> </div> <div class="section" id="mne-copy-processing-history"> <h4>mne_copy_processing_history<a class="headerlink" href="#mne-copy-processing-history" title="Permalink to this headline">¶</a></h4> <p>This new utility copies the processing history block from one data file to another.</p> </div> </div> </div> <div class="section" id="release-notes-for-mne-software-2-7"> <h2><a class="toc-backref" href="#id52">Release notes for MNE software 2.7</a><a class="headerlink" href="#release-notes-for-mne-software-2-7" title="Permalink to this headline">¶</a></h2> <div class="section" id="software-engineering"> <h3><a class="toc-backref" href="#id53">Software engineering</a><a class="headerlink" href="#software-engineering" title="Permalink to this headline">¶</a></h3> <p>There have been two significant changes in the software engineering since MNE Version 2.6:</p> <ul class="simple"> <li>CMake is now used in building the software package and</li> <li>Subversion (SVN) is now used for revision control instead of Concurrent Versions System (CVS).</li> </ul> <p>These changes have the effects on the distribution of the MNE software and setup for individual users:</p> <ul class="simple"> <li>There is now a separate software package for each of the platforms supported.</li> <li>The software is now organized completely under standard directories (bin, lib, and share). In particular, the directory setup/mne has been moved to share/mne and the directories app-defaults and doc are now under share. All files under share are platform independent.</li> <li>The use of shared libraries has been minimized. This alleviates compatibility problems across operating system versions.</li> <li>The setup scripts have changed.</li> </ul> <p>The installation and user-level effects of the new software organization are discussed in <a class="reference internal" href="../../install_mne_c.html#install-mne-c"><span class="std std-ref">Install MNE-C</span></a>.</p> <p>In addition, several minor bugs have been fixed in the source code. Most relevant changes visible to the user are listed below.</p> </div> <div class="section" id="matlab-tools"> <h3><a class="toc-backref" href="#id54">Matlab tools</a><a class="headerlink" href="#matlab-tools" title="Permalink to this headline">¶</a></h3> <ul class="simple"> <li>The performance of the fiff I/O routines has been significantly improved thanks to the contributions of François Tadel at USC.</li> <li>Label file I/O routines mne_read_label_file and mne_write_label_file as well as a routine to extract time courses corresponding to a label from an stc file (mne_label_time_courses) have been added.</li> <li>The patch information is now read from the source space file and included in the source space data structure.</li> </ul> </div> <div class="section" id="id15"> <h3><a class="toc-backref" href="#id55">mne_browse_raw</a><a class="headerlink" href="#id15" title="Permalink to this headline">¶</a></h3> <ul class="simple"> <li>Rejection criteria to detect flat channels have been added.</li> <li>Possibility to detect temporal skew between trigger input lines has been added.</li> <li><code class="docutils literal notranslate"><span class="pre">--allowmaxshield</span></code> option now works in the batch mode as well.</li> <li>Added the <code class="docutils literal notranslate"><span class="pre">--projevent</span></code> option to batch mode.</li> <li>It is now possible to compute an SSP operator for EEG.</li> </ul> </div> <div class="section" id="id16"> <h3><a class="toc-backref" href="#id56">mne_analyze</a><a class="headerlink" href="#id16" title="Permalink to this headline">¶</a></h3> <ul class="simple"> <li>Both hemispheres can now be displayed simultaneously.</li> <li>If the source space was created with mne_make_source_space version 2.3 or later, the subject’s surface data are automatically loaded after loading the data and the inverse operator.</li> </ul> </div> <div class="section" id="miscellaneous"> <h3><a class="toc-backref" href="#id57">Miscellaneous</a><a class="headerlink" href="#miscellaneous" title="Permalink to this headline">¶</a></h3> <ul class="simple"> <li>mne_smooth_w was renamed to mne_smooth and can now handle both w and stc files. Say <code class="docutils literal notranslate"><span class="pre">mne_smooth</span> <span class="pre">--help</span></code> to find the options.</li> <li>All binaries now reside in $MNE_ROOT/bin. There are no separate bin/mne and bin/admin directories.</li> <li>mne_anonymize now has the <code class="docutils literal notranslate"><span class="pre">--his</span></code> option to remove the HIS ID of the subject.</li> <li>mne_check_surface now has the <code class="docutils literal notranslate"><span class="pre">--bem</span></code> and <code class="docutils literal notranslate"><span class="pre">--id</span></code> options to check surfaces from a BEM fif file.</li> <li>mne_compute_raw_inverse now has the <code class="docutils literal notranslate"><span class="pre">--orignames</span></code> option.</li> <li>Added <code class="docutils literal notranslate"><span class="pre">--headcoord</span></code> option to mne_convert_dig_data.</li> <li>Added <code class="docutils literal notranslate"><span class="pre">--talairach</span></code> option to mne_make_cor_set.</li> <li>Added the <code class="docutils literal notranslate"><span class="pre">--morph</span></code> option to mne_setup_source_space and mne_make_source_space.</li> <li>Added the <code class="docutils literal notranslate"><span class="pre">--prefix</span></code> option to mne_morph_labels.</li> <li>Added the <code class="docutils literal notranslate"><span class="pre">--blocks</span></code> and <code class="docutils literal notranslate"><span class="pre">--indent</span></code> options to mne_show_fiff.</li> <li>Added the <code class="docutils literal notranslate"><span class="pre">--proj</span></code> option as well as map types 5 and 6 to mne_sensitivity_map.</li> <li>Fixed a bug in mne_inverse_operator which caused erroneous calculation of EEG-only source estimates if the data were processed with Maxfilter software and sometimes caused similar behavior on MEG/EEG source estimates.</li> </ul> </div> </div> <div class="section" id="release-notes-for-mne-software-2-7-1"> <h2><a class="toc-backref" href="#id58">Release notes for MNE software 2.7.1</a><a class="headerlink" href="#release-notes-for-mne-software-2-7-1" title="Permalink to this headline">¶</a></h2> <div class="section" id="id17"> <h3><a class="toc-backref" href="#id59">mne_analyze</a><a class="headerlink" href="#id17" title="Permalink to this headline">¶</a></h3> <ul class="simple"> <li>Added a new restricted mode for visualizing head position within the helmet.</li> <li>Added information about mne_make_scalp_surfaces to <a class="reference internal" href="../gui/analyze.html#chdcghif"><span class="std std-ref">Using a high-resolution head surface tessellations</span></a>.</li> </ul> </div> <div class="section" id="id18"> <h3><a class="toc-backref" href="#id60">mne_browse_raw</a><a class="headerlink" href="#id18" title="Permalink to this headline">¶</a></h3> <ul class="simple"> <li>Added possibility for multiple event parameters and the mask parameter in averaging and noise covariance calculation.</li> <li>Added simple conditional averaging.</li> </ul> </div> </div> <div class="section" id="release-notes-for-mne-software-2-7-2"> <h2><a class="toc-backref" href="#id61">Release notes for MNE software 2.7.2</a><a class="headerlink" href="#release-notes-for-mne-software-2-7-2" title="Permalink to this headline">¶</a></h2> <div class="section" id="id19"> <h3><a class="toc-backref" href="#id62">mne_add_patch_info</a><a class="headerlink" href="#id19" title="Permalink to this headline">¶</a></h3> <p>Added the capability to compute distances between source space vertices.</p> </div> <div class="section" id="id20"> <h3><a class="toc-backref" href="#id63">Matlab toolbox</a><a class="headerlink" href="#id20" title="Permalink to this headline">¶</a></h3> <ul class="simple"> <li>Added new functions to for stc and w file I/O to employ 1-based vertex numbering inside Matlab, see Table 10.11.</li> <li>mne_read_source_spaces.m now reads the inter-vertex distance information now optionally produced by mne_add_patch_info.</li> </ul> </div> <div class="section" id="id21"> <h3><a class="toc-backref" href="#id64">Miscellaneous</a><a class="headerlink" href="#id21" title="Permalink to this headline">¶</a></h3> <ul class="simple"> <li>Added <code class="docutils literal notranslate"><span class="pre">--shift</span></code> option to mne_convert_surface.</li> <li>Added <code class="docutils literal notranslate"><span class="pre">--alpha</span></code> option to mne_make_movie.</li> <li>Added <code class="docutils literal notranslate"><span class="pre">--noiserank</span></code> option to mne_inverse_operator and mne_do_inverse_operator.</li> <li>The fif output from mne_convert_dig_data now includes the transformation between the digitizer and MNE head coordinate systems if such a transformation has been requested. This also affects the output from mne_eximia2fiff.</li> <li>Added <code class="docutils literal notranslate"><span class="pre">--noflash30</span></code>, <code class="docutils literal notranslate"><span class="pre">--noconvert</span></code>, and <code class="docutils literal notranslate"><span class="pre">--unwarp</span></code> options to mne_flash_bem.</li> </ul> </div> </div> <div class="section" id="release-notes-for-mne-software-2-7-3"> <h2><a class="toc-backref" href="#id65">Release notes for MNE software 2.7.3</a><a class="headerlink" href="#release-notes-for-mne-software-2-7-3" title="Permalink to this headline">¶</a></h2> <div class="section" id="id22"> <h3><a class="toc-backref" href="#id66">Miscellaneous</a><a class="headerlink" href="#id22" title="Permalink to this headline">¶</a></h3> <ul class="simple"> <li>Added preservation of the volume geometry information in the FreeSurfer surface files.</li> <li>The <code class="docutils literal notranslate"><span class="pre">--mghmri</span></code> option in combination with <code class="docutils literal notranslate"><span class="pre">--surfout</span></code> inserts the volume geometry information to the output of mne_convert_surface.</li> <li>Added <code class="docutils literal notranslate"><span class="pre">--replacegeom</span></code> option to mne_convert_surface.</li> <li>Modified mne_watershed_bem and mne_flash_bem to include the volume geometry information to the output. This allows viewing of the output surfaces in the FreeSurfer freeview utility.</li> </ul> </div> </div> </div> </div> </div> </div> <footer class="footer"> <div class="container"><img src="../../_static/institutions.png" alt="Institutions"></div> <div class="container"> <ul class="list-inline"> <li><a href="https://github.com/mne-tools/mne-python">GitHub</a></li> <li>·</li> <li><a href="https://mail.nmr.mgh.harvard.edu/mailman/listinfo/mne_analysis">Mailing list</a></li> <li>·</li> <li><a href="https://gitter.im/mne-tools/mne-python">Gitter</a></li> <li>·</li> <li><a href="whats_new.html">What's new</a></li> <li>·</li> <li><a href="faq.html#cite">Cite MNE</a></li> <li class="pull-right"><a href="#">Back to top</a></li> </ul> <p>&copy; Copyright 2012-2019, MNE Developers. Last updated on 2019-02-22.</p> </div> </footer> <script src="https://mne.tools/versionwarning.js"></script> </body> </html>
{ "content_hash": "5650d4bbe808bb88bdd04e3cb6b2121e", "timestamp": "", "source": "github", "line_count": 1053, "max_line_length": 742, "avg_line_length": 60.414055080721745, "alnum_prop": 0.7154017857142857, "repo_name": "mne-tools/mne-tools.github.io", "id": "309971501e94d5d18593633359fde6df5c58b65c", "size": "63714", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "0.17/manual/appendix/c_release_notes.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "708696" }, { "name": "Dockerfile", "bytes": "1820" }, { "name": "HTML", "bytes": "1526247783" }, { "name": "JavaScript", "bytes": "1323087" }, { "name": "Jupyter Notebook", "bytes": "24820047" }, { "name": "Python", "bytes": "18575494" } ], "symlink_target": "" }
#ifndef HMLIB_ENUMERATORS_INC #define HMLIB_ENUMERATORS_INC 100 # #include"enumerators/enumerator.hpp" #include"enumerators/traversal_ability.hpp" #include"enumerators/algorithm_ability.hpp" #include"enumerators/random_algorithm_ability.hpp" #include"enumerators/numeric_ability.hpp" #include"enumerators/enumerator_defines.hpp" # #endif
{ "content_hash": "a8f9f329399ba7392891c15c2d9ed0dd", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 50, "avg_line_length": 30.818181818181817, "alnum_prop": 0.8230088495575221, "repo_name": "hmito/hmLib", "id": "d6f4d50eec31db039b7a64e4cc9eae3579001fc7", "size": "341", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "enumerators.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "16639" }, { "name": "C++", "bytes": "1187907" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_02) on Tue Oct 20 05:53:13 CEST 2015 --> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <title>org.gradle.api.initialization (Gradle API 2.8)</title> <meta name="date" content="2015-10-20"> <link rel="stylesheet" type="text/css" href="../../../../javadoc.css" title="Style"> </head> <body> <h1 class="bar"><a href="../../../../org/gradle/api/initialization/package-summary.html" target="classFrame">org.gradle.api.initialization</a></h1> <div class="indexContainer"> <h2 title="Interfaces">Interfaces</h2> <ul title="Interfaces"> <li><a href="ProjectDescriptor.html" title="interface in org.gradle.api.initialization" target="classFrame"><i>ProjectDescriptor</i></a></li> <li><a href="Settings.html" title="interface in org.gradle.api.initialization" target="classFrame"><i>Settings</i></a></li> </ul> </div> </body> </html>
{ "content_hash": "e4f32f59ec61e392e6f949a0fca2fc96", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 147, "avg_line_length": 49.142857142857146, "alnum_prop": 0.6908914728682171, "repo_name": "FinishX/coolweather", "id": "5be64fe30de85629987a6df16016a7c62496a3e9", "size": "1032", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gradle/gradle-2.8/docs/javadoc/org/gradle/api/initialization/package-frame.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "277" }, { "name": "C", "bytes": "97569" }, { "name": "C++", "bytes": "912105" }, { "name": "CSS", "bytes": "105486" }, { "name": "CoffeeScript", "bytes": "201" }, { "name": "GAP", "bytes": "212" }, { "name": "Groovy", "bytes": "1162135" }, { "name": "HTML", "bytes": "35827007" }, { "name": "Java", "bytes": "12908568" }, { "name": "JavaScript", "bytes": "195155" }, { "name": "Objective-C", "bytes": "2977" }, { "name": "Objective-C++", "bytes": "442" }, { "name": "Scala", "bytes": "12789" }, { "name": "Shell", "bytes": "5398" } ], "symlink_target": "" }
package internalversion import ( "bytes" "fmt" "net" "sort" "strconv" "strings" "time" appsv1beta1 "k8s.io/api/apps/v1beta1" autoscalingv2beta1 "k8s.io/api/autoscaling/v2beta1" batchv1 "k8s.io/api/batch/v1" batchv1beta1 "k8s.io/api/batch/v1beta1" certificatesv1beta1 "k8s.io/api/certificates/v1beta1" coordinationv1 "k8s.io/api/coordination/v1" apiv1 "k8s.io/api/core/v1" extensionsv1beta1 "k8s.io/api/extensions/v1beta1" policyv1beta1 "k8s.io/api/policy/v1beta1" rbacv1beta1 "k8s.io/api/rbac/v1beta1" schedulingv1beta1 "k8s.io/api/scheduling/v1beta1" storagev1 "k8s.io/api/storage/v1" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/duration" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/kubernetes/pkg/apis/apps" "k8s.io/kubernetes/pkg/apis/autoscaling" "k8s.io/kubernetes/pkg/apis/batch" "k8s.io/kubernetes/pkg/apis/certificates" "k8s.io/kubernetes/pkg/apis/coordination" api "k8s.io/kubernetes/pkg/apis/core" "k8s.io/kubernetes/pkg/apis/core/helper" "k8s.io/kubernetes/pkg/apis/networking" nodeapi "k8s.io/kubernetes/pkg/apis/node" "k8s.io/kubernetes/pkg/apis/policy" "k8s.io/kubernetes/pkg/apis/rbac" "k8s.io/kubernetes/pkg/apis/scheduling" "k8s.io/kubernetes/pkg/apis/storage" storageutil "k8s.io/kubernetes/pkg/apis/storage/util" "k8s.io/kubernetes/pkg/printers" "k8s.io/kubernetes/pkg/util/node" ) const ( loadBalancerWidth = 16 // labelNodeRolePrefix is a label prefix for node roles // It's copied over to here until it's merged in core: https://github.com/kubernetes/kubernetes/pull/39112 labelNodeRolePrefix = "node-role.kubernetes.io/" // nodeLabelRole specifies the role of a node nodeLabelRole = "kubernetes.io/role" ) // AddHandlers adds print handlers for default Kubernetes types dealing with internal versions. // TODO: handle errors from Handler func AddHandlers(h printers.PrintHandler) { podColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Ready", Type: "string", Description: "The aggregate readiness state of this pod for accepting traffic."}, {Name: "Status", Type: "string", Description: "The aggregate status of the containers in this pod."}, {Name: "Restarts", Type: "integer", Description: "The number of times the containers in this pod have been restarted."}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, {Name: "IP", Type: "string", Priority: 1, Description: apiv1.PodStatus{}.SwaggerDoc()["podIP"]}, {Name: "Node", Type: "string", Priority: 1, Description: apiv1.PodSpec{}.SwaggerDoc()["nodeName"]}, {Name: "Nominated Node", Type: "string", Priority: 1, Description: apiv1.PodStatus{}.SwaggerDoc()["nominatedNodeName"]}, {Name: "Readiness Gates", Type: "string", Priority: 1, Description: apiv1.PodSpec{}.SwaggerDoc()["readinessGates"]}, } h.TableHandler(podColumnDefinitions, printPodList) h.TableHandler(podColumnDefinitions, printPod) podTemplateColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Containers", Type: "string", Description: "Names of each container in the template."}, {Name: "Images", Type: "string", Description: "Images referenced by each container in the template."}, {Name: "Pod Labels", Type: "string", Description: "The labels for the pod template."}, } h.TableHandler(podTemplateColumnDefinitions, printPodTemplate) h.TableHandler(podTemplateColumnDefinitions, printPodTemplateList) podDisruptionBudgetColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Min Available", Type: "string", Description: "The minimum number of pods that must be available."}, {Name: "Max Unavailable", Type: "string", Description: "The maximum number of pods that may be unavailable."}, {Name: "Allowed Disruptions", Type: "integer", Description: "Calculated number of pods that may be disrupted at this time."}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, } h.TableHandler(podDisruptionBudgetColumnDefinitions, printPodDisruptionBudget) h.TableHandler(podDisruptionBudgetColumnDefinitions, printPodDisruptionBudgetList) replicationControllerColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Desired", Type: "integer", Description: apiv1.ReplicationControllerSpec{}.SwaggerDoc()["replicas"]}, {Name: "Current", Type: "integer", Description: apiv1.ReplicationControllerStatus{}.SwaggerDoc()["replicas"]}, {Name: "Ready", Type: "integer", Description: apiv1.ReplicationControllerStatus{}.SwaggerDoc()["readyReplicas"]}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, {Name: "Containers", Type: "string", Priority: 1, Description: "Names of each container in the template."}, {Name: "Images", Type: "string", Priority: 1, Description: "Images referenced by each container in the template."}, {Name: "Selector", Type: "string", Priority: 1, Description: apiv1.ReplicationControllerSpec{}.SwaggerDoc()["selector"]}, } h.TableHandler(replicationControllerColumnDefinitions, printReplicationController) h.TableHandler(replicationControllerColumnDefinitions, printReplicationControllerList) replicaSetColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Desired", Type: "integer", Description: extensionsv1beta1.ReplicaSetSpec{}.SwaggerDoc()["replicas"]}, {Name: "Current", Type: "integer", Description: extensionsv1beta1.ReplicaSetStatus{}.SwaggerDoc()["replicas"]}, {Name: "Ready", Type: "integer", Description: extensionsv1beta1.ReplicaSetStatus{}.SwaggerDoc()["readyReplicas"]}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, {Name: "Containers", Type: "string", Priority: 1, Description: "Names of each container in the template."}, {Name: "Images", Type: "string", Priority: 1, Description: "Images referenced by each container in the template."}, {Name: "Selector", Type: "string", Priority: 1, Description: extensionsv1beta1.ReplicaSetSpec{}.SwaggerDoc()["selector"]}, } h.TableHandler(replicaSetColumnDefinitions, printReplicaSet) h.TableHandler(replicaSetColumnDefinitions, printReplicaSetList) daemonSetColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Desired", Type: "integer", Description: extensionsv1beta1.DaemonSetStatus{}.SwaggerDoc()["desiredNumberScheduled"]}, {Name: "Current", Type: "integer", Description: extensionsv1beta1.DaemonSetStatus{}.SwaggerDoc()["currentNumberScheduled"]}, {Name: "Ready", Type: "integer", Description: extensionsv1beta1.DaemonSetStatus{}.SwaggerDoc()["numberReady"]}, {Name: "Up-to-date", Type: "integer", Description: extensionsv1beta1.DaemonSetStatus{}.SwaggerDoc()["updatedNumberScheduled"]}, {Name: "Available", Type: "integer", Description: extensionsv1beta1.DaemonSetStatus{}.SwaggerDoc()["numberAvailable"]}, {Name: "Node Selector", Type: "string", Description: apiv1.PodSpec{}.SwaggerDoc()["nodeSelector"]}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, {Name: "Containers", Type: "string", Priority: 1, Description: "Names of each container in the template."}, {Name: "Images", Type: "string", Priority: 1, Description: "Images referenced by each container in the template."}, {Name: "Selector", Type: "string", Priority: 1, Description: extensionsv1beta1.DaemonSetSpec{}.SwaggerDoc()["selector"]}, } h.TableHandler(daemonSetColumnDefinitions, printDaemonSet) h.TableHandler(daemonSetColumnDefinitions, printDaemonSetList) jobColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Completions", Type: "string", Description: batchv1.JobStatus{}.SwaggerDoc()["succeeded"]}, {Name: "Duration", Type: "string", Description: "Time required to complete the job."}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, {Name: "Containers", Type: "string", Priority: 1, Description: "Names of each container in the template."}, {Name: "Images", Type: "string", Priority: 1, Description: "Images referenced by each container in the template."}, {Name: "Selector", Type: "string", Priority: 1, Description: batchv1.JobSpec{}.SwaggerDoc()["selector"]}, } h.TableHandler(jobColumnDefinitions, printJob) h.TableHandler(jobColumnDefinitions, printJobList) cronJobColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Schedule", Type: "string", Description: batchv1beta1.CronJobSpec{}.SwaggerDoc()["schedule"]}, {Name: "Suspend", Type: "boolean", Description: batchv1beta1.CronJobSpec{}.SwaggerDoc()["suspend"]}, {Name: "Active", Type: "integer", Description: batchv1beta1.CronJobStatus{}.SwaggerDoc()["active"]}, {Name: "Last Schedule", Type: "string", Description: batchv1beta1.CronJobStatus{}.SwaggerDoc()["lastScheduleTime"]}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, {Name: "Containers", Type: "string", Priority: 1, Description: "Names of each container in the template."}, {Name: "Images", Type: "string", Priority: 1, Description: "Images referenced by each container in the template."}, {Name: "Selector", Type: "string", Priority: 1, Description: batchv1.JobSpec{}.SwaggerDoc()["selector"]}, } h.TableHandler(cronJobColumnDefinitions, printCronJob) h.TableHandler(cronJobColumnDefinitions, printCronJobList) serviceColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Type", Type: "string", Description: apiv1.ServiceSpec{}.SwaggerDoc()["type"]}, {Name: "Cluster-IP", Type: "string", Description: apiv1.ServiceSpec{}.SwaggerDoc()["clusterIP"]}, {Name: "External-IP", Type: "string", Description: apiv1.ServiceSpec{}.SwaggerDoc()["externalIPs"]}, {Name: "Port(s)", Type: "string", Description: apiv1.ServiceSpec{}.SwaggerDoc()["ports"]}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, {Name: "Selector", Type: "string", Priority: 1, Description: apiv1.ServiceSpec{}.SwaggerDoc()["selector"]}, } h.TableHandler(serviceColumnDefinitions, printService) h.TableHandler(serviceColumnDefinitions, printServiceList) ingressColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Hosts", Type: "string", Description: "Hosts that incoming requests are matched against before the ingress rule"}, {Name: "Address", Type: "string", Description: "Address is a list containing ingress points for the load-balancer"}, {Name: "Ports", Type: "string", Description: "Ports of TLS configurations that open"}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, } h.TableHandler(ingressColumnDefinitions, printIngress) h.TableHandler(ingressColumnDefinitions, printIngressList) statefulSetColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Ready", Type: "string", Description: "Number of the pod with ready state"}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, {Name: "Containers", Type: "string", Priority: 1, Description: "Names of each container in the template."}, {Name: "Images", Type: "string", Priority: 1, Description: "Images referenced by each container in the template."}, } h.TableHandler(statefulSetColumnDefinitions, printStatefulSet) h.TableHandler(statefulSetColumnDefinitions, printStatefulSetList) endpointColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Endpoints", Type: "string", Description: apiv1.Endpoints{}.SwaggerDoc()["subsets"]}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, } h.TableHandler(endpointColumnDefinitions, printEndpoints) h.TableHandler(endpointColumnDefinitions, printEndpointsList) nodeColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Status", Type: "string", Description: "The status of the node"}, {Name: "Roles", Type: "string", Description: "The roles of the node"}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, {Name: "Version", Type: "string", Description: apiv1.NodeSystemInfo{}.SwaggerDoc()["kubeletVersion"]}, {Name: "Internal-IP", Type: "string", Priority: 1, Description: apiv1.NodeStatus{}.SwaggerDoc()["addresses"]}, {Name: "External-IP", Type: "string", Priority: 1, Description: apiv1.NodeStatus{}.SwaggerDoc()["addresses"]}, {Name: "OS-Image", Type: "string", Priority: 1, Description: apiv1.NodeSystemInfo{}.SwaggerDoc()["osImage"]}, {Name: "Kernel-Version", Type: "string", Priority: 1, Description: apiv1.NodeSystemInfo{}.SwaggerDoc()["kernelVersion"]}, {Name: "Container-Runtime", Type: "string", Priority: 1, Description: apiv1.NodeSystemInfo{}.SwaggerDoc()["containerRuntimeVersion"]}, } h.TableHandler(nodeColumnDefinitions, printNode) h.TableHandler(nodeColumnDefinitions, printNodeList) eventColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Last Seen", Type: "string", Description: apiv1.Event{}.SwaggerDoc()["lastTimestamp"]}, {Name: "Type", Type: "string", Description: apiv1.Event{}.SwaggerDoc()["type"]}, {Name: "Reason", Type: "string", Description: apiv1.Event{}.SwaggerDoc()["reason"]}, {Name: "Object", Type: "string", Description: apiv1.Event{}.SwaggerDoc()["involvedObject"]}, {Name: "Subobject", Type: "string", Priority: 1, Description: apiv1.Event{}.InvolvedObject.SwaggerDoc()["fieldPath"]}, {Name: "Source", Type: "string", Priority: 1, Description: apiv1.Event{}.SwaggerDoc()["source"]}, {Name: "Message", Type: "string", Description: apiv1.Event{}.SwaggerDoc()["message"]}, {Name: "First Seen", Type: "string", Priority: 1, Description: apiv1.Event{}.SwaggerDoc()["firstTimestamp"]}, {Name: "Count", Type: "string", Priority: 1, Description: apiv1.Event{}.SwaggerDoc()["count"]}, {Name: "Name", Type: "string", Priority: 1, Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, } h.TableHandler(eventColumnDefinitions, printEvent) h.TableHandler(eventColumnDefinitions, printEventList) namespaceColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Status", Type: "string", Description: "The status of the namespace"}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, } h.TableHandler(namespaceColumnDefinitions, printNamespace) h.TableHandler(namespaceColumnDefinitions, printNamespaceList) secretColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Type", Type: "string", Description: apiv1.Secret{}.SwaggerDoc()["type"]}, {Name: "Data", Type: "string", Description: apiv1.Secret{}.SwaggerDoc()["data"]}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, } h.TableHandler(secretColumnDefinitions, printSecret) h.TableHandler(secretColumnDefinitions, printSecretList) serviceAccountColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Secrets", Type: "string", Description: apiv1.ServiceAccount{}.SwaggerDoc()["secrets"]}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, } h.TableHandler(serviceAccountColumnDefinitions, printServiceAccount) h.TableHandler(serviceAccountColumnDefinitions, printServiceAccountList) persistentVolumeColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Capacity", Type: "string", Description: apiv1.PersistentVolumeSpec{}.SwaggerDoc()["capacity"]}, {Name: "Access Modes", Type: "string", Description: apiv1.PersistentVolumeSpec{}.SwaggerDoc()["accessModes"]}, {Name: "Reclaim Policy", Type: "string", Description: apiv1.PersistentVolumeSpec{}.SwaggerDoc()["persistentVolumeReclaimPolicy"]}, {Name: "Status", Type: "string", Description: apiv1.PersistentVolumeStatus{}.SwaggerDoc()["phase"]}, {Name: "Claim", Type: "string", Description: apiv1.PersistentVolumeSpec{}.SwaggerDoc()["claimRef"]}, {Name: "StorageClass", Type: "string", Description: "StorageClass of the pv"}, {Name: "Reason", Type: "string", Description: apiv1.PersistentVolumeStatus{}.SwaggerDoc()["reason"]}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, } h.TableHandler(persistentVolumeColumnDefinitions, printPersistentVolume) h.TableHandler(persistentVolumeColumnDefinitions, printPersistentVolumeList) persistentVolumeClaimColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Status", Type: "string", Description: apiv1.PersistentVolumeClaimStatus{}.SwaggerDoc()["phase"]}, {Name: "Volume", Type: "string", Description: apiv1.PersistentVolumeClaimSpec{}.SwaggerDoc()["volumeName"]}, {Name: "Capacity", Type: "string", Description: apiv1.PersistentVolumeClaimStatus{}.SwaggerDoc()["capacity"]}, {Name: "Access Modes", Type: "string", Description: apiv1.PersistentVolumeClaimStatus{}.SwaggerDoc()["accessModes"]}, {Name: "StorageClass", Type: "string", Description: "StorageClass of the pvc"}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, } h.TableHandler(persistentVolumeClaimColumnDefinitions, printPersistentVolumeClaim) h.TableHandler(persistentVolumeClaimColumnDefinitions, printPersistentVolumeClaimList) componentStatusColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Status", Type: "string", Description: "Status of the component conditions"}, {Name: "Message", Type: "string", Description: "Message of the component conditions"}, {Name: "Error", Type: "string", Description: "Error of the component conditions"}, } h.TableHandler(componentStatusColumnDefinitions, printComponentStatus) h.TableHandler(componentStatusColumnDefinitions, printComponentStatusList) deploymentColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Ready", Type: "string", Description: "Number of the pod with ready state"}, {Name: "Up-to-date", Type: "string", Description: extensionsv1beta1.DeploymentStatus{}.SwaggerDoc()["updatedReplicas"]}, {Name: "Available", Type: "string", Description: extensionsv1beta1.DeploymentStatus{}.SwaggerDoc()["availableReplicas"]}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, {Name: "Containers", Type: "string", Priority: 1, Description: "Names of each container in the template."}, {Name: "Images", Type: "string", Priority: 1, Description: "Images referenced by each container in the template."}, {Name: "Selector", Type: "string", Priority: 1, Description: extensionsv1beta1.DeploymentSpec{}.SwaggerDoc()["selector"]}, } h.TableHandler(deploymentColumnDefinitions, printDeployment) h.TableHandler(deploymentColumnDefinitions, printDeploymentList) horizontalPodAutoscalerColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Reference", Type: "string", Description: autoscalingv2beta1.HorizontalPodAutoscalerSpec{}.SwaggerDoc()["scaleTargetRef"]}, {Name: "Targets", Type: "string", Description: autoscalingv2beta1.HorizontalPodAutoscalerSpec{}.SwaggerDoc()["metrics"]}, {Name: "MinPods", Type: "string", Description: autoscalingv2beta1.HorizontalPodAutoscalerSpec{}.SwaggerDoc()["minReplicas"]}, {Name: "MaxPods", Type: "string", Description: autoscalingv2beta1.HorizontalPodAutoscalerSpec{}.SwaggerDoc()["maxReplicas"]}, {Name: "Replicas", Type: "string", Description: autoscalingv2beta1.HorizontalPodAutoscalerStatus{}.SwaggerDoc()["currentReplicas"]}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, } h.TableHandler(horizontalPodAutoscalerColumnDefinitions, printHorizontalPodAutoscaler) h.TableHandler(horizontalPodAutoscalerColumnDefinitions, printHorizontalPodAutoscalerList) configMapColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Data", Type: "string", Description: apiv1.ConfigMap{}.SwaggerDoc()["data"]}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, } h.TableHandler(configMapColumnDefinitions, printConfigMap) h.TableHandler(configMapColumnDefinitions, printConfigMapList) podSecurityPolicyColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Priv", Type: "string", Description: policyv1beta1.PodSecurityPolicySpec{}.SwaggerDoc()["privileged"]}, {Name: "Caps", Type: "string", Description: policyv1beta1.PodSecurityPolicySpec{}.SwaggerDoc()["allowedCapabilities"]}, {Name: "SELinux", Type: "string", Description: policyv1beta1.PodSecurityPolicySpec{}.SwaggerDoc()["seLinux"]}, {Name: "RunAsUser", Type: "string", Description: policyv1beta1.PodSecurityPolicySpec{}.SwaggerDoc()["runAsUser"]}, {Name: "FsGroup", Type: "string", Description: policyv1beta1.PodSecurityPolicySpec{}.SwaggerDoc()["fsGroup"]}, {Name: "SupGroup", Type: "string", Description: policyv1beta1.PodSecurityPolicySpec{}.SwaggerDoc()["supplementalGroups"]}, {Name: "ReadOnlyRootFs", Type: "string", Description: policyv1beta1.PodSecurityPolicySpec{}.SwaggerDoc()["readOnlyRootFilesystem"]}, {Name: "Volumes", Type: "string", Description: policyv1beta1.PodSecurityPolicySpec{}.SwaggerDoc()["volumes"]}, } h.TableHandler(podSecurityPolicyColumnDefinitions, printPodSecurityPolicy) h.TableHandler(podSecurityPolicyColumnDefinitions, printPodSecurityPolicyList) networkPolicyColumnDefinitioins := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Pod-Selector", Type: "string", Description: extensionsv1beta1.NetworkPolicySpec{}.SwaggerDoc()["podSelector"]}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, } h.TableHandler(networkPolicyColumnDefinitioins, printNetworkPolicy) h.TableHandler(networkPolicyColumnDefinitioins, printNetworkPolicyList) roleBindingsColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, {Name: "Role", Type: "string", Priority: 1, Description: rbacv1beta1.RoleBinding{}.SwaggerDoc()["roleRef"]}, {Name: "Users", Type: "string", Priority: 1, Description: "Users in the roleBinding"}, {Name: "Groups", Type: "string", Priority: 1, Description: "Groups in the roleBinding"}, {Name: "ServiceAccounts", Type: "string", Priority: 1, Description: "ServiceAccounts in the roleBinding"}, } h.TableHandler(roleBindingsColumnDefinitions, printRoleBinding) h.TableHandler(roleBindingsColumnDefinitions, printRoleBindingList) clusterRoleBindingsColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, {Name: "Role", Type: "string", Priority: 1, Description: rbacv1beta1.ClusterRoleBinding{}.SwaggerDoc()["roleRef"]}, {Name: "Users", Type: "string", Priority: 1, Description: "Users in the clusterRoleBinding"}, {Name: "Groups", Type: "string", Priority: 1, Description: "Groups in the clusterRoleBinding"}, {Name: "ServiceAccounts", Type: "string", Priority: 1, Description: "ServiceAccounts in the clusterRoleBinding"}, } h.TableHandler(clusterRoleBindingsColumnDefinitions, printClusterRoleBinding) h.TableHandler(clusterRoleBindingsColumnDefinitions, printClusterRoleBindingList) certificateSigningRequestColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, {Name: "Requestor", Type: "string", Description: certificatesv1beta1.CertificateSigningRequestSpec{}.SwaggerDoc()["request"]}, {Name: "Condition", Type: "string", Description: certificatesv1beta1.CertificateSigningRequestStatus{}.SwaggerDoc()["conditions"]}, } h.TableHandler(certificateSigningRequestColumnDefinitions, printCertificateSigningRequest) h.TableHandler(certificateSigningRequestColumnDefinitions, printCertificateSigningRequestList) leaseColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Holder", Type: "string", Description: coordinationv1.LeaseSpec{}.SwaggerDoc()["holderIdentity"]}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, } h.TableHandler(leaseColumnDefinitions, printLease) h.TableHandler(leaseColumnDefinitions, printLeaseList) storageClassColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Provisioner", Type: "string", Description: storagev1.StorageClass{}.SwaggerDoc()["provisioner"]}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, } h.TableHandler(storageClassColumnDefinitions, printStorageClass) h.TableHandler(storageClassColumnDefinitions, printStorageClassList) statusColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Status", Type: "string", Description: metav1.Status{}.SwaggerDoc()["status"]}, {Name: "Reason", Type: "string", Description: metav1.Status{}.SwaggerDoc()["reason"]}, {Name: "Message", Type: "string", Description: metav1.Status{}.SwaggerDoc()["Message"]}, } h.TableHandler(statusColumnDefinitions, printStatus) controllerRevisionColumnDefinition := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Controller", Type: "string", Description: "Controller of the object"}, {Name: "Revision", Type: "string", Description: appsv1beta1.ControllerRevision{}.SwaggerDoc()["revision"]}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, } h.TableHandler(controllerRevisionColumnDefinition, printControllerRevision) h.TableHandler(controllerRevisionColumnDefinition, printControllerRevisionList) resourceQuotaColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, {Name: "Request", Type: "string", Description: "Request represents a minimum amount of cpu/memory that a container may consume."}, {Name: "Limit", Type: "string", Description: "Limits control the maximum amount of cpu/memory that a container may use independent of contention on the node."}, } h.TableHandler(resourceQuotaColumnDefinitions, printResourceQuota) h.TableHandler(resourceQuotaColumnDefinitions, printResourceQuotaList) priorityClassColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Value", Type: "integer", Description: schedulingv1beta1.PriorityClass{}.SwaggerDoc()["value"]}, {Name: "Global-Default", Type: "boolean", Description: schedulingv1beta1.PriorityClass{}.SwaggerDoc()["globalDefault"]}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, } h.TableHandler(priorityClassColumnDefinitions, printPriorityClass) h.TableHandler(priorityClassColumnDefinitions, printPriorityClassList) runtimeClassColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Handler", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["handler"]}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, } h.TableHandler(runtimeClassColumnDefinitions, printRuntimeClass) h.TableHandler(runtimeClassColumnDefinitions, printRuntimeClassList) volumeAttachmentColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Attacher", Type: "string", Format: "name", Description: storagev1.VolumeAttachmentSpec{}.SwaggerDoc()["attacher"]}, {Name: "PV", Type: "string", Description: storagev1.VolumeAttachmentSource{}.SwaggerDoc()["persistentVolumeName"]}, {Name: "Node", Type: "string", Description: storagev1.VolumeAttachmentSpec{}.SwaggerDoc()["nodeName"]}, {Name: "Attached", Type: "boolean", Description: storagev1.VolumeAttachmentStatus{}.SwaggerDoc()["attached"]}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, } h.TableHandler(volumeAttachmentColumnDefinitions, printVolumeAttachment) h.TableHandler(volumeAttachmentColumnDefinitions, printVolumeAttachmentList) AddDefaultHandlers(h) } // AddDefaultHandlers adds handlers that can work with most Kubernetes objects. func AddDefaultHandlers(h printers.PrintHandler) { // types without defined columns objectMetaColumnDefinitions := []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string", Format: "name", Description: metav1.ObjectMeta{}.SwaggerDoc()["name"]}, {Name: "Age", Type: "string", Description: metav1.ObjectMeta{}.SwaggerDoc()["creationTimestamp"]}, } h.DefaultTableHandler(objectMetaColumnDefinitions, printObjectMeta) } func printObjectMeta(obj runtime.Object, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { if meta.IsListType(obj) { rows := make([]metav1beta1.TableRow, 0, 16) err := meta.EachListItem(obj, func(obj runtime.Object) error { nestedRows, err := printObjectMeta(obj, options) if err != nil { return err } rows = append(rows, nestedRows...) return nil }) if err != nil { return nil, err } return rows, nil } rows := make([]metav1beta1.TableRow, 0, 1) m, err := meta.Accessor(obj) if err != nil { return nil, err } row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } row.Cells = append(row.Cells, m.GetName(), translateTimestampSince(m.GetCreationTimestamp())) rows = append(rows, row) return rows, nil } // Pass ports=nil for all ports. func formatEndpoints(endpoints *api.Endpoints, ports sets.String) string { if len(endpoints.Subsets) == 0 { return "<none>" } list := []string{} max := 3 more := false count := 0 for i := range endpoints.Subsets { ss := &endpoints.Subsets[i] if len(ss.Ports) == 0 { // It's possible to have headless services with no ports. for i := range ss.Addresses { if len(list) == max { more = true } if !more { list = append(list, ss.Addresses[i].IP) } count++ } } else { // "Normal" services with ports defined. for i := range ss.Ports { port := &ss.Ports[i] if ports == nil || ports.Has(port.Name) { for i := range ss.Addresses { if len(list) == max { more = true } addr := &ss.Addresses[i] if !more { hostPort := net.JoinHostPort(addr.IP, strconv.Itoa(int(port.Port))) list = append(list, hostPort) } count++ } } } } } ret := strings.Join(list, ",") if more { return fmt.Sprintf("%s + %d more...", ret, count-max) } return ret } // translateTimestampSince returns the elapsed time since timestamp in // human-readable approximation. func translateTimestampSince(timestamp metav1.Time) string { if timestamp.IsZero() { return "<unknown>" } return duration.HumanDuration(time.Since(timestamp.Time)) } // translateTimestampUntil returns the elapsed time until timestamp in // human-readable approximation. func translateTimestampUntil(timestamp metav1.Time) string { if timestamp.IsZero() { return "<unknown>" } return duration.HumanDuration(time.Until(timestamp.Time)) } var ( podSuccessConditions = []metav1beta1.TableRowCondition{{Type: metav1beta1.RowCompleted, Status: metav1beta1.ConditionTrue, Reason: string(api.PodSucceeded), Message: "The pod has completed successfully."}} podFailedConditions = []metav1beta1.TableRowCondition{{Type: metav1beta1.RowCompleted, Status: metav1beta1.ConditionTrue, Reason: string(api.PodFailed), Message: "The pod failed."}} ) func printPodList(podList *api.PodList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(podList.Items)) for i := range podList.Items { r, err := printPod(&podList.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printPod(pod *api.Pod, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { restarts := 0 totalContainers := len(pod.Spec.Containers) readyContainers := 0 reason := string(pod.Status.Phase) if pod.Status.Reason != "" { reason = pod.Status.Reason } row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: pod}, } switch pod.Status.Phase { case api.PodSucceeded: row.Conditions = podSuccessConditions case api.PodFailed: row.Conditions = podFailedConditions } initializing := false for i := range pod.Status.InitContainerStatuses { container := pod.Status.InitContainerStatuses[i] restarts += int(container.RestartCount) switch { case container.State.Terminated != nil && container.State.Terminated.ExitCode == 0: continue case container.State.Terminated != nil: // initialization is failed if len(container.State.Terminated.Reason) == 0 { if container.State.Terminated.Signal != 0 { reason = fmt.Sprintf("Init:Signal:%d", container.State.Terminated.Signal) } else { reason = fmt.Sprintf("Init:ExitCode:%d", container.State.Terminated.ExitCode) } } else { reason = "Init:" + container.State.Terminated.Reason } initializing = true case container.State.Waiting != nil && len(container.State.Waiting.Reason) > 0 && container.State.Waiting.Reason != "PodInitializing": reason = "Init:" + container.State.Waiting.Reason initializing = true default: reason = fmt.Sprintf("Init:%d/%d", i, len(pod.Spec.InitContainers)) initializing = true } break } if !initializing { restarts = 0 hasRunning := false for i := len(pod.Status.ContainerStatuses) - 1; i >= 0; i-- { container := pod.Status.ContainerStatuses[i] restarts += int(container.RestartCount) if container.State.Waiting != nil && container.State.Waiting.Reason != "" { reason = container.State.Waiting.Reason } else if container.State.Terminated != nil && container.State.Terminated.Reason != "" { reason = container.State.Terminated.Reason } else if container.State.Terminated != nil && container.State.Terminated.Reason == "" { if container.State.Terminated.Signal != 0 { reason = fmt.Sprintf("Signal:%d", container.State.Terminated.Signal) } else { reason = fmt.Sprintf("ExitCode:%d", container.State.Terminated.ExitCode) } } else if container.Ready && container.State.Running != nil { hasRunning = true readyContainers++ } } // change pod status back to "Running" if there is at least one container still reporting as "Running" status if reason == "Completed" && hasRunning { reason = "Running" } } if pod.DeletionTimestamp != nil && pod.Status.Reason == node.NodeUnreachablePodReason { reason = "Unknown" } else if pod.DeletionTimestamp != nil { reason = "Terminating" } row.Cells = append(row.Cells, pod.Name, fmt.Sprintf("%d/%d", readyContainers, totalContainers), reason, int64(restarts), translateTimestampSince(pod.CreationTimestamp)) if options.Wide { nodeName := pod.Spec.NodeName nominatedNodeName := pod.Status.NominatedNodeName podIP := pod.Status.PodIP if podIP == "" { podIP = "<none>" } if nodeName == "" { nodeName = "<none>" } if nominatedNodeName == "" { nominatedNodeName = "<none>" } readinessGates := "<none>" if len(pod.Spec.ReadinessGates) > 0 { trueConditions := 0 for _, readinessGate := range pod.Spec.ReadinessGates { conditionType := readinessGate.ConditionType for _, condition := range pod.Status.Conditions { if condition.Type == conditionType { if condition.Status == api.ConditionTrue { trueConditions += 1 } break } } } readinessGates = fmt.Sprintf("%d/%d", trueConditions, len(pod.Spec.ReadinessGates)) } row.Cells = append(row.Cells, podIP, nodeName, nominatedNodeName, readinessGates) } return []metav1beta1.TableRow{row}, nil } func printPodTemplate(obj *api.PodTemplate, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } names, images := layoutContainerCells(obj.Template.Spec.Containers) row.Cells = append(row.Cells, obj.Name, names, images, labels.FormatLabels(obj.Template.Labels)) return []metav1beta1.TableRow{row}, nil } func printPodTemplateList(list *api.PodTemplateList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printPodTemplate(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printPodDisruptionBudget(obj *policy.PodDisruptionBudget, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } var minAvailable string var maxUnavailable string if obj.Spec.MinAvailable != nil { minAvailable = obj.Spec.MinAvailable.String() } else { minAvailable = "N/A" } if obj.Spec.MaxUnavailable != nil { maxUnavailable = obj.Spec.MaxUnavailable.String() } else { maxUnavailable = "N/A" } row.Cells = append(row.Cells, obj.Name, minAvailable, maxUnavailable, int64(obj.Status.PodDisruptionsAllowed), translateTimestampSince(obj.CreationTimestamp)) return []metav1beta1.TableRow{row}, nil } func printPodDisruptionBudgetList(list *policy.PodDisruptionBudgetList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printPodDisruptionBudget(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } // TODO(AdoHe): try to put wide output in a single method func printReplicationController(obj *api.ReplicationController, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } desiredReplicas := obj.Spec.Replicas currentReplicas := obj.Status.Replicas readyReplicas := obj.Status.ReadyReplicas row.Cells = append(row.Cells, obj.Name, int64(desiredReplicas), int64(currentReplicas), int64(readyReplicas), translateTimestampSince(obj.CreationTimestamp)) if options.Wide { names, images := layoutContainerCells(obj.Spec.Template.Spec.Containers) row.Cells = append(row.Cells, names, images, labels.FormatLabels(obj.Spec.Selector)) } return []metav1beta1.TableRow{row}, nil } func printReplicationControllerList(list *api.ReplicationControllerList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printReplicationController(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printReplicaSet(obj *apps.ReplicaSet, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } desiredReplicas := obj.Spec.Replicas currentReplicas := obj.Status.Replicas readyReplicas := obj.Status.ReadyReplicas row.Cells = append(row.Cells, obj.Name, int64(desiredReplicas), int64(currentReplicas), int64(readyReplicas), translateTimestampSince(obj.CreationTimestamp)) if options.Wide { names, images := layoutContainerCells(obj.Spec.Template.Spec.Containers) row.Cells = append(row.Cells, names, images, metav1.FormatLabelSelector(obj.Spec.Selector)) } return []metav1beta1.TableRow{row}, nil } func printReplicaSetList(list *apps.ReplicaSetList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printReplicaSet(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printJob(obj *batch.Job, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } var completions string if obj.Spec.Completions != nil { completions = fmt.Sprintf("%d/%d", obj.Status.Succeeded, *obj.Spec.Completions) } else { parallelism := int32(0) if obj.Spec.Parallelism != nil { parallelism = *obj.Spec.Parallelism } if parallelism > 1 { completions = fmt.Sprintf("%d/1 of %d", obj.Status.Succeeded, parallelism) } else { completions = fmt.Sprintf("%d/1", obj.Status.Succeeded) } } var jobDuration string switch { case obj.Status.StartTime == nil: case obj.Status.CompletionTime == nil: jobDuration = duration.HumanDuration(time.Now().Sub(obj.Status.StartTime.Time)) default: jobDuration = duration.HumanDuration(obj.Status.CompletionTime.Sub(obj.Status.StartTime.Time)) } row.Cells = append(row.Cells, obj.Name, completions, jobDuration, translateTimestampSince(obj.CreationTimestamp)) if options.Wide { names, images := layoutContainerCells(obj.Spec.Template.Spec.Containers) row.Cells = append(row.Cells, names, images, metav1.FormatLabelSelector(obj.Spec.Selector)) } return []metav1beta1.TableRow{row}, nil } func printJobList(list *batch.JobList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printJob(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printCronJob(obj *batch.CronJob, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } lastScheduleTime := "<none>" if obj.Status.LastScheduleTime != nil { lastScheduleTime = translateTimestampSince(*obj.Status.LastScheduleTime) } row.Cells = append(row.Cells, obj.Name, obj.Spec.Schedule, printBoolPtr(obj.Spec.Suspend), int64(len(obj.Status.Active)), lastScheduleTime, translateTimestampSince(obj.CreationTimestamp)) if options.Wide { names, images := layoutContainerCells(obj.Spec.JobTemplate.Spec.Template.Spec.Containers) row.Cells = append(row.Cells, names, images, metav1.FormatLabelSelector(obj.Spec.JobTemplate.Spec.Selector)) } return []metav1beta1.TableRow{row}, nil } func printCronJobList(list *batch.CronJobList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printCronJob(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } // loadBalancerStatusStringer behaves mostly like a string interface and converts the given status to a string. // `wide` indicates whether the returned value is meant for --o=wide output. If not, it's clipped to 16 bytes. func loadBalancerStatusStringer(s api.LoadBalancerStatus, wide bool) string { ingress := s.Ingress result := sets.NewString() for i := range ingress { if ingress[i].IP != "" { result.Insert(ingress[i].IP) } else if ingress[i].Hostname != "" { result.Insert(ingress[i].Hostname) } } r := strings.Join(result.List(), ",") if !wide && len(r) > loadBalancerWidth { r = r[0:(loadBalancerWidth-3)] + "..." } return r } func getServiceExternalIP(svc *api.Service, wide bool) string { switch svc.Spec.Type { case api.ServiceTypeClusterIP: if len(svc.Spec.ExternalIPs) > 0 { return strings.Join(svc.Spec.ExternalIPs, ",") } return "<none>" case api.ServiceTypeNodePort: if len(svc.Spec.ExternalIPs) > 0 { return strings.Join(svc.Spec.ExternalIPs, ",") } return "<none>" case api.ServiceTypeLoadBalancer: lbIps := loadBalancerStatusStringer(svc.Status.LoadBalancer, wide) if len(svc.Spec.ExternalIPs) > 0 { results := []string{} if len(lbIps) > 0 { results = append(results, strings.Split(lbIps, ",")...) } results = append(results, svc.Spec.ExternalIPs...) return strings.Join(results, ",") } if len(lbIps) > 0 { return lbIps } return "<pending>" case api.ServiceTypeExternalName: return svc.Spec.ExternalName } return "<unknown>" } func makePortString(ports []api.ServicePort) string { pieces := make([]string, len(ports)) for ix := range ports { port := &ports[ix] pieces[ix] = fmt.Sprintf("%d/%s", port.Port, port.Protocol) if port.NodePort > 0 { pieces[ix] = fmt.Sprintf("%d:%d/%s", port.Port, port.NodePort, port.Protocol) } } return strings.Join(pieces, ",") } func printService(obj *api.Service, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } svcType := obj.Spec.Type internalIP := obj.Spec.ClusterIP if len(internalIP) == 0 { internalIP = "<none>" } externalIP := getServiceExternalIP(obj, options.Wide) svcPorts := makePortString(obj.Spec.Ports) if len(svcPorts) == 0 { svcPorts = "<none>" } row.Cells = append(row.Cells, obj.Name, string(svcType), internalIP, externalIP, svcPorts, translateTimestampSince(obj.CreationTimestamp)) if options.Wide { row.Cells = append(row.Cells, labels.FormatLabels(obj.Spec.Selector)) } return []metav1beta1.TableRow{row}, nil } func printServiceList(list *api.ServiceList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printService(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } // backendStringer behaves just like a string interface and converts the given backend to a string. func backendStringer(backend *networking.IngressBackend) string { if backend == nil { return "" } return fmt.Sprintf("%v:%v", backend.ServiceName, backend.ServicePort.String()) } func formatHosts(rules []networking.IngressRule) string { list := []string{} max := 3 more := false for _, rule := range rules { if len(list) == max { more = true } if !more && len(rule.Host) != 0 { list = append(list, rule.Host) } } if len(list) == 0 { return "*" } ret := strings.Join(list, ",") if more { return fmt.Sprintf("%s + %d more...", ret, len(rules)-max) } return ret } func formatPorts(tls []networking.IngressTLS) string { if len(tls) != 0 { return "80, 443" } return "80" } func printIngress(obj *networking.Ingress, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } hosts := formatHosts(obj.Spec.Rules) address := loadBalancerStatusStringer(obj.Status.LoadBalancer, options.Wide) ports := formatPorts(obj.Spec.TLS) createTime := translateTimestampSince(obj.CreationTimestamp) row.Cells = append(row.Cells, obj.Name, hosts, address, ports, createTime) return []metav1beta1.TableRow{row}, nil } func printIngressList(list *networking.IngressList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printIngress(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printStatefulSet(obj *apps.StatefulSet, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } desiredReplicas := obj.Spec.Replicas readyReplicas := obj.Status.ReadyReplicas createTime := translateTimestampSince(obj.CreationTimestamp) row.Cells = append(row.Cells, obj.Name, fmt.Sprintf("%d/%d", int64(readyReplicas), int64(desiredReplicas)), createTime) if options.Wide { names, images := layoutContainerCells(obj.Spec.Template.Spec.Containers) row.Cells = append(row.Cells, names, images) } return []metav1beta1.TableRow{row}, nil } func printStatefulSetList(list *apps.StatefulSetList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printStatefulSet(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printDaemonSet(obj *apps.DaemonSet, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } desiredScheduled := obj.Status.DesiredNumberScheduled currentScheduled := obj.Status.CurrentNumberScheduled numberReady := obj.Status.NumberReady numberUpdated := obj.Status.UpdatedNumberScheduled numberAvailable := obj.Status.NumberAvailable row.Cells = append(row.Cells, obj.Name, int64(desiredScheduled), int64(currentScheduled), int64(numberReady), int64(numberUpdated), int64(numberAvailable), labels.FormatLabels(obj.Spec.Template.Spec.NodeSelector), translateTimestampSince(obj.CreationTimestamp)) if options.Wide { names, images := layoutContainerCells(obj.Spec.Template.Spec.Containers) row.Cells = append(row.Cells, names, images, metav1.FormatLabelSelector(obj.Spec.Selector)) } return []metav1beta1.TableRow{row}, nil } func printDaemonSetList(list *apps.DaemonSetList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printDaemonSet(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printEndpoints(obj *api.Endpoints, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } row.Cells = append(row.Cells, obj.Name, formatEndpoints(obj, nil), translateTimestampSince(obj.CreationTimestamp)) return []metav1beta1.TableRow{row}, nil } func printEndpointsList(list *api.EndpointsList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printEndpoints(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printNamespace(obj *api.Namespace, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } row.Cells = append(row.Cells, obj.Name, string(obj.Status.Phase), translateTimestampSince(obj.CreationTimestamp)) return []metav1beta1.TableRow{row}, nil } func printNamespaceList(list *api.NamespaceList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printNamespace(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printSecret(obj *api.Secret, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } row.Cells = append(row.Cells, obj.Name, string(obj.Type), int64(len(obj.Data)), translateTimestampSince(obj.CreationTimestamp)) return []metav1beta1.TableRow{row}, nil } func printSecretList(list *api.SecretList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printSecret(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printServiceAccount(obj *api.ServiceAccount, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } row.Cells = append(row.Cells, obj.Name, int64(len(obj.Secrets)), translateTimestampSince(obj.CreationTimestamp)) return []metav1beta1.TableRow{row}, nil } func printServiceAccountList(list *api.ServiceAccountList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printServiceAccount(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printNode(obj *api.Node, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } conditionMap := make(map[api.NodeConditionType]*api.NodeCondition) NodeAllConditions := []api.NodeConditionType{api.NodeReady} for i := range obj.Status.Conditions { cond := obj.Status.Conditions[i] conditionMap[cond.Type] = &cond } var status []string for _, validCondition := range NodeAllConditions { if condition, ok := conditionMap[validCondition]; ok { if condition.Status == api.ConditionTrue { status = append(status, string(condition.Type)) } else { status = append(status, "Not"+string(condition.Type)) } } } if len(status) == 0 { status = append(status, "Unknown") } if obj.Spec.Unschedulable { status = append(status, "SchedulingDisabled") } roles := strings.Join(findNodeRoles(obj), ",") if len(roles) == 0 { roles = "<none>" } row.Cells = append(row.Cells, obj.Name, strings.Join(status, ","), roles, translateTimestampSince(obj.CreationTimestamp), obj.Status.NodeInfo.KubeletVersion) if options.Wide { osImage, kernelVersion, crVersion := obj.Status.NodeInfo.OSImage, obj.Status.NodeInfo.KernelVersion, obj.Status.NodeInfo.ContainerRuntimeVersion if osImage == "" { osImage = "<unknown>" } if kernelVersion == "" { kernelVersion = "<unknown>" } if crVersion == "" { crVersion = "<unknown>" } row.Cells = append(row.Cells, getNodeInternalIP(obj), getNodeExternalIP(obj), osImage, kernelVersion, crVersion) } return []metav1beta1.TableRow{row}, nil } // Returns first external ip of the node or "<none>" if none is found. func getNodeExternalIP(node *api.Node) string { for _, address := range node.Status.Addresses { if address.Type == api.NodeExternalIP { return address.Address } } return "<none>" } // Returns the internal IP of the node or "<none>" if none is found. func getNodeInternalIP(node *api.Node) string { for _, address := range node.Status.Addresses { if address.Type == api.NodeInternalIP { return address.Address } } return "<none>" } // findNodeRoles returns the roles of a given node. // The roles are determined by looking for: // * a node-role.kubernetes.io/<role>="" label // * a kubernetes.io/role="<role>" label func findNodeRoles(node *api.Node) []string { roles := sets.NewString() for k, v := range node.Labels { switch { case strings.HasPrefix(k, labelNodeRolePrefix): if role := strings.TrimPrefix(k, labelNodeRolePrefix); len(role) > 0 { roles.Insert(role) } case k == nodeLabelRole && v != "": roles.Insert(v) } } return roles.List() } func printNodeList(list *api.NodeList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printNode(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printPersistentVolume(obj *api.PersistentVolume, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } claimRefUID := "" if obj.Spec.ClaimRef != nil { claimRefUID += obj.Spec.ClaimRef.Namespace claimRefUID += "/" claimRefUID += obj.Spec.ClaimRef.Name } modesStr := helper.GetAccessModesAsString(obj.Spec.AccessModes) reclaimPolicyStr := string(obj.Spec.PersistentVolumeReclaimPolicy) aQty := obj.Spec.Capacity[api.ResourceStorage] aSize := aQty.String() phase := obj.Status.Phase if obj.ObjectMeta.DeletionTimestamp != nil { phase = "Terminating" } row.Cells = append(row.Cells, obj.Name, aSize, modesStr, reclaimPolicyStr, string(phase), claimRefUID, helper.GetPersistentVolumeClass(obj), obj.Status.Reason, translateTimestampSince(obj.CreationTimestamp)) return []metav1beta1.TableRow{row}, nil } func printPersistentVolumeList(list *api.PersistentVolumeList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printPersistentVolume(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printPersistentVolumeClaim(obj *api.PersistentVolumeClaim, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } phase := obj.Status.Phase if obj.ObjectMeta.DeletionTimestamp != nil { phase = "Terminating" } storage := obj.Spec.Resources.Requests[api.ResourceStorage] capacity := "" accessModes := "" if obj.Spec.VolumeName != "" { accessModes = helper.GetAccessModesAsString(obj.Status.AccessModes) storage = obj.Status.Capacity[api.ResourceStorage] capacity = storage.String() } row.Cells = append(row.Cells, obj.Name, string(phase), obj.Spec.VolumeName, capacity, accessModes, helper.GetPersistentVolumeClaimClass(obj), translateTimestampSince(obj.CreationTimestamp)) return []metav1beta1.TableRow{row}, nil } func printPersistentVolumeClaimList(list *api.PersistentVolumeClaimList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printPersistentVolumeClaim(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printEvent(obj *api.Event, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } // While watching event, we should print absolute time. var firstTimestamp, lastTimestamp string if options.AbsoluteTimestamps { firstTimestamp = obj.FirstTimestamp.String() lastTimestamp = obj.LastTimestamp.String() } else { firstTimestamp = translateTimestampSince(obj.FirstTimestamp) lastTimestamp = translateTimestampSince(obj.LastTimestamp) } var target string if len(obj.InvolvedObject.Name) > 0 { target = fmt.Sprintf("%s/%s", strings.ToLower(obj.InvolvedObject.Kind), obj.InvolvedObject.Name) } else { target = strings.ToLower(obj.InvolvedObject.Kind) } if options.Wide { row.Cells = append(row.Cells, lastTimestamp, obj.Type, obj.Reason, target, obj.InvolvedObject.FieldPath, formatEventSource(obj.Source), strings.TrimSpace(obj.Message), firstTimestamp, int64(obj.Count), obj.Name, ) } else { row.Cells = append(row.Cells, lastTimestamp, obj.Type, obj.Reason, target, strings.TrimSpace(obj.Message), ) } return []metav1beta1.TableRow{row}, nil } // Sorts and prints the EventList in a human-friendly format. func printEventList(list *api.EventList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printEvent(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printRoleBinding(obj *rbac.RoleBinding, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } row.Cells = append(row.Cells, obj.Name, translateTimestampSince(obj.CreationTimestamp)) if options.Wide { roleRef := fmt.Sprintf("%s/%s", obj.RoleRef.Kind, obj.RoleRef.Name) users, groups, sas, _ := rbac.SubjectsStrings(obj.Subjects) row.Cells = append(row.Cells, roleRef, strings.Join(users, ", "), strings.Join(groups, ", "), strings.Join(sas, ", ")) } return []metav1beta1.TableRow{row}, nil } // Prints the RoleBinding in a human-friendly format. func printRoleBindingList(list *rbac.RoleBindingList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printRoleBinding(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printClusterRoleBinding(obj *rbac.ClusterRoleBinding, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } row.Cells = append(row.Cells, obj.Name, translateTimestampSince(obj.CreationTimestamp)) if options.Wide { roleRef := fmt.Sprintf("%s/%s", obj.RoleRef.Kind, obj.RoleRef.Name) users, groups, sas, _ := rbac.SubjectsStrings(obj.Subjects) row.Cells = append(row.Cells, roleRef, strings.Join(users, ", "), strings.Join(groups, ", "), strings.Join(sas, ", ")) } return []metav1beta1.TableRow{row}, nil } // Prints the ClusterRoleBinding in a human-friendly format. func printClusterRoleBindingList(list *rbac.ClusterRoleBindingList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printClusterRoleBinding(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printCertificateSigningRequest(obj *certificates.CertificateSigningRequest, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } status, err := extractCSRStatus(obj) if err != nil { return nil, err } row.Cells = append(row.Cells, obj.Name, translateTimestampSince(obj.CreationTimestamp), obj.Spec.Username, status) return []metav1beta1.TableRow{row}, nil } func extractCSRStatus(csr *certificates.CertificateSigningRequest) (string, error) { var approved, denied bool for _, c := range csr.Status.Conditions { switch c.Type { case certificates.CertificateApproved: approved = true case certificates.CertificateDenied: denied = true default: return "", fmt.Errorf("unknown csr condition %q", c) } } var status string // must be in order of presidence if denied { status += "Denied" } else if approved { status += "Approved" } else { status += "Pending" } if len(csr.Status.Certificate) > 0 { status += ",Issued" } return status, nil } func printCertificateSigningRequestList(list *certificates.CertificateSigningRequestList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printCertificateSigningRequest(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printComponentStatus(obj *api.ComponentStatus, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } status := "Unknown" message := "" error := "" for _, condition := range obj.Conditions { if condition.Type == api.ComponentHealthy { if condition.Status == api.ConditionTrue { status = "Healthy" } else { status = "Unhealthy" } message = condition.Message error = condition.Error break } } row.Cells = append(row.Cells, obj.Name, status, message, error) return []metav1beta1.TableRow{row}, nil } func printComponentStatusList(list *api.ComponentStatusList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printComponentStatus(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printDeployment(obj *apps.Deployment, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } desiredReplicas := obj.Spec.Replicas updatedReplicas := obj.Status.UpdatedReplicas readyReplicas := obj.Status.ReadyReplicas availableReplicas := obj.Status.AvailableReplicas age := translateTimestampSince(obj.CreationTimestamp) containers := obj.Spec.Template.Spec.Containers selector, err := metav1.LabelSelectorAsSelector(obj.Spec.Selector) if err != nil { // this shouldn't happen if LabelSelector passed validation return nil, err } row.Cells = append(row.Cells, obj.Name, fmt.Sprintf("%d/%d", int64(readyReplicas), int64(desiredReplicas)), int64(updatedReplicas), int64(availableReplicas), age) if options.Wide { containers, images := layoutContainerCells(containers) row.Cells = append(row.Cells, containers, images, selector.String()) } return []metav1beta1.TableRow{row}, nil } func printDeploymentList(list *apps.DeploymentList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printDeployment(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func formatHPAMetrics(specs []autoscaling.MetricSpec, statuses []autoscaling.MetricStatus) string { if len(specs) == 0 { return "<none>" } list := []string{} max := 2 more := false count := 0 for i, spec := range specs { switch spec.Type { case autoscaling.ExternalMetricSourceType: if spec.External.Target.AverageValue != nil { current := "<unknown>" if len(statuses) > i && statuses[i].External != nil && &statuses[i].External.Current.AverageValue != nil { current = statuses[i].External.Current.AverageValue.String() } list = append(list, fmt.Sprintf("%s/%s (avg)", current, spec.External.Target.AverageValue.String())) } else { current := "<unknown>" if len(statuses) > i && statuses[i].External != nil { current = statuses[i].External.Current.Value.String() } list = append(list, fmt.Sprintf("%s/%s", current, spec.External.Target.Value.String())) } case autoscaling.PodsMetricSourceType: current := "<unknown>" if len(statuses) > i && statuses[i].Pods != nil { current = statuses[i].Pods.Current.AverageValue.String() } list = append(list, fmt.Sprintf("%s/%s", current, spec.Pods.Target.AverageValue.String())) case autoscaling.ObjectMetricSourceType: current := "<unknown>" if len(statuses) > i && statuses[i].Object != nil { current = statuses[i].Object.Current.Value.String() } list = append(list, fmt.Sprintf("%s/%s", current, spec.Object.Target.Value.String())) case autoscaling.ResourceMetricSourceType: if spec.Resource.Target.AverageValue != nil { current := "<unknown>" if len(statuses) > i && statuses[i].Resource != nil { current = statuses[i].Resource.Current.AverageValue.String() } list = append(list, fmt.Sprintf("%s/%s", current, spec.Resource.Target.AverageValue.String())) } else { current := "<unknown>" if len(statuses) > i && statuses[i].Resource != nil && statuses[i].Resource.Current.AverageUtilization != nil { current = fmt.Sprintf("%d%%", *statuses[i].Resource.Current.AverageUtilization) } target := "<auto>" if spec.Resource.Target.AverageUtilization != nil { target = fmt.Sprintf("%d%%", *spec.Resource.Target.AverageUtilization) } list = append(list, fmt.Sprintf("%s/%s", current, target)) } default: list = append(list, "<unknown type>") } count++ } if count > max { list = list[:max] more = true } ret := strings.Join(list, ", ") if more { return fmt.Sprintf("%s + %d more...", ret, count-max) } return ret } func printHorizontalPodAutoscaler(obj *autoscaling.HorizontalPodAutoscaler, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } reference := fmt.Sprintf("%s/%s", obj.Spec.ScaleTargetRef.Kind, obj.Spec.ScaleTargetRef.Name) minPods := "<unset>" metrics := formatHPAMetrics(obj.Spec.Metrics, obj.Status.CurrentMetrics) if obj.Spec.MinReplicas != nil { minPods = fmt.Sprintf("%d", *obj.Spec.MinReplicas) } maxPods := obj.Spec.MaxReplicas currentReplicas := obj.Status.CurrentReplicas row.Cells = append(row.Cells, obj.Name, reference, metrics, minPods, int64(maxPods), int64(currentReplicas), translateTimestampSince(obj.CreationTimestamp)) return []metav1beta1.TableRow{row}, nil } func printHorizontalPodAutoscalerList(list *autoscaling.HorizontalPodAutoscalerList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printHorizontalPodAutoscaler(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printConfigMap(obj *api.ConfigMap, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } row.Cells = append(row.Cells, obj.Name, int64(len(obj.Data)), translateTimestampSince(obj.CreationTimestamp)) return []metav1beta1.TableRow{row}, nil } func printConfigMapList(list *api.ConfigMapList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printConfigMap(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printPodSecurityPolicy(obj *policy.PodSecurityPolicy, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } capabilities := make([]string, len(obj.Spec.AllowedCapabilities)) for i, c := range obj.Spec.AllowedCapabilities { capabilities[i] = string(c) } volumes := make([]string, len(obj.Spec.Volumes)) for i, v := range obj.Spec.Volumes { volumes[i] = string(v) } row.Cells = append(row.Cells, obj.Name, fmt.Sprintf("%v", obj.Spec.Privileged), strings.Join(capabilities, ","), string(obj.Spec.SELinux.Rule), string(obj.Spec.RunAsUser.Rule), string(obj.Spec.FSGroup.Rule), string(obj.Spec.SupplementalGroups.Rule), obj.Spec.ReadOnlyRootFilesystem, strings.Join(volumes, ",")) return []metav1beta1.TableRow{row}, nil } func printPodSecurityPolicyList(list *policy.PodSecurityPolicyList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printPodSecurityPolicy(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printNetworkPolicy(obj *networking.NetworkPolicy, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } row.Cells = append(row.Cells, obj.Name, metav1.FormatLabelSelector(&obj.Spec.PodSelector), translateTimestampSince(obj.CreationTimestamp)) return []metav1beta1.TableRow{row}, nil } func printNetworkPolicyList(list *networking.NetworkPolicyList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printNetworkPolicy(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printStorageClass(obj *storage.StorageClass, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } name := obj.Name if storageutil.IsDefaultAnnotation(obj.ObjectMeta) { name += " (default)" } provtype := obj.Provisioner row.Cells = append(row.Cells, name, provtype, translateTimestampSince(obj.CreationTimestamp)) return []metav1beta1.TableRow{row}, nil } func printStorageClassList(list *storage.StorageClassList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printStorageClass(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printLease(obj *coordination.Lease, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } var holderIdentity string if obj.Spec.HolderIdentity != nil { holderIdentity = *obj.Spec.HolderIdentity } row.Cells = append(row.Cells, obj.Name, holderIdentity, translateTimestampSince(obj.CreationTimestamp)) return []metav1beta1.TableRow{row}, nil } func printLeaseList(list *coordination.LeaseList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printLease(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printStatus(obj *metav1.Status, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } row.Cells = append(row.Cells, obj.Status, obj.Reason, obj.Message) return []metav1beta1.TableRow{row}, nil } // Lay out all the containers on one line if use wide output. func layoutContainerCells(containers []api.Container) (names string, images string) { var namesBuffer bytes.Buffer var imagesBuffer bytes.Buffer for i, container := range containers { namesBuffer.WriteString(container.Name) imagesBuffer.WriteString(container.Image) if i != len(containers)-1 { namesBuffer.WriteString(",") imagesBuffer.WriteString(",") } } return namesBuffer.String(), imagesBuffer.String() } // formatEventSource formats EventSource as a comma separated string excluding Host when empty func formatEventSource(es api.EventSource) string { EventSourceString := []string{es.Component} if len(es.Host) > 0 { EventSourceString = append(EventSourceString, es.Host) } return strings.Join(EventSourceString, ", ") } func printControllerRevision(obj *apps.ControllerRevision, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } controllerRef := metav1.GetControllerOf(obj) controllerName := "<none>" if controllerRef != nil { withKind := true gv, err := schema.ParseGroupVersion(controllerRef.APIVersion) if err != nil { return nil, err } gvk := gv.WithKind(controllerRef.Kind) controllerName = printers.FormatResourceName(gvk.GroupKind(), controllerRef.Name, withKind) } revision := obj.Revision age := translateTimestampSince(obj.CreationTimestamp) row.Cells = append(row.Cells, obj.Name, controllerName, revision, age) return []metav1beta1.TableRow{row}, nil } func printControllerRevisionList(list *apps.ControllerRevisionList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printControllerRevision(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printResourceQuota(resourceQuota *api.ResourceQuota, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: resourceQuota}, } resources := make([]api.ResourceName, 0, len(resourceQuota.Status.Hard)) for resource := range resourceQuota.Status.Hard { resources = append(resources, resource) } sort.Sort(SortableResourceNames(resources)) requestColumn := bytes.NewBuffer([]byte{}) limitColumn := bytes.NewBuffer([]byte{}) for i := range resources { w := requestColumn resource := resources[i] usedQuantity := resourceQuota.Status.Used[resource] hardQuantity := resourceQuota.Status.Hard[resource] // use limitColumn writer if a resource name prefixed with "limits" is found if pieces := strings.Split(resource.String(), "."); len(pieces) > 1 && pieces[0] == "limits" { w = limitColumn } fmt.Fprintf(w, "%s: %s/%s, ", resource, usedQuantity.String(), hardQuantity.String()) } age := translateTimestampSince(resourceQuota.CreationTimestamp) row.Cells = append(row.Cells, resourceQuota.Name, age, strings.TrimSuffix(requestColumn.String(), ", "), strings.TrimSuffix(limitColumn.String(), ", ")) return []metav1beta1.TableRow{row}, nil } func printResourceQuotaList(list *api.ResourceQuotaList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printResourceQuota(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printPriorityClass(obj *scheduling.PriorityClass, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } name := obj.Name value := obj.Value globalDefault := obj.GlobalDefault row.Cells = append(row.Cells, name, int64(value), globalDefault, translateTimestampSince(obj.CreationTimestamp)) return []metav1beta1.TableRow{row}, nil } func printPriorityClassList(list *scheduling.PriorityClassList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printPriorityClass(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printRuntimeClass(obj *nodeapi.RuntimeClass, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } name := obj.Name handler := obj.Handler row.Cells = append(row.Cells, name, handler, translateTimestampSince(obj.CreationTimestamp)) return []metav1beta1.TableRow{row}, nil } func printRuntimeClassList(list *nodeapi.RuntimeClassList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printRuntimeClass(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printVolumeAttachment(obj *storage.VolumeAttachment, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: obj}, } name := obj.Name pvName := "" if obj.Spec.Source.PersistentVolumeName != nil { pvName = *obj.Spec.Source.PersistentVolumeName } row.Cells = append(row.Cells, name, obj.Spec.Attacher, pvName, obj.Spec.NodeName, obj.Status.Attached, translateTimestampSince(obj.CreationTimestamp)) return []metav1beta1.TableRow{row}, nil } func printVolumeAttachmentList(list *storage.VolumeAttachmentList, options printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(list.Items)) for i := range list.Items { r, err := printVolumeAttachment(&list.Items[i], options) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func printBoolPtr(value *bool) string { if value != nil { return printBool(*value) } return "<unset>" } func printBool(value bool) string { if value { return "True" } return "False" } type SortableResourceNames []api.ResourceName func (list SortableResourceNames) Len() int { return len(list) } func (list SortableResourceNames) Swap(i, j int) { list[i], list[j] = list[j], list[i] } func (list SortableResourceNames) Less(i, j int) bool { return list[i] < list[j] }
{ "content_hash": "739198c14dabed87ebf5ec6fc4e5a32f", "timestamp": "", "source": "github", "line_count": 2060, "max_line_length": 262, "avg_line_length": 40.61504854368932, "alnum_prop": 0.7258775861450751, "repo_name": "cosmincojocar/kubernetes", "id": "782a569a3a0c8b4944770e11dbab21f1cc713954", "size": "84236", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pkg/printers/internalversion/printers.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2840" }, { "name": "Go", "bytes": "40344291" }, { "name": "HTML", "bytes": "1199467" }, { "name": "Makefile", "bytes": "79030" }, { "name": "Python", "bytes": "2678339" }, { "name": "Ruby", "bytes": "1780" }, { "name": "Shell", "bytes": "1389412" } ], "symlink_target": "" }
<DataObjects> <PointSet name="inputHolder"> <Input>DeltaTimeScramToAux,DG1recoveryTime</Input> <Output>OutputPlaceHolder</Output> </PointSet> <PointSet name="Pointset_from_database_for_rom_trainer"> <Input>DeltaTimeScramToAux,DG1recoveryTime</Input> <Output>CladTempThreshold,time</Output> </PointSet> <HistorySet name="Historyset_from_database_for_rom_trainer"> <Input>DeltaTimeScramToAux,DG1recoveryTime</Input> <Output>CladTempThreshold</Output> </HistorySet> <PointSet name="data_for_sampling_empty_at_begin"> <Input>DeltaTimeScramToAux,DG1recoveryTime</Input> <Output>OutputPlaceHolder</Output> </PointSet> <PointSet name="data_for_sampling_empty_at_begin_nd"> <Input>DeltaTimeScramToAux,DG1recoveryTime</Input> <Output>OutputPlaceHolder</Output> </PointSet> <PointSet name="outputMontecarloRom"> <Input>DeltaTimeScramToAux,DG1recoveryTime</Input> <!--Output>CladTempThreshold</Output--> </PointSet> <HistorySet name="outputMontecarloRomHS"> <Input>GRO_targets</Input> <Output>CladTempThreshold,time</Output> </HistorySet> <PointSet name="outputMontecarloRomND"> <Input>DeltaTimeScramToAux,DG1recoveryTime</Input> <Output>CladTempThreshold</Output> </PointSet> </DataObjects>
{ "content_hash": "f2e32784867c57dcaacd475ba16fcd46", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 61, "avg_line_length": 36.205882352941174, "alnum_prop": 0.7749796913078798, "repo_name": "joshua-cogliati-inl/raven", "id": "b47d460661d23ae3e1f4dd16fc18d915feb08f4f", "size": "1231", "binary": false, "copies": "2", "ref": "refs/heads/devel", "path": "tests/framework/CodeInterfaceTests/RAVEN/ROM/ext_dataobjects.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "1556080" }, { "name": "Batchfile", "bytes": "1095" }, { "name": "C", "bytes": "148504" }, { "name": "C++", "bytes": "48279546" }, { "name": "CMake", "bytes": "9998" }, { "name": "Jupyter Notebook", "bytes": "84202" }, { "name": "MATLAB", "bytes": "202335" }, { "name": "Makefile", "bytes": "2399" }, { "name": "Perl", "bytes": "1297" }, { "name": "Python", "bytes": "6952659" }, { "name": "R", "bytes": "67" }, { "name": "SWIG", "bytes": "8574" }, { "name": "Shell", "bytes": "124279" }, { "name": "TeX", "bytes": "479725" } ], "symlink_target": "" }
@interface MasterViewController () @property NSMutableArray *objects; @end @implementation MasterViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.navigationItem.leftBarButtonItem = self.editButtonItem; UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(insertNewObject:)]; self.navigationItem.rightBarButtonItem = addButton; self.detailViewController = (DetailViewController *)[[self.splitViewController.viewControllers lastObject] topViewController]; } - (void)viewWillAppear:(BOOL)animated { self.clearsSelectionOnViewWillAppear = self.splitViewController.isCollapsed; [super viewWillAppear:animated]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (void)insertNewObject:(id)sender { if (!self.objects) { self.objects = [[NSMutableArray alloc] init]; } [self.objects insertObject:[NSDate date] atIndex:0]; NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; } #pragma mark - Segues - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([[segue identifier] isEqualToString:@"showDetail"]) { NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow]; NSDate *object = self.objects[indexPath.row]; DetailViewController *controller = (DetailViewController *)[[segue destinationViewController] topViewController]; [controller setDetailItem:object]; controller.navigationItem.leftBarButtonItem = self.splitViewController.displayModeButtonItem; controller.navigationItem.leftItemsSupplementBackButton = YES; } } #pragma mark - Table View - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.objects.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; NSDate *object = self.objects[indexPath.row]; cell.textLabel.text = [object description]; return cell; } - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the specified item to be editable. return YES; } - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { [self.objects removeObjectAtIndex:indexPath.row]; [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; } else if (editingStyle == UITableViewCellEditingStyleInsert) { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } @end
{ "content_hash": "49059f4f250c24a5deaf585f249f03e5", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 159, "avg_line_length": 39.80487804878049, "alnum_prop": 0.7594975490196079, "repo_name": "ShenYj/Demos", "id": "13c4aa51784e029cdd5b499d549371c1cec1dd1c", "size": "3481", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "PopTest/UIView转场动画/MasterViewController.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "154288" }, { "name": "HTML", "bytes": "1581" }, { "name": "Objective-C", "bytes": "2365278" }, { "name": "Objective-J", "bytes": "1077" }, { "name": "Ruby", "bytes": "5627" }, { "name": "Swift", "bytes": "17953" } ], "symlink_target": "" }
package com.easycodebox.common.freemarker; import com.easycodebox.common.processor.Processor; import com.easycodebox.common.validate.Assert; import freemarker.template.*; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ResourceLoaderAware; import org.springframework.core.io.*; import java.io.*; /** * 快速构建Freemarker生成文件功能类 * @author WangXiaoJin * */ public class FreemarkerGenerate implements Processor, ResourceLoaderAware { private final Logger log = LoggerFactory.getLogger(getClass()); private ResourceLoader resourceLoader = new DefaultResourceLoader(); private Configuration configuration; /** * 模板路径 */ private String ftlPath; /** * 输出路径 */ private String outputPath; private String encoding = "UTF-8"; private Object dataModel; @Override public Object process() { Assert.notNull(configuration); Assert.notBlank(ftlPath); Assert.notBlank(outputPath); Writer out = null; try { log.info("Start generate file '{}' by freemarker.", outputPath); Template tpl = configuration.getTemplate(ftlPath); Resource resource = resourceLoader.getResource(outputPath); out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(resource.getFile()), encoding)); tpl.process(dataModel, out); log.info("Generate file '{}' successfully by freemarker.", outputPath); } catch (TemplateException | IOException e) { log.error("Freemarker generate file error.", e); } finally { IOUtils.closeQuietly(out); } return null; } @Override public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } public Configuration getConfiguration() { return configuration; } public void setConfiguration(Configuration configuration) { this.configuration = configuration; } public String getFtlPath() { return ftlPath; } public void setFtlPath(String ftlPath) { this.ftlPath = ftlPath; } public String getOutputPath() { return outputPath; } public void setOutputPath(String outputPath) { this.outputPath = outputPath; } public String getEncoding() { return encoding; } public void setEncoding(String encoding) { this.encoding = encoding; } public Object getDataModel() { return dataModel; } public void setDataModel(Object dataModel) { this.dataModel = dataModel; } }
{ "content_hash": "f5600a1ea87feb75d9b0b9b52d781386", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 104, "avg_line_length": 24.00952380952381, "alnum_prop": 0.7108290360967869, "repo_name": "easycodebox/easycode", "id": "58e5a6514dafc930df99ea7dd42df8bd13b8c164", "size": "2559", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "easycode-common/src/main/java/com/easycodebox/common/freemarker/FreemarkerGenerate.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "3851" }, { "name": "FreeMarker", "bytes": "104273" }, { "name": "Java", "bytes": "1158076" }, { "name": "JavaScript", "bytes": "52486" } ], "symlink_target": "" }
/** * @author Vladimir Kozhin <affka@affka.ru> * @license MIT */ 'use strict'; /** * @namespace Jii * @ignore */ var Jii = require('../Jii'); require('./Context'); /** * @class Jii.base.Module * @extends Jii.base.Context */ Jii.defineClass('Jii.base.Module', /** @lends Jii.base.Module.prototype */{ __extends: Jii.base.Context, /** * @type {string} */ id: null, /** * The parent module of this module. Null if this module does not have a parent. * @type {Jii.base.Module} */ module: null, /** * Mapping from controller ID to controller configurations. * Each name-value pair specifies the configuration of a single controller. * A controller configuration can be either a string or an array. * If the former, the string should be the fully qualified class name of the controller. * If the latter, the array must contain a 'class' element which specifies * the controller's fully qualified class name, and the rest of the name-value pairs * in the array are used to initialize the corresponding controller properties. For example, * * ~~~ * { * account: 'app.controllers.UserController', * article: { * className: 'app.controllers.PostController', * pageTitle: 'something new' * } * } * ~~~ * @type {object} */ controllerMap: {}, /** * String the namespace that controller classes are in. If not set, * it will use the "controllers" sub-namespace under the namespace of this module. * For example, if the namespace of this module is "foo\bar", then the default * controller namespace would be "foo\bar\controllers". * @type {string} */ controllerNamespace: null, /** * The default route of this module. Defaults to 'default'. * The route may consist of child module ID, controller ID, and/or action ID. * For example, `help`, `post/create`, `admin/post/create`. * If action ID is not given, it will take the default value as specified in defaultAction. * @type {string} */ defaultRoute: 'default', /** * The layout that should be applied for views within this module. This refers to a view name * relative to [[layoutPath]]. If this is not set, it means the layout value of the [[module|parent module]] * will be taken. If this is false, layout will be disabled within this module. * @type {string|boolean} */ layout: null, /** * @type {object} */ _modules: null, /** */ constructor: function (id, moduleObject, config) { this.id = id; this.module = moduleObject; this._modules = {}; this.__super(config); }, init: function () { if (this.controllerNamespace === null) { var index = Jii._.lastIndexOf(this.className(), '.'); this.controllerNamespace = this.className().substr(0, index); } }, /** * * @returns {Promise} */ start: function() { var promises = []; Jii._.each(this._components, function(component) { if (Jii._.isFunction(component.start)) { promises.push(component.start()); } }); return Promise.all(promises); }, /** * * @returns {Promise} */ stop: function() { var promises = []; Jii._.each(this._components, function(component) { if (Jii._.isFunction(component.stop)) { promises.push(component.stop()); } }); return Promise.all(promises); }, getUniqueId: function () { if (this.module) { var id = this.module.getUniqueId() + '/' + this.id; return Jii._s.ltrim(id, '/'); } return this.id; }, /** * The root directory of the module. * @type {string} */ _basePath: null, /** * Returns the root directory of the module. * It defaults to the directory containing the module class file. * @return {string} the root directory of the module. */ getBasePath: function () { if (this._basePath === null) { this._basePath = Jii.getAlias('@' + this.className().replace(/\.[^.]+$/, '')) } return this._basePath; }, /** * Sets the root directory of the module. * This method can only be invoked at the beginning of the constructor. * @param {string} path the root directory of the module. This can be either a directory name or a path alias. */ setBasePath: function (path) { this._basePath = Jii.getAlias(path); }, /** * Returns the directory that contains the controller classes according to [[controllerNamespace]]. * Note that in order for this method to return a value, you must define * an alias for the root namespace of [[controllerNamespace]]. * @return {string} the directory that contains the controller classes. */ getControllerPath: function () { return Jii.getAlias('@' + this.controllerNamespace.replace('.', '/')); }, /** * The root directory that contains view files for this module * @type {string} */ _viewPath: null, /** * Returns the directory that contains the view files for this module. * @return {string} the root directory of view files. Defaults to "[[basePath]]/view". */ getViewPath: function () { if (this._viewPath === null) { this._viewPath = this.getBasePath() + '/views'; } return this._viewPath; }, /** * Sets the directory that contains the view files. * @param {string} path the root directory of view files. */ setViewPath: function (path) { this._viewPath = Jii.getAlias(path); }, /** * The root directory that contains layout view files for this module. * @type {string} */ _layoutPath: null, /** * Returns the directory that contains layout view files for this module. * @return {string} the root directory of layout files. Defaults to "[[viewPath]]/layouts". */ getLayoutPath: function () { if (this._layoutPath === null) { this._layoutPath = this.getViewPath() + '/layouts'; } return this._layoutPath; }, /** * Sets the directory that contains the layout files. * @param {string} path the root directory of layout files. */ setLayoutPath: function (path) { this._layoutPath = Jii.getAlias(path); }, /** * Checks whether the child module of the specified ID exists. * This method supports checking the existence of both child and grand child modules. * @param {string} id module ID. For grand child modules, use ID path relative to this module (e.g. `admin/content`). * @return {boolean} whether the named module exists. Both loaded and unloaded modules * are considered. */ hasModule: function (id) { var index = Jii._.indexOf(id, '.'); if (index !== -1) { var moduleId = id.substr(0, index); var childModuleId = id.substr(index + 1); // Check sub-module var moduleObject = this.getModule(moduleId); return moduleObject !== null ? moduleObject.hasModule(childModuleId) : false; } return Jii._.has(this._modules[id]); }, /** * Retrieves the child module of the specified ID. * This method supports retrieving both child modules and grand child modules. * @param {string} id module ID (case-sensitive). To retrieve grand child modules, * use ID path relative to this module (e.g. `admin/content`). * @return {Jii.base.Module} the module instance, null if the module does not exist. */ getModule: function (id) { // Get sub-module var index = Jii._.indexOf(id, '.'); if (index !== -1) { var moduleId = id.substr(0, index); var childModuleId = id.substr(index + 1); var moduleObject = this.getModule(moduleId); return moduleObject !== null ? moduleObject.getModule(childModuleId) : null; } return this._modules[id] || null; }, /** * Adds a sub-module to this module. * @param {string} id module ID * @param {Jii.base.Module|array|null} moduleObject the sub-module to be added to this module. This can * be one of the followings: * * - a [[Jii.base.Module]] object * - a configuration array: when [[getModule()]] is called initially, the array * will be used to instantiate the sub-module * - null: the named sub-module will be removed from this module */ setModule: function (id, moduleObject) { if (moduleObject === null) { delete this._modules[id]; } else { // Create module instance moduleObject = Jii.createObject(moduleObject, id, this); // Add link this._modules[id] = moduleObject; } }, /** * Returns the sub-modules in this module. * @return {Jii.base.Module[]} the modules (indexed by their IDs) */ getModules: function () { return this._modules; }, /** * Registers sub-modules in the current module. * * Each sub-module should be specified as a name-value pair, where * name refers to the ID of the module and value the module or a configuration * array that can be used to create the module. In the latter case, [[Jii.createObject()]] * will be used to create the module. * * If a new sub-module has the same ID as an existing one, the existing one will be overwritten silently. * * The following is an example for registering two sub-modules: * * ~~~ * [ * 'comment' => [ * 'class' => 'app\modules\comment\CommentModule', * 'db' => 'db', * ], * 'booking' => ['class' => 'app\modules\booking\BookingModule'], * ] * ~~~ * * @param {object} modules modules (id => module configuration or instances) */ setModules: function (modules) { Jii._.each(modules, Jii._.bind(function (moduleObject, id) { this._modules[id] = moduleObject; }, this)); }, /** * Runs a controller action specified by a route. * This method parses the specified route and creates the corresponding child module(s), controller and action * instances. It then calls [[Jii.base.Controller::runAction()]] to run the action with the given parameters. * If the route is empty, the method will use [[defaultRoute]]. * @param {string} route the route that specifies the action. * @param {Jii.base.Context} context * @return {Promise} the result of the action. * @throws {Jii.exceptions.InvalidRouteException} if the requested route cannot be resolved into an action successfully */ runAction: function (route, context) { var parts = this.createController(route); if (parts !== null) { /** @type {Jii.base.Controller} */ var controller = parts[0]; var actionId = parts[1]; return controller.runAction(actionId, context); } var id = this.getUniqueId(); var requestName = id ? id + '/' + route : route; //throw new Jii.exceptions.InvalidRouteException('Unable to resolve the request `' + requestName + '`.'); Jii.info('Unable to resolve the request `' + requestName + '`.'); }, /** * * @param {string} route * @return {boolean} */ existsRoute: function(route) { if (route === '') { route = this.defaultRoute; } var id; var index = route.indexOf('/'); if (index !== -1) { id = route.substr(0, index); route = route.substr(index + 1); } else { id = route; route = ''; } if (Jii._.has(this.controllerMap, id)) { return true; } var moduleObject = this.getModule(id); if (moduleObject !== null) { return moduleObject.existsRoute(route); } if (/^[a-z0-9\\-_]+$/.test(id)) { var className = id.charAt(0).toUpperCase() + id.slice(1); className = className.replace('-', '') + 'Controller'; className = this.controllerNamespace + '.' + className; var controllerClass = Jii.namespace(className); if (Jii._.isFunction(controllerClass)) { var controller = new controllerClass(id, this); return controller.hasAction(route); } } return false; }, /** * Creates a controller instance based on the controller ID. * * The controller is created within this module. The method first attempts to * create the controller based on the [[controllerMap]] of the module. * * @param {string} route the route consisting of module, controller and action IDs. * @return {[]|null} If the controller is created successfully, it will be returned together * with the requested action ID. Otherwise false will be returned. * @throws {Jii.exceptions.InvalidConfigException} if the controller class and its file do not match. */ createController: function (route) { if (route === '') { route = this.defaultRoute; } var id; var controller = null; var index = route.indexOf('/'); if (index !== -1) { id = route.substr(0, index); route = route.substr(index + 1); } else { id = route; route = ''; } if (Jii._.has(this.controllerMap, id)) { controller = Jii.createObject(this.controllerMap[id], id, this); return controller !== null ? [controller, route] : null; } var moduleObject = this.getModule(id); if (moduleObject !== null) { return moduleObject.createController(route); } if (/^[a-z0-9\\-_]+$/.test(id)) { var className = id.charAt(0).toUpperCase() + id.slice(1); className = className.replace('-', '') + 'Controller'; className = this.controllerNamespace + '.' + className; var controllerClass = Jii.namespace(className); if (Jii._.isFunction(controllerClass)) { controller = new controllerClass(id, this); if (!(controller instanceof Jii.base.Controller)) { throw new Jii.exceptions.InvalidConfigException("Controller class must extend from Jii.base.Controller."); } } } return controller !== null ? [controller, route] : null; }, /** * This method is invoked right before an action of this module is to be executed (after all possible filters.) * You may override this method to do last-minute preparation for the action. * Make sure you call the parent implementation so that the relevant event is triggered. * @param {Jii.base.Action} action the action to be executed. * @return {boolean} whether the action should continue to be executed. */ beforeAction: function (action) { return true; }, /** * This method is invoked right after an action of this module has been executed. * You may override this method to do some postprocessing for the action. * Make sure you call the parent implementation so that the relevant event is triggered. * @param {Jii.base.Action} action the action just executed. */ afterAction: function (action) { } });
{ "content_hash": "a148d16bf94ace5eed09f0a361bf7d74", "timestamp": "", "source": "github", "line_count": 480, "max_line_length": 120, "avg_line_length": 29.558333333333334, "alnum_prop": 0.654849168311249, "repo_name": "Mirocow/jii", "id": "09c02e11a28a53de1978ebb70e9b6a47180db3bd", "size": "14188", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/base/Module.js", "mode": "33261", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "114864" }, { "name": "PHP", "bytes": "6824" } ], "symlink_target": "" }