text:
namespace Client.Logic.IO
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Text;
    using System.Xml;

    /// <summary>
    /// Class for easily editing XML files.
    /// </summary>
    public class XmlEditor
    {
        #region Fields

        private XmlDocument mXmlDocument;
        private string m_RootNode;
        private string m_path;

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="XmlEditor"/> class.
        /// </summary>
        /// <param name="xmlPath">The path for the file. This can be a local file, or a HTTP URL (A web address).</param>
        /// <param name="rootNode">The root node of the Xml File</param>
        internal XmlEditor(string xmlPath, string rootNode)
        {
            m_path = IO.CreateOSPath(xmlPath);
            m_RootNode = rootNode;
        }

        #endregion Constructors

        #region Properties

        /// <summary>
        /// Gets the file path of the XML File.
        /// </summary>
        /// <value>The file path.</value>
        public string FilePath
        {
            get { return m_path; }
        }

        /// <summary>
        /// Gets or sets the root node of the Xml File.
        /// </summary>
        public string RootNode
        {
            get { return m_RootNode; }
            set { m_RootNode = value; }
        }

        /// <summary>
        /// Gets the root XML node.
        /// </summary>
        /// <value>The root XML node.</value>
        public XmlNode RootXmlNode
        {
            get {
                return mXmlDocument.DocumentElement.SelectSingleNode("/" + m_RootNode);
            }
        }

        #endregion Properties

        #region Methods

        /// <summary>
        /// Deletes the specified node.
        /// </summary>
        /// <param name="XmlNode">The XML node.</param>
        /// <param name="Node">The parent node.</param>
        public void DeleteNode(XmlNode XmlNode, string Node)
        {
            XmlNode xmlnodeToDelete = mXmlDocument.DocumentElement.SelectSingleNode((("/" + m_RootNode + "/") + Node + "/add[@key=\"") + GetAttributeValue(XmlNode, "key") + "\"]");
            xmlnodeToDelete.ParentNode.RemoveChild(xmlnodeToDelete);
        }

        /// <summary>
        /// Deletes the specified node.
        /// </summary>
        /// <param name="Key">The key of the node to delete.</param>
        /// <param name="Node">The parent node.</param>
        public void DeleteNode(string Key, string Node)
        {
            XmlNode xmlnode = mXmlDocument.DocumentElement.SelectSingleNode((("/" + m_RootNode + "/") + Node + "/add[@key=\"") + Key + "\"]");
            xmlnode.ParentNode.RemoveChild(xmlnode);
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        public void Dispose()
        {
            mXmlDocument = null;
        }

        /// <summary>
        /// Gets all child nodes in the specified parent node.
        /// </summary>
        /// <param name="Node">The parent node.</param>
        /// <returns></returns>
        public XmlNodeList GetAllNodes(string Node)
        {
            XmlNode xmlnode = mXmlDocument.DocumentElement.SelectSingleNode(Node);
            XmlNode Root = mXmlDocument.DocumentElement.SelectSingleNode(Node);
            if (Root == null) {
                try {
                    Root = mXmlDocument.DocumentElement.SelectSingleNode("/" + m_RootNode + "");
                    xmlnode = Root.AppendChild(mXmlDocument.CreateElement(Node));
                } catch (Exception ex) {
                    throw new Exception("An error occured while saving the value", ex);
                }
            }
            if (xmlnode != null) {
                return xmlnode.ChildNodes;
            } else {
                return null;
            }
        }

        /// <summary>
        /// Gets all child nodes in the specified parent node.
        /// </summary>
        /// <param name="Node">The parent node.</param>
        /// <returns></returns>
        public XmlNodeList GetAllNodes(XmlNode Node)
        {
            XmlNode xmlnode = mXmlDocument.DocumentElement.SelectSingleNode(Node.Name);
            XmlNode Root = mXmlDocument.DocumentElement.SelectSingleNode(Node.Name);
            if (Root == null) {
                try {
                    Root = mXmlDocument.DocumentElement.SelectSingleNode("/" + m_RootNode + "");
                    xmlnode = Root.AppendChild(mXmlDocument.CreateElement(Node.Name));
                } catch (Exception ex) {
                    throw new Exception("An error occured while saving the value", ex);
                }
            }
            if (xmlnode != null) {
                return xmlnode.ChildNodes;
            } else {
                return null;
            }
        }

        /// <summary>
        /// Gets all child nodes in the root node.
        /// </summary>
        /// <returns></returns>
        public XmlNodeList GetAllNodes()
        {
            if (mXmlDocument.DocumentElement.ParentNode != null) {
                return mXmlDocument.DocumentElement.SelectSingleNode("/" + m_RootNode).ChildNodes;
            } else {
                return null;
            }
        }

        /// <summary>
        /// Gets the value of an attribute of an XML Node.
        /// </summary>
        /// <param name="XmlNode">The XML node.</param>
        /// <param name="Attribute">The attribute.</param>
        /// <returns></returns>
        public string GetAttributeValue(XmlNode XmlNode, string Attribute)
        {
            if (XmlNode != null) {
                return XmlNode.Attributes.GetNamedItem(Attribute).Value;
            } else {
                return "";
            }
        }

        /// <summary>
        /// Gets the value of an attribute of an XML Node. The XML Node is first found, using the Key.
        /// </summary>
        /// <param name="Key">The key.</param>
        /// <param name="Node">The node.</param>
        /// <param name="Attribute">The attribute.</param>
        /// <returns></returns>
        public string GetAttributeValue(string Key, string Node, string Attribute)
        {
            XmlNode node = GetNode(Key, Node);
            if (node != null) {
                return GetAttributeValue(GetNode(Key, Node), Attribute);
            } else {
                return "";
            }
        }

        /// <summary>
        /// Gets the value of an attribute of an XML Node. The XML Node is first found, using the Key. Looks in the "Settings" node for the key.
        /// </summary>
        /// <param name="Key">The key.</param>
        /// <param name="Attribute">The attribute.</param>
        /// <returns></returns>
        public string GetAttributeValue(string Key, string Attribute)
        {
            return GetAttributeValue(Key, "Settings", Attribute);
        }

        /// <summary>
        /// Gets the XmlNode with the selected key.
        /// </summary>
        /// <param name="Key">The key to look for.</param>
        /// <param name="Node">The node to look in.</param>
        /// <returns></returns>
        public XmlNode GetNode(string Key, string Node)
        {
            XmlNode returnValue = mXmlDocument.DocumentElement.SelectSingleNode((("/" + m_RootNode + "/") + Node + "/add[@key=\"") + Key + "\"]");
            return returnValue;
        }

        /// <summary>
        /// Gets the XmlNode of the selected key. This will look in the "Settings" node.
        /// </summary>
        /// <param name="Key">The key to look for.</param>
        /// <returns></returns>
        public XmlNode GetNode(string Key)
        {
            return GetNode(Key, "Settings");
        }

        /// <summary>
        /// Gets the setting from the default node.
        /// </summary>
        /// <param name="Key">The key.</param>
        /// <returns></returns>
        public string GetSetting(string Key)
        {
            return GetSetting(Key, "Settings");
        }

        /// <summary>
        /// Gets the setting from the specified node.
        /// </summary>
        /// <param name="Key">The key.</param>
        /// <param name="XmlNode">The node.</param>
        /// <returns></returns>
        public string GetSetting(string Key, string XmlNode)
        {
            XmlNode node = mXmlDocument.DocumentElement.SelectSingleNode((("/" + m_RootNode + "/") + XmlNode + "/add[@key=\"") + Key + "\"]");
            if (node != null) {
                return node.Attributes.GetNamedItem("value").Value;
            } else {
                return "";
            }
        }

        /// <summary>
        /// Loads the XML files.
        /// </summary>
        public void LoadDocument()
        {
            CheckXMLFile();
            mXmlDocument = new XmlDocument();
            mXmlDocument.Load(IO.CreateOSPath(m_path));
        }

        /// <summary>
        /// Loads a new document.
        /// </summary>
        /// <param name="xmlPath">The file path.</param>
        public void LoadNewDocument(string xmlPath)
        {
            m_path = xmlPath;
            CheckXMLFile();
            LoadDocument();
        }

        /// <summary>
        /// Reloads the document.
        /// </summary>
        public void ReloadDocument()
        {
            LoadDocument();
        }

        /// <summary>
        /// Saves the XML file.
        /// </summary>
        public void Save()
        {
            mXmlDocument.Save(m_path);
        }

        /// <summary>
        /// Saves an attribute.
        /// </summary>
        /// <param name="Key">The key.</param>
        /// <param name="Node">The node.</param>
        /// <param name="Name">The name.</param>
        /// <param name="Value">The value.</param>
        public void SaveAttribute(string Key, string Node, string Name, string Value)
        {
            XmlElement Xmlnode = (XmlElement)(mXmlDocument.DocumentElement.SelectSingleNode((("/" + m_RootNode + "/") + Node + "/add[@key=\"") + Key + "\"]"));
            Xmlnode.SetAttribute(Name, Value);
        }

        /// <summary>
        /// Saves a new node with the specified attributes.
        /// </summary>
        /// <param name="Key">The key.</param>
        /// <param name="XmlNode">The parent node.</param>
        /// <param name="Attributes">The attributes.</param>
        /// <returns></returns>
        public XmlNode SaveNode(string Key, string XmlNode, XmlAttributes Attributes)
        {
            XmlElement node = (XmlElement)(mXmlDocument.DocumentElement.SelectSingleNode((("/" + m_RootNode + "/") + XmlNode + "/add[@key=\"") + Key + "\"]"));
            if (node != null) {
                foreach (string strKey in Attributes.Keys) {
                    node.SetAttribute(strKey, Attributes[strKey]);
                }
                return node;
            } else {
                node = mXmlDocument.CreateElement("add");
                node.SetAttribute("key", Key);
                foreach (string strKey in Attributes.Keys) {
                    node.SetAttribute(strKey.Replace(" ", ""), Attributes[strKey]);
                }
                XmlNode Root = mXmlDocument.DocumentElement.SelectSingleNode(("/" + m_RootNode + "/") + XmlNode);
                if (Root != null) {
                    Root.AppendChild(node);
                    return node;
                } else {
                    try {
                        Root = mXmlDocument.DocumentElement.SelectSingleNode("/" + m_RootNode + "");
                        Root.AppendChild(mXmlDocument.CreateElement(XmlNode));
                        Root = mXmlDocument.DocumentElement.SelectSingleNode(("/" + m_RootNode + "/") + XmlNode);
                        Root.AppendChild(node);
                        return node;
                    } catch (Exception ex) {
                        throw new Exception("An error occured while saving the value", ex);
                    }
                }
            }
        }

        /// <summary>
        /// Saves the setting to the default node.
        /// </summary>
        /// <param name="Key">The key.</param>
        /// <param name="Value">The value.</param>
        public void SaveSetting(string Key, string Value)
        {
            SaveSetting(Key, Value, "Settings");
        }

        /// <summary>
        /// Saves the setting to the specified node.
        /// </summary>
        /// <param name="Key">The key.</param>
        /// <param name="Value">The value.</param>
        /// <param name="XmlNode">The node.</param>
        public void SaveSetting(string Key, string Value, string XmlNode)
        {
            XmlElement node = (XmlElement)(mXmlDocument.DocumentElement.SelectSingleNode((("/" + m_RootNode + "/") + XmlNode + "/add[@key=\"") + Key + "\"]"));
            if (true) {
                if ((node != null)) {
                    node.Attributes.GetNamedItem("value").Value = Value;
                } else {
                    node = mXmlDocument.CreateElement("add");
                    node.SetAttribute("key", Key);
                    node.SetAttribute("value", Value);
                    XmlNode Root = mXmlDocument.DocumentElement.SelectSingleNode(("/" + m_RootNode + "/") + XmlNode);
                    if ((Root != null)) {
                        Root.AppendChild(node);
                    } else {
                        try {
                            Root = mXmlDocument.DocumentElement.SelectSingleNode("/" + m_RootNode + "");
                            Root.AppendChild(mXmlDocument.CreateElement(XmlNode));
                            Root = mXmlDocument.DocumentElement.SelectSingleNode(("/" + m_RootNode + "/") + XmlNode);
                            Root.AppendChild(node);
                        } catch (Exception ex) {
                            throw new Exception("An error occured while saving the value", ex);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Gets the value of an attribute of an XML Node.
        /// </summary>
        /// <param name="XmlNode">The XML node.</param>
        /// <param name="Attribute">The attribute.</param>
        /// <returns></returns>
        public string TryGetAttributeValue(XmlNode XmlNode, string Attribute)
        {
            try {
                if (XmlNode != null) {
                    return XmlNode.Attributes.GetNamedItem(Attribute).Value;
                } else {
                    return "";
                }
            } catch {
                return "";
            }
        }

        /// <summary>
        /// Gets the value of an attribute of an XML Node. The XML Node is first found, using the Key.
        /// </summary>
        /// <param name="Key">The key.</param>
        /// <param name="Node">The node.</param>
        /// <param name="Attribute">The attribute.</param>
        /// <returns></returns>
        public string TryGetAttributeValue(string Key, string Node, string Attribute)
        {
            try {
                XmlNode node = GetNode(Key, Node);
                if (node != null) {
                    return GetAttributeValue(node, Attribute);
                } else {
                    return "";
                }
            } catch {
                return "";
            }
        }

        /// <summary>
        /// Gets the value of an attribute of an XML Node. The XML Node is first found, using the Key. Looks in the "Settings" node for the key.
        /// </summary>
        /// <param name="Key">The key.</param>
        /// <param name="Attribute">The attribute.</param>
        /// <returns></returns>
        public string TryGetAttributeValue(string Key, string Attribute)
        {
            try {
                return GetAttributeValue(Key, "Settings", Attribute);
            } catch {
                return "";
            }
        }

        /// <summary>
        /// Gets the setting from the default node.
        /// </summary>
        /// <param name="Key">The key.</param>
        /// <returns></returns>
        public string TryGetSetting(string Key)
        {
            return TryGetSetting(Key, "Settings");
        }

        /// <summary>
        /// Gets the setting from the specified node.
        /// </summary>
        /// <param name="Key">The key.</param>
        /// <param name="XmlNode">The node.</param>
        /// <returns></returns>
        public string TryGetSetting(string Key, string XmlNode)
        {
            try {
                XmlNode node = mXmlDocument.DocumentElement.SelectSingleNode((("/" + m_RootNode + "/") + XmlNode + "/add[@key=\"") + Key + "\"]");
                if (node != null) {
                    return node.Attributes.GetNamedItem("value").Value;
                } else {
                    return "";
                }
            } catch {
                return "";
            }
        }

        /// <summary>
        /// Checks if the XML File exists, and if not, creates a new one.
        /// </summary>
        private void CheckXMLFile()
        {
            if (System.IO.File.Exists(m_path) != true) {
                StringBuilder fn = new StringBuilder();
                fn.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                fn.AppendLine(string.Format("<{0}>", m_RootNode));
                fn.AppendLine(string.Format("</{0}>", m_RootNode));
                System.IO.File.WriteAllText(IO.CreateOSPath(m_path), fn.ToString());
            }
        }

        #endregion Methods
    }
}


text:
var jcApp = jcApp || {};

(function($,app) {

	app.index = '#tpl-index';
	app.output = $('#tpl-output');
	app.attrUrl = 'data-url';

	app.print = function (url) {
		window.console && console.log(url);
		var source   = $(url).html();
		var template = Handlebars.compile(source);
		app.output.html(template);
	};

	app.print(app.index);

	$('.tpl-link').on('click', function(e){
		e.preventDefault();
		app.print($(this).attr(app.attrUrl));
	});

	$('.external').attr('target','_blank');

})(jQuery,jcApp);

redpajama_set_name: RedPajamaGithub


text:
namespace nc {
namespace pcap {

void PacketHandler::HandleTCP(Timestamp timestamp, const IPHeader& ip_header,
                              const TCPHeader& tcp_header,
                              uint16_t payload_len) {
  Unused(timestamp);
  Unused(ip_header);
  Unused(tcp_header);
  Unused(payload_len);
}

void PacketHandler::HandleUDP(Timestamp timestamp, const IPHeader& ip_header,
                              const UDPHeader& udp_header,
                              uint16_t payload_len) {
  Unused(timestamp);
  Unused(ip_header);
  Unused(udp_header);
  Unused(payload_len);
}
void PacketHandler::HandleICMP(Timestamp timestamp, const IPHeader& ip_header,
                               const ICMPHeader& icmp_header,
                               uint16_t payload_len) {
  Unused(timestamp);
  Unused(ip_header);
  Unused(icmp_header);
  Unused(payload_len);
}
void PacketHandler::HandleUnknownIP(Timestamp timestamp,
                                    const IPHeader& ip_header,
                                    uint16_t payload_len) {
  Unused(timestamp);
  Unused(ip_header);
  Unused(payload_len);
}

bool VerifyTCPHeader(const IPHeader& ip_header, const TCPHeader& tcp_header,
                     uint16_t* payload_size) {
  if (tcp_header.th_off < 5) {
    LOG(INFO) << Substitute("TCP header offset too short: $0 words",
                            tcp_header.th_off);

    return false;
  }

  uint32_t headers_size = (ip_header.ip_hl + tcp_header.th_off) * 4;
  uint16_t ip_len = ntohs(ip_header.ip_len);
  if (headers_size > ip_len) {
    LOG(INFO) << Substitute("Wrong TCP header size: ip_len $0, headers_size $1",
                            ip_len, headers_size);

    return false;
  }

  *payload_size = ip_len - headers_size;
  return true;
}

bool VerifyUDPHeader(const IPHeader& ip_header, uint16_t* payload_size) {
  uint32_t headers_size = ip_header.ip_hl * 4 + pcap::kSizeUDP;
  uint16_t ip_len = ntohs(ip_header.ip_len);
  if (headers_size > ip_len) {
    LOG(INFO) << Substitute("Wrong UDP header size: ip_len $0, headers_size $1",
                            ip_len, headers_size);

    return false;
  }

  *payload_size = ip_len - headers_size;
  return true;
}

bool VerifyICMPHeader(const IPHeader& ip_header, uint16_t* payload_size) {
  uint32_t headers_size = ip_header.ip_hl * 4 + pcap::kSizeICMP;
  uint16_t ip_len = ntohs(ip_header.ip_len);
  if (headers_size > ip_len) {
    LOG(INFO) << Substitute(
        "Wrong ICMP header size estimate: ip_len $0, headers_size $1", ip_len,
        headers_size);

    return false;
  }

  *payload_size = ip_len - headers_size;
  return true;
}

// Called to handle a single packet. Will dispatch it to HandleTcp or
// HandleUdp.This is in a free function because the pcap library expects an
// unbound function pointer
static void HandlePkt(u_char* d, const struct pcap_pkthdr* header,
                      const u_char* packet) {
  using namespace std::chrono;
  PcapBase* data = reinterpret_cast<PcapBase*>(d);

  Timestamp timestamp;
  ExternalTimestampProvider* external_timestamp_provider =
      data->timestamp_provider();
  if (external_timestamp_provider) {
    timestamp = external_timestamp_provider->NextTimestamp();
  } else {
    // Timestamp is assumed to have microsecond precision.
    timestamp = seconds(header->ts.tv_sec) + microseconds(header->ts.tv_usec);
  }

  int datalink = data->datalink();
  size_t offset;
  // Have to figure out what the offset is.
  switch (datalink) {
    case DLT_EN10MB: {
      if (header->caplen < 14) {
        return;
      }
      // Only handle IP and 802.1Q VLAN tagged packets
      if (packet[12] == 8 && packet[13] == 0) {
        // Regular ethernet
        offset = kSizeEthernet;
      } else if (packet[12] == 0x81 && packet[13] == 0) {
        // Skip 802.1Q VLAN and priority information
        offset = kSizeEthernetDotOneQ;
      } else {
        LOG(ERROR) << "Non-IP frame";
        return;
      }
      break;
    }

    case DLT_RAW: {
      offset = 0;
      break;
    }

    case DLT_NULL: {
      offset = 4;
      break;
    }

    case DLT_LINUX_SLL: {
      offset = 16;
      break;
    }

    default: {
      LOG(FATAL) << "Unknown datalink " << datalink;
      return;
    }
  }

  const IPHeader* ip_header =
      reinterpret_cast<const IPHeader*>(packet + offset);

  uint16_t off = ntohs(ip_header->ip_off);
  if (off && !(off & IP_DF)) {
    // Don't know how to deal with fragments yet.
    return;
  }

  if (off & IP_RF) {
    // Reserved bit set -- rfc3541
    LOG(INFO) << "Packet with evil bit";
    return;
  }

  size_t size_ip = ip_header->ip_hl * 4;
  if (size_ip < 20) {
    LOG(INFO) << Substitute(
        "Invalid IP header length: $0 bytes, pcap header len: $1", size_ip,
        header->len);

    return;
  }

  PacketHandler* handler = data->handler();
  uint16_t payload_len;
  switch (ip_header->ip_p) {
    case IPPROTO_TCP: {
      const TCPHeader* tcp_header =
          reinterpret_cast<const TCPHeader*>(packet + offset + size_ip);
      if (!VerifyTCPHeader(*ip_header, *tcp_header, &payload_len)) {
        return;
      }

      handler->HandleTCP(timestamp, *ip_header, *tcp_header, payload_len);
      break;
    }
    case IPPROTO_UDP: {
      const UDPHeader* udp_header =
          reinterpret_cast<const UDPHeader*>(packet + offset + size_ip);
      if (!VerifyUDPHeader(*ip_header, &payload_len)) {
        return;
      }

      handler->HandleUDP(timestamp, *ip_header, *udp_header, payload_len);
      break;
    }
    case IPPROTO_ICMP: {
      const ICMPHeader* icmp_header =
          reinterpret_cast<const ICMPHeader*>(packet + offset + size_ip);
      if (!VerifyICMPHeader(*ip_header, &payload_len)) {
        return;
      }

      handler->HandleICMP(timestamp, *ip_header, *icmp_header, payload_len);
      break;
    }
    default: {
      // This will be off, but we don't know what the protocol is.
      payload_len = ntohs(ip_header->ip_len) - ip_header->ip_hl * 4;
      handler->HandleUnknownIP(timestamp, *ip_header, payload_len);
    }
  }
}

int PcapBase::datalink() const {
  CHECK(handle_ != nullptr);
  return datalink_;
}

void PcapBase::set_timestamp_provider(
    ExternalTimestampProvider* timestamp_provider) {
  timestamp_provider_ = timestamp_provider;
}

ExternalTimestampProvider* PcapBase::timestamp_provider() const {
  return timestamp_provider_;
}

// pcap_compile is inherently thread unsafe.
static std::mutex pcap_compile_mutex_;

void PcapBase::InstallBPF(bpf_u_int32 net) {
  std::lock_guard<std::mutex> lock(pcap_compile_mutex_);

  struct bpf_program fp;
  if (pcap_compile(handle_, &fp, bpf_filter_.c_str(), 0, net) == -1) {
    pcap_freecode(&fp);
    LOG(FATAL) << "Could not parse filter " << bpf_filter_
               << ", pcap said: " << std::string(pcap_geterr(handle_));
  }

  if (pcap_setfilter(handle_, &fp) == -1) {
    pcap_freecode(&fp);
    LOG(FATAL) << "Could not install filter " << bpf_filter_
               << ", pcap said: " << std::string(pcap_geterr(handle_));
  }

  pcap_freecode(&fp);
}

void OnlinePcap::PcapOpen(const std::string& source) {
  char errbuf[PCAP_ERRBUF_SIZE];
  bpf_u_int32 mask = 0;
  bpf_u_int32 net = 0;

  // A c-style string for the source.
  const char* source_c = source.c_str();
  handle_ = pcap_open_live(source_c, snapshot_len_, 1, 1000, errbuf);
  CHECK(handle_ != nullptr) << "Could not open source " << source
                            << ", pcap said: " << std::string(errbuf);

  datalink_ = pcap_datalink(handle_);
  CHECK(pcap_lookupnet(source_c, &net, &mask, errbuf) != -1)
      << "Could not get netmask for device " << source
      << ", pcap said: " << std::string(errbuf);
  CHECK(pcap_setnonblock(handle_, 1, errbuf) != -1)
      << "Could not set to non-blocking device " << source
      << ", pcap said: " << std::string(errbuf);
  InstallBPF(net);
}

void OnlinePcap::Run() {
  int poll_result;
  pollfd pfd;
  LOG(INFO) << "Will start listening on " << source_;

  pfd.fd = pcap_fileno(handle_);
  pfd.events = POLLIN;

  while (true) {
    poll_result = poll(&pfd, 1, 1000);
    CHECK(poll_result != -1) << "Bad poll on pcap fd";

    switch (poll_result) {
      case 0:  // timeout
        break;

      default:  // packet
        pcap_dispatch(handle_, -1, HandlePkt, reinterpret_cast<u_char*>(this));
    }
  }
}

void OfflinePcap::Run() {
  // Will get a series of sources from the source provider and process
  // every one of them in order.
  while (true) {
    std::string next_source = source_->NextSource();
    if (next_source.empty()) {
      break;
    }

    PcapOpen(next_source);
    LOG(INFO) << "Will start reading from " << next_source;
    int ret =
        pcap_loop(handle_, -1, HandlePkt, reinterpret_cast<u_char*>(this));
    if (ret == 0) {
      LOG(INFO) << "Done reading from " << next_source;
    } else {
      LOG(ERROR) << "Error while reading from " << next_source
                 << ", pcap said: " << std::string(pcap_geterr(handle_));
    }

    pcap_close(handle_);
    handle_ = nullptr;
  }
}

bool OfflinePcap::NextPacket() {
  if (handle_ == nullptr) {
    std::string next_source = source_->NextSource();
    if (next_source.empty()) {
      return false;
    }

    PcapOpen(next_source);
    LOG(INFO) << "Will start reading from " << next_source;
  }

  struct pcap_pkthdr* header_ptr;
  const u_char* packet_ptr;

  int ret = pcap_next_ex(handle_, &header_ptr, &packet_ptr);
  CHECK(ret != -1) << "Error while reading, pcap said: "
                   << std::string(pcap_geterr(handle_));
  if (ret == -2) {
    LOG(INFO) << "Done reading";
    pcap_close(handle_);
    handle_ = nullptr;
    return NextPacket();
  }

  HandlePkt(reinterpret_cast<u_char*>(this), header_ptr, packet_ptr);
  return true;
}

void OfflinePcap::PcapOpen(const std::string& source) {
  char errbuf[PCAP_ERRBUF_SIZE];
  FILE* fp = fopen(source.c_str(), "rb");
  CHECK(fp != nullptr) << "Unable to open file";

  handle_ = pcap_fopen_offline(fp, errbuf);
  CHECK(handle_ != nullptr) << "Could not open source " << source
                            << ", pcap said: " << std::string(errbuf);
  datalink_ = pcap_datalink(handle_);
  InstallBPF(PCAP_NETMASK_UNKNOWN);
}

DefaultOfflineSourceProvider::DefaultOfflineSourceProvider(
    const std::string& filename)
    : next_index_(0), filenames_({filename}) {}

DefaultOfflineSourceProvider::DefaultOfflineSourceProvider(
    const std::vector<std::string>& filenames)
    : next_index_(0), filenames_(filenames) {}

std::string DefaultOfflineSourceProvider::NextSource() {
  if (next_index_ == filenames_.size()) {
    return "";
  }

  return filenames_[next_index_++];
}

}  // namespace pcap
}  // namespace nc


text:
import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, Resolve} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import {Observer} from 'rxjs/Observer';
import {AppService} from './app.service';

declare let toastr: any;
declare let $: any;

@Injectable()
export class BaseResolver implements Resolve<any> {
  constructor(private appService: AppService) {}

  resolve(route: ActivatedRouteSnapshot): Observable<any> {
    return Observable.create((observer: Observer<any>) => {
      this.appService.getMetadata().subscribe(
        (metadata: any) => {
          AppService.MetaDataEvent.next(metadata);
          observer.next(metadata);
        }, (err: any) => {
          console.log('BaseComponent - ngOnInit - getMetadata - Failed: ' + err);
          toastr.error(err, 'Failed to get metadata');
        }, () => {
          observer.complete();
        });
    });
  }
}


text:
package org.eigenbase.sql.advise;

import java.util.List;

import org.eigenbase.sql.validate.SqlMoniker;

/**
 * This class is used to return values for {@link SqlAdvisor#getCompletionHints
 * (String, int, String[])}.
 */
public class SqlAdvisorHint {
  /** Fully qualified object name as string. */
  public final String id;
  /** Fully qualified object name as array of names. */
  public final String[] names;
  /** One of {@link org.eigenbase.sql.validate.SqlMonikerType}. */
  public final String type;

  public SqlAdvisorHint(String id, String[] names, String type) {
    this.id = id;
    this.names = names;
    this.type = type;
  }

  public SqlAdvisorHint(SqlMoniker id) {
    this.id = id.toString();
    final List<String> names = id.getFullyQualifiedNames();
    this.names = names == null
      ? null
      : names.toArray(new String[names.size()]);
    type = id.getType().name();
  }
}


text:
{-# LANGUAGE CPP #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module Codec.Picture.Png.Internal.Metadata( extractMetadatas
                                 , encodeMetadatas
                                 ) where

#if !MIN_VERSION_base(4,8,0)
import Control.Applicative( (<$>), (<*>), pure )
import Data.Monoid( Monoid, mempty )
import Data.Foldable( foldMap )
#endif

import Data.Maybe( fromMaybe )
import Data.Binary( Binary( get, put ), encode )
import Data.Binary.Get( getLazyByteStringNul, getWord8 )
import Data.Binary.Put( putLazyByteString, putWord8 )
import qualified Data.ByteString.Lazy.Char8 as L
#if !MIN_VERSION_base(4,11,0)
import Data.Monoid( (<>) )
#endif

import qualified Codec.Compression.Zlib as Z

import Codec.Picture.InternalHelper
import qualified Codec.Picture.Metadata as Met
import Codec.Picture.Metadata ( Metadatas
                              , dotsPerMeterToDotPerInch
                              , Elem( (:=>) ) )
import Codec.Picture.Png.Internal.Type

#if !MIN_VERSION_base(4,7,0)
eitherFoldMap :: Monoid m => (a -> m) -> Either e a -> m
eitherFoldMap f v = case v of
  Left _ -> mempty
  Right a -> f a
#else
eitherFoldMap :: Monoid m => (a -> m) -> Either e a -> m
eitherFoldMap = foldMap
#endif

getGamma :: [L.ByteString] -> Metadatas
getGamma [] = mempty
getGamma (g:_) = eitherFoldMap unpackGamma $ runGet get g
  where
    unpackGamma gamma = Met.singleton Met.Gamma (getPngGamma gamma)

getDpis :: [L.ByteString] -> Metadatas
getDpis [] = mempty
getDpis (b:_) = eitherFoldMap unpackPhys $ runGet get b
  where
    unpackPhys PngPhysicalDimension { pngUnit = PngUnitUnknown } =
      Met.insert Met.DpiX 72 $ Met.singleton Met.DpiY 72
    unpackPhys phy@PngPhysicalDimension { pngUnit = PngUnitMeter } =
      Met.insert Met.DpiX dpx $ Met.singleton Met.DpiY dpy
        where
          dpx = dotsPerMeterToDotPerInch . fromIntegral $ pngDpiX phy
          dpy = dotsPerMeterToDotPerInch . fromIntegral $ pngDpiY phy

data PngText = PngText
  { pngKeyword :: !L.ByteString
  , pngData    :: !L.ByteString
  }
  deriving Show

instance Binary PngText where
  get = PngText <$> getLazyByteStringNul <*> getRemainingLazyBytes
  put (PngText kw pdata) = do
    putLazyByteString kw
    putWord8 0
    putLazyByteString pdata

data PngZText = PngZText
  { pngZKeyword :: !L.ByteString
  , pngZData    :: !L.ByteString
  }
  deriving Show

instance Binary PngZText where
  get = PngZText <$> getLazyByteStringNul <* getCompressionType <*> (Z.decompress <$> getRemainingLazyBytes)
    where
      getCompressionType = do
        0 <- getWord8
        return ()
  put (PngZText kw pdata) = do
    putLazyByteString kw
    putWord8 0
    putWord8 0 -- compression type
    putLazyByteString (Z.compress pdata)

aToMetadata :: (a -> L.ByteString) -> (a -> L.ByteString) -> a -> Metadatas
aToMetadata pkeyword pdata ptext = case pkeyword ptext of
  "Title" -> strValue Met.Title
  "Author" -> strValue Met.Author
  "Description" -> strValue Met.Description
  "Copyright" -> strValue Met.Copyright
  {-"Creation Time" -> strValue Creation-}
  "Software" -> strValue Met.Software
  "Disclaimer" -> strValue Met.Disclaimer
  "Warning" -> strValue Met.Warning
  "Source" -> strValue Met.Source
  "Comment" -> strValue Met.Comment
  other ->
    Met.singleton
      (Met.Unknown $ L.unpack other)
      (Met.String . L.unpack $ pdata ptext)
  where
    strValue k = Met.singleton k . L.unpack $ pdata ptext

textToMetadata :: PngText -> Metadatas
textToMetadata = aToMetadata pngKeyword pngData

ztxtToMetadata :: PngZText -> Metadatas
ztxtToMetadata = aToMetadata pngZKeyword pngZData

getTexts :: [L.ByteString] -> Metadatas
getTexts = foldMap (eitherFoldMap textToMetadata . runGet get)

getZTexts :: [L.ByteString] -> Metadatas
getZTexts = foldMap (eitherFoldMap ztxtToMetadata . runGet get)

extractMetadatas :: PngRawImage -> Metadatas
extractMetadatas img = getDpis (chunksOf pHYsSignature)
                    <> getGamma (chunksOf gammaSignature)
                    <> getTexts (chunksOf tEXtSignature)
                    <> getZTexts (chunksOf zTXtSignature)
  where
    chunksOf = chunksWithSig img

encodePhysicalMetadata :: Metadatas -> [PngRawChunk]
encodePhysicalMetadata metas = fromMaybe [] $ do
  dx <- Met.lookup Met.DpiX metas
  dy <- Met.lookup Met.DpiY metas
  let to = fromIntegral . Met.dotPerInchToDotsPerMeter
      dim = PngPhysicalDimension (to dx) (to dy) PngUnitMeter
  pure [mkRawChunk pHYsSignature $ encode dim]

encodeSingleMetadata :: Metadatas -> [PngRawChunk]
encodeSingleMetadata = Met.foldMap go where
  go :: Elem Met.Keys -> [PngRawChunk]
  go v = case v of
    Met.Exif _ :=> _ -> mempty
    Met.DpiX :=> _ -> mempty
    Met.DpiY :=> _ -> mempty
    Met.Width :=> _ -> mempty
    Met.Height :=> _ -> mempty
    Met.Format :=> _ -> mempty
    Met.Gamma       :=> g ->
      pure $ mkRawChunk gammaSignature . encode $ PngGamma g
    Met.ColorSpace  :=> _ -> mempty
    Met.Title       :=> tx -> txt "Title" (L.pack tx)
    Met.Description :=> tx -> txt "Description" (L.pack tx)
    Met.Author      :=> tx -> txt "Author" (L.pack tx)
    Met.Copyright   :=> tx -> txt "Copyright" (L.pack tx)
    Met.Software    :=> tx -> txt "Software" (L.pack tx)
    Met.Comment     :=> tx -> txt "Comment" (L.pack tx)
    Met.Disclaimer  :=> tx -> txt "Disclaimer" (L.pack tx)
    Met.Source      :=> tx -> txt "Source" (L.pack tx)
    Met.Warning     :=> tx -> txt "Warning" (L.pack tx)
    Met.Unknown k   :=> Met.String tx -> txt (L.pack k) (L.pack tx)
    Met.Unknown _   :=> _ -> mempty

  txt k c = pure . mkRawChunk tEXtSignature . encode $ PngText k c

encodeMetadatas :: Metadatas -> [PngRawChunk]
encodeMetadatas m = encodePhysicalMetadata m <> encodeSingleMetadata m


text:
package io.selendroid.android;

import io.selendroid.ServerInstrumentation;
import io.selendroid.util.SelendroidLogger;
import android.app.Instrumentation;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.webkit.WebView;

public class WebViewKeySender extends InstrumentedKeySender {
  private final WebView webview;
  private volatile boolean done;

  public WebViewKeySender(Instrumentation instrumentation, WebView webview) {
    super(instrumentation);
    this.webview = webview;
  }

  /**
   * Sends key strokes to the given text to the element in focus within the webview.
   *
   * Note: This assumes that the focus has been set before on the element at sake.
   *
   * @param text
   */
  @Override
  public void send(final CharSequence text) {
    final KeyCharacterMap characterMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);

    long timeout =
        System.currentTimeMillis()
            + ServerInstrumentation.getInstance().getAndroidWait().getTimeoutInMillis();
    SelendroidLogger.info("Using timeout of " + timeout + " milli seconds.");

    done = false;

    instrumentation.runOnMainSync(new Runnable() {
      public void run() {
        for (int i = 0; i < text.length(); i++) {
          char c = text.charAt(i);
          int code = WebViewKeys.getKeyEventFromUnicodeKey(c);
          if (code != -1) {
            webview.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, code));
            webview.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, code));
          } else {
            KeyEvent[] arr = characterMap.getEvents(new char[] {c});
            if (arr != null) {
              for (int j = 0; j < arr.length; j++) {
                webview.dispatchKeyEvent(arr[j]);
              }
            }
          }
        }
        done = true;
      }
    });
  }
}


text:
package jintgen.jigir;

import java.util.LinkedList;
import java.util.List;

/**
 * The StmtVisitor interface implements the visitor pattern so that clients can visit the abstract syntax
 * tree nodes representing statements in the program.
 *
 * @author Ben L. Titzer
 */
public class StmtRebuilder<Env> extends CodeRebuilder<Env> implements StmtAccumulator<Stmt, Env> {

    List<Stmt> newList;
    boolean changed;

    public Stmt visit(CallStmt s, Env env) {
        List<Expr> na = visitExprList(s.args, env);
        if (na != s.args) return rebuild(s, na);
        else return s;
    }

    protected Stmt rebuild(CallStmt s, List<Expr> na) {
        CallStmt callStmt = new CallStmt(s.method, na);
        callStmt.setDecl(s.getDecl());
        return callStmt;
    }

    public Stmt visit(WriteStmt s, Env env) {
        Expr ne = visitExpr(s.expr, env);
        if ( ne != s.expr ) return rebuild(s, ne);
        return s;
    }

    protected WriteStmt rebuild(WriteStmt s, Expr ne) {
        WriteStmt writeStmt = new WriteStmt(s.method, s.typeRef, s.operand, ne);
        writeStmt.setAccessor(s.getAccessor());
        return writeStmt;
    }

    public Stmt visit(CommentStmt s, Env env) {
        return s;
    }

    public Stmt visit(DeclStmt s, Env env) {
        Expr ni = visitExpr(s.init, env);
        if (ni != s.init)
            return new DeclStmt(s.name, s.typeRef, ni);
        else
            return s;
    }

    public Stmt visit(IfStmt s, Env env) {
        Expr nc = visitExpr(s.cond, env);
        List<Stmt> nt = visitStmtList(s.trueBranch, env);
        List<Stmt> nf = visitStmtList(s.falseBranch, env);

        if (nc != s.cond || nt != s.trueBranch || nf != s.falseBranch)
            return new IfStmt(nc, nt, nf);
        else
            return s;
    }

    public List<Stmt> visitStmtList(List<Stmt> l, Env env) {
        List<Stmt> oldList = this.newList;
        boolean oldChanged = changed;
        newList = new LinkedList<Stmt>();
        changed = false;

        visitStmts(l, env);

        if (changed) l = newList;
        this.newList = oldList;
        changed = oldChanged;
        return l;
    }

    protected void visitStmts(List<Stmt> l, Env env) {
        for (Stmt sa : l) {
            Stmt na = sa.accept(this, env);
            if (na != sa) changed = true;
            if (na != null)
                newList.add(na);
        }
    }

    protected void addStmt(Stmt s) {
        newList.add(s);
        changed = true;
    }

    public Stmt visit(AssignStmt s, Env env) {
        Expr ni = visitExpr(s.dest, env);
        Expr ne = visitExpr(s.expr, env);
        if (ni != s.dest || ne != s.expr)
            return new AssignStmt(ni, ne);
        else
            return s;
    }

    public Stmt visit(AssignStmt.Var s, Env env) {
        VarExpr ni = (VarExpr)visitExpr(s.dest, env);
        Expr ne = visitExpr(s.expr, env);
        if (ni != s.dest || ne != s.expr)
            return new AssignStmt.Var(ni, ne);
        else
            return s;
    }

    public Stmt visit(AssignStmt.Map s, Env env) {
        VarExpr nm = (VarExpr)visitExpr(s.map, env);
        Expr ni = visitExpr(s.index, env);
        Expr ne = visitExpr(s.expr, env);
        if (nm != s.map || ni != s.index || ne != s.expr)
            return new AssignStmt.Map(nm, ni, ne);
        else
            return s;
    }

    public Stmt visit(AssignStmt.Bit s, Env env) {
        VarExpr ni = (VarExpr)visitExpr(s.dest, env);
        Expr nb = visitExpr(s.bit, env);
        Expr ne = visitExpr(s.expr, env);
        if (ni != s.dest || nb != s.bit || ne != s.expr)
            return new AssignStmt.Bit(ni, nb, ne);
        else
            return s;
    }

    public Stmt visit(AssignStmt.FixedRange s, Env env) {
        VarExpr ni = (VarExpr)visitExpr(s.dest, env);
        Expr ne = visitExpr(s.expr, env);
        if (ni != s.dest || ne != s.expr)
            return new AssignStmt.FixedRange(ni, s.low_bit, s.high_bit, ne);
        else
            return s;
    }

    public Stmt visit(ReturnStmt s, Env env) {
        Expr ne = visitExpr(s.expr, env);
        if (ne != s.expr)
            return new ReturnStmt(ne);
        else
            return s;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

	<integer name="pile_empty">0</integer>
	<integer name="pile_not_empty">1</integer>
	<integer name="pile_transition">2</integer>
	<integer name="arrows_nothing">8</integer>
	<integer name="arrows_countdown_3">9</integer>
	<integer name="arrows_countdown_2">10</integer>
	<integer name="arrows_countdown_1">11</integer>
	<integer name="arrow_pickup_down">0</integer>
	<integer name="arrow_pickup_down_under">1</integer>

</resources>


text:
package com.Kuesty.services;

public interface RequestTaskHandler {

	public void onSuccess(String result);
	public void onError(String message);
}


text:
package com.bumptech.glide.load.engine.prefill;

import android.graphics.Bitmap;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import com.bumptech.glide.util.Preconditions;

/**
 * A container for a put of options used to pre-fill a
 * {@link com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool} with {@link Bitmap Bitmaps} of a
 * single size and configuration.
 */
public final class PreFillType {
  @VisibleForTesting
  static final Bitmap.Config DEFAULT_CONFIG = Bitmap.Config.RGB_565;
  private final int width;
  private final int height;
  private final Bitmap.Config config;
  private final int weight;

  /**
   * Constructor for a single type of {@link android.graphics.Bitmap}.
   *
   * @param width  The width in pixels of the {@link android.graphics.Bitmap Bitmaps} to pre-fill.
   * @param height The height in pixels of the {@link android.graphics.Bitmap Bitmaps} to pre-fill.
   * @param config The {@link android.graphics.Bitmap.Config} of the
   *               {@link android.graphics.Bitmap Bitmaps} to pre-fill.
   * @param weight An integer indicating how to balance pre-filling this size and configuration of
   *               {@link android.graphics.Bitmap} against any other sizes/configurations that may
   *               be being pre-filled.
   */
  PreFillType(int width, int height, Bitmap.Config config, int weight) {
    this.config = Preconditions.checkNotNull(config, "Config must not be null");
    this.width = width;
    this.height = height;
    this.weight = weight;
  }

  /**
   * Returns the width in pixels of the {@link android.graphics.Bitmap Bitmaps}.
   */
  int getWidth() {
    return width;
  }

  /**
   * Returns the height in pixels of the {@link android.graphics.Bitmap Bitmaps}.
   */
  int getHeight() {
    return height;
  }

  /**
   * Returns the {@link android.graphics.Bitmap.Config} of the
   * {@link android.graphics.Bitmap Bitmaps}.
   */
  Bitmap.Config getConfig() {
    return config;
  }

  /**
   * Returns the weight of the {@link android.graphics.Bitmap Bitmaps} of this type.
   */
  int getWeight() {
    return weight;
  }

  @Override
  public boolean equals(Object o) {
    if (o instanceof PreFillType) {
      PreFillType other = (PreFillType) o;
      return height == other.height && width == other.width && weight == other.weight
          && config == other.config;
    }
    return false;
  }

  @Override
  public int hashCode() {
    int result = width;
    result = 31 * result + height;
    result = 31 * result + config.hashCode();
    result = 31 * result + weight;
    return result;
  }

  @Override
  public String toString() {
    return "PreFillSize{" + "width=" + width + ", height=" + height + ", config=" + config
        + ", weight=" + weight + '}';
  }

  /**
   * Builder for {@link PreFillType}.
   */
  public static class Builder {
    private final int width;
    private final int height;

    private Bitmap.Config config;
    private int weight = 1;

    /**
     * Constructor for a builder that uses the given size as the width and height of the Bitmaps to
     * prefill.
     *
     * @param size The width and height in pixels of the Bitmaps to prefill.
     */
    public Builder(int size) {
      this(size, size);
    }

    /**
     * Constructor for a builder that uses the given dimensions as the dimensions of the Bitmaps to
     * prefill.
     *
     * @param width  The width in pixels of the Bitmaps to prefill.
     * @param height The height in pixels of the Bitmaps to prefill.
     */
    public Builder(int width, int height) {
      if (width <= 0) {
        throw new IllegalArgumentException("Width must be > 0");
      }
      if (height <= 0) {
        throw new IllegalArgumentException("Height must be > 0");
      }
      this.width = width;
      this.height = height;
    }

    /**
     * Sets the {@link android.graphics.Bitmap.Config} for the Bitmaps to pre-fill.
     *
     * @param config The config to use, or null to use Glide's default.
     * @return This builder.
     */
    public Builder setConfig(@Nullable Bitmap.Config config) {
      this.config = config;
      return this;
    }

    /**
     * Returns the current {@link android.graphics.Bitmap.Config}.
     */
    Bitmap.Config getConfig() {
      return config;
    }

    /**
     * Sets the weight to use to balance how many Bitmaps of this type are prefilled relative to the
     * other requested types.
     *
     * @param weight An integer indicating how to balance pre-filling this size and configuration of
     *               {@link android.graphics.Bitmap} against any other sizes/configurations that may
     *               be being pre-filled.
     * @return This builder.
     */
    public Builder setWeight(int weight) {
      if (weight <= 0) {
        throw new IllegalArgumentException("Weight must be > 0");
      }
      this.weight = weight;
      return this;
    }

    /**
     * Returns a new {@link PreFillType}.
     */
    PreFillType build() {
      return new PreFillType(width, height, config, weight);
    }
  }
}


text:
layout: note
title: Math
permalink: /misc/book/math/
---


text:
<ion-nav-bar class="bar-energized"></ion-nav-bar>
<ion-view title="段子">
    <ion-content class="has-header padding">

                    {{duanzi.thumbsup}}

                    {{duanzi.thumbsdown}}

        <ion-infinite-scroll
                ng-if="showMore"
                icon="ion-loading-c"
                on-infinite="fetchDuanzis()">
        </ion-infinite-scroll>
        <div class="bar bar-footer" ng-if="count <= duanzis.length">

段子没有了,靠你了

    </ion-content>
</ion-view>


text:
var ContactField = function (type, value) {
    this.type = type || "";
    this.value = value || "";
};

Object.defineProperty(ContactField, "HOME", {"value": "home"});
Object.defineProperty(ContactField, "WORK", {"value": "work"});
Object.defineProperty(ContactField, "OTHER", {"value": "other"});
Object.defineProperty(ContactField, "MOBILE", {"value": "mobile"});
Object.defineProperty(ContactField, "DIRECT", {"value": "direct"});

module.exports = ContactField;


text:
{-# LANGUAGE KindSignatures, ScopedTypeVariables, MultiParamTypeClasses #-}
-- | Some motivating examples for the "IfCxt" module.
module IfCxt.Examples
    ( cxtShow
    , cxtShowTypeable
    , cxtNub
    , Magic
    , magic
    )
    where

import IfCxt
import Data.List
import Data.Typeable

mkIfCxtInstances ''Ord
mkIfCxtInstances ''Show
mkIfCxtInstances ''Typeable

-- | A version of "show" that can be called on any type.
-- If the type is not an instance of "Show", then @<<unshowable>>@ gets displayed.
cxtShow :: forall a. IfCxt (Show a) => a -> String
cxtShow a = ifCxt (Proxy::Proxy (Show a))
    (show a)
    "<<unshowable>>"

-- | Like "cxtShow" above, but if @a@ is not an instance of "Show" then we print out the type.
cxtShowTypeable :: forall a.
    ( IfCxt (Show a)
    , IfCxt (Typeable a)
    ) => a -> String
cxtShowTypeable = ifCxt (Proxy::Proxy (Show a))
    show
    ( ifCxt (Proxy::Proxy (Typeable a))
        (\a -> "<<"++show (typeOf a) ++">>")
        (const "<<unshowable>>")
    )

-- | A version of "nub" that is maximally efficient for the given type.
-- If we only have an "Eq" constraint, then "cxtNub" takes time @O(n^2)@,
-- but if we also have an "Ord" constraint, then "cxtNub" only takes time @O(n*log n)@.
-- If the type @a@ does have an "Ord" constraint, then the order of the elements may change.
cxtNub :: forall a. (Eq a, IfCxt (Ord a)) => [a] -> [a]
cxtNub = ifCxt (Proxy::Proxy (Ord a)) nubOrd nub
    where
        nubOrd :: Ord a => [a] -> [a]
        nubOrd = go . sort
            where
                go (x1:x2:xs)
                    | x1==x2    =      go (x2:xs)
                    | otherwise = x1 : go (x2:xs)
                go [x] = [x]
                go []  = []

-- | A version of "sum" that uses the numerically stable Kahan summation technique on floating point values.
cxtSum :: forall a. (Num a, IfCxt (Floating a)) => [a] -> a
cxtSum = ifCxt (Proxy::Proxy (Floating a)) sumKahan sumSimple
    where
        sumSimple :: Num b => [b] -> b
        sumSimple = foldl' (+) 0

        sumKahan :: Num b => [b] -> b
        sumKahan = snd . foldl' go (0,0)
            where
                go (c,t) i = ((t'-t)-y,t')
                    where
                        y = i-c
                        t' = t+y

class Magic

-- | This function behaves differently depending on whether there exists a 'Magic' instance or not.
magic :: Int
magic = ifCxt (Proxy::Proxy Magic) 1 2


text:
<?php

namespace Pin;

interface RequestInterface
{
    const METHOD_OPTIONS = 'OPTIONS';
    const METHOD_GET     = 'GET';
    const METHOD_HEAD    = 'HEAD';
    const METHOD_POST    = 'POST';
    const METHOD_PUT     = 'PUT';
    const METHOD_DELETE  = 'DELETE';
    const METHOD_PATCH   = 'PATCH';

    /**
     * Get our end-point's expected method.
     *
     * @return string
     */
    public function getMethod();

    /**
     * Get our end-point path.
     *
     * @return string
     */
    public function getPath();

    /**
     * Get our sendable data.
     *
     * @return array
     */
    public function getData();
}


text:
class PossibleError < RuntimeError

end


text:
package org.apache.wicket.markup.parser.filter;

import java.text.ParseException;

import org.apache.wicket.Component;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.behavior.Behavior;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.MarkupElement;
import org.apache.wicket.markup.MarkupResourceStream;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.markup.WicketTag;
import org.apache.wicket.markup.html.TransparentWebMarkupContainer;
import org.apache.wicket.markup.parser.AbstractMarkupFilter;
import org.apache.wicket.markup.resolver.IComponentResolver;
import org.apache.wicket.request.UrlUtils;
import org.apache.wicket.request.cycle.RequestCycle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The purpose of this filter is to make all "href", "src" and "background" attributes found in the
 * markup which contain a relative URL like "myDir/myPage.gif" actually resolve in the output HTML,
 * by prefixing them with with an appropriate path to make the link work properly, even if the
 * current page is being displayed at a mounted URL or whatever. It is applied to all non wicket
 * component tags, except for auto-linked tags.
 *
 * It achieves this by being both an IMarkupFilter and IComponentResolver, and works similarly to
 * the <wicket:message> code. For each tag, we look to see if the path in "href", "src" and
 * "background" attributes is relative. If it is, we assume it's relative to the context path and we
 * should prefix it appropriately so that it resolves correctly for the current request, even if
 * that's for something that's not at the context root. This is done for ServletWebRequests by
 * prepending with "../" tokens, for example.
 *
 *
 * @author Al Maw
 */
public final class RelativePathPrefixHandler extends AbstractMarkupFilter
	implements
		IComponentResolver
{
	private static final long serialVersionUID = 1L;

	/** Logging */
	private static final Logger log = LoggerFactory.getLogger(RelativePathPrefixHandler.class);

	/**
	 * The id automatically assigned to tags without an id which we need to prepend a relative path
	 * to.
	 */
	public static final String WICKET_RELATIVE_PATH_PREFIX_CONTAINER_ID = "_relative_path_prefix_";

	/** List of attribute names considered */
	private static final String attributeNames[] = new String[] { "href", "src", "background",
			"action" };

	/**
	 * Behavior that adds a prefix to src, href and background attributes to make them
	 * context-relative
	 */
	public static final Behavior RELATIVE_PATH_BEHAVIOR = new Behavior()
	{
		private static final long serialVersionUID = 1L;

		@Override
		public void onComponentTag(Component component, ComponentTag tag)
		{
			// Modify all relevant attributes
			for (String attrName : attributeNames)
			{
				String attrValue = tag.getAttributes().getString(attrName);

				if ((attrValue != null) && (attrValue.startsWith("/") == false) &&
					(!attrValue.contains(":")) && !(attrValue.startsWith("#")))
				{
					tag.getAttributes().put(attrName,
						UrlUtils.rewriteToContextRelative(attrValue, RequestCycle.get()));
				}
			}
		}
	};

	/**
	 * Constructor for the IComponentResolver role.
	 */
	public RelativePathPrefixHandler()
	{
		this(null);
	}

	/**
	 * Constructor for the IMarkupFilter role
	 * @param markup
	 *      The markup created by reading the markup file
	 */
	public RelativePathPrefixHandler(final MarkupResourceStream markup)
	{
		super(markup);
	}

	@Override
	protected final MarkupElement onComponentTag(ComponentTag tag) throws ParseException
	{
		if (tag.isClose())
		{
			return tag;
		}

		String wicketIdAttr = getWicketNamespace() + ":" + "id";

		// Don't touch any wicket:id component and any auto-components
		if ((tag instanceof WicketTag) || (tag.isAutolinkEnabled() == true) ||
			(tag.getAttributes().get(wicketIdAttr) != null))
		{
			return tag;
		}

		// Work out whether we have any attributes that require us to add a
		// behavior that prepends the relative path.
		for (String attrName : attributeNames)
		{
			String attrValue = tag.getAttributes().getString(attrName);
			if ((attrValue != null) && (attrValue.startsWith("/") == false) &&
				(!attrValue.contains(":")) && !(attrValue.startsWith("#")))
			{
				if (tag.getId() == null)
				{
					tag.setId(getWicketRelativePathPrefix(null));
					tag.setAutoComponentTag(true);
				}
				tag.addBehavior(RELATIVE_PATH_BEHAVIOR);
				tag.setModified(true);
				break;
			}
		}

		return tag;
	}

	@Override
	public Component resolve(final MarkupContainer container, final MarkupStream markupStream,
		final ComponentTag tag)
	{
		if ((tag != null) && (tag.getId().equals(getWicketRelativePathPrefix(markupStream))))
		{
			String id = tag.getId() + container.getPage().getAutoIndex();

			// we do not want to mess with the hierarchy, so the container has to be
			// transparent as it may have wicket components inside. for example a raw anchor tag
			// that contains a label.
			return new TransparentWebMarkupContainer(id);
		}
		return null;
	}

	private String getWicketRelativePathPrefix(final MarkupStream markupStream)
	{
		return getWicketNamespace(markupStream) + WICKET_RELATIVE_PATH_PREFIX_CONTAINER_ID;
	}
}


text:
Contains little libs to work with AVR chip internals as well as to speak with peripherpherals.
Additionally allows for compiling sketches that have been renamed ```sketch-name.cpp``` and
have fixed paths. Please read the ```CMakeLists.txt``` examples to understand how to tell the build
system which libraries your code needs.

## Building

The build process is based upon [CMake](http://www.cmake.org/), which plays nice with a number
of IDEs. However, as we have to create some special dependencies there is a certain directory
structure to be followed:

```
<project>
 +-lib (contains directories with linkable libraries)
 +-src (contains the sources for pure AVR programs)
 +-sketches
   +-<sketch> (a possible Arduino sketch)
   +-libraries (directory with 3rd party Arduino libs)
```

The cmake process will scan through both the ```src``` and ```lib``` directory and add all
directories that contain a ```CMakeLists.txt``` build file. These individual build files may
contain additional specific cmake configurations not covered by the general toolchain.

If the ```ARDUINO_SDK_PATH``` variable is set (```cmake -DARDUINO_SDK_PATH=...```) the
[Arduino SDK](https://www.arduino.cc/en/Main/Software) is also set up and cmake will look in the
```sketches``` directory for Sketch and 3rd party libraries.

> Be aware that sketches also need a ```CMakeLists.txt``` build file declaring dependencies.

SDK libraries are available, like ```SoftwareSerial```,```Wire```, etc. The core library is
called ```arduino-core``` and must be declared for Sketches that have no other dependencies.

### Prerequisits

Install the toolchain:

For MacOS X the simplest way to get the toolchain is [homebew](http://brew.sh/):

```
brew tap larsimmisch/avr
brew install avr-binutils avr-gcc avr-libc avrdude
brew install cmake
```

If you want to be able to compile [Arduino](https://www.arduino.cc/) sketches you will also need
the [Arduino SDK](https://www.arduino.cc/en/Main/Software) and set the environment variable ARDUINO_SDK_PATH.

### Make

1. Edit CMakeLists.txt and set PROGRAMMER and SERIAL_DEV to your flash programmer and device.
2. follow the following procedure:

```
mkdir build
cd build
cmake ..
make eliza-flash monitor
```

To flash a target use the directory name with added -flash (twitest-flash for the TWI example).

> Unless you make significant changes to the CMakeLists.txt you only need to run ```make``` in
> the build directory from now on.

## SimAVR (testing code)

To run code inside of [SIMAVR](https://github.com/buserror/simavr), just download and install simavr as well as the simduino
example:

```
git clone git@github.com:buserror/simavr.git
cd simavr
make
cd examples/board_simduino
./obj-x86_64-apple-darwin14.4.0/simduino.elf
```

Now the simulator is running with the Arduino bootloader code and it tells us the tty we can
use to connect and flash code on to the virtual device:

```
read_ihex_chunks: ATmegaBOOT_168_atmega328.ihex, unsupported check type 03
atmega328p booloader 0x07800: 1950 bytes
avr_interrupt_init
avr_special_init
uart_pty_init bridge on port *** /dev/ttys005 ***
uart_pty_connect: /tmp/simavr-uart0 now points to /dev/ttys005
```

Edit ```CMakeLists.txt``` to set the correct SERIAL_DEV and then just follow the instructions above.

## Library Code

### debug

This lib mainly contains some macros that help debugging and will not be compiled into your
code if you compile for release.

### eliza

This is [code](https://github.com/itmm/eliza)
I found online which I rewrote to work with the limited capacity of the atmega328p by
moving most of the strings into [PROGMEM](http://www.fourwalledcubicle.com/AVRArticles.php).

### i2c

Library to access the [TWI](http://www.nongnu.org/avr-libc/user-manual/group__twi__demo.html)
(two wire interface, or i2c) interface in the AVR. Has the most basic functions to initialize
the bus and send and receive data.

### isl29125

Library that talks to the [ISL29125](http://www.intersil.com/content/dam/Intersil/documents/isl2/isl29125.pdf)
RGB sensor via i2c. Also contains code to downsample the 48bit color depth to a more useful 24bit.

### uart

Basic communication with the board is done using the the UART. This library is basically
the [demo code](http://www.nongnu.org/avr-libc/user-manual/group__stdiodemo.html) from
the [avr-libc](http://www.nongnu.org/avr-libc/).

## Main Targets

There are a number of executables available under ```src```. These are described below:

### Eliza

This little program puts Eliza on the board. Why? Because I wanted to learn how to
program the Arduino compatible board without the IDE using just the standard toolchain
[avr-libc](http://www.nongnu.org/avr-libc/) and [cmake](http://www.cmake.org/).

Another goal was to learn about how to set up the serial communication to work with
the standard tools, like puts(), fgets(), printf(), etc. As a side effect I even learned
something about [PROGMEM](http://www.fourwalledcubicle.com/AVRArticles.php).

Enjoy a little chat with Eliza!

### TWI Test

The TWI (two wire interface, also known as i2c) is a short test program that scans the i2c
bus for devices and outputs the device id.

### RGB Sensor Example

Using the i2c library, this example talks to an [ISL29125 RGB sensor](https://www.sparkfun.com/products/12829)
and reads the data via i2c and displays the results on the serial console.

### OLED Breakout

The [OLED Breakout](https://www.sparkfun.com/products/13003) is a nice little display also found in
the [MicroView](http://microview.io/). In this example a few methods of accessing the display via i2c
are explored and coupled with the RGB sensor.

## LICENSE

    Copyright 2015 ubirch GmbH (http://www.ubirch.com)

    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.


text:
class Splam::Rules::Punctuation < Splam::Rule

  def run
    punctuation = @body.scan(/[.,] /)
    add_score 10, "Text has no punctuation" if punctuation.size == 0

    @body.split(/[.,]/).each do |sentence|
      words = sentence.split(" ")
      # long sentence, add a point.
      add_score 1, "Sentence has more than 10 words" if words.size > 10
      add_score 10, "Sentence has more than 30 words" if words.size > 30
    end
  end
end


text:
(function () {
    'use strict';

    angular
        .module('app')
        .controller('RegisterController', RegisterController);

    RegisterController.$inject = ['UserService', '$location', '$rootScope', 'FlashService'];
    function RegisterController(UserService, $location, $rootScope, FlashService) {
        var vm = this;

        vm.register = register;

        function register() {
            vm.dataLoading = true;
            UserService.Create(vm.user)
                .then(function (response) {
                    if (response.success || response._id !== undefined) {
                        FlashService.Success('Registration successful', true);
                        $location.path('/login');
                    } else {
                        FlashService.Error(response.message);
                        vm.dataLoading = false;
                    }
                });
        }
    }

})();


text:
Docker is a free and open-source containerization software that helps to deploy, run applications in a container. The containers are similar to a virtual machine but consume fewer resource, easy to manage and can run anywhere regardless of operating environment it is running in.

Docker uses cgroups and namespace to allow the independent containers to run within a single Linux instance.

- This guide will help you installing Docker on Debian 9 Stretch.
- This guide should also work on the previous version, i.e., Debian 8 (Jessie)

- Note: Docker needs a 64-bit version of Debian OS and Kernel version should be at least 3.10.

- Docker is now available in two editions:
    Community Edition (CE) and Enterprise Edition (EE).
    we are installing the community edition ( CE )

- Prerequisites

  - Uninstall older versions of Docker called "docker" or "docker-engine" along with associated dependencies. If your system does not have a Docker package, skip the below step.

    - `sudo apt-get -y remove docker docker-engine docker.io`

    - Contents such as volumes, images, and networks under /var/lib/docker/ directory are preserved.

- Setup Docker Repository

Install the below packages to have "apt" get the support of https method.

sudo apt-get update
 sudo apt-get install -y apt-transport-https ca-certificates wget software-properties-common

Add the GPG key for Docker repository on your system.

wget https://download.docker.com/linux/debian/gpg
 sudo apt-key add gpg

Add the official Docker repository to the system by running below command in the terminal.

echo "deb [arch=amd64] https://download.docker.com/linux/debian $(lsb_release -cs) stable" | sudo tee -a /etc/apt/sources.list.d/docker.list

Update the apt database.

sudo apt-get update

Make sure you are installing Docker from the official repository, not from the default Debian repository.

sudo apt-cache policy docker-ce

You should see the output like below with the Docker repository details.

docker-ce:
 Installed: (none)
 Candidate: 17.06.0~ce-0~debian
 Version table:
 17.06.0~ce-0~debian 500
 500 https://download.docker.com/linux/debian stretch/stable amd64 Packages
 17.03.2~ce-0~debian-stretch 500
 500 https://download.docker.com/linux/debian stretch/stable amd64 Packages
 17.03.1~ce-0~debian-stretch 500
 500 https://download.docker.com/linux/debian stretch/stable amd64 Packages
 17.03.0~ce-0~debian-stretch 500
 500 https://download.docker.com/linux/debian stretch/stable amd64 Packages

Install Docker

Install Docker using the "apt-get" command.

sudo apt-get -y install docker-ce

Control Docker service

To start Docker, run:

sudo systemctl start docker

To stop Docker service, run:

sudo systemctl stop docker

To restart Docker service, run:

sudo systemctl restart docker

To check the status of Docker service, run:

sudo systemctl status docker

To enable Docker service to autostart on system boot, run:

sudo systemctl enable docker

Verify Docker Installation

To test the Docker installation, we will run "hello-world" container.

sudo docker run hello-world

Below output confirms that we have correctly installed Docker on Debian OS.

Unable to find image 'hello-world:latest' locally
 latest: Pulling from library/hello-world
 b04784fba78d: Pull complete
 Digest: sha256:f3b3b28a45160805bb16542c9531888519430e9e6d6ffc09d72261b0d26ff74f
 Status: Downloaded newer image for hello-world:latest

 Hello from Docker!
 This message shows that your installation appears to be working correctly.

Allow Non-root user to run Docker

By default, to run Docker commands, the user should have root privileges or equivalent privileges via sudo. Sometimes we may need to allow non-root users to run Docker containers, so follow the below steps to allow them to run containers.

Create a group "docker", if it does not exist.

sudo groupadd docker

Add your user to docker group, replace "raj" with your username.

sudo useradd raj

Add a user to docker group.

sudo usermod -aG docker raj

Log out and log back in. You should now be able to run Docker commands without prefixing sudo.

docker run hello-world

Interested Topics

Docker BasicTopics:

1: Top Important Docker Commands – Working with Docker Containers

2: Working with Docker Images – Building Docker Images

3: How to Build Docker Images with DockerFile

Docker Advanced Topics:

1: How to Setup Docker Private Registry on CentOS 7 / Ubuntu 16.04 / Fedora 27/26

2: How to Install and Configure Docker Swarm on CentOS 7 / Ubuntu 16.04 / Fedora 27/26


text:
-   BOSH and WebSocket transports are now based on Duplex streams.
-   Stream management state caching may now by async.
-   Expanded the set of events related to stream management. See [Using Stream Management](./docs/Using_Stream_Management.md). These events are:
    -   `stanza:hibernated`
    -   `message:hibernated`
    -   `message:acked`
    -   `message:failed`
    -   `message:retry`

## 12.9.0

-   The default external service discovery namespace was changed to `urn:xmpp:extdisco:2`. Querying using the `:1` namespace can be done with `client.discoverICEServers({ version: '1' })`.

## 12.0.0

**WARNING:** Unlike many previous major version bumps that were almost entirely backwards compatible, v12 is _not_ backwards compatible. Upgrading to v12 _will_ require modifications in existing code.

-   Complete TypeScript support
-   Changed JXT implementation (**old JXT definitions will not work**). See [JXT docs](./docs/jxt/README.md) for more information.
-   **Changed structure/names of JXT definitions for supported XEPs.** See [Supported XEP Formats]('./docs/Supported_XEP_Formats.md) for links to the type definitions of each XEP supported by StanzaJS.
-   **Removed support for callbacks.** All methods now support Promises only.
-   Methods using IQ stanzas now return the requested data instead of the full IQ stanza data.
-   Changed SASL implementation. Old, custom SASL mechanisms will not work.
-   **Removed JID objects.** JIDs are now treated as strings only. [See src/JID.ts for helper functions.]('./src/JID.ts)
-   Implemented Stringprep (not PRECIS, yet).
-   **Removed WildEmitter.** Now using standard EventEmitter. Event handlers using `*` wildcards will need to be changed.
    -   The `*` and `raw:*` events are still supported.
-   Added input/display helpers for Realtime Text.
-   **Configuration of transports has changed.** The wsURL/boshURL/transport fields are no longer used. Configuring transports is now done by setting the `transports` field to an object:

    ```
    XMPP.createClient({
        transports: {
            websocket: 'wss://...',
            bosh: 'https://...'
        }
    })
    ```

    Using `false` instead of a URL will disable that transport type. An object can be used to pass additional configuration, such as BOSH pre-binding rid/sid:

    ```
    XMPP.createClient({
        transports: {
            websocket: false,
            bosh: {
                url: 'https://...',
                rid: 1234,
                sid: '...'
            }
        }
    })
    ```

## 11.1.0

-   Jingle sessions now queue local actions to allow safer handling of WebRTC peer connection objects.

## 11.0.0

-   **Changed package name from `stanza.io` to `stanza`.**
-   The new website URL is https://stanzajs.org

## 10.0.0 -> 10.1.0

-   Renamed `muc:affiliation` event to `muc:other`

## 10.0.0

-   Converted to ES modules, using Typescript compiler for downleveling.
-   Moved stanza definitions back from `jxt-xmpp`, obsoleting both `jxt-xmpp` and `jxt-xmpp-types`.
-   Replaced use of `request` and `xhr` with `cross-fetch`.
-   SASL mech implementations now live inside `stanza.io`.
-   Moved host-meta fetching logic into `stanza.io`.
-   Moved `xmpp-jid` implementation back into `stanza.io`, obsoleting `xmpp-jid`.
-   Use `ws` module instead of `faye-websocket`.
-   Dropped support of old, pre-RFC XMPP-over-WebSocket.
-   Moved `jingle` implementation back into `stanza.io`.

## 9.1.0 -> 9.2.0

-   Fixed CSI namespace to use `urn:xmpp:csi:0`
-   Added support for XEP-0333 Chat Markers

## 6.0.0 -> 6.0.1

-   **Bug Fixes**
    -   [#31: Resolve Unicode interop with other clients](https://github.com/otalk/stanza.io/issues/31)

## 5.x.x -> 6.0.0

-   **Breaking Changes**

    -   Removed `client.call()`

        See the [jingle-interop-demos](https://github.com/legastero/jingle-interop-demos/commit/79f50cd481859ce837bda5eff0b7a6a272f0d1d8) for how to recreate the behaviour by working directly with the [jingle.js](https://github.com/otalk/jingle.js) and [localmedia](https://github.com/otalk/localmedia) libraries.

        ```javascript
        var localMedia = require('localmedia');

        localMedia.start();

        //...

        var sess = client.jingle.createMediaSession(peerJID);
        sess.addStream(localMedia.localStream);
        sess.start();
        ```

    * `client.jingle` was updated to a `jingle.js v1.0` instance.

        The method `client.jingle.startLocalMedia()` has been removed, in favor of using the [localmedia](https://github.com/otalk/localmedia) module instead (which is not bundled in `stanza.io`).


text:
<?php

namespace NTLAB\RtfTree\Document;

use NTLAB\RtfTree\Node\Node;

class FontTable
{
    const FONT_FAM_NIL = 'nil';
    const FONT_FAM_ROMAN = 'roman';
    const FONT_FAM_SWISS = 'swiss';
    const FONT_FAM_MODERN = 'modern';
    const FONT_FAM_SCRIPT = 'script';
    const FONT_FAM_DECOR = 'decor';
    const FONT_FAM_TECH = 'tech';
    const FONT_FAM_BIDI = 'bidi';

    /**
     * @var int
     */
    protected $index;

    /**
     * @var string
     */
    protected $name;

    /**
     * @var array
     */
    protected $families = [];

    /**
     * @var int
     */
    protected $charset;

    /**
     * @var int
     */
    protected $pitch;

    /**
     * Constructor.
     *
     * @param int $index  The font index
     * @param string $name  The font name
     */
    public function __construct($index, $name)
    {
        $this->index = $index;
        $this->name = $name;
    }

    /**
     * Get font index.
     *
     * @return int
     */
    public function getIndex()
    {
        return $this->index;
    }

    /**
     * Set font index.
     *
     * @param int $index  The index
     * @return \NTLAB\RtfTree\Document\FontTable
     */
    public function setIndex($index)
    {
        $this->index = $index;
        return $this;
    }

    /**
     * Get font name.
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set font name.
     *
     * @param string $name  The name
     * @return \NTLAB\RtfTree\Document\FontTable
     */
    public function setName($name)
    {
        $this->name = $name;
        return $this;
    }

    /**
     * Get font families.
     *
     * @return array
     */
    public function getFamilies()
    {
        return $this->families;
    }

    /**
     * Add font family.
     *
     * @param string $family  The font family
     * @return \NTLAB\RtfTree\Document\FontTable
     */
    public function addFamily($family)
    {
        if (!in_array($family, $this->families)) {
            $this->families[] = $family;
        }
        return $this;
    }

    /**
     * Get font charset.
     *
     * @return int
     */
    public function getCharset()
    {
        return $this->charset;
    }

    /**
     * Set font charset.
     *
     * @param int $charset  The charset
     * @return \NTLAB\RtfTree\Document\FontTable
     */
    public function setCharset($charset)
    {
        $this->charset = $charset;
        return $this;
    }

    /**
     * Get font pitch.
     *
     * @return int
     */
    public function getPitch()
    {
        return $this->pitch;
    }

    /**
     * Set font pitch.
     *
     * @param int $pitch  The pitch
     * @return \NTLAB\RtfTree\Document\FontTable
     */
    public function setPitch($pitch)
    {
        $this->pitch = $pitch;
        return $this;
    }

    /**
     * Create tree node.
     *
     * @return \NTLAB\RtfTree\Node\Node
     */
    public function createNode()
    {
        $node = Node::createTyped(Node::GROUP);
        $node->appendChild(Node::create(Node::KEYWORD, 'f', true, $this->index));
        foreach (count($this->families) ? $this->families : [static::FONT_FAM_NIL] as $family) {
            $node->appendChild(Node::create(Node::KEYWORD, 'f'.$family));
        }
        if (null !== $this->charset) {
            $node->appendChild(Node::create(Node::KEYWORD, 'fcharset', true, $this->charset));
        }
        if (null !== $this->pitch) {
            $node->appendChild(Node::create(Node::KEYWORD, 'fprq', true, $this->pitch));
        }
        $node->appendChild(Node::create(Node::TEXT, $this->name.';'));
        return $node;
    }

    /**
     * Detect font families.
     *
     * @return \NTLAB\RtfTree\Document\FontTable
     */
    public function detectFamilies()
    {
        foreach ([
            'times new roman'   => static::FONT_FAM_ROMAN,
            'arial'             => static::FONT_FAM_SWISS,
            'courier new'       => static::FONT_FAM_MODERN,
            'cursiva'           => static::FONT_FAM_SCRIPT,
            'symbol'            => static::FONT_FAM_TECH,
            'arabic'            => static::FONT_FAM_BIDI,
        ] as $font => $fam) {
            if (false !== strpos(strtolower($this->name), $font)) {
                $this->addFamily($fam);
            }
        }
        return $this;
    }

    /**
     * Create font table from array.
     *
     * @param array $array  Font table descriptor
     * @return \NTLAB\RtfTree\Document\FontTable
     */
    public static function create($array = [])
    {
        if (is_array($array) && count($array) > 1) {
            $fontTable = new self($array[0], $array[1]);
            // font family
            if (count($array) > 2 && is_array($array[2])) {
                foreach ($array[2] as $family) {
                    $fontTable->addFamily($family);
                }
            }
            // font charset
            if (count($array) > 3 && null !== $array[3]) {
                $fontTable->setCharset($array[3]);
            }
            // font pitch
            if (count($array) > 4 && null !== $array[4]) {
                $fontTable->setPitch($array[4]);
            }
            return $fontTable;
        }
    }

    /**
     * Extract font information from font table group node.
     *
     * @param \NTLAB\RtfTree\Node\Node $node  The font table group node
     * @return array
     */
    public static function extract(Node $node)
    {
        $fName = null;
        $fIndex = null;
        $fFamilies = null;
        $fCharset = null;
        $fPitch = null;
        foreach ($node->getChildren() as $cnode) {
            if ($cnode->isEquals('f')) {
                $fIndex = $cnode->getParameter();
                continue;
            }
            if ('f' === substr($cnode->getKey(), 0, 1)) {
                $fType = substr($cnode->getKey(), 1);
                if ($cnode->hasParameter()) {
                    switch ($fType) {
                        case 'charset':
                            $fCharset = $cnode->getParameter();
                            break;

                        case 'prq':
                            $fPitch = $cnode->getParameter();
                            break;
                    }
                } else {
                    if (null === $fFamilies) {
                        $fFamilies = [];
                    }
                    if (!in_array($fType, $fFamilies)) {
                        $fFamilies[] = $fType;
                    }
                }
                continue;
            }
            if ($cnode->is(Node::TEXT)) {
                $fName = substr($cnode->getKey(), 0, -1);
                continue;
            }
        }
        if (null !== $fName) {
            return [$fIndex, $fName, $fFamilies, $fCharset, $fPitch];
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@color/background_dark" >

    <ImageView
        android:id="@+id/arrowDown"
        android:layout_width="40dp"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="8dp"
        android:gravity="center"
        android:maxWidth="20dip"
        android:padding="4dp"
        android:scaleType="fitXY"
        android:src="@drawable/arrow_down_grey"
        android:textColor="@color/black" />

    <TextView
        android:id="@+id/charactersCounter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="55dp"
        android:background="@drawable/counter_bg"
        android:text="34"
        android:textColor="@color/black" />

    <TextView
        android:id="@+id/worldName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/imageViewTemplateIcon"
        android:layout_alignLeft="@+id/templateName"
        android:layout_marginBottom="5dp"
        android:text="World name"
        android:textColor="@color/light_grey" />

    <TextView
        android:id="@+id/templateName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/imageViewTemplateIcon"
        android:layout_marginTop="5dp"
        android:layout_toRightOf="@+id/imageViewTemplateIcon"
        android:text="Template Name"
        android:textColor="@color/white"
        android:textSize="18sp" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toLeftOf="@+id/charactersCounter"
        android:adjustViewBounds="true"
        android:gravity="center"
        android:maxWidth="30dip"
        android:padding="4dp"
        android:src="@drawable/character_white" />

    <ImageView
        android:id="@+id/imageViewTemplateIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_margin="8dp"
        android:adjustViewBounds="true"
        android:gravity="center"
        android:maxWidth="50dip"
        android:padding="4dp"
        android:scaleType="fitXY"
        android:src="@drawable/template_white" />

</RelativeLayout>


text:
// AUTONOMOUS CODE THAT FLIES FROM ANOTHER SERVER
// JSFly offers the #createAirport method that creates a server
// that is capable of receiving code from another server and running it
var jsfly = require('../jsfly');

// The #createAirport method receives an options parameter with the desired port
var options = {
    port: '3600'
};

// A callback must be supplied to receive the 'airport' object
// in order to start handling JSFly events
jsfly.createAirport(options, function (airport) {
    // The 'ready' event is emitted when the server is created
    airport.on('ready', function () {
        console.log('JSFly airport ready.');
    });
    // The 'newJSPlane' event is emitted each time a new piece of code is received
    airport.on('landing', function (jsPlane) {
        console.log(jsPlane.name + ' is running here now!');
    });
});

/*OUTPUT:
myNameIs is running here now!
Hello world!       // Every 1 second
Hello world!
Hello world!
Same airport:  Departure and target airport are the same. Denied permission to fly.
Hello world!
Hello world!
Good bye world!    // After 5.2 seconds
*/


text:
autopilot
=========

IoC container for node.js


text:
class PemNotConfiguredError < StandardError
  def initialize
    super 'PEM is not configured properly.'
  end
end


text:
/*
 * @file Leds.cpp
 * @Author BeeeOn team - Richard Wolfert (wolfert.richard@gmail.com)
 * @date July 2016
 * @brief
 */

#include "Leds.h"

using namespace std;

Leds::Leds()
{
	setConfiguration(defaultLeds);
}

bool Leds::setConfiguration(struct ledConfiguration conf)
{
	ofstream red,green,blue;
	red.open(RED_BRIGHTNESS);
	green.open(GREEN_BRIGHTNESS);
	blue.open(BLUE_BRIGHTNESS);

	if (conf.red)
		red << "0";
	else
		red << "1";

	if (conf.green)
		green << "1";
	else
		green << "0";

	unsigned char blueIntensity = 100-conf.blue;
	if (conf.blue == 100)
		blue << "1";
	else if (conf.blue == 0)
		blue << "255";
	else
		blue << to_string((int)(blueIntensity*2.55));

	red.close();
	blue.close();
	green.close();

	return true;
}


text:
<!doctype html>

		<title>C-File Browser - Wiki - Github</title>
		<meta name="author" content="Outout14">
		<meta name="description" content="C-File Browser on Github">
		<link rel="stylesheet" href="assets/style.css">
		<meta charset="UTF-8">

 Acceuil Wiki Github

C-File Browser

Github page

Bienvenue sur le Wiki de C-File Browser

 L'Installation

Télécharger C-File Browser

 Télécharger en ZIP  Télécharger en Tar.gz  Voir sur github

&copy 2016 Outout14 - Hosted on Github pages


text:
<a href="<?php echo site_url('Dashboard') ?>"> Dashboard

 First Semester

                <a href="<?php echo site_url('Notes/IT/Introduction_To_Information_Technology'); ?>">
                    Introduction To Information Technology

                <a href="<?php echo site_url('Notes/C/Fundamentals_of_Computer_Programming'); ?>">Fundamentals of Computer Programming

                <a href="<?php echo site_url('Notes/PS/Probability_And_Statistics'); ?>">Probability and Statistics

                <a href="<?php echo site_url('Notes/CAG/Calculus_And_Analytical_Geometry'); ?>">Calculus and Analytical Geometry

                <a href="<?php echo site_url('Notes/PI/Physics_I'); ?>">Physics I

                <a href="<?php echo site_url('Notes/SI/Statistics_I'); ?>">Statistics I

 Second Semester

                Digital Logic

                Discrete Structure

                Microprocessor

                Data Structure and Algorithms

                Linear Algebra

                Physics II

                Statistics II


text:
package com.opnitech.rules.core.test.engine.test_workflow.rule.group;

import com.opnitech.rules.core.enums.WhenEnum;

/**
 * @author Rigre Gregorio Garciandia Sonora
 */
public abstract class AbstractGroupRule2 extends AbstractGroupRule {

    public AbstractGroupRule2() {
        // Default constructor
    }

    @Override
    protected WhenEnum doCondition() {

        return WhenEnum.ACCEPT;
    }
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = parser;

function _parser() {
  const data = require("@babel/parser");

  _parser = function () {
    return data;
  };

  return data;
}

function _codeFrame() {
  const data = require("@babel/code-frame");

  _codeFrame = function () {
    return data;
  };

  return data;
}

var _missingPluginHelper = _interopRequireDefault(require("./util/missing-plugin-helper"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function* parser(pluginPasses, {
  parserOpts,
  highlightCode = true,
  filename = "unknown"
}, code) {
  try {
    const results = [];

    for (const plugins of pluginPasses) {
      for (const plugin of plugins) {
        const {
          parserOverride
        } = plugin;

        if (parserOverride) {
          const ast = parserOverride(code, parserOpts, _parser().parse);
          if (ast !== undefined) results.push(ast);
        }
      }
    }

    if (results.length === 0) {
      return (0, _parser().parse)(code, parserOpts);
    } else if (results.length === 1) {
      yield* [];

      if (typeof results[0].then === "function") {
        throw new Error(`You appear to be using an async parser plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`);
      }

      return results[0];
    }

    throw new Error("More than one plugin attempted to override parsing.");
  } catch (err) {
    if (err.code === "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED") {
      err.message += "\nConsider renaming the file to '.mjs', or setting sourceType:module " + "or sourceType:unambiguous in your Babel config for this file.";
    }

    const {
      loc,
      missingPlugin
    } = err;

    if (loc) {
      const codeFrame = (0, _codeFrame().codeFrameColumns)(code, {
        start: {
          line: loc.line,
          column: loc.column + 1
        }
      }, {
        highlightCode
      });

      if (missingPlugin) {
        err.message = `${filename}: ` + (0, _missingPluginHelper.default)(missingPlugin[0], loc, codeFrame);
      } else {
        err.message = `${filename}: ${err.message}\n\n` + codeFrame;
      }

      err.code = "BABEL_PARSE_ERROR";
    }

    throw err;
  }
}


text:
#include <stdio.h>
#include <string.h>

#include "py/nlr.h"
#include "py/compile.h"
#include "py/runtime0.h"
#include "py/runtime.h"
#include "py/stackctrl.h"
#include "py/frozenmod.h"
#include "py/gc.h"
#include "pyexec.h"
#include "gccollect.h"
#include MICROPY_HAL_H
#include "user_interface.h"

STATIC char heap[16384];

STATIC void mp_reset(void) {
    mp_stack_set_limit(10240);
    mp_hal_init();
    gc_init(heap, heap + sizeof(heap));
    mp_init();
    mp_obj_list_init(mp_sys_path, 0);
    mp_obj_list_init(mp_sys_argv, 0);
#if MICROPY_MODULE_FROZEN
    mp_lexer_t *lex = mp_find_frozen_module("main", 4);
    mp_parse_compile_execute(lex, MP_PARSE_FILE_INPUT, mp_globals_get(), mp_locals_get());
#endif
}

void soft_reset(void) {
    mp_hal_stdout_tx_str("PYB: soft reset\r\n");
    mp_hal_udelay(10000); // allow UART to flush output
    mp_reset();
    pyexec_event_repl_init();
}

void init_done(void) {
    mp_reset();
    mp_hal_stdout_tx_str("\r\n");
    pyexec_event_repl_init();
    uart_task_init();
}

void user_init(void) {
    system_init_done_cb(init_done);
}

mp_lexer_t *mp_lexer_new_from_file(const char *filename) {
    return NULL;
}

mp_import_stat_t mp_import_stat(const char *path) {
    return MP_IMPORT_STAT_NO_EXIST;
}

mp_obj_t mp_builtin_open(uint n_args, const mp_obj_t *args, mp_map_t *kwargs) {
    return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open);

void nlr_jump_fail(void *val) {
    printf("NLR jump failed\n");
    for (;;) {
    }
}

//void __assert(const char *file, int line, const char *func, const char *expr) {
void __assert(const char *file, int line, const char *expr) {
    printf("Assertion '%s' failed, at file %s:%d\n", expr, file, line);
    for (;;) {
    }
}


text:
"""Methods related to optimizing and transforming PauliStrings."""

from cirq.contrib.paulistring.convert_to_pauli_string_phasors import (
    ConvertToPauliStringPhasors,
)

from cirq.contrib.paulistring.convert_to_clifford_gates import (
    ConvertToSingleQubitCliffordGates,
)

from cirq.contrib.paulistring.convert_gate_set import (
    converted_gate_set,
)

from cirq.contrib.paulistring.separate import (
    convert_and_separate_circuit,
    pauli_string_half,
    regular_half,
)

from cirq.contrib.paulistring.pauli_string_dag import (
    pauli_string_dag_from_circuit,
    pauli_string_reorder_pred,
)

from cirq.contrib.paulistring.recombine import (
    move_pauli_strings_into_circuit,
)

from cirq.contrib.paulistring.pauli_string_optimize import (
    pauli_string_optimized_circuit,
)

from cirq.contrib.paulistring.clifford_optimize import (
    clifford_optimized_circuit,
)

from cirq.contrib.paulistring.optimize import (
    optimized_circuit,
)


text:
Thanks for contributing!

## Installation

```sh
git clone https://github.com/prettier/prettier-linter-helpers.git
cd prettier-linter-helpers
yarn install
```

## Running the tests

```sh
yarn run test
```

Linting is ran as part of `yarn run test`. The build will fail if there are any linting errors. You can run `yarn run lint --fix` to fix some linting errors (including formatting to match prettier's expectations). To run the tests without linting run `yarn run test`.

## Publishing

- Ensure you are on the master branch locally.
- Update `CHANGELOG.md` and commit.
- Run the following:

  ```sh
  yarn publish
  git push --follow-tags
  ```

  Running `yarn publish` shall:

  - Bump the version in package.json (asking you for the new version number)
  - Create a new commit containing that version bump in package.json
  - Create a tag for that commit
  - Publish to the npm repository

  Running `git push --follow-tags` shall:

  - Push the commit and tag to GitHub


text:
namespace glslang {

    class HlslTokenStream {
    public:
        explicit HlslTokenStream(HlslScanContext& scanner)
            : scanner(scanner), preTokenStackSize(0), tokenBufferPos(0) { }
        virtual ~HlslTokenStream() { }

    public:
        void advanceToken();
        void recedeToken();
        bool acceptTokenClass(EHlslTokenClass);
        EHlslTokenClass peek() const;
        bool peekTokenClass(EHlslTokenClass) const;

    protected:
        HlslToken token;                  // the token we are currently looking at, but have not yet accepted

    private:
        HlslTokenStream();
        HlslTokenStream& operator=(const HlslTokenStream&);

        HlslScanContext& scanner;         // lexical scanner, to get next token

        // This is the number of tokens we can recedeToken() over.
        static const int tokenBufferSize = 2;

        // Previously scanned tokens, returned for future advances,
        // so logically in front of the token stream.
        // Is logically a stack; needs last in last out semantics.
        // Currently implemented as a stack of size 2.
        HlslToken preTokenStack[tokenBufferSize];
        int preTokenStackSize;
        void pushPreToken(const HlslToken&);
        HlslToken popPreToken();

        // Previously scanned tokens, not yet returned for future advances,
        // but available for that.
        // Is logically a fifo for normal advances, and a stack for recession.
        // Currently implemented with an intrinsic size of 2.
        HlslToken tokenBuffer[tokenBufferSize];
        int tokenBufferPos;
        void pushTokenBuffer(const HlslToken&);
        HlslToken popTokenBuffer();
    };

} // end namespace glslang

#endif // HLSLTOKENSTREAM_H_


text:
"""
Django settings for {{ project_name }} project.

For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(__file__)

import dj_database_url
from project_runpy import env

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env.get('SECRET_KEY', 'Rotom')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env.get('DEBUG', False)

TEMPLATE_DEBUG = DEBUG

ALLOWED_HOSTS = ['*']  # TODO

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # support
    'django_extensions',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = '{{ project_name }}.urls'

WSGI_APPLICATION = '{{ project_name }}.wsgi.application'

# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases

DATABASES = {'default': dj_database_url.config(default='sqlite:///{{ project_name }}.db')}

# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = False

USE_L10N = False

USE_TZ = True

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates'),
)

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/dev/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'root': {
        'level': os.environ.get('LOGGING_LEVEL', 'WARNING'),
        'handlers': ['console'],
    },
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse',
        },
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
        'readable_sql': {
            '()': 'project_runpy.ReadableSqlFilter',
        },
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'project_runpy.ColorizingStreamHandler',
        },
    },
    'loggers': {
        'django.db.backends': {
            'level': 'DEBUG' if env.get('SQL', False) else 'INFO',
            'handlers': ['console'],
            'filters': ['require_debug_true', 'readable_sql'],
            'propagate': False,
        },
        'factory': {
            'level': 'ERROR',
            'propagate': False,
        },
    },
}