text:
<!DOCTYPE html>

<meta charset="UTF-8">

<title>module RubyXL::LegacyCell - rubyXL 3.3.13</title>

<link href="../css/fonts.css" rel="stylesheet">
<link href="../css/rdoc.css" rel="stylesheet">

    Home

    Pages
    Classes
    Methods

  <form action="#" method="get" accept-charset="utf-8">

      <input id="search-field" role="combobox" aria-label="Search"
             aria-autocomplete="list" aria-controls="search-results"
             type="text" name="search" placeholder="Search" spellcheck="false"
             title="Type to search, Up and Down to navigate, Enter to load">

  </form>

Methods

#change_fill

#change_font_bold

#change_font_color

#change_font_italics

#change_font_name

#change_font_size

#change_font_strikethrough

#change_font_underline

#font_switch

#workbook

    module RubyXL::LegacyCell

Attributes

          formula[RW]

          worksheet[RW]

Public Instance Methods

          change_fill(rgb = 'ffffff')

          click to toggle source

changes fill color of cell

# File lib/rubyXL/cell.rb, line 22
def change_fill(rgb = 'ffffff')
  validate_worksheet
  Color.validate_color(rgb)
  self.style_index = workbook.modify_fill(self.style_index, rgb)
end

          change_font_bold(bolded = false)

          click to toggle source

Changes font bold settings of cell

# File lib/rubyXL/cell.rb, line 67
def change_font_bold(bolded = false)
  validate_worksheet

  font = get_cell_font.dup
  font.set_bold(bolded)
  update_font_references(font)
end

          change_font_color(font_color = '000000')

          click to toggle source

Changes font color of cell

# File lib/rubyXL/cell.rb, line 48
def change_font_color(font_color = '000000')
  validate_worksheet
  Color.validate_color(font_color)

  font = get_cell_font.dup
  font.set_rgb_color(font_color)
  update_font_references(font)
end

          change_font_italics(italicized = false)

          click to toggle source

Changes font italics settings of cell

# File lib/rubyXL/cell.rb, line 58
def change_font_italics(italicized = false)
  validate_worksheet

  font = get_cell_font.dup
  font.set_italic(italicized)
  update_font_references(font)
end

          change_font_name(new_font_name = 'Verdana')

          click to toggle source

Changes font name of cell

# File lib/rubyXL/cell.rb, line 29
def change_font_name(new_font_name = 'Verdana')
  validate_worksheet

  font = get_cell_font.dup
  font.set_name(new_font_name)
  update_font_references(font)
end

          change_font_size(font_size = 10)

          click to toggle source

Changes font size of cell

# File lib/rubyXL/cell.rb, line 38
def change_font_size(font_size = 10)
  validate_worksheet
  raise 'Argument must be a number' unless font_size.is_a?(Integer) || font_size.is_a?(Float)

  font = get_cell_font.dup
  font.set_size(font_size)
  update_font_references(font)
end

          change_font_strikethrough(struckthrough = false)

          click to toggle source

# File lib/rubyXL/cell.rb, line 84
def change_font_strikethrough(struckthrough = false)
  validate_worksheet

  font = get_cell_font.dup
  font.set_strikethrough(struckthrough)
  update_font_references(font)
end

          change_font_underline(underlined = false)

          click to toggle source

Changes font underline settings of cell

# File lib/rubyXL/cell.rb, line 76
def change_font_underline(underlined = false)
  validate_worksheet

  font = get_cell_font.dup
  font.set_underline(underlined)
  update_font_references(font)
end

          font_switch(change_type, arg)

          click to toggle source

Performs correct modification based on what type of change_type is
specified

# File lib/rubyXL/cell.rb, line 100
def font_switch(change_type, arg)
  case change_type
    when Worksheet::NAME          then change_font_name(arg)
    when Worksheet::SIZE          then change_font_size(arg)
    when Worksheet::COLOR         then change_font_color(arg)
    when Worksheet::ITALICS       then change_font_italics(arg)
    when Worksheet::BOLD          then change_font_bold(arg)
    when Worksheet::UNDERLINE     then change_font_underline(arg)
    when Worksheet::STRIKETHROUGH then change_font_strikethrough(arg)
    else raise 'Invalid change_type'
  end
end

          workbook()

          click to toggle source

# File lib/rubyXL/cell.rb, line 17
def workbook
  @worksheet.workbook
end

Validate

Generated by RDoc 4.2.0.

Based on Darkfish by Michael Granger.


text:
package org.semanticweb.HermiT.debugger.commands;

import java.io.PrintWriter;

import org.semanticweb.HermiT.debugger.Debugger;

public class AgainCommand extends AbstractCommand {

    public AgainCommand(Debugger debugger) {
        super(debugger);
    }

    public String getCommandName() {
        return "a";
    }

    public String[] getDescription() {
        return new String[]{"", "executes the last command again"};
    }

    public void printHelp(PrintWriter writer) {
        writer.println("usage: a");
        writer.println("    Executes the last command again.");
    }

    public void execute(String[] args) {
        String commandLine = m_debugger.getLastCommand();
        if (commandLine != null) {
            m_debugger.getOutput().println("# " + commandLine);
            m_debugger.processCommandLine(commandLine);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
static const unsigned char _pad0[16] = { 0 };

int
crypto_aead_chacha20poly1305_encrypt_detached(unsigned char *c,
                                              unsigned char *mac,
                                              unsigned long long *maclen_p,
                                              const unsigned char *m,
                                              unsigned long long mlen,
                                              const unsigned char *ad,
                                              unsigned long long adlen,
                                              const unsigned char *nsec,
                                              const unsigned char *npub,
                                              const unsigned char *k)
{
    crypto_onetimeauth_poly1305_state state;
    unsigned char                     block0[64U];
    unsigned char                     slen[8U];

    (void) nsec;
    crypto_stream_chacha20(block0, sizeof block0, npub, k);
    crypto_onetimeauth_poly1305_init(&state, block0);
    sodium_memzero(block0, sizeof block0);

    crypto_onetimeauth_poly1305_update(&state, ad, adlen);
    STORE64_LE(slen, (uint64_t) adlen);
    crypto_onetimeauth_poly1305_update(&state, slen, sizeof slen);

    crypto_stream_chacha20_xor_ic(c, m, mlen, npub, 1U, k);

    crypto_onetimeauth_poly1305_update(&state, c, mlen);
    STORE64_LE(slen, (uint64_t) mlen);
    crypto_onetimeauth_poly1305_update(&state, slen, sizeof slen);

    crypto_onetimeauth_poly1305_final(&state, mac);
    sodium_memzero(&state, sizeof state);

    if (maclen_p != NULL) {
        *maclen_p = crypto_aead_chacha20poly1305_ABYTES;
    }
    return 0;
}

int
crypto_aead_chacha20poly1305_encrypt(unsigned char *c,
                                     unsigned long long *clen_p,
                                     const unsigned char *m,
                                     unsigned long long mlen,
                                     const unsigned char *ad,
                                     unsigned long long adlen,
                                     const unsigned char *nsec,
                                     const unsigned char *npub,
                                     const unsigned char *k)
{
    unsigned long long clen = 0ULL;
    int                ret;

    if (mlen > crypto_aead_chacha20poly1305_MESSAGEBYTES_MAX) {
        sodium_misuse();
    }
    ret = crypto_aead_chacha20poly1305_encrypt_detached(c,
                                                        c + mlen, NULL,
                                                        m, mlen,
                                                        ad, adlen,
                                                        nsec, npub, k);
    if (clen_p != NULL) {
        if (ret == 0) {
            clen = mlen + crypto_aead_chacha20poly1305_ABYTES;
        }
        *clen_p = clen;
    }
    return ret;
}

int
crypto_aead_chacha20poly1305_ietf_encrypt_detached(unsigned char *c,
                                                   unsigned char *mac,
                                                   unsigned long long *maclen_p,
                                                   const unsigned char *m,
                                                   unsigned long long mlen,
                                                   const unsigned char *ad,
                                                   unsigned long long adlen,
                                                   const unsigned char *nsec,
                                                   const unsigned char *npub,
                                                   const unsigned char *k)
{
    crypto_onetimeauth_poly1305_state state;
    unsigned char                     block0[64U];
    unsigned char                     slen[8U];

    (void) nsec;
    crypto_stream_chacha20_ietf(block0, sizeof block0, npub, k);
    crypto_onetimeauth_poly1305_init(&state, block0);
    sodium_memzero(block0, sizeof block0);

    crypto_onetimeauth_poly1305_update(&state, ad, adlen);
    crypto_onetimeauth_poly1305_update(&state, _pad0, (0x10 - adlen) & 0xf);

    crypto_stream_chacha20_ietf_xor_ic(c, m, mlen, npub, 1U, k);

    crypto_onetimeauth_poly1305_update(&state, c, mlen);
    crypto_onetimeauth_poly1305_update(&state, _pad0, (0x10 - mlen) & 0xf);

    STORE64_LE(slen, (uint64_t) adlen);
    crypto_onetimeauth_poly1305_update(&state, slen, sizeof slen);

    STORE64_LE(slen, (uint64_t) mlen);
    crypto_onetimeauth_poly1305_update(&state, slen, sizeof slen);

    crypto_onetimeauth_poly1305_final(&state, mac);
    sodium_memzero(&state, sizeof state);

    if (maclen_p != NULL) {
        *maclen_p = crypto_aead_chacha20poly1305_ietf_ABYTES;
    }
    return 0;
}

int
crypto_aead_chacha20poly1305_ietf_encrypt(unsigned char *c,
                                          unsigned long long *clen_p,
                                          const unsigned char *m,
                                          unsigned long long mlen,
                                          const unsigned char *ad,
                                          unsigned long long adlen,
                                          const unsigned char *nsec,
                                          const unsigned char *npub,
                                          const unsigned char *k)
{
    unsigned long long clen = 0ULL;
    int                ret;

    if (mlen > crypto_aead_chacha20poly1305_ietf_MESSAGEBYTES_MAX) {
        sodium_misuse();
    }
    ret = crypto_aead_chacha20poly1305_ietf_encrypt_detached(c,
                                                             c + mlen, NULL,
                                                             m, mlen,
                                                             ad, adlen,
                                                             nsec, npub, k);
    if (clen_p != NULL) {
        if (ret == 0) {
            clen = mlen + crypto_aead_chacha20poly1305_ietf_ABYTES;
        }
        *clen_p = clen;
    }
    return ret;
}

int
crypto_aead_chacha20poly1305_decrypt_detached(unsigned char *m,
                                              unsigned char *nsec,
                                              const unsigned char *c,
                                              unsigned long long clen,
                                              const unsigned char *mac,
                                              const unsigned char *ad,
                                              unsigned long long adlen,
                                              const unsigned char *npub,
                                              const unsigned char *k)
{
    crypto_onetimeauth_poly1305_state state;
    unsigned char                     block0[64U];
    unsigned char                     slen[8U];
    unsigned char                     computed_mac[crypto_aead_chacha20poly1305_ABYTES];
    unsigned long long                mlen;
    int                               ret;

    (void) nsec;
    crypto_stream_chacha20(block0, sizeof block0, npub, k);
    crypto_onetimeauth_poly1305_init(&state, block0);
    sodium_memzero(block0, sizeof block0);

    crypto_onetimeauth_poly1305_update(&state, ad, adlen);
    STORE64_LE(slen, (uint64_t) adlen);
    crypto_onetimeauth_poly1305_update(&state, slen, sizeof slen);

    mlen = clen;
    crypto_onetimeauth_poly1305_update(&state, c, mlen);
    STORE64_LE(slen, (uint64_t) mlen);
    crypto_onetimeauth_poly1305_update(&state, slen, sizeof slen);

    crypto_onetimeauth_poly1305_final(&state, computed_mac);
    sodium_memzero(&state, sizeof state);

    COMPILER_ASSERT(sizeof computed_mac == 16U);
    ret = crypto_verify_16(computed_mac, mac);
    sodium_memzero(computed_mac, sizeof computed_mac);
    if (m == NULL) {
        return ret;
    }
    if (ret != 0) {
        memset(m, 0, mlen);
        return -1;
    }
    crypto_stream_chacha20_xor_ic(m, c, mlen, npub, 1U, k);

    return 0;
}

int
crypto_aead_chacha20poly1305_decrypt(unsigned char *m,
                                     unsigned long long *mlen_p,
                                     unsigned char *nsec,
                                     const unsigned char *c,
                                     unsigned long long clen,
                                     const unsigned char *ad,
                                     unsigned long long adlen,
                                     const unsigned char *npub,
                                     const unsigned char *k)
{
    unsigned long long mlen = 0ULL;
    int                ret = -1;

    if (clen >= crypto_aead_chacha20poly1305_ABYTES) {
        ret = crypto_aead_chacha20poly1305_decrypt_detached
            (m, nsec,
             c, clen - crypto_aead_chacha20poly1305_ABYTES,
             c + clen - crypto_aead_chacha20poly1305_ABYTES,
             ad, adlen, npub, k);
    }
    if (mlen_p != NULL) {
        if (ret == 0) {
            mlen = clen - crypto_aead_chacha20poly1305_ABYTES;
        }
        *mlen_p = mlen;
    }
    return ret;
}

int
crypto_aead_chacha20poly1305_ietf_decrypt_detached(unsigned char *m,
                                                   unsigned char *nsec,
                                                   const unsigned char *c,
                                                   unsigned long long clen,
                                                   const unsigned char *mac,
                                                   const unsigned char *ad,
                                                   unsigned long long adlen,
                                                   const unsigned char *npub,
                                                   const unsigned char *k)
{
    crypto_onetimeauth_poly1305_state state;
    unsigned char                     block0[64U];
    unsigned char                     slen[8U];
    unsigned char                     computed_mac[crypto_aead_chacha20poly1305_ietf_ABYTES];
    unsigned long long                mlen;
    int                               ret;

    (void) nsec;
    crypto_stream_chacha20_ietf(block0, sizeof block0, npub, k);
    crypto_onetimeauth_poly1305_init(&state, block0);
    sodium_memzero(block0, sizeof block0);

    crypto_onetimeauth_poly1305_update(&state, ad, adlen);
    crypto_onetimeauth_poly1305_update(&state, _pad0, (0x10 - adlen) & 0xf);

    mlen = clen;
    crypto_onetimeauth_poly1305_update(&state, c, mlen);
    crypto_onetimeauth_poly1305_update(&state, _pad0, (0x10 - mlen) & 0xf);

    STORE64_LE(slen, (uint64_t) adlen);
    crypto_onetimeauth_poly1305_update(&state, slen, sizeof slen);

    STORE64_LE(slen, (uint64_t) mlen);
    crypto_onetimeauth_poly1305_update(&state, slen, sizeof slen);

    crypto_onetimeauth_poly1305_final(&state, computed_mac);
    sodium_memzero(&state, sizeof state);

    COMPILER_ASSERT(sizeof computed_mac == 16U);
    ret = crypto_verify_16(computed_mac, mac);
    sodium_memzero(computed_mac, sizeof computed_mac);
    if (m == NULL) {
        return ret;
    }
    if (ret != 0) {
        memset(m, 0, mlen);
        return -1;
    }
    crypto_stream_chacha20_ietf_xor_ic(m, c, mlen, npub, 1U, k);

    return 0;
}

int
crypto_aead_chacha20poly1305_ietf_decrypt(unsigned char *m,
                                          unsigned long long *mlen_p,
                                          unsigned char *nsec,
                                          const unsigned char *c,
                                          unsigned long long clen,
                                          const unsigned char *ad,
                                          unsigned long long adlen,
                                          const unsigned char *npub,
                                          const unsigned char *k)
{
    unsigned long long mlen = 0ULL;
    int                ret = -1;

    if (clen >= crypto_aead_chacha20poly1305_ietf_ABYTES) {
        ret = crypto_aead_chacha20poly1305_ietf_decrypt_detached
            (m, nsec,
             c, clen - crypto_aead_chacha20poly1305_ietf_ABYTES,
             c + clen - crypto_aead_chacha20poly1305_ietf_ABYTES,
             ad, adlen, npub, k);
    }
    if (mlen_p != NULL) {
        if (ret == 0) {
            mlen = clen - crypto_aead_chacha20poly1305_ietf_ABYTES;
        }
        *mlen_p = mlen;
    }
    return ret;
}

size_t
crypto_aead_chacha20poly1305_ietf_keybytes(void)
{
    return crypto_aead_chacha20poly1305_ietf_KEYBYTES;
}

size_t
crypto_aead_chacha20poly1305_ietf_npubbytes(void)
{
    return crypto_aead_chacha20poly1305_ietf_NPUBBYTES;
}

size_t
crypto_aead_chacha20poly1305_ietf_nsecbytes(void)
{
    return crypto_aead_chacha20poly1305_ietf_NSECBYTES;
}

size_t
crypto_aead_chacha20poly1305_ietf_abytes(void)
{
    return crypto_aead_chacha20poly1305_ietf_ABYTES;
}

size_t
crypto_aead_chacha20poly1305_ietf_messagebytes_max(void)
{
    return crypto_aead_chacha20poly1305_ietf_MESSAGEBYTES_MAX;
}

void
crypto_aead_chacha20poly1305_ietf_keygen(unsigned char k[crypto_aead_chacha20poly1305_ietf_KEYBYTES])
{
    randombytes_buf(k, crypto_aead_chacha20poly1305_ietf_KEYBYTES);
}

size_t
crypto_aead_chacha20poly1305_keybytes(void)
{
    return crypto_aead_chacha20poly1305_KEYBYTES;
}

size_t
crypto_aead_chacha20poly1305_npubbytes(void)
{
    return crypto_aead_chacha20poly1305_NPUBBYTES;
}

size_t
crypto_aead_chacha20poly1305_nsecbytes(void)
{
    return crypto_aead_chacha20poly1305_NSECBYTES;
}

size_t
crypto_aead_chacha20poly1305_abytes(void)
{
    return crypto_aead_chacha20poly1305_ABYTES;
}

size_t
crypto_aead_chacha20poly1305_messagebytes_max(void)
{
    return crypto_aead_chacha20poly1305_MESSAGEBYTES_MAX;
}

void
crypto_aead_chacha20poly1305_keygen(unsigned char k[crypto_aead_chacha20poly1305_KEYBYTES])
{
    randombytes_buf(k, crypto_aead_chacha20poly1305_KEYBYTES);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Json.Syntax
{
   public class JsonObject : JsonValue
   {
      public JsonObject(Dictionary<string, JsonValue> values)
      {
         this.Values = values;
      }

      public Dictionary<string, JsonValue> Values
      {
         get;
         private set;
      }
   }
}


text:
package org.wso2.appserver;

import org.testng.annotations.Test;
import org.wso2.appserver.configuration.listeners.Utils;
import org.wso2.appserver.configuration.server.AppServerConfiguration;
import org.wso2.appserver.exceptions.ApplicationServerConfigurationException;
import org.wso2.appserver.exceptions.ApplicationServerException;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * This class defines unit-tests for XML utilities.
 *
 * @since 6.0.0
 */
public class UtilsTest {
    @Test(description = "Attempts to load the XML file content with a non-existent XML schema file for validation",
            expectedExceptions = { ApplicationServerConfigurationException.class })
    public void testLoadingObjectFromNonExistentSchemaAsPath()
            throws IOException, ApplicationServerConfigurationException {
        Path xmlSource = Paths.get(TestConstants.TEST_RESOURCES, Constants.APP_SERVER_DESCRIPTOR);
        Path xmlSchema = Paths.get(TestConstants.TEST_RESOURCES, TestConstants.NON_EXISTENT_SCHEMA);
        Utils.getUnmarshalledObject(xmlSource, xmlSchema, AppServerConfiguration.class);
    }

    @Test(description = "Uses an invalid XML schema file for validation",
            expectedExceptions = { ApplicationServerConfigurationException.class })
    public void testLoadingObjectWithInvalidSchema() throws IOException, ApplicationServerException {
        Path xmlSchema = Paths.get(TestConstants.TEST_RESOURCES, TestConstants.INVALID_SCHEMA_FILE);
        Utils.getXMLUnmarshaller(xmlSchema, AppServerConfiguration.class);
    }

    @Test(description = "Attempts to load content from a file source with invalid XML syntax",
            expectedExceptions = { ApplicationServerConfigurationException.class })
    public void testLoadingObjectFromInvalidFile() throws IOException, ApplicationServerException {
        Path xmlSource = Paths.get(TestConstants.TEST_RESOURCES, TestConstants.INVALID_DESCRIPTOR);
        Path xmlSchema = Paths.get(TestConstants.TEST_RESOURCES, Constants.APP_SERVER_DESCRIPTOR_SCHEMA);
        Utils.getUnmarshalledObject(xmlSource, xmlSchema, AppServerConfiguration.class);
    }

    @Test(description = "Attempts to load content from a file input stream with invalid XML syntax",
            expectedExceptions = { ApplicationServerConfigurationException.class })
    public void testLoadingObjectFromInvalidInputStream() throws IOException, ApplicationServerException {
        Path xmlSource = Paths.get(TestConstants.TEST_RESOURCES, TestConstants.INVALID_DESCRIPTOR);
        Path xmlSchema = Paths.get(TestConstants.TEST_RESOURCES, Constants.APP_SERVER_DESCRIPTOR_SCHEMA);
        Utils.getUnmarshalledObject(Files.newInputStream(xmlSource), xmlSchema, AppServerConfiguration.class);
    }
}


text:
package tifmo

import dcstree.DCSTreeEdge
import dcstree.DCSTreeEdgeNormal
import dcstree.DCSTreeEdgeQuantifier
import dcstree.QuantifierALL
import dcstree.QuantifierNO
import dcstree.DCSTreeNode
import dcstree.Ref
import dcstree.RefOutput
import dcstree.RefGerm
import dcstree.Context
import dcstree.ContextA
import dcstree.ContextB
import dcstree.DeclarativeSubRef
import inference.IEngine

package onthefly {

	case class PathAlignment(subPath: Path, supPath: Path) {
		/**
		 * Make a tree transformation and generate on-the-fly knowledge.
		 *
		 * The process will generate a transformed DCS tree with some contexts.
		 * Given context candidates are logically filtered to make contexts.
		 *
		 * @param ie Inference engine used to logically filter context candidates.
		 * @param ctx Context candidates.
		 * @return A [[tifmo.dcstree.DeclarativeSubRef]] representing the generated on-the-fly knowledge.
		 */
		def toOnTheFly(ie: IEngine, ctx: Set[Ref]) = {

			val subords = subPath.start.subOrdinate.map(_._3) -- subPath.last.subOrdinate.map(_._3)
			val qtall = (for (end <- subords; if end.node.selection == null) yield {
				end.quantifyALL
			}).flatten
			val qtno = (for (end <- subords; if end.node.selection == null) yield {
				end.quantifyNO
			}).flatten

			val sup = {

				def xctxqt(cdash: Set[(DCSTreeEdge, DCSTreeNode)]) = {
					val xctx = (for ((DCSTreeEdgeNormal(r), n) <- cdash) yield {
						val tm = ie.getTerm(n.output)
						for (ref <- ctx; if (ie.getTerm(ref.getDenotation).superSets intersect tm.superSets).exists(!_.isW)) yield {
							ContextA(r, ref):Context
						}
					}).flatten
					val xqt = (for ((e:DCSTreeEdgeQuantifier, n) <- cdash) yield {
						val tm = ie.getTerm(n.output)
						val pool = e.quantifier match {
							case QuantifierALL => qtall
							case QuantifierNO => qtno
						}
						for (ref <- pool; if (ie.getTerm(ref.getDenotation).superSets intersect tm.superSets).exists(!_.isW)) yield {
							(e:DCSTreeEdge, ref.node.copy)
						}
					}).flatten
					(xctx, xqt)
				}

				def mkDCSTreeNode(cp: DCSTreeNode, seq: Seq[(DCSTreeEdgeNormal, DCSTreeNode)]): Seq[DCSTreeNode] = {
					val cdash = if (seq.isEmpty) cp.children else (cp.children - seq.head)
					val (xctx, xqt) = xctxqt(cdash)
					val (prechild, rettail) = if (seq.isEmpty) {
						(Set.empty[(DCSTreeEdge, DCSTreeNode)], Seq.empty[DCSTreeNode])
					} else {
						val tmp = mkDCSTreeNode(seq.head._2, seq.tail)
						(Set((seq.head._1:DCSTreeEdge, tmp.head)), tmp)
					}
					new DCSTreeNode(
						prechild ++ xqt,
						cp.rseq,
						cp.token,
						cp.sign,
						cp.selection,
						cp.outRole,
						xctx
					) +: rettail
				}

				val topref = if (supPath.asc.isEmpty) {
					supPath.start
				} else {
					val (tmpn, tmpe) = supPath.asc.last
					RefGerm(tmpn, tmpe.inRole)
				}
				val pretopctx = if (topref.isInstanceOf[RefGerm] && topref.node.compare2outRole(topref.role) >= 0 && topref.node.parent != null) {
					val (pn, e) = topref.node.parent
					val tm = ie.getTerm(pn.germ(e.inRole))
					for (ref <- ctx; if (ie.getTerm(ref.getDenotation).superSets intersect tm.superSets).exists(!_.isW)) yield {
						ContextB(ref):Context
					}
				} else {
					Set.empty[Context]
				}
				val ascrev = if (supPath.asc.isEmpty) {
					Seq.empty[(DCSTreeEdgeNormal, DCSTreeNode)]
				} else {
					val (tmp1, tmp2) = supPath.asc.unzip
					(tmp2 zip (supPath.start.node +: tmp1.init)).reverse
				}
				val topcdash = topref.node.children -- supPath.dec.take(1) -- ascrev.take(1)
				val (topctx, topqt) = xctxqt(topcdash)
				val topc1 = if (supPath.dec.isEmpty) {
					Set.empty[(DCSTreeEdge, DCSTreeNode)]
				} else {
					val tmp = mkDCSTreeNode(supPath.dec.head._2, supPath.dec.tail)
					Set((supPath.dec.head._1:DCSTreeEdge, tmp.head))
				}
				val (topc2, lastnode) = if (ascrev.isEmpty) {
					(Set.empty[(DCSTreeEdge, DCSTreeNode)], null:DCSTreeNode)
				} else {
					val tmp = mkDCSTreeNode(ascrev.head._2, ascrev.tail)
					(Set((ascrev.head._1:DCSTreeEdge, tmp.head)), tmp.last)
				}
				val rt = new DCSTreeNode(
					topc1 ++ topc2 ++ topqt,
					topref.node.rseq,
					topref.node.token,
					topref.node.sign,
					topref.node.selection,
					topref.node.outRole,
					topctx ++ pretopctx
				)
				rt.upward()
				rt.downward(null)
				if (ascrev.isEmpty) {
					supPath.start match {
						case RefOutput(n) => RefOutput(rt)
						case RefGerm(n, r) => RefGerm(rt, r)
					}
				} else {
					RefGerm(lastnode, supPath.start.role)
				}
			}

			DeclarativeSubRef(subPath.start, sup)
		}

	}

}


text:
<?php
/**
 * the main class for all the mvc application
 *
 * PHP version >= 5.3
 *
 *
 *
 * @package Mvc
 * @author  dknx01 <e.witthauer@gmail.com>
 * @license https://github.com/dknx01/micromvc/blob/master/license.txt BSD License
 *
 */
namespace Mvc;

use \Mvc\Config as Config;
use \Mvc\Db as Db;
use \Mvc\View as View;
use \Mvc\System as System;
use \Exception;
use PDOException;

/**
 * the application class to run it all
 */
class Application
{
    /**
     * request handler
     * @var \Mvc\Helper\Request
     */
    protected $request = null;
    /**
     * name of the controller
     * @var string
     */
    protected $controller = '';
    /**
     * name of the action method
     * @var string
     */
    protected $action = '';
    /**
     * the loaded and parsed config file
     * @var \Mvc\Config\Definition\Config
     */
    protected $config = null;
    /**
     * an instance of the view output
     * @var \Mvc\View\Output
     */
    protected $viewOutput = null;

    /**
     * @var string
     */
    private $cssRoot;

    /**
     * @var string
     */
    private $jsRoot;

    /**
     * @var \Mvc\View\ConfigData
     */
    private $viewConfigData;

    /**
     * prepare the application
     */
    public function __construct()
    {
        $this->request = System::getInstance()->getRequest();
        $this->viewOutput = new View\Output($this->getRequest());
        $this->startUp();
    }
    /**
     * run the application
     *
     * @return void
     * @throws \Exception
     */
    public function run()
    {
        try {
            $controllerName = $this->getController();
            /**
             * @var \Mvc\Controller\ControllerAbstract
             */
            $controller = new $controllerName();
            $actionMethod = $this->getAction();
            $controller->$actionMethod();
            $this->proccessOutput($controller);
            $this->shutDown();
        } catch (Exception $e) {
            throw new Exception($e->getMessage() . PHP_EOL . $e->getTraceAsString() . PHP_EOL);
        }

    }
    /**
     * return the request object
     *
     * @return \Mvc\Helper\Request
     */
    public function getRequest()
    {
        return $this->request;
    }
    /**
     * set the request objec
     *
     * @param \Mvc\Helper\Request $request
     * @return \Mvc\Application
     */
    public function setRequest(\Mvc\Helper\Request $request)
    {
        $this->request = $request;
        return $this;
    }

    /**
     * return the current controller name
     *
     * @return string
     */
    public function getController()
    {
        return $this->controller;
    }

    /**
     * set the controller name
     * @param string $_controller
     * @return \Mvc\Application
     */
    public function setController($_controller)
    {
        $this->controller = 'Application\Controller\\' . $_controller;
        return $this;
    }
    /**
     * prepare the database connection and store them in the registry
     *
     * @return \Mvc\Application
     * @throws \Exception
     */
    protected function prepareDatabase()
    {
        if ($this->config->getDatabaseStatus() == true) {
                try {
                    if (strtolower($this->config->getDatabaseType()) == 'mongodb') {
                        $db = new Db\MongoDb\Adapter();
                    } else {
                        $db = new Db\Adapter();
                    }
                    System::getInstance()->database($db);
                    System::getInstance()->serviceLocator()->set('db', $db);
                } catch (PDOException $exc) {
                    throw new Exception($exc->getMessage() . PHP_EOL . $exc->getTraceAsString());
                }
        }
        return $this;
    }
    /**
     * the current action
     *
     * @return string the action method name
     */
    public function getAction()
    {
        return $this->action;
    }
    /**
     * set the action method name
     *
     * @param string $action
     * @return \Mvc\Application
     */
    public function setAction($action)
    {
        $this->action = $action . 'Action';
        return $this;
    }
    /**
     * proccess and render the output
     *
     * @param \Mvc\Controller\ControllerAbstract $controller
     */
    protected function proccessOutput(\Mvc\Controller\ControllerAbstract $controller)
    {
        $viewNameController = $controller->getViewName();
        $this->viewOutput->setViewData($controller->getViewData())
                   ->setConfig($this->config)
                   ->setLayout($controller->getLayout())
                    ->setContentHeader($controller->getContentHeader())
                   ->isAjax($controller->isAjax());
        if (!empty($viewNameController)) {
            $this->viewOutput->setView($viewNameController);
        }
        if (\Mvc\System::getInstance()->get('isCli') == true) {
            $viewName = substr($this->viewOutput->getView(),0 , -5) . 'cli.phtml';
            $viewHeader = substr($this->viewOutput->getHeader(),0 , -5) . 'cli.phtml';
            $viewFooter = substr($this->viewOutput->getFooter(),0 , -5) . 'cli.phtml';
            if (file_exists($viewName)) {
                $this->viewOutput->setView($viewName);
            }
            if (file_exists($viewHeader)) {
                $this->viewOutput->setHeader($viewHeader);
            }
            if (file_exists($viewFooter)) {
                $this->viewOutput->setFooter($viewFooter);
            }
        }
        $this->viewOutput->renderComplete();
    }
    /**
     * the shutdown function for everything at the end
     */
    protected function shutDown()
    {
        if (!is_null(System::getInstance()->database())) {
            System::getInstance()->set('database', null);
        }
    }
    /**
     * additional work before the rendering
     *
     * @throws \Exception
     */
    protected function startUp()
    {
        if (file_exists(APPDIR . '/Config/Bootstrap.php')) {
            try {
                include_once APPDIR . '/Config/Bootstrap.php';
            } catch (Exception $exc) {
                throw new Exception($exc->getMessage() . PHP_EOL . $exc->getTraceAsString());
            }
        }
        $config = new Config\ParseConfig();
        $this->config = $config->getConfigData();
        System::getInstance()->configuration($this->config);
        $this->viewConfigData = new View\ConfigData();

        $this->setController($this->getRequest()->getControllerName())
            ->setAction($this->getRequest()->getAction())
            ->prepareDatabase();
        $this->viewConfigData->addJavascriptFilesFromConfig();
        $this->viewConfigData->addCssFilesFromConfig();
        $this->viewConfigData->addExternalDataToView();
    }
}


text:
package app.interfaces;

public interface ObservableTarget extends Target, Subject {

}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.OverlayManager = void 0;

class OverlayManager {
  constructor() {
    this._overlays = {};
    this._active = null;
    this._keyDownBound = this._keyDown.bind(this);
  }

  get active() {
    return this._active;
  }

  async register(name, element, callerCloseMethod = null, canForceClose = false) {
    let container;

    if (!name || !element || !(container = element.parentNode)) {
      throw new Error("Not enough parameters.");
    } else if (this._overlays[name]) {
      throw new Error("The overlay is already registered.");
    }

    this._overlays[name] = {
      element,
      container,
      callerCloseMethod,
      canForceClose
    };
  }

  async unregister(name) {
    if (!this._overlays[name]) {
      throw new Error("The overlay does not exist.");
    } else if (this._active === name) {
      throw new Error("The overlay cannot be removed while it is active.");
    }

    delete this._overlays[name];
  }

  async open(name) {
    if (!this._overlays[name]) {
      throw new Error("The overlay does not exist.");
    } else if (this._active) {
      if (this._overlays[name].canForceClose) {
        this._closeThroughCaller();
      } else if (this._active === name) {
        throw new Error("The overlay is already active.");
      } else {
        throw new Error("Another overlay is currently active.");
      }
    }

    this._active = name;

    this._overlays[this._active].element.classList.remove("hidden");

    this._overlays[this._active].container.classList.remove("hidden");

    window.addEventListener("keydown", this._keyDownBound);
  }

  async close(name) {
    if (!this._overlays[name]) {
      throw new Error("The overlay does not exist.");
    } else if (!this._active) {
      throw new Error("The overlay is currently not active.");
    } else if (this._active !== name) {
      throw new Error("Another overlay is currently active.");
    }

    this._overlays[this._active].container.classList.add("hidden");

    this._overlays[this._active].element.classList.add("hidden");

    this._active = null;
    window.removeEventListener("keydown", this._keyDownBound);
  }

  _keyDown(evt) {
    if (this._active && evt.keyCode === 27) {
      this._closeThroughCaller();

      evt.preventDefault();
    }
  }

  _closeThroughCaller() {
    if (this._overlays[this._active].callerCloseMethod) {
      this._overlays[this._active].callerCloseMethod();
    }

    if (this._active) {
      this.close(this._active);
    }
  }

}

exports.OverlayManager = OverlayManager;


text:
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using Verno.Reports.Models;

namespace Verno.Reports.Reports.Dtos
{
    [AutoMap(typeof(ReportColumn))]
    public class ReportColumnDto : EntityDto
    {
        public string Field { get; set; }
        public string Title { get; set; }
        public string Format { get; set; }
        public string LinkUrl { get; set; }
        public string Formula { get; set; }
        public string Aggregate { get; set; }
        public bool Display { get; set; }
        public int SortOrder { get; set; }
        public int? ColumnGroupId { get; set; }
    }
}


text:
.class public interface abstract Lcom/android/music/IMediaPlaybackService;
.super Ljava/lang/Object;
.source "IMediaPlaybackService.java"

# interfaces
.implements Landroid/os/IInterface;

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/android/music/IMediaPlaybackService$Stub;
    }
.end annotation

# virtual methods
.method public abstract duration()J
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract enqueue([JI)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract getAlbumId()J
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract getAlbumName()Ljava/lang/String;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract getArtistId()J
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract getArtistName()Ljava/lang/String;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract getAudioId()J
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract getAudioSessionId()I
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract getMIMEType()Ljava/lang/String;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract getMediaMountedCount()I
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract getPath()Ljava/lang/String;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract getQueue()[J
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract getQueuePosition()I
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract getRepeatMode()I
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract getShuffleMode()I
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract getTrackFilePathName()Ljava/lang/String;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract getTrackName()Ljava/lang/String;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract isPlaying()Z
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract moveQueueItem(II)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract next()V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract open([JI)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract openFile(Ljava/lang/String;)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract pause()V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract play()V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract position()J
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract prev()V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract removeTrack(J)I
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract removeTracks(II)I
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract seek(J)J
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract setQueuePosition(I)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract setRepeatMode(I)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract setShuffleMode(I)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract stop()V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method


text:
from bs4 import BeautifulSoup

 #for using urllib module
import urllib   # for using urlib module
response = urllib.urlopen("http://video9.in/english/")
html = response.read()
soup = BeautifulSoup(html,"html.parser")

'''#for using urllib2 , Request module
import urllib2  # for using urllib2 module
req = urllib2.Request("http://video9.in/english/")

response = urllib2.urlopen(req)
html = response.read()

soup = BeautifulSoup(html,"html.parser")
'''

''' #for using requests module

import requests

url = "http://video9.in/english/"

r  = requests.get(url)

data = r.text

soup = BeautifulSoup(data)
'''

for link in soup.find_all('div',{"class": "updates"}):
    print (link.text)


text:
package org.apache.reef.tests.messaging.driver;

import org.apache.reef.client.*;
import org.apache.reef.tang.Configuration;
import org.apache.reef.tang.Tang;
import org.apache.reef.tang.annotations.Unit;
import org.apache.reef.tang.exceptions.BindException;
import org.apache.reef.tang.exceptions.InjectionException;
import org.apache.reef.util.EnvironmentUtils;
import org.apache.reef.util.Optional;
import org.apache.reef.wake.EventHandler;

import javax.inject.Inject;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;

@Unit
public final class DriverMessaging {

  private static final Logger LOG = Logger.getLogger(DriverMessaging.class.getName());

  private final REEF reef;

  private String lastMessage = null;
  private Optional<RunningJob> theJob = Optional.empty();
  private LauncherStatus status = LauncherStatus.INIT;

  @Inject
  private DriverMessaging(final REEF reef) {
    this.reef = reef;
  }

  public static LauncherStatus run(final Configuration runtimeConfiguration,
                                   final int launcherTimeout) throws BindException, InjectionException {

    final Configuration clientConfiguration = ClientConfiguration.CONF
        .set(ClientConfiguration.ON_JOB_RUNNING, DriverMessaging.RunningJobHandler.class)
        .set(ClientConfiguration.ON_JOB_MESSAGE, DriverMessaging.JobMessageHandler.class)
        .set(ClientConfiguration.ON_JOB_COMPLETED, DriverMessaging.CompletedJobHandler.class)
        .set(ClientConfiguration.ON_JOB_FAILED, DriverMessaging.FailedJobHandler.class)
        .set(ClientConfiguration.ON_RUNTIME_ERROR, DriverMessaging.RuntimeErrorHandler.class)
        .build();

    return Tang.Factory.getTang()
        .newInjector(runtimeConfiguration, clientConfiguration)
        .getInstance(DriverMessaging.class).run(launcherTimeout, 1000);
  }

  public synchronized void close() {
    if (this.status.isRunning()) {
      this.status = LauncherStatus.FORCE_CLOSED;
    }
    if (this.theJob.isPresent()) {
      this.theJob.get().close();
    }
    this.notify();
  }

  private LauncherStatus run(final long jobTimeout, final long statusTimeout) {

    final long startTime = System.currentTimeMillis();
    LOG.log(Level.INFO, "Submitting REEF Job");

    final Configuration driverConfig = DriverConfiguration.CONF
        .set(DriverConfiguration.GLOBAL_LIBRARIES, EnvironmentUtils.getClassLocation(this.getClass()))
        .set(DriverConfiguration.DRIVER_IDENTIFIER, "DriverMessagingTest")
        .set(DriverConfiguration.ON_DRIVER_STARTED, DriverMessagingDriver.StartHandler.class)
        .set(DriverConfiguration.ON_EVALUATOR_ALLOCATED, DriverMessagingDriver.AllocatedEvaluatorHandler.class)
        .set(DriverConfiguration.ON_CLIENT_MESSAGE, DriverMessagingDriver.ClientMessageHandler.class)
        .build();

    this.reef.submit(driverConfig);

    synchronized (this) {
      while (!this.status.isDone()) {
        LOG.log(Level.INFO, "Waiting for REEF job to finish.");
        try {
          this.wait(statusTimeout);
        } catch (final InterruptedException ex) {
          LOG.log(Level.FINER, "Waiting for REEF job interrupted.", ex);
        }
        if (System.currentTimeMillis() - startTime >= jobTimeout) {
          LOG.log(Level.INFO, "Waiting for REEF job timed out after {0} sec.",
              (System.currentTimeMillis() - startTime) / 1000);
          break;
        }
      }
    }

    this.reef.close();
    return this.status;
  }

  final class JobMessageHandler implements EventHandler<JobMessage> {
    @Override
    public void onNext(final JobMessage message) {
      final String msg = new String(message.get(), StandardCharsets.UTF_8);
      synchronized (DriverMessaging.this) {
        if (!msg.equals(DriverMessaging.this.lastMessage)) {
          LOG.log(Level.SEVERE, "Expected {0} but got {1}",
              new Object[]{DriverMessaging.this.lastMessage, msg});
          DriverMessaging.this.status = LauncherStatus.FAILED;
          DriverMessaging.this.notify();
        }
      }
    }
  }

  final class RunningJobHandler implements EventHandler<RunningJob> {
    @Override
    public void onNext(final RunningJob job) {
      LOG.log(Level.INFO, "The Job {0} is running", job.getId());
      synchronized (DriverMessaging.this) {
        DriverMessaging.this.status = LauncherStatus.RUNNING;
        DriverMessaging.this.theJob = Optional.of(job);
        DriverMessaging.this.lastMessage = "Hello, REEF!";
        DriverMessaging.this.theJob.get().send(DriverMessaging.this.lastMessage.getBytes(StandardCharsets.UTF_8));
      }
    }
  }

  final class CompletedJobHandler implements EventHandler<CompletedJob> {
    @Override
    public void onNext(final CompletedJob job) {
      LOG.log(Level.INFO, "Job Completed: {0}", job);
      synchronized (DriverMessaging.this) {
        DriverMessaging.this.status = LauncherStatus.COMPLETED;
        DriverMessaging.this.notify();
      }
    }
  }

  final class FailedJobHandler implements EventHandler<FailedJob> {
    @Override
    public void onNext(final FailedJob job) {
      LOG.log(Level.SEVERE, "Received an error for job " + job.getId(), job.getReason().orElse(null));
      synchronized (DriverMessaging.this) {
        DriverMessaging.this.status = LauncherStatus.failed(job.getReason());
        DriverMessaging.this.notify();
      }
    }
  }

  final class RuntimeErrorHandler implements EventHandler<FailedRuntime> {
    @Override
    public void onNext(final FailedRuntime error) {
      LOG.log(Level.SEVERE, "Received a runtime error: " + error, error.getReason().orElse(null));
      synchronized (DriverMessaging.this) {
        DriverMessaging.this.status = LauncherStatus.failed(error.getReason());
        DriverMessaging.this.notify();
      }
    }
  }
}


text:
package com.ak47.cms.cms.service.impl;

import com.ak47.cms.cms.dao.ShiroMenuJapRepository;
import com.ak47.cms.cms.entity.ShiroMenu;
import com.ak47.cms.cms.service.ShiroMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ShiroMenuServiceImpl implements ShiroMenuService{
    @Autowired
    private ShiroMenuJapRepository shiroMenuJapRepository;
    @Override
    public ShiroMenu save(ShiroMenu shiroMenu) {
        return shiroMenuJapRepository.save(shiroMenu);
    }

    @Override
    public List<ShiroMenu> findAll() {
        return shiroMenuJapRepository.findAll( new Sort(Sort.Direction.ASC,"shiroOrder"));
    }

    @Override
    public void delete(Long id) {
        shiroMenuJapRepository.deleteById(id);
    }

    @Override
    public ShiroMenu findOne(Long id) {
        return shiroMenuJapRepository.getOne(id);
    }
}


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.searchers.test;

import com.yahoo.cloud.config.ClusterInfoConfig;
import com.yahoo.component.chain.Chain;
import com.yahoo.metrics.simple.Bucket;
import com.yahoo.metrics.simple.MetricReceiver;
import com.yahoo.metrics.simple.Point;
import com.yahoo.metrics.simple.UntypedMetric;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.search.config.RateLimitingConfig;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchers.RateLimitingSearcher;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;

/**
 * A benchmark and multithread stress test of rate limiting.
 * The purpose of this is to simulate the environment the rate limiter will work under in production
 * and verify that it manages to keep rates more or less within set bounds and does not lead to excessive contention.
 *
 * @author bratseth
 */
public class RateLimitingBenchmark {

    private final int clientCount = 10;
    private final int threadCount = 250;
    private final int epochs = 100; // the number of times the sequence of load types are repeated
    private final int totalQueriesPerThread = 4 * 1000 * 10;

    // This number produces a theoretical max request rate of 1000/5*threadCount = 50 k rps
    // which in practice on my machine is about 40 k rps.
    // With the number set to 0 my machine does about 150 k rps.
    // This means that peaks (when it is zero) are roughly 3x base.
    private final int sleepMsBetweenRequests = 5;
    private final int peakDurationMs = 1000;
    private final int timeBetweenPeaksMs = 2000;

    private final Chain<Searcher> chain;
    private final MetricReceiver metric;
    private Bucket metricSnapshot;

    private final Map<String, RequestCounts> requestCounters = new HashMap<>();

    public RateLimitingBenchmark() {
        RateLimitingConfig.Builder rateLimitingConfig = new RateLimitingConfig.Builder();
        /* Defaults:
        rateLimitingConfig.maxAvailableCapacity(10000);
        rateLimitingConfig.capacityIncrement(1000);
        rateLimitingConfig.recheckForCapacityProbability(0.001);
        */

        rateLimitingConfig.maxAvailableCapacity(10000);
        rateLimitingConfig.capacityIncrement(1000);
        rateLimitingConfig.recheckForCapacityProbability(0.001);

        ClusterInfoConfig.Builder clusterInfoConfig = new ClusterInfoConfig.Builder();
        clusterInfoConfig.clusterId("testCluster");
        clusterInfoConfig.nodeCount(1);

        this.metric = new MetricReceiver.MockReceiver();

        chain = new Chain<>("test", new RateLimitingSearcher(new RateLimitingConfig(rateLimitingConfig),
                                    new ClusterInfoConfig(clusterInfoConfig), metric));

        for (int i = 0; i < clientCount ; i++)
            requestCounters.put(toClientId(i), new RequestCounts());
    }

    public void run() throws InterruptedException {
        long startTime = System.currentTimeMillis();
        runWorkers();
        long totalTime = Math.max(1, System.currentTimeMillis() - startTime);

        metricSnapshot = metric.getSnapshot();
        double totalAttemptedRate = 0;
        for (int i=0; i < clientCount; i++) {
            double attemptedRate = requestCounters.get(toClientId(i)).attempted.get() * 1000d / totalTime;
            double allowedRate = requestCounters.get(toClientId(i)).allowed.get() * 1000d / totalTime;
            System.out.println(String.format(Locale.ENGLISH,
                                             "Client %1$2d:  Attempted rate: %2$10.2f.  Target allowed rate: %3$10.2f.  Allowed rate: %4$10.2f.  Rejected requests: %5$8d",
                                             i, attemptedRate, Math.pow(4, i), allowedRate, rejectedRequests(i)));
            totalAttemptedRate += attemptedRate;
        }
        System.out.println(String.format(Locale.ENGLISH, "\nTotal attempted rate: %1$10.2f seconds", totalAttemptedRate));
        System.out.println(String.format(Locale.ENGLISH, "\nTotal time: %1$8.2f seconds", totalTime/1000.0));
    }

    private void runWorkers() {
        try {
            long startTime = System.currentTimeMillis();

            Thread[] threads = new Thread[threadCount];
            for (int i = 0; i < threadCount; i++)
                threads[i] = new Thread(new Worker(startTime));

            for (int i = 0; i < threadCount; i++)
                threads[i].start();

            for (int i = 0; i < threadCount; i++)
                threads[i].join();
        }
        catch (Exception e) { // not production code
            throw new RuntimeException(e);
        }
    }

    private int rejectedRequests(int id) {
        Point context = metric.pointBuilder().set("id", toClientId(id)).build();
        UntypedMetric rejectedRequestsMetric = metricSnapshot.getMapForMetric("requestsOverQuota").get(context);
        if (rejectedRequestsMetric == null) return 0;
        return (int)rejectedRequestsMetric.getCount();
    }

    private class Worker implements Runnable {

        private final int sequences = 5;
        private final long startTime;

        public Worker(long startTime) {
            this.startTime = startTime;
        }

        @Override
        public void run() {
            try {
                for (int i = 0; i < epochs; i++) {
                    issueRequests(this::pickClientFairly);
                    issueRequests(this::pickClientSkewedToLowerNumbers);
                    issueRequests(this::pickClientSkewedToHigherNumbers);
                    issueRequests(this::pickClientFairly);
                    issueRequests(this::pickClientSkewedToHigherNumbers);
                }
            }
            catch (InterruptedException e) {
                // just end
            }
        }

        private void issueRequests(Supplier<Integer> clientNumberSupplier) throws InterruptedException {
            for (int i = 0; i< totalQueriesPerThread/(epochs * sequences); i++) {
                int clientNumber = clientNumberSupplier.get();
                requestCounters.get(toClientId(clientNumber)).addRequest(executeWasAllowed(chain, clientNumber));
                if ( ! isInPeak())
                    Thread.sleep(sleepMsBetweenRequests);
            }
        }

        private boolean isInPeak() {
            long timeSinceStart = System.currentTimeMillis() - startTime;
            return timeSinceStart % timeBetweenPeaksMs < peakDurationMs; // a peak is at every start of every timeBetweenPeaks interval
        }

        protected int pickClientFairly() {
            return ThreadLocalRandom.current().nextInt(clientCount);
        }

        protected int pickClientSkewedToLowerNumbers() {
            int nr = (int)Math.floor((Math.pow(ThreadLocalRandom.current().nextDouble(), 3) * clientCount));
            if (nr > clientCount-1) return clientCount-1;
            return nr;
        }

        protected int pickClientSkewedToHigherNumbers() {
            int nr = (int)Math.floor( ( 1- Math.pow(ThreadLocalRandom.current().nextDouble(), 3)) * clientCount);
            if (nr > clientCount-1) return clientCount-1;
            return nr;
        }

    }

    private String toClientId(int n) {
        return "id" + n;
    }

    private boolean executeWasAllowed(Chain<Searcher> chain, int id) {
        Query query = new Query();
        query.properties().set("rate.id", toClientId(id));
        query.properties().set("rate.cost", 1);
        query.properties().set("rate.quota", Math.pow(4, id));
        query.properties().set("rate.idDimension", "id");
        Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
        if (result.hits().getError() != null && result.hits().getError().getCode() == 429)
            return false;
        else
            return true;
    }

    public static void main(String[] args) throws InterruptedException {
        new RateLimitingBenchmark().run();
    }

    private static class RequestCounts {

        private AtomicInteger attempted = new AtomicInteger(0);
        private AtomicInteger allowed = new AtomicInteger(0);

        public void addRequest(boolean wasAllowed) {
            attempted.incrementAndGet();
            if (wasAllowed) allowed.incrementAndGet();
        }

    }

}


text:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const routes = require('./routes/index');
const tc = require('./lib/text-censor');

const app = express();
app.use(express.static(path.join(__dirname, 'static')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use('/', routes);

var server = app.listen(9000, function() {
    var host = server.address().address
    var port = server.address().port

    console.log("应用实例,访问地址为 http://%s:%s", host, port)
})

var redis = require('redis');
var redisclient = redis.createClient();

var sub = function(c) {
    var c = c || 'chatchannel';
    redisclient.subscribe(c, function(e) {
        console.log('subscribe channel : ' + c);
    });
}
sub();
// 引入 socket.io 模块并绑定到服务器
io = require('socket.io').listen(server);
// 服务器当前在线用户列表
var nameList = []
// socket 部分
io.on('connection', function(socket) {
    console.log('a user connected');
    socket.emit('whoYouAre');
    // socket 断开时发送下线消息
    socket.on('disconnect', function() {
        console.log('user disconnected');
        if (socket.name) {
            nameList.splice(nameList.indexOf(socket.name), 1);
            socket.broadcast.emit('system', socket.name, nameList, 'logout');
            socket.disconnect()
        }
    });
    // 新用户登录时 记录名字并广播给其他用户
    socket.on('name', function(data) {
        var userName = data || '匿名'
        console.log(data);
        nameList.push(userName)
        socket.name = userName
        console.log('socket.name:', userName);
        socket.emit('loginSuccess', nameList);
        io.sockets.emit('system', userName, nameList, 'login');
    });
    socket.on('logOut', function(data) {
        // var userName = data || '匿名'
        // console.log(data);
        // nameList.push(userName)
        // socket.name = userName
        // console.log('socket.name:', userName);
        // socket.emit('loginSuccess', nameList);
        // io.sockets.emit('system', userName, nameList, 'login');
        socket.disconnect()
    });
    // 聊天消息
    socket.on('message', function(data) {
        if (data !== '') {
            console.log('message data:', data);
            var time = new Date().toLocaleString()
            // socket.emit('message', new Date(), socket.name, data
            if (data.length > 50) {
                io.sockets.emit('message', time, socket.name, data)
            }
            else {
                tc.filter(data, (err, filtered) => {
                    io.sockets.emit('message', time, socket.name, filtered)
                })
            }
        }
    });
    // redis 订阅 系统广播
    redisclient.on('message', function(error, msg) {
        console.log('connection');
        console.log(msg);
        var time = new Date().toLocaleString()
        socket.emit('systemBroadcast', msg);
    });
});


text:
require 'spec_helper'

describe Bank do
  let(:valid_attributes) {
    { currency: 'BOB', name: 'Banco Uno 12365498', address: 'Uno', amount: 100, phone: '55-6678', website: 'mind.com' }
  }

  it "returns to_s" do
    b = Bank.new name: 'Banco Central 121-121289'
    b.to_s.should eq("Banco Central 121-121289")
  end

  it 'should create an instance' do
    UserSession.user = build :user, id: 1
    b = Bank.new(valid_attributes)

    b.save.should eq(true)

    valid_attributes.each do |k, v|
      b.send(k).should eq(v)
    end
  end

  it 'should update attributes' do
    UserSession.user = build :user, id: 1
    b = Bank.new(valid_attributes)
    b.save.should eq(true)
    b.should be_persisted

    h = {:website => "www.bnb.com.bo", :address => "Very near", :phone => "2798888"}
    b.update_attributes(h).should eq(true)

    b.reload

    h.each do |k, v|
      b.send(k).should eq(v)
    end
  end

  it "#attributes" do
    attrs = { email: 'test@mail.com', address: 'Por ahi', phone: '555 555', website: 'mysite..com' }
    b = Bank.new(attrs)

    attrs.each do |k, v|
      b.attributes[k.to_s].should eq(v)
    end
  end

end


text:
<?php
namespace gossi\trixionary\action\model;

use gossi\trixionary\domain\PositionDomain;
use keeko\framework\foundation\AbstractAction;
use keeko\framework\utils\Parameters;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Paginates positions
 *
 * This code is automatically created. Modifications will probably be overwritten.
 *
 * @author Thomas Gossmann
 */
class PositionPaginateAction extends AbstractAction {

	/**
	 * @param OptionsResolver $resolver
	 */
	public function configureParams(OptionsResolver $resolver) {
		$resolver->setDefaults(['include' => [], 'fields' => [], 'sort' => [], 'filter' => [], 'page' => []]);
	}

	/**
	 * Automatically generated run method
	 *
	 * @param Request $request
	 * @return Response
	 */
	public function run(Request $request) {
		$params = new Parameters($request->query->all());
		$domain = new PositionDomain($this->getServiceContainer());
		$payload = $domain->paginate($params);
		return $this->responder->run($request, $payload);
	}
}


text:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, mapper
import sqlalchemy.exc
import tables
import time

class DB(object):
    def __init__(self):
        Session = sessionmaker(bind=tables.engine)
        self.session = Session()

    def checkRecordExists(self, mac):
        if not (self.session.query(tables.Clients).filter(tables.Clients.mac == mac).first() == None):
            return True
        else:
            return False

    def addMAC(self, mac, longterm=False):
        try:
            expire = time.time() + 3600 * (24 * 90 if longterm else 12)
            self.session.add(tables.Clients(mac=mac, time=time.time(), expire=expire))
            self.session.commit()
        except:
            raise

    def rmMAC(self, mac):
        try:
            res = self.session.query(tables.Clients).filter(tables.Clients.mac == mac).one()
            self.session.delete(res)
            self.session.commit()
        except:
            raise

    def removeExpired(self):
        now = time.time()
        res = self.session.query(tables.Clients).filter(tables.Clients.expire < now)
        for row in res:
            self.session.delete(row)
        self.session.commit()

    def getExpiredMACs(self):
        now = time.time()
        res = self.session.query(tables.Clients.mac).filter(tables.Clients.expire < now).all()
        mac_list = [e[0] for e in res]
        return mac_list

    def getMACs(self):
        res = self.session.query(tables.Clients.mac).all()
        mac_list = [e[0] for e in res]
        return mac_list

if __name__ == '__main__':
        pass


text:
//-----------------------------------------------------------
//  Ensure we have our namespace
//-----------------------------------------------------------
if (!HUB) {
	var HUB = {};
}

//----------------------------------------------------------
// Project Notes JS
//----------------------------------------------------------

if (!jq) {
	var jq = $;
}

HUB.ProjectNotes = {
	jQuery: jq,

	initialize: function()
	{
		var $ = this.jQuery;
		var frm = $('#hubForm');
		var notetitle = $('#title');
		var default_title = 'New Note';
		var default_temp_title = 'Template: New';

		// Check that title is there
		if (notetitle) {
			HUB.ProjectNotes.checkTitle(notetitle, default_title, default_temp_title);
			notetitle.on('keyup', function(e) {
				HUB.ProjectNotes.checkTitle(notetitle, default_title, default_temp_title);
			});
		}

		// Prevent form submission if no title
		if ($('#hubForm') && notetitle && $('#page-submit')) {
			$('#page-submit').on('click', function(e) {
				if (notetitle.val() == '' || notetitle.val() == default_title || notetitle.val() == default_temp_title ) {
					// can't submit
					e.preventDefault();
				}
			});
		}
	},

	checkTitle: function(title, default_title, default_temp_title)
	{
		var $ = this.jQuery;
		value = title.val();

		if ((value == '' || value == default_title || value == default_temp_title)) {
			title.addClass('wrongvalue');
			var stoptext = 'Please provide a new or different page title before saving this note.';
			if (value == default_temp_title) {
				stoptext = 'Please provide a new or different template page title (starting with Template:) before saving this note.';
			}

			if (!$('#stopit').length)
			{
				$('#hubForm').append('

');
				$('#stopit').html(stoptext);
			}

		} else if (title.hasClass('wrongvalue')) {
			title.removeClass('wrongvalue');
			if ($('#stopit').length) {
				$('#stopit').remove();
			}
		}
	}
}

jQuery(document).ready(function($){
	HUB.ProjectNotes.initialize();
});


text:
/** @file ProgressHandler.hpp
 *  @brief Abstract base class 'ProgressHandler'.
 */
#ifndef INCLUDED_AI_DEFAULTPROGRESSHANDLER_H
#define INCLUDED_AI_DEFAULTPROGRESSHANDLER_H

#include <assimp/ProgressHandler.hpp>

namespace Assimp {

// ------------------------------------------------------------------------------------
/**
 *  @brief Internal default implementation of the #ProgressHandler interface.
 */
class DefaultProgressHandler : public ProgressHandler    {
public:
    ///	@brief Ignores the update callback.
    bool Update(float) override {
        return false;
    }
};

} // Namespace Assimp

#endif // INCLUDED_AI_DEFAULTPROGRESSHANDLER_H


text:
namespace SchoolSystem.Framework.IdGenerators
{
    public class TeacherIdGenerator : IIdGenerator
    {
        private int id;

        public TeacherIdGenerator()
        {
            this.id = 0;
        }

        public int GetId
        {
            get
            {
                return this.id++;
            }
        }
    }
}


text:
import CCO.Component (ioWrap)
import CCO.TypeCheck (typeCheck)

main = ioWrap typeCheck


text:
@interface FPAFHTTPRequestOperation ()
@property (readwrite, nonatomic, retain) NSError *HTTPError;
@end

@implementation FPAFHTTPRequestOperation
@synthesize acceptableStatusCodes = _acceptableStatusCodes;
@synthesize acceptableContentTypes = _acceptableContentTypes;
@synthesize HTTPError = _HTTPError;

- (id)initWithRequest:(NSURLRequest *)request {
    self = [super initWithRequest:request];
    if (!self) {
        return nil;
    }

    self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];

    return self;
}

- (void)dealloc {
    [_acceptableStatusCodes release];
    [_acceptableContentTypes release];
    [_HTTPError release];
    [super dealloc];
}

- (NSHTTPURLResponse *)response {
    return (NSHTTPURLResponse *)[super response];
}

- (NSError *)error {
    if (self.response && !self.HTTPError) {
        if (![self hasAcceptableStatusCode]) {
            NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
            [userInfo setValue:[NSString stringWithFormat:NSLocalizedString(@"Expected status code %@, got %d", nil), self.acceptableStatusCodes, [self.response statusCode]] forKey:NSLocalizedDescriptionKey];
            [userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];

            self.HTTPError = [[[NSError alloc] initWithDomain:FPAFNetworkingErrorDomain code:NSURLErrorBadServerResponse userInfo:userInfo] autorelease];
        } else if ([self.responseData length] > 0 && ![self hasAcceptableContentType]) { // Don't invalidate content type if there is no content
            NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
            [userInfo setValue:[NSString stringWithFormat:NSLocalizedString(@"Expected content type %@, got %@", nil), self.acceptableContentTypes, [self.response MIMEType]] forKey:NSLocalizedDescriptionKey];
            [userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];

            self.HTTPError = [[[NSError alloc] initWithDomain:FPAFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo] autorelease];
        }
    }

    if (self.HTTPError) {
        return self.HTTPError;
    } else {
        return [super error];
    }
}

- (BOOL)hasAcceptableStatusCode {
    NSUInteger status = (NSUInteger)[self.response statusCode];
    return !self.acceptableStatusCodes || [self.acceptableStatusCodes containsIndex:status];
}

- (BOOL)hasAcceptableContentType {
    return !self.acceptableContentTypes || [self.acceptableContentTypes containsObject:[self.response MIMEType]];
}

- (void)setCompletionBlockWithSuccess:(void (^)(FPAFHTTPRequestOperation *operation, id responseObject))success
                              failure:(void (^)(FPAFHTTPRequestOperation *operation, NSError *error))failure
{
    self.completionBlock = ^ {
        if ([self isCancelled]) {
            return;
        }

        if (self.error) {
            if (failure) {
                dispatch_async(dispatch_get_main_queue(), ^(void) {
                    failure(self, self.error);
                });
            }
        } else {
            if (success) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    success(self, self.responseData);
                });
            }
        }
    };
}

#pragma mark - FPAFHTTPClientOperation

+ (BOOL)canProcessRequest:(NSURLRequest *)request {
    return YES;
}

@end


text:
/* @flow */

import {
  getEntityRanges,
  BLOCK_TYPE,
  ENTITY_TYPE,
  INLINE_STYLE,
} from '../stateUtils/main';
import {Entity} from 'draft-js-whkfzyx';

import type {ContentState, ContentBlock} from 'draft-js-whkfzyx';

import DraftBlockTypeAnalysis from '../DraftBlockTypeAnalysis'

const {
  BOLD,
  CODE,
  ITALIC,
  STRIKETHROUGH,
  UNDERLINE,
} = INLINE_STYLE;

const CODE_INDENT = '    ';

class MarkupGenerator {
  blocks: Array<ContentBlock>;
  contentState: ContentState;
  currentBlock: number;
  output: Array<string>;
  totalBlocks: number;
  listItemCounts: Object;

  constructor(contentState: ContentState) {
    this.contentState = contentState;
  }

  generate(): string {
    this.output = [];
    this.blocks = this.contentState.getBlockMap().toArray();
    this.totalBlocks = this.blocks.length;
    this.currentBlock = 0;
    this.listItemCounts = {};
    while (this.currentBlock < this.totalBlocks) {
      this.processBlock();
    }
    return this.output.join('');
  }

  processBlock() {
    let block = this.blocks[this.currentBlock];
    let blockType = block.getType();
    //ul和ol的下拉按钮的type都转成ul与ol的type,保持跟ul和ol的操作不变
    blockType = DraftBlockTypeAnalysis.getDraftBlockTypeAnalysis(blockType);

    switch (blockType) {
      case BLOCK_TYPE.HEADER_ONE: {
        this.insertLineBreaks(1);
        this.output.push('# ' + this.renderBlockContent(block) + '\n');
        break;
      }
      case BLOCK_TYPE.HEADER_TWO: {
        this.insertLineBreaks(1);
        this.output.push('## ' + this.renderBlockContent(block) + '\n');
        break;
      }
      case BLOCK_TYPE.HEADER_THREE: {
        this.insertLineBreaks(1);
        this.output.push('### ' + this.renderBlockContent(block) + '\n');
        break;
      }
      case BLOCK_TYPE.HEADER_FOUR: {
        this.insertLineBreaks(1);
        this.output.push('#### ' + this.renderBlockContent(block) + '\n');
        break;
      }
      case BLOCK_TYPE.HEADER_FIVE: {
        this.insertLineBreaks(1);
        this.output.push('##### ' + this.renderBlockContent(block) + '\n');
        break;
      }
      case BLOCK_TYPE.HEADER_SIX: {
        this.insertLineBreaks(1);
        this.output.push('###### ' + this.renderBlockContent(block) + '\n');
        break;
      }
      case BLOCK_TYPE.UNORDERED_LIST_ITEM: {
        let blockDepth = block.getDepth();
        let lastBlock = this.getLastBlock();
        let lastBlockType = lastBlock ? lastBlock.getType() : null;
        //ul和ol的下拉按钮的type都转成ul与ol的type,保持跟ul和ol的操作不变
        lastBlockType = DraftBlockTypeAnalysis.getDraftBlockTypeAnalysis(lastBlockType);
        let lastBlockDepth = lastBlock && canHaveDepth(lastBlockType) ?
          lastBlock.getDepth() :
          null;
        if (
          lastBlockType !== blockType &&
          lastBlockDepth !== blockDepth - 1
        ) {
          this.insertLineBreaks(1);
          // Insert an additional line break if following opposite list type.
          if (lastBlockType === BLOCK_TYPE.ORDERED_LIST_ITEM) {
            this.insertLineBreaks(1);
          }
        }
        let indent = ' '.repeat(block.depth * 4);
        this.output.push(
          indent + '- ' + this.renderBlockContent(block) + '\n'
        );
        break;
      }
      case BLOCK_TYPE.ORDERED_LIST_ITEM: {
        let blockDepth = block.getDepth();
        let lastBlock = this.getLastBlock();
        let lastBlockType = lastBlock ? lastBlock.getType() : null;
        //ul和ol的下拉按钮的type都转成ul与ol的type,保持跟ul和ol的操作不变
        lastBlockType = DraftBlockTypeAnalysis.getDraftBlockTypeAnalysis(lastBlockType);
        let lastBlockDepth = lastBlock && canHaveDepth(lastBlockType) ?
          lastBlock.getDepth() :
          null;
        if (lastBlockType !== blockType && lastBlockDepth !== blockDepth - 1) {
          this.insertLineBreaks(1);
          // Insert an additional line break if following opposite list type.
          if (lastBlockType === BLOCK_TYPE.UNORDERED_LIST_ITEM) {
            this.insertLineBreaks(1);
          }
        }
        let indent = ' '.repeat(blockDepth * 4);
        // TODO: figure out what to do with two-digit numbers
        let count = this.getListItemCount(block) % 10;
        this.output.push(
          indent + `${count}. ` + this.renderBlockContent(block) + '\n'
        );
        break;
      }
      case BLOCK_TYPE.BLOCKQUOTE: {
        this.insertLineBreaks(1);
        this.output.push(' > ' + this.renderBlockContent(block) + '\n');
        break;
      }
      case BLOCK_TYPE.CODE: {
        this.insertLineBreaks(1);
        this.output.push(CODE_INDENT + this.renderBlockContent(block) + '\n');
        break;
      }
      default: {
        this.insertLineBreaks(1);
        this.output.push(this.renderBlockContent(block) + '\n');
        break;
      }
    }
    this.currentBlock += 1;
  }

  getLastBlock(): ContentBlock {
    return this.blocks[this.currentBlock - 1];
  }

  getNextBlock(): ContentBlock {
    return this.blocks[this.currentBlock + 1];
  }

  getListItemCount(block: ContentBlock): number {
    let blockType = block.getType();
    //ul和ol的下拉按钮的type都转成ul与ol的type,保持跟ul和ol的操作不变
    blockType = DraftBlockTypeAnalysis.getDraftBlockTypeAnalysis(blockType);
    let blockDepth = block.getDepth();
    // To decide if we need to start over we need to backtrack (skipping list
    // items that are of greater depth)
    let index = this.currentBlock - 1;
    let prevBlock = this.blocks[index];
    while (
      prevBlock &&
      canHaveDepth(prevBlock.getType()) &&
      prevBlock.getDepth() > blockDepth
    ) {
      index -= 1;
      prevBlock = this.blocks[index];
    }
    if (
      !prevBlock ||
      DraftBlockTypeAnalysis.getDraftBlockTypeAnalysis(prevBlock.getType()) !== blockType ||
      prevBlock.getDepth() !== blockDepth
    ) {
      this.listItemCounts[blockDepth] = 0;
    }
    return (
      this.listItemCounts[blockDepth] = this.listItemCounts[blockDepth] + 1
    );
  }

  insertLineBreaks() {
    if (this.currentBlock > 0) {
      this.output.push('\n');
    }
  }

  renderBlockContent(block: ContentBlock): string {
    let blockType = block.getType();
    //ul和ol的下拉按钮的type都转成ul与ol的type,保持跟ul和ol的操作不变
    blockType = DraftBlockTypeAnalysis.getDraftBlockTypeAnalysis(blockType);
    let text = block.getText();
    if (text === '') {
      // Prevent element collapse if completely empty.
      // TODO: Replace with constant.
      return '\u200B';
    }
    let charMetaList = block.getCharacterList();
    let entityPieces = getEntityRanges(text, charMetaList);
    return entityPieces.map(([entityKey, stylePieces]) => {
      let content = stylePieces.map(([text, style]) => {
        // Don't allow empty inline elements.
        if (!text) {
          return '';
        }
        let content = encodeContent(text);
        if (style.has(BOLD)) {
          content = `**${content}**`;
        }
        if (style.has(UNDERLINE)) {
          // TODO: encode `+`?
          content = `++${content}++`;
        }
        if (style.has(ITALIC)) {
          content = `_${content}_`;
        }
        if (style.has(STRIKETHROUGH)) {
          // TODO: encode `~`?
          content = `~~${content}~~`;
        }
        if (style.has(CODE)) {
          content = (blockType === BLOCK_TYPE.CODE) ? content : '`' + content + '`';
        }
        return content;
      }).join('');
      let entity = entityKey ? Entity.get(entityKey) : null;
      if (entity != null && DraftBlockTypeAnalysis.getDraftBlockTypeAnalysis(entity.getType()) === ENTITY_TYPE.LINK) {
        let data = entity.getData();
        let url = data.url || '';
        let title = data.title ? ` "${escapeTitle(data.title)}"` : '';
        return `[${content}](${encodeURL(url)}${title})`;
      } else if (entity != null && DraftBlockTypeAnalysis.getDraftBlockTypeAnalysis(entity.getType()) === ENTITY_TYPE.IMAGE) {
        let data = entity.getData();
        let src = data.src || '';
        let alt = data.alt ? ` "${escapeTitle(data.alt)}"` : '';
        return `![${alt}](${encodeURL(src)})`;
      } else {
        return content;
      }
    }).join('');
  }
}

function canHaveDepth(blockType: any): boolean {
  //ul和ol的下拉按钮的type都转成ul与ol的type,保持跟ul和ol的操作不变
  blockType = DraftBlockTypeAnalysis.getDraftBlockTypeAnalysis(blockType);

  switch (blockType) {
    case BLOCK_TYPE.UNORDERED_LIST_ITEM:
    case BLOCK_TYPE.ORDERED_LIST_ITEM:
      return true;
    default:
      return false;
  }
}

function encodeContent(text) {
  return text.replace(/[*_`]/g, '\\$&');
}

// Encode chars that would normally be allowed in a URL but would conflict with
// our markdown syntax: `[foo](http://foo/)`
function encodeURL(url) {
  return url.replace(/\)/g, '%29');
}

// Escape quotes using backslash.
function escapeTitle(text) {
  return text.replace(/"/g, '\\"');
}

export default function stateToMarkdown(content: ContentState): string {
  return new MarkupGenerator(content).generate();
}


text:
import PropTypes from 'prop-types';
import React, { cloneElement, Children, Component } from 'react';
import cx from 'classnames';

import css from './ProgressSteps.css';

export default class ProgressSteps extends Component {
  static propTypes = {
    children: PropTypes.array.isRequired,
    lastCompletedIndex: PropTypes.number,
    className: PropTypes.string,
    /* eslint-disable react/no-unused-prop-types */
    containerQuery: PropTypes.shape({
      [css.horizontal]: PropTypes.bool,
    }),
    /* eslint-enable react/no-unused-prop-types */
    stepCss: PropTypes.string,
  };

  render() {
    const {
      children: steps,
      lastCompletedIndex,
      className,
      containerQuery,
      stepCss,
      ...rest,
    } = this.props;

    const stepStyles = {};

    if (containerQuery && containerQuery[css.horizontal]) {
      stepStyles.width = `${100 / steps.length}%`;
    }

    return (
      <dl
        className={ cx(css.root, className, containerQuery) }
        { ...rest }
      >
        { Children.map(steps, (step, i) => {
          const completed = i <= lastCompletedIndex;

          return cloneElement(step, {
            step: i + 1,
            completed,
            style: stepStyles,
            css: stepCss,
          });
        }) }
      </dl>
    );
  }
}


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

<!--
   Licensed to the Apache Software Foundation (ASF) under one
   or more contributor license agreements.  See the NOTICE file
   distributed with this work for additional information
   regarding copyright ownership.  The ASF licenses this file
   to you 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.
-->

<!-- set the basedir value to point to the top level of the project -->

<project name="Apache UIMA RDF CAS Consumer Documentation" default="all" basedir=".">

  <property name="book_name" value="RDFCASConsumerUserGuide"/>
  <property name="artifactId" value="RDFCASConsumer"/>

  <import file="${basedir}/../SandboxDocs/sandbox_build.xml"/>

</project>


text:
Belgium, 2015-04-14

I hereby agree to the terms of the Odoo Individual Contributor License
Agreement v1.0.

I declare that I am authorized and able to make this agreement and sign this
declaration.

Signed,

Julien Laloux julien.laloux@jlaloux.be https://github.com/jlaloux


text:
managedClasspath="./target/streams/runtime/managedClasspath/\$global/streams/export"
unmanagedClasspath="./target/streams/runtime/unmanagedJars/\$global/streams/export"

# Using server defined in build.sbt
# java -mx4g -cp "$(< $managedClasspath)" edu.stanford.nlp.pipeline.StanfordCoreNLPServer
# TODO: Make this actually work:Using server from lib, i.e. latest from HEAD as of 5 May 2016
java -mx12g -cp "$(< ${unmanagedClasspath}):$(< ${managedClasspath})" edu.stanford.nlp.pipeline.StanfordCoreNLPServer


text:
class GeolocationError(Exception):
    """
    An error that occurs whenever a user cannot be
    geolocated.
    """
    pass


text:
btn-audio-html5-and-jquery
==========================

ejecutar audio con un boton y pausar con jquery


text:
package com.adobe.acs.commons.auth.saml.impl;

import io.wcm.testing.mock.aem.junit.AemContext;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
import org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletResponse;
import org.junit.Rule;
import org.junit.Test;

import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import static org.junit.Assert.*;

public class OktaLogoutHandlerTest {

    @Rule
    public final AemContext context = new AemContext(ResourceResolverType.RESOURCERESOLVER_MOCK);

    private OktaLogoutHandler underTest = new OktaLogoutHandler();

    @Test
    public void testExtractCredentialsReturnsNull() {
        assertNull(underTest.extractCredentials(context.request(), context.response()));
    }

    @Test
    public void testRequestCredentialsReturnsFalse() throws Exception {
        assertFalse(underTest.requestCredentials(context.request(), context.response()));
    }

    @Test(expected = IllegalArgumentException.class)
    public void activateWithoutHostThrowsIllegalArgumentException() {
        underTest.activate(Collections.emptyMap());
    }

    @Test
    public void testDropCredentials() throws Exception {
        underTest.activate(Collections.singletonMap("okta.host.name", "www.okta.com"));
        underTest.dropCredentials(context.request(), context.response());

        assertRedirect("https://www.okta.com/login/signout", context.response());
    }

    @Test
    public void testDropCredentialsWithFromUri() throws Exception {
        Map<String, Object> properties = new HashMap<>();
        properties.put("okta.host.name", "www.okta.com");
        properties.put("from.uri", "www.myco.com");

        underTest.activate(properties);
        underTest.dropCredentials(context.request(), context.response());

        assertRedirect("https://www.okta.com/login/signout?fromURI=www.myco.com", context.response());
    }

    private void assertRedirect(String expected, MockSlingHttpServletResponse response) {
        assertEquals(HttpServletResponse.SC_MOVED_TEMPORARILY, response.getStatus());
        assertEquals(expected, response.getHeader("Location"));
    }
}


text:
package is.heklapunch;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

public class QRActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_qr);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_qr, menu);
		return true;
	}

	// Go to organize mode
	public void read_qr(View view) {
		IntentIntegrator integrator = new IntentIntegrator(this);
		integrator.initiateScan();
	}

	// QR Scan result
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		IntentResult scanResult = IntentIntegrator.parseActivityResult(
				requestCode, resultCode, intent
		);
		if (scanResult != null && scanResult.getContents().length() != 0) {
			// handle scan result
			Toast.makeText(this, scanResult.getContents(), Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(this, "No scan", Toast.LENGTH_SHORT).show();
		}
	}

}


text:
<?php

namespace app\controllers;

use yii\web\UploadedFile;
use app\models\Basket;
use app\models\Categories;
use app\models\Description;
use app\models\ItemsPhotos;
use app\models\ItemsRating;
use app\models\SubCatgories;
use app\models\UserBasket;
use Yii;
use app\models\Items;
use app\models\UploadForm;
use yii\rbac\Item;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\models\Comment;
use yii\data\ActiveDataProvider;
/**
 * ItemsController implements the CRUD actions for Items model.
 */
class ItemsController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Items models.
     * @return mixed
     */
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => Items::find(),
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Items model.
     * @param integer $id
     * @return mixed
     */

    public function actionView($id)
    {
        $commentsData = comment::getComments($id);
        $model = $this->findModel($id);
        $newComment = new Comment();
        $addToBasket = new basket();
        $description = new Description();
        $description->find()->where(['item_id' => $id])->all();
        $itemRating = ItemsRating::findOne($id);
        if ($model->count == 0)
            Yii::$app->db->createCommand(" UPDATE `items` SET items.is_aviable=0 WHERE items.id =" . $id)->execute();
        else {
            if (!Yii::$app->user->isGuest) {
                $uid = Yii::$app->user->identity->getId();
                $get_user = \dektrium\user\models\User::getUser($uid)->getModels()[0]['username'];
                if (isset($_POST['Comment'])) {
//            print_r($_POST['Comment']['text']);
                    $newComment = new Comment;
                    $newComment->author = $get_user;
                    $newComment->item_id = $id;
                    $newComment->user_id = $uid;
                    $newComment->date = date("Y-m-d h:i:s");
                    $newComment->text = $_POST['Comment']['text'];
                    $newComment->save();
                }
                if (isset($_POST['Basket'])) {
                    if($model->is_aviable) {
                        if($_POST['Basket']['count']<=$model->count) {
                            $addToBasket = new Basket();
                            $have = $addToBasket->find()->where(['item_id' => $id, 'user_id' => $uid])->all();
                            if (!$have) {
                                $addToBasket->item_id = $id;
                                $addToBasket->user_id = $uid;
                                $addToBasket->name = $model->name;
                                $addToBasket->price = $model->price;
                                $addToBasket->count = $_POST['Basket']['count'];
                                $addToBasket->sum = $model->price * $_POST['Basket']['count'];
                                $addToBasket->save();
                            }
                        }
                    }
                    return $this->redirect(['view', 'id' => $id]);
                }
            }
        }
        return $this->render('view', [
            'model' => $model,
            'commentsData' => $commentsData,
            'newComment' => $newComment,
            'itemRating' => $itemRating,
            'addToBasket' => $addToBasket,
            'description' =>$description
        ]);
    }

    /**
     * Creates a new Items model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionSetrating($id,$value)
    {
        if ($value <= 5) {
            $uid = Yii::$app->user->identity->getId();
            $itemsRating = ItemsRating::getItemRating($id);
            $is_find = 0;

            for ($i = 0; $i < count($itemsRating->getModels()); $i++) {
//            echo $itemsRating->getModels()[$i]['user_id']."---". $uid;
                echo $itemsRating->getModels()[$i]['id'];
                if ($itemsRating->getModels()[$i]['user_id'] == $uid) {
                    $is_find = 1;
                    break;
                } else {
                    $is_find = 0;
                }
            }
            if ($is_find == 0) {
//                echo $itemsRating->getModels()[$i]['user_id'] . "---" . $uid;
                Yii::$app->db->createCommand('INSERT INTO `itemsRating` (`id`, `item_id`, `user_id`, `rating`)   VALUES (NULL,' . $id . ',' . $uid . ', 1)')->execute();
                $allRatings = Yii::$app->db->createCommand('SELECT avg(rating) FROM `itemsRating` WHERE item_id=' . $id)->queryAll();
                $itemRating = $allRatings[0]['avg(rating)'];
                Yii::$app->db->createCommand('UPDATE `items` SET `items`.rating=' . $itemRating . ' WHERE items.id =' . $id)->execute();

            } else {

                Yii::$app->db->createCommand('UPDATE `itemsRating` SET
                  itemsRating.id=' . $itemsRating->getModels()[$i]['id'] . ',
                  itemsRating.user_id=' . $uid . ',
                  itemsRating.item_id=' . $id . ',
                  itemsRating.rating=' . $value . '     WHERE itemsRating.id =' . $itemsRating->getModels()[$i]['id'])->execute();
                $allRatings = Yii::$app->db->createCommand('SELECT avg(rating) FROM `itemsRating` WHERE item_id=' . $id)->queryAll();
                $itemRating = $allRatings[0]['avg(rating)'];
                Yii::$app->db->createCommand('UPDATE `items` SET `items`.rating=' . $itemRating . ' WHERE items.id =' . $id)->execute();
            }
            return $this->redirect(['view', 'id' => $id]);
        }
        else return $this->redirect(['view', 'id' => $id]);
    }

    public function actionCreate()
    {
        $model = new Items();
	$upload = new UploadForm();
        $category = new Categories();
        $subCat = new SubCatgories();
        $category->find()->all();
        $subCat->find()->all();
        $model->is_aviable=1;
        $description = new Description();
        $description->item_id = 1;
        $description->sub_id = 1;
        $description->text="s";
        $description->save();
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            if (isset($_POST['Description'])) {
//                print_r($_POST['Description']['sub_name']);
                $subCat = new SubCatgories();
                $subCat->find()->where(['name'=>$_POST['Description']['sub_name']])->all();
                $s= $subCat->find()->where(['name'=>$_POST['Description']['sub_name']])->all();
                $description = new Description();
                $description->item_id = $model->id;
                $description->sub_id = $s[0]['id'];
                $description->text =$_POST['Description']['text'];
                $description->category_name=$_POST['Description']['category_name'];
                $description->sub_name=$_POST['Description']['sub_name'];
                $description->save();
//                echo "sssss";
//                echo $description->sub_id;
//                echo $description->item_id;
            }
             if (isset($_POST['Description'])) {
            $upload = new UploadForm();

            $upload->imageFiles = UploadedFile::getInstances($upload, 'imageFiles');
            if ($upload->upload()) {
                echo "upload";
                // file is uploaded successfully
                // return;
            }
        }
	//	else
	  //      	return $this->redirect(['view', 'id' => $model->id]);

        }
        else {
            return $this->render('create', [
                'model' => $model,
                'category' => $category,
                'subCat' => $subCat,
                'description' => $description,
		        'upload' => $upload,
            ]);
        }

}

    /**
     * Updates an existing Items model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdatecount($id,$count){
	$model = $this->findModel($id);
	$model->count -= $count;
	$model->save();
    }
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Items model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Items model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Items the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Items::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
<!doctype html>

    <title>polymer-ui-menu-item</title>

    <link rel="import" href="polymer-ui-menu-item.html">
    <link rel="stylesheet" href="../basic.css">

polymer-ui-light-theme

      <polymer-ui-menu-item icon="settings" label="Settings"></polymer-ui-menu-item>
      <polymer-ui-menu-item icon="dialog" label="Dialog" active></polymer-ui-menu-item>

polymer-ui-dark-theme

      <polymer-ui-menu-item icon="settings" label="Settings"></polymer-ui-menu-item>
      <polymer-ui-menu-item icon="dialog" label="Dialog" active></polymer-ui-menu-item>