text:
require "mongoid/persistence/atomic"
require "mongoid/persistence/command"
require "mongoid/persistence/insert"
require "mongoid/persistence/insert_embedded"
require "mongoid/persistence/remove"
require "mongoid/persistence/remove_all"
require "mongoid/persistence/remove_embedded"
require "mongoid/persistence/update"

module Mongoid #:nodoc:

  # The persistence module is a mixin to provide database accessor methods for
  # the document. These correspond to the appropriate accessors on a
  # mongo collection and retain the same DSL.
  #
  # @example Sample persistence operations.
  #   document.insert
  #   document.update
  #   document.upsert
  module Persistence
    extend ActiveSupport::Concern
    include Atomic

    # Remove the document from the datbase with callbacks.
    #
    # @example Destroy a document.
    #   document.destroy
    #
    # @param [ Hash ] options Options to pass to destroy.
    #
    # @return [ true, false ] True if successful, false if not.
    def destroy(options = {})
      run_callbacks(:destroy) { remove(options) }
    end

    # Insert a new document into the database. Will return the document
    # itself whether or not the save was successful.
    #
    # @example Insert a document.
    #   document.insert
    #
    # @param [ Hash ] options Options to pass to insert.
    #
    # @return [ Document ] The persisted document.
    def insert(options = {})
      Insert.new(self, options).persist
    end

    # Remove the document from the datbase.
    #
    # @example Remove the document.
    #   document.remove
    #
    # @param [ Hash ] options Options to pass to remove.
    #
    # @return [ TrueClass ] True.
    def remove(options = {})
      if Remove.new(self, options).persist
        attributes.freeze
        self.destroyed = true
        cascade!
      end; true
    end
    alias :delete :remove

    # Save the document - will perform an insert if the document is new, and
    # update if not. If a validation error occurs an error will get raised.
    #
    # @example Save the document.
    #   document.save!
    #
    # @param [ Hash ] options Options to pass to the save.
    #
    # @return [ true, false ] True if validation passed.
    def save!(options = {})
      self.class.fail_validate!(self) unless upsert(options); true
    end

    # Update the document in the datbase.
    #
    # @example Update an existing document.
    #   document.update
    #
    # @param [ Hash ] options Options to pass to update.
    #
    # @return [ true, false ] True if succeeded, false if not.
    def update(options = {})
      Update.new(self, options).persist
    end

    # Update a single attribute and persist the entire document.
    # This skips validation but fires the callbacks.
    #
    # @example Update the attribute.
    #   person.update_attribute(:title, "Sir")
    #
    # @param [ Symbol, String ] name The name of the attribute.
    # @param [ Object ] value The new value of the attribute.a
    #
    # @return [ true, false ] True if save was successfull, false if not.
    #
    # @since 2.0.0.rc.6
    def update_attribute(name, value)
      write_attribute(name, value); save(:validate => false)
    end

    # Update the document attributes in the datbase.
    #
    # @example Update the document's attributes
    #   document.update_attributes(:title => "Sir")
    #
    # @param [ Hash ] attributes The attributes to update.
    #
    # @return [ true, false ] True if validation passed, false if not.
    def update_attributes(attributes = {})
      write_attributes(attributes); save
    end

    # Update the document attributes in the database and raise an error if
    # validation failed.
    #
    # @example Update the document's attributes.
    #   document.update_attributes(:title => "Sir")
    #
    # @param [ Hash ] attributes The attributes to update.
    #
    # @raise [ Errors::Validations ] If validation failed.
    #
    # @return [ true, false ] True if validation passed.
    def update_attributes!(attributes = {})
      update_attributes(attributes).tap do |result|
        self.class.fail_validate!(self) unless result
      end
    end

    # Upsert the document - will perform an insert if the document is new, and
    # update if not.
    #
    # @example Upsert the document.
    #   document.upsert
    #
    # @param [ Hash ] options Options to pass to the upsert.
    #
    # @return [ true, false ] True is success, false if not.
    def upsert(options = {})
      if new_record?
        insert(options).persisted?
      else
        update(options)
      end
    end
    alias :save :upsert

    module ClassMethods #:nodoc:

      # Create a new document. This will instantiate a new document and
      # insert it in a single call. Will always return the document
      # whether save passed or not.
      #
      # @example Create a new document.
      #   Person.create(:title => "Mr")
      #
      # @param [ Hash ] attributes The attributes to create with.
      #
      # @return [ Document ] The newly created document.
      def create(attributes = {}, &block)
        new(attributes, &block).tap(&:save)
      end

      # Create a new document. This will instantiate a new document and
      # insert it in a single call. Will always return the document
      # whether save passed or not, and if validation fails an error will be
      # raise.
      #
      # @example Create a new document.
      #   Person.create!(:title => "Mr")
      #
      # @param [ Hash ] attributes The attributes to create with.
      #
      # @return [ Document ] The newly created document.
      def create!(attributes = {}, &block)
        document = new(attributes, &block)
        fail_validate!(document) if document.insert.errors.any?
        document
      end

      # Delete all documents given the supplied conditions. If no conditions
      # are passed, the entire collection will be dropped for performance
      # benefits. Does not fire any callbacks.
      #
      # @example Delete matching documents from the collection.
      #   Person.delete_all(:conditions => { :title => "Sir" })
      #
      # @example Delete all documents from the collection.
      #   Person.delete_all
      #
      # @param [ Hash ] conditions Optional conditions to delete by.
      #
      # @return [ Integer ] The number of documents deleted.
      def delete_all(conditions = {})
        RemoveAll.new(
          self,
          { :validate => false },
          conditions[:conditions] || {}
        ).persist
      end

      # Delete all documents given the supplied conditions. If no conditions
      # are passed, the entire collection will be dropped for performance
      # benefits. Fires the destroy callbacks if conditions were passed.
      #
      # @example Destroy matching documents from the collection.
      #   Person.destroy_all(:conditions => { :title => "Sir" })
      #
      # @example Destroy all documents from the collection.
      #   Person.destroy_all
      #
      # @param [ Hash ] conditions Optional conditions to destroy by.
      #
      # @return [ Integer ] The number of documents destroyed.
      def destroy_all(conditions = {})
        documents = all(conditions)
        documents.count.tap do
          documents.each { |doc| doc.destroy }
        end
      end

      # Raise an error if validation failed.
      #
      # @example Raise the validation error.
      #   Person.fail_validate!(person)
      #
      # @param [ Document ] document The document to fail.
      def fail_validate!(document)
        raise Errors::Validations.new(document)
      end
    end
  end
end


text:
package org.attentiveness.news.util.schedulers;

import android.support.annotation.NonNull;

import io.reactivex.Scheduler;

public interface BaseSchedulerProvider {

    @NonNull
    Scheduler computation();

    @NonNull
    Scheduler io();

    @NonNull
    Scheduler ui();
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class net.sf.jasperreports.engine.JRPrintElementIndex (JasperReports 5.6.0 API)</title>
<meta name="date" content="2014-05-27">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
net.sf.jasperreports.engine.JRPrintElementIndex

Packages that use JRPrintElementIndex

Package
Description

net.sf.jasperreports.engine

Provides access to the library's main functionality through facade classes for compiling, filling
 and exporting reports and also publishes the library's main interfaces and classes.

net.sf.jasperreports.engine.export

Provides utility classes for exporting reports to various popular formats such as
 PDF, HTML, RTF, CSV, Excel, DOCX, PPTX, ODT, ODS, XML, Text, etc.

net.sf.jasperreports.engine.export.oasis

Provides utility classes for exporting reports to Open Document Format, such as
 ODT and ODS.

net.sf.jasperreports.engine.export.ooxml

Provides utility classes for exporting reports to Office Open XML Format, such as
 DOCX, XLSX and PPTX.

Uses of JRPrintElementIndex in net.sf.jasperreports.engine

Methods in net.sf.jasperreports.engine that return JRPrintElementIndex

Modifier and Type
Method and Description

static JRPrintElementIndex
JRPrintElementIndex.parsePrintElementIndex(java.lang.String indexStr)

Parses a String representation as obtained by toString() back
 into an element index instance.

Uses of JRPrintElementIndex in net.sf.jasperreports.engine.export

Methods in net.sf.jasperreports.engine.export that return JRPrintElementIndex

Modifier and Type
Method and Description

protected JRPrintElementIndex
JRXhtmlExporter.getElementIndex()

Deprecated.

protected JRPrintElementIndex
JRHtmlExporter.getElementIndex(JRExporterGridCell gridCell)

Deprecated.

protected JRPrintElementIndex
HtmlExporter.getElementIndex(TableCell cell)

static JRPrintElementIndex
AbstractHtmlExporter.getPrintElementIndex(java.lang.String imageName)

Methods in net.sf.jasperreports.engine.export with parameters of type JRPrintElementIndex

Modifier and Type
Method and Description

static JRPrintImage
AbstractHtmlExporter.getImage(java.util.List<JasperPrint> jasperPrintList,
        JRPrintElementIndex imageIndex)

static java.lang.String
AbstractHtmlExporter.getImageName(JRPrintElementIndex printElementIndex)

Uses of JRPrintElementIndex in net.sf.jasperreports.engine.export.oasis

Methods in net.sf.jasperreports.engine.export.oasis that return JRPrintElementIndex

Modifier and Type
Method and Description

protected JRPrintElementIndex
DocumentBuilder.getElementIndex(JRExporterGridCell gridCell)

static JRPrintElementIndex
DocumentBuilder.getPrintElementIndex(java.lang.String imageName)

Methods in net.sf.jasperreports.engine.export.oasis with parameters of type JRPrintElementIndex

Modifier and Type
Method and Description

protected void
JROdtExporter.exportGrid(JRGridLayout gridLayout,
          JRPrintElementIndex frameIndex)

static java.lang.String
DocumentBuilder.getImageName(JRPrintElementIndex printElementIndex)

protected void
DocumentBuilder.processImage(JRPrintImage image,
            JRPrintElementIndex imageIndex)

Uses of JRPrintElementIndex in net.sf.jasperreports.engine.export.ooxml

Fields in net.sf.jasperreports.engine.export.ooxml with type parameters of type JRPrintElementIndex

Modifier and Type
Field and Description

protected java.util.List<JRPrintElementIndex>
JRXlsxExporter.imagesToProcess

Methods in net.sf.jasperreports.engine.export.ooxml that return JRPrintElementIndex

Modifier and Type
Method and Description

protected JRPrintElementIndex
JRPptxExporter.getElementIndex()

protected JRPrintElementIndex
JRXlsxExporter.getElementIndex(JRExporterGridCell gridCell)

protected JRPrintElementIndex
JRDocxExporter.getElementIndex(JRExporterGridCell gridCell)

static JRPrintElementIndex
JRPptxExporter.getPrintElementIndex(java.lang.String imageName)

protected void writeImageMap(String imageMapName, JRPrintHyperlink mainHyperlink, List imageMapAreas)
        {
                writer.write("<map name=\"" + imageMapName + "\">\n");

                for (Iterator it = imageMapAreas.iterator(); it.hasNext();)
                {
                        JRPrintImageAreaHyperlink areaHyperlink = (JRPrintImageAreaHyperlink) it.next();
                        JRPrintImageArea area = areaHyperlink.getArea();

                        writer.write("  <area shape=\"" + JRPrintImageArea.getHtmlShape(area.getShape()) + "\"");
                        writeImageAreaCoordinates(area);
                        writeImageAreaHyperlink(areaHyperlink.getHyperlink());
                        writer.write("/>\n");
                }

                if (mainHyperlink.getHyperlinkTypeValue() !

static JRPrintElementIndex
JRXlsxExporter.getPrintElementIndex(java.lang.String imageName)

protected void writeImageMap(String imageMapName, JRPrintHyperlink mainHyperlink, List imageMapAreas) throws IOException
        {
                writer.write("<map name=\"" + imageMapName + "\">\n");

                for (Iterator it = imageMapAreas.iterator(); it.hasNext();)
                {
                        JRPrintImageAreaHyperlink areaHyperlink = (JRPrintImageAreaHyperlink) it.next();
                        JRPrintImageArea area = areaHyperlink.getArea();

                        writer.write("  <area shape=\"" + JRPrintImageArea.getHtmlShape(area.getShape()) + "\"");
                        writeImageAreaCoordinates(area);
                        writeImageAreaHyperlink(areaHyperlink.getHyperlink());
                        writer.write("/>\n");
                }

                if (mainHyperlink.getHyperlinkTypeValue() !

static JRPrintElementIndex
JRDocxExporter.getPrintElementIndex(java.lang.String imageName)

protected void writeImageMap(String imageMapName, JRPrintHyperlink mainHyperlink, List imageMapAreas)
        {
                writer.write("<map name=\"" + imageMapName + "\">\n");

                for (Iterator it = imageMapAreas.iterator(); it.hasNext();)
                {
                        JRPrintImageAreaHyperlink areaHyperlink = (JRPrintImageAreaHyperlink) it.next();
                        JRPrintImageArea area = areaHyperlink.getArea();

                        writer.write("  <area shape=\"" + JRPrintImageArea.getHtmlShape(area.getShape()) + "\"");
                        writeImageAreaCoordinates(area);
                        writeImageAreaHyperlink(areaHyperlink.getHyperlink());
                        writer.write("/>\n");
                }

                if (mainHyperlink.getHyperlinkTypeValue() !

Methods in net.sf.jasperreports.engine.export.ooxml with parameters of type JRPrintElementIndex

Modifier and Type
Method and Description

protected void
JRDocxExporter.exportGrid(JRGridLayout gridLayout,
          JRPrintElementIndex frameIndex)

JRPrintImage
JRXlsxExporter.getImage(ExporterInput exporterInput,
        JRPrintElementIndex imageIndex)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

© 2001-2010 Jaspersoft Corporation www.jaspersoft.com


text:
require 'optparse'
require 'highline'
require 'amazon/util/user_data_store'

module Amazon
module WebServices
module Util

class CommandLine

  SDKS = ['Mechanical Turk']

  MISSING_AUTH = "You are missing authentication information required to utilize Amazon Web Services.  You will now be prompted for your <%= color('Access Key ID',BOLD) %> and your <%= color('Secret Access Key',BOLD) %>.  If you do not have this information, please log into http://www.amazonaws.com/  \n\n"
  RESUME_AUTH = "Authentication information has been initialized.  Continuing... \n\n"

  MAIN_HELP = <<EOF

This is the <%= color('RubyAWS', RED, BOLD) %> Command Line Application's Interactive mode.
You got here by typing:

  <%= color('$ ruby-aws',GREEN) %>

This application currently supports the following functionality:

<%= list( ['Amazon Web Services Authentication Configuration'] ) %>
You can also invoke this tool with commandline parameters.  For more information:

  <%= color('$ ruby-aws --help',GREEN) %>

Thanks for using Amazon Web Services!

EOF

  def initialize( interactive = true )
    @interactive = interactive
    @h = HighLine.new
    @h.wrap_at = :auto
    @store = Amazon::Util::UserDataStore.new :AWS
    HighLine.use_color = useColor?
    HighLine.track_eof = false # disabling because it misbehaves
  end

  def checkAuthConfig
    if @store.get(:Auth,:AccessKeyId).nil? or @store.get(:Auth,:SecretAccessKey).nil?
      @h.say MISSING_AUTH
      getAuthConfig
      @h.say RESUME_AUTH
    end
  end

  def getAuthConfig( default={} )
    id = @h.ask( 'What is your Access Key ID?' ) {|q| q.validate = /^[A-Z0-9]{20}$/ ; q.default = authId.to_s ; q.first_answer = default[:ID] }
    key = @h.ask( 'What is your Secret Access Key?' ) {|q| q.validate = /^[\w\/+]{40}$/ ; q.default = authKey.to_s ; q.first_answer = default[:Key] }

    @store.set(:Auth,:AccessKeyId,id)
    @store.set(:Auth,:SecretAccessKey,key)
    @store.save
  rescue
    raise "Unable to retrieve authentication information from the Console"
  end

  def authKey
    @store.get(:Auth,:SecretAccessKey)
  end
  def authId
    @store.get(:Auth,:AccessKeyId)
  end

  def useColor?
    if @store.get(:Misc,:ColorTerminal).nil?
      if @interactive and @h.agree( "Should the console application use color? (y/n)" )
        @store.set(:Misc,:ColorTerminal,true)
      else
        @store.set(:Misc,:ColorTerminal,false)
      end
      @store.save
    end
    return @store.get(:Misc,:ColorTerminal)
  end

  def toggleColor
    value = !useColor?
    @store.set(:Misc,:ColorTerminal,value)
    HighLine.use_color = value
  end

  def default_menu
    loop do
      @h.choose do |menu|
        menu.header = "\n" + @h.color('RubyAWS',HighLine::BOLD,HighLine::RED) + " " + @h.color('Command Line Application',HighLine::BOLD) + " " + @h.color('[Interactive Mode]',HighLine::GREEN,HighLine::BOLD)
        menu.select_by = :index
        menu.choice( 'Configure Amazon Web Services Authentication' ) do
          if @h.agree( "\nCurrent ID: #{@h.color(authId,HighLine::BOLD)}\nCurrent Key: #{@h.color(authKey,HighLine::BOLD)}\nDo you want to change?" )
            getAuthConfig
          end
        end
        menu.choice( 'Toggle Color' ) { toggleColor }
        menu.choice( :help ) do
          @h.say MAIN_HELP
        end
        menu.choice( 'Save and Quit' ) { @store.save ; exit }
        menu.prompt = "\nWhat would you like to do? "
      end
    end
  end

  def parseOptions
    res = {}
    opts = OptionParser.new

    opts.on( '-i', '--interactive', 'Load Interactive Mode' ) { res[:Interactive] = true }
    opts.on( '-a', '--authenticate', 'Configure Authentication Options' ) { res[:Auth] = true }
    opts.on( '--id=ID', 'Set Access Key ID (requires "-a")' ) { |id| res[:ID] = id }
    opts.on( '--key=KEY', 'Set Secret Access Key (requires "-a")' ) { |key| res[:Key] = key }

    begin
      opts.parse(ARGV)
      raise "-i and -a are exclusive options.  Please pick one." if res[:Interactive] and res[:Auth]
      raise "--id requires -a" if res[:ID] and !res[:Auth]
      raise "--key requires -a" if res[:Key] and !res[:Auth]
      res[:Mode] = res[:Auth] ? :Auth : :Interactive
    rescue => e
      p e.message
    end
    res
  end

  def run

    opts = parseOptions

    case opts[:Mode]
    when :Interactive

      @h.say "\n<%= color('Welcome to',BOLD) %> <%= color('RubyAWS #{RubyAWS::VERSION}',BOLD,RED) %>"
      @h.say "This version includes SDK extensions for: <%= list (#{SDKS.inspect}.collect {|a| color(a,BOLD)}), :inline, ' and ' %>\n\n"

      checkAuthConfig

      default_menu
    when :Auth

      getAuthConfig( :Key => opts[:Key], :ID => opts[:ID] )

    end
  end

end

end # Amazon::WebServices::Util
end # Amazon::WebServices
end # Amazon::WebServices


text:
etcd is a consistent and durable key value store with [mini-transaction][txn] support. The key value store is exposed through the KV APIs. etcd tries to ensure the strongest consistency and durability guarantees for a distributed system. This specification enumerates the KV API guarantees made by etcd.

### APIs to consider

* Read APIs
    * range
    * watch
* Write APIs
    * put
    * delete
* Combination (read-modify-write) APIs
    * txn

### etcd specific definitions

#### Operation completed

An etcd operation is considered complete when it is committed through consensus, and therefore "executed" -- permanently stored -- by the etcd storage engine. The client knows an operation is completed when it receives a response from the etcd server. Note that the client may be uncertain about the status of an operation if it times out, or there is a network disruption between the client and the etcd member. etcd may also abort operations when there is a leader election. etcd does not send `abort` responses to  clients' outstanding requests in this event.

#### Revision

An etcd operation that modifies the key value store is assigned with a single increasing revision. A transaction operation might modifies the key value store multiple times, but only one revision is assigned. The revision attribute of a key value pair that modified by the operation has the same value as the revision of the operation. The revision can be used as a logical clock for key value store. A key value pair that has a larger revision is modified after a key value pair with a smaller revision. Two key value pairs that have the same revision are modified by an operation "concurrently".

### Guarantees provided

#### Atomicity

All API requests are atomic; an operation either completes entirely or not at all. For watch requests, all events generated by one operation will be in one watch response. Watch never observes partial events for a single operation.

#### Consistency

All API calls ensure [sequential consistency][seq_consistency], the strongest consistency guarantee available from distributed systems. No matter which etcd member server a client makes requests to, a client reads the same events in the same order. If two members complete the same number of operations, the state of the two members is consistent.

For watch operations, etcd guarantees to return the same value for the same key across all members for the same revision. For range operations, etcd has a similar guarantee for [linearized][Linearizability] access; serialized access may be behind the quorum state, so that the later revision is not yet available.

As with all distributed systems, it is impossible for etcd to ensure [strict consistency][strict_consistency]. etcd does not guarantee that it will return to a read the "most recent" value (as measured by a wall clock when a request is completed) available on any cluster member.

#### Isolation

etcd ensures [serializable isolation][serializable_isolation], which is the highest isolation level available in distributed systems. Read operations will never observe any intermediate data.

#### Durability

Any completed operations are durable. All accessible data is also durable data. A read will never return data that has not been made durable.

#### Linearizability

Linearizability (also known as Atomic Consistency or External Consistency) is a consistency level between strict consistency and sequential consistency.

For linearizability, suppose each operation receives a timestamp from a loosely synchronized global clock. Operations are linearized if and only if they always complete as though they were executed in a sequential order and each operation appears to complete in the order specified by the program. Likewise, if an operation's timestamp precedes another, that operation must also precede the other operation in the sequence.

For example, consider a client completing a write at time point 1 (*t1*). A client issuing a read at *t2* (for *t2* > *t1*) should receive a value at least as recent as the previous write, completed at *t1*. However, the read might actually complete only by *t3*, and the returned value, current at *t2* when the read began, might be "stale" by *t3*.

etcd does not ensure linearizability for watch operations. Users are expected to verify the revision of watch responses to ensure correct ordering.

etcd ensures linearizability for all other operations by default. Linearizability comes with a cost, however, because linearized requests must go through the Raft consensus process. To obtain lower latencies and higher throughput for read requests, clients can configure a request's consistency mode to `serializable`, which may access stale data with respect to quorum, but removes the performance penalty of linearized accesses' reliance on live consensus.

[seq_consistency]: https://en.wikipedia.org/wiki/Consistency_model#Sequential_consistency
[strict_consistency]: https://en.wikipedia.org/wiki/Consistency_model#Strict_consistency
[serializable_isolation]: https://en.wikipedia.org/wiki/Isolation_(database_systems)#Serializable
[Linearizability]: #Linearizability
[txn]: api.md#transactions


text:
package com.intellij.psi.impl.source.tree.injected;

import com.intellij.injected.editor.VirtualFileWindow;
import com.intellij.lang.Language;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.testFramework.LightVirtualFile;
import org.jetbrains.annotations.NotNull;

class VirtualFileWindowImpl extends LightVirtualFile implements VirtualFileWindow {
  private static final @NotNull Logger LOG = Logger.getInstance(VirtualFileWindowImpl.class);

  private final VirtualFile myDelegate;
  private final DocumentWindowImpl myDocumentWindow;

  VirtualFileWindowImpl(@NotNull String name,
                        @NotNull VirtualFile delegate,
                        @NotNull DocumentWindowImpl window,
                        @NotNull Language language,
                        @NotNull CharSequence text) {
    super(name, language, text);
    setCharset(delegate.getCharset(), null, false);
    setFileType(language.getAssociatedFileType());
    if (delegate instanceof VirtualFileWindow) throw new IllegalArgumentException(delegate +" must not be injected");
    myDelegate = delegate;
    myDocumentWindow = window;
  }

  @NotNull
  @Override
  public VirtualFile getDelegate() {
    return myDelegate;
  }

  @NotNull
  @Override
  public DocumentWindowImpl getDocumentWindow() {
    return myDocumentWindow;
  }

  @Override
  public boolean isValid() {
    return myDelegate.isValid() && myDocumentWindow.isValid();
  }

  @Override
  public String toString() {
    return "VirtualFileWindow in " + myDelegate.getPresentableUrl();
  }

  @Override
  public boolean isWritable() {
    return myDelegate.isWritable();
  }

  @Override
  public void setWritable(boolean writable) {
    LOG.error("Operation is not supported");
  }
}


text:
package org.opensingular.form.wicket.mapper.selection;

import org.apache.wicket.markup.html.form.TextField;
import org.junit.Before;
import org.junit.Test;
import org.opensingular.form.SIComposite;
import org.opensingular.form.STypeComposite;
import org.opensingular.form.type.core.STypeDecimal;
import org.opensingular.form.type.core.STypeInteger;
import org.opensingular.form.type.core.STypeString;
import org.opensingular.form.wicket.helpers.SingularFormDummyPageTester;

public class STypeCompositeSelectItemAutoCompleteTest {
    private SingularFormDummyPageTester tester;

    private static STypeComposite<SIComposite> base;
    private static STypeString                 name;

    private static void buildBaseType(STypeComposite<?> baseType) {
        base = baseType.addFieldComposite("myPlanets");

        name = base.addFieldString("name");
        STypeInteger position = base.addFieldInteger("position");
        STypeDecimal diameter = base.addFieldDecimal("diameterInKm");

        base.autocomplete()
                .id(name)
                .display("Planeta: ${name}, Posição: ${position}, Diametro(Km): ${diameterInKm}")
                .simpleProvider(builder -> {
                    builder.add().set(name, "Mercury").set(position, 1).set(diameter, 4879);
                    builder.add().set(name, "Venus").set(position, 2).set(diameter, 12104);
                    builder.add().set(name, "Earth").set(position, 3).set(diameter, 12756);
                });
    }

    @Before
    public void setUp(){
        tester = new SingularFormDummyPageTester();
        tester.getDummyPage().setTypeBuilder(STypeCompositeSelectItemAutoCompleteTest::buildBaseType);
        tester.startDummyPage();
    }

    @Test
    public void renderOnlyLabels(){
        tester.assertContains("Mercury");
        tester.assertContains("Venus");
        tester.assertContains("Earth");
    }

    @Test
    public void submitsSelectedCompositeValue(){
        tester.newFormTester()
                .setValue(tester.getAssertionsForm().getSubComponents(TextField.class).element(1).getTarget(), "Venus")
                .submit();

        tester.getAssertionsForm().getSubComponentWithType(base)
                .assertSInstance().isComposite().field(name.getNameSimple()).isValueEquals("Venus");
    }
}


text:
class WorkerNode < ActiveRecord::Base
  has_many :scalarm_managers

  def password
    if self.password_hashed
      Base64.decode64(self.password_hashed).decrypt
    else
      nil
    end
  end

  def password=(new_password)
    self.password_hashed = Base64.encode64(new_password.encrypt)
  end
end


text:
require 'volt/utils/generic_pool'
require 'volt/models/persistors/query/query_listener'

# Keeps track of all query listeners, so they can be reused in different
# places.  Dynamically generated queries may end up producing the same
# query in different places.  This makes it so we only need to track a
# single query at once.  Data updates will only be sent once as well.
class QueryListenerPool < GenericPool
end


text:
(function() {
  var Github;
  var API_URL = 'https://api.github.com';

  Github = window.Github = function(options) {

    // Util
    // =======

    function headers() {
      var headers = {}
      if (options.auth === 'oauth' && !options.token) return { Accept: 'application/vnd.github.raw' };
      if (options.auth === 'basic' && (!options.username || !options.password)) return { Accept: 'application/vnd.github.raw' };
      return options.auth == 'oauth'
             ? { Authorization: 'token '+ options.token, Accept: 'application/vnd.github.raw' }
             : { Authorization : 'Basic ' + Base64.encode(options.username + ':' + options.password), Accept: 'application/vnd.github.raw' }
    }

    function _request(method, path, data, cb) {
      $.ajax({
        type: method,
        url: API_URL + path,
        data: JSON.stringify(data),
        dataType: 'json',
        contentType: 'application/x-www-form-urlencoded',
        success: function(res) { cb(null, res); },
        error: function(err) { cb(err); },
        headers : headers()
      });
    }

    function _raw_request(method, path, data, cb) {
      $.ajax({
        type: method,
        url: API_URL + path,
        data: JSON.stringify(data),
        contentType: 'application/x-www-form-urlencoded',
        success: function(res) { cb(null, res); },
        error: function(err) { cb(err); },
        headers : headers()
      });
    }

    // USER API
    // =======

    Github.User = function() {
      this.repos = function(cb) {
        _request("GET", "/user/repos?type=all&per_page=100", null, function(err, res) {
          cb(err, res);
        });
      };
    };

    // Repository API
    // =======

    Github.Repository = function(options) {
      var repo = options.name;
      var user = options.user;

      var that = this;
      var repoPath = "/repos/" + user + "/" + repo;

      var currentTree = {
        "branch": null,
        "sha": null
      };

      // Uses the cache if branch has not been changed
      // -------

      function updateTree(branch, cb) {
        if (branch === currentTree.branch && currentTree.sha) return cb(null, currentTree.sha);
        that.getRef(branch, function(err, sha) {
          currentTree.branch = branch;
          currentTree.sha = sha;
          cb(err, sha);
        });
      }

      // Get a particular reference
      // -------

      this.getRef = function(ref, cb) {
        _request("GET", repoPath + "/git/refs/heads/" + ref, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.object.sha);
        });
      };

      // List all branches of a repository
      // -------

      this.listBranches = function(cb) {
        _request("GET", repoPath + "/git/refs/heads", null, function(err, heads) {
          if (err) return cb(err);
          cb(null, _.map(heads, function(head) { return _.last(head.ref.split('/')); }));
        });
      };

      // Retrieve the contents of a blob
      // -------

      this.getBlob = function(sha, cb) {
        _raw_request("GET", repoPath + "/git/blobs/" + sha, null, cb);
      };

      // For a given file path, get the corresponding sha (blob for files, tree for dirs)
      // TODO: So inefficient, it sucks hairy donkey balls.
      // -------

      this.getSha = function(branch, path, cb) {
        // Just use head if path is empty
        if (path === "") return that.getRef(branch, cb);
        that.getTree(branch+"?recursive=true", function(err, tree) {
          var file = _.select(tree, function(file) {
            return file.path === path;
          })[0];
          cb(null, file ? file.sha : null);
        });
      };

      // Retrieve the tree a commit points to
      // -------

      this.getTree = function(tree, cb) {
        _request("GET", repoPath + "/git/trees/"+tree, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.tree);
        });
      };

      // Post a new blob object, getting a blob SHA back
      // -------

      this.postBlob = function(content, cb) {
        var data = {
          "content": content,
          "encoding": "utf-8"
        };
        _request("POST", repoPath + "/git/blobs", data, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update an existing tree adding a new blob object getting a tree SHA back
      // -------

      this.updateTree = function(baseTree, path, blob, cb) {
        var data = {
          "base_tree": baseTree,
          "tree": [
            {
              "path": path,
              "mode": "100644",
              "type": "blob",
              "sha": blob
            }
          ]
        };
        _request("POST", repoPath + "/git/trees", data, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Post a new tree object having a file path pointer replaced
      // with a new blob SHA getting a tree SHA back
      // -------

      this.postTree = function(tree, cb) {
        _request("POST", repoPath + "/git/trees", { "tree": tree }, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Create a new commit object with the current commit SHA as the parent
      // and the new tree SHA, getting a commit SHA back
      // -------

      this.commit = function(parent, tree, message, cb) {
        var data = {
          "message": message,
          "author": {
            "name": options.username
          },
          "parents": [
            parent
          ],
          "tree": tree
        };

        _request("POST", repoPath + "/git/commits", data, function(err, res) {
          currentTree.sha = res.sha; // update latest commit
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update the reference of your head to point to the new commit SHA
      // -------

      this.updateHead = function(head, commit, cb) {
        _request("PATCH", repoPath + "/git/refs/heads/" + head, { "sha": commit }, function(err, res) {
          cb(err);
        });
      };

      // Show repository information
      // -------

      this.show = function(cb) {
        _request("GET", repoPath, null, function(err, info) {
          cb(null, info);
        });
      };

      // Read file at given path
      // -------

      this.read = function(branch, path, cb) {
        that.getSha(branch, path, function(err, sha) {
          if (!sha) return cb("not found", null);
          that.getBlob(sha, cb);
        });
      };

      // Remove a file from the tree
      // -------

      this.remove = function(branch, path, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            var newTree = _.reject(tree, function(ref) { return ref.path === path });
            _.each(newTree, function(ref) {
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(newTree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Move a file to a new location
      // -------

      this.move = function(branch, path, newPath, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            _.each(tree, function(ref) {
              if (ref.path === path) ref.path = newPath;
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(tree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Write file contents to a given branch and path
      // -------

      this.write = function(branch, path, content, message, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.postBlob(content, function(err, blob) {
            that.updateTree(latestCommit, path, blob, function(err, tree) {
              that.commit(latestCommit, tree, message, function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  if (err) console.log('error while writing new head', err);
                  cb(err);
                });
              });
            });
          });
        });
      };
    };

    // Top Level API
    // -------

    this.getRepo = function(user, repo) {
      return new Github.Repository({user: user, name: repo});
    };

    this.getUser = function() {
      return new Github.User();
    };
  };
}).call(this);


text:
#!/usr/bin/env python
import csv
import subprocess
import json
import shlex
import os
import sys
import getopt
import urllib

DOCCNV_BASEURL='https://gateway.watsonplatform.net/document-conversion/api'
DOCCNV_CREDS='username:password'
DOCCNV_CNVURL = '%s/v1/convert_document?version=2015-12-15' % (DOCCNV_BASEURL)

CSV_FILE=''
OUT_FOLDER=''
DEBUG=False
VERBOSE=''

def usage():
    print ('convert.py -u <username:password> -c <csv file> -i <input folder> -o <output folder> -d [enable debug output for script] -v [ enable verbose output for curl]')

try:
    opts, args = getopt.getopt(sys.argv[1:],"hdvu:c:i:o:",["user=","in_csvfile=","inputfolder=","outputfolder="])
except getopt.GetoptError as err:
    print str(err)
    print usage()
    sys.exit(2)
for opt, arg in opts:
    if opt == '-h':
        usage()
        sys.exit()
    elif opt in ("-u", "--user"):
        DOCCNV_CREDS = arg
    elif opt in ("-c", "--in_csvfile"):
        CSV_FILE = arg
    elif opt in ("-i", "--inputfolder"):
        IN_FOLDER = arg
    elif opt in ("-o", "--outputfolder"):
        OUT_FOLDER = arg
    elif opt == '-d':
        DEBUG = True
    elif opt == '-v':
        VERBOSE = '-v'

if not CSV_FILE or not IN_FOLDER or not OUT_FOLDER:
    print ('Required argument missing.')
    usage()
    sys.exit(2)

print("Input csv file is %s" % (CSV_FILE))
print("Output folder is %s" % (OUT_FOLDER))

with open(CSV_FILE, 'rb') as in_csvfile:
    input_csv = csv.reader(in_csvfile)
    print ('Converting Official Eclipse FAQ data...')
    for row in input_csv:
        if len(row) == 0:
            continue

        docid = row[0]
        title = row[2]
        url = row[3]

        htmlfilename = '%s/%s.html' % (IN_FOLDER, docid)
        jsonfilename = '%s/%s.json' % (OUT_FOLDER, docid)
        titlefilename = '%s/%s.title.txt' % (OUT_FOLDER, docid)
        bodyfilename = '%s/%s.body.txt' % (OUT_FOLDER, docid)

        print('Processing %s' % (htmlfilename))

        try:
            os.remove(jsonfilename)
        except OSError:
            pass

        try:
            os.remove(titlefilename)
        except OSError:
            pass

        try:
            os.remove(bodyfilename)
        except OSError:
            pass

        curl_cmd = 'curl -k -s %s -u %s -F "config={\\"conversion_target\\":\\"ANSWER_UNITS\\"}" -F "file=@%s" "%s"' % (VERBOSE, DOCCNV_CREDS, htmlfilename, DOCCNV_CNVURL)
        if DEBUG:
            print (curl_cmd)
        process = subprocess.Popen(shlex.split(curl_cmd), stdout=subprocess.PIPE)
        output = process.communicate()[0]
        with open(jsonfilename, "a") as jsonfile:
            jsonfile.write(output)
        if DEBUG:
            print (output)
        try:
            parsed_json = json.loads(output)
            answer_units = parsed_json['answer_units']
            for answer_unit in answer_units:
                if answer_unit['type'] == 'h1':
                    title = answer_unit['title'].encode('utf8')
                    with open(titlefilename, "w") as titlefile:
                        titlefile.write(title)
                    body = answer_unit['content'][0]['text'].encode('utf8')
                    with open(bodyfilename, "w") as bodyfile:
                        bodyfile.write(body)
        except:
            print ('Command:')
            print (curl_cmd)
            print ('Response:')
            print (output)
            raise
    print ('Converting data complete.')


text:
package com.ansorgit.plugins.bash.lang.psi.impl.word;

import javax.annotation.Nonnull;

import com.ansorgit.plugins.bash.lang.lexer.BashTokenTypes;
import com.ansorgit.plugins.bash.lang.parser.BashElementTypes;
import com.ansorgit.plugins.bash.lang.psi.BashVisitor;
import com.ansorgit.plugins.bash.lang.psi.api.word.BashWord;
import com.ansorgit.plugins.bash.lang.psi.impl.BashBaseStubElementImpl;
import com.ansorgit.plugins.bash.lang.psi.util.BashPsiUtils;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.stubs.StubElement;
import com.intellij.psi.tree.TokenSet;

/**
 * User: jansorg
 * Date: 21.05.2009
 * Time: 10:36:06
 */
public class BashWordImpl extends BashBaseStubElementImpl<StubElement> implements BashWord {
    private final static TokenSet nonWrappableChilds =
            TokenSet.create(BashElementTypes.STRING_ELEMENT, BashTokenTypes.STRING2, BashTokenTypes.WORD);

    public BashWordImpl(final ASTNode astNode) {
        super(astNode, "bash combined word");
    }

    @Override
    public void accept(@Nonnull PsiElementVisitor visitor) {
        if (visitor instanceof BashVisitor) {
            ((BashVisitor) visitor).visitCombinedWord(this);
        } else {
            visitor.visitElement(this);
        }
    }

    public boolean isWrappable() {
        PsiElement[] children = getChildren();
        return children.length > 1 && findChildByType(nonWrappableChilds) == null;
    }

    public String getUnwrappedCharSequence() {
        String text = getText();

        //if it is a single quoted string unqote it
        if (isStatic() && text.length() >= 2 && text.startsWith("'")) {
            return text.substring(1, text.length() - 1);
        }

        return text;
    }

    public boolean isStatic() {
        return BashPsiUtils.isStaticWordExpr(getFirstChild());
    }

    @Nonnull
    public TextRange getTextContentRange() {
        String text = getText();
        if (text.startsWith("'") && text.endsWith("'")) {
            return TextRange.from(1, getTextLength() - 2);
        }

        return TextRange.from(0, getTextLength());
    }
}


text:
package org.slc.sli.modeling.xmi.comp;

/**
 * Symbolic constants for values that are persisted.
 */
public final class XmiMappingValues {

    public static final String STATUS_ALIGN = "align";
    public static final String STATUS_BUG = "bug";
    public static final String STATUS_FINANCIAL = "financial";
    public static final String STATUS_IGNORABLE = "ignorable";
    public static final String STATUS_MATCH = "match";
    public static final String STATUS_TRANSIENT = "transient";
    public static final String STATUS_UNKNOWN = "unknown";

    public XmiMappingValues() {
        throw new UnsupportedOperationException();
    }
}


text:
var enums = require("ui/enums");
var converters = require("./converters");
var Font = (function () {
    function Font(family, size, style, weight) {
        this._fontFamily = family;
        this._fontSize = size;
        this._fontStyle = style;
        this._fontWeight = weight;
    }
    Object.defineProperty(Font.prototype, "fontFamily", {
        get: function () {
            return this._fontFamily;
        },
        set: function (value) {
            throw new Error("fontFamily is read-only");
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Font.prototype, "fontStyle", {
        get: function () {
            return this._fontStyle;
        },
        set: function (value) {
            throw new Error("fontStyle is read-only");
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Font.prototype, "fontWeight", {
        get: function () {
            return this._fontWeight;
        },
        set: function (value) {
            throw new Error("fontWeight is read-only");
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Font.prototype, "fontSize", {
        get: function () {
            return this._fontSize;
        },
        set: function (value) {
            throw new Error("fontSize is read-only");
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Font.prototype, "isBold", {
        get: function () {
            return this._fontWeight.toLowerCase() === enums.FontWeight.bold
                || this._fontWeight.toLowerCase() === "700";
        },
        set: function (value) {
            throw new Error("isBold is read-only");
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Font.prototype, "isItalic", {
        get: function () {
            return this._fontStyle.toLowerCase() === enums.FontStyle.italic;
        },
        set: function (value) {
            throw new Error("isItalic is read-only");
        },
        enumerable: true,
        configurable: true
    });
    Font.prototype.getAndroidTypeface = function () {
        return undefined;
    };
    Font.prototype.getUIFont = function (defaultFont) {
        return undefined;
    };
    Font.prototype.withFontFamily = function (family) {
        throw new Error("This should be called on the derived class");
    };
    Font.prototype.withFontStyle = function (style) {
        throw new Error("This should be called on the derived class");
    };
    Font.prototype.withFontWeight = function (weight) {
        throw new Error("This should be called on the derived class");
    };
    Font.prototype.withFontSize = function (size) {
        throw new Error("This should be called on the derived class");
    };
    Font.equals = function (value1, value2) {
        if (!value1 && !value2) {
            return true;
        }
        if (!value1 || !value2) {
            return false;
        }
        return value1.fontFamily === value2.fontFamily &&
            value1.fontSize === value2.fontSize &&
            value1.fontStyle === value2.fontStyle &&
            value1.fontWeight === value2.fontWeight;
    };
    Font.parse = function (cssValue) {
        var parsed = parseFont(cssValue);
        var size = converters.fontSizeConverter(parsed.fontSize);
        size = !!size ? size : undefined;
        return new Font(parsed.fontFamily, size, parsed.fontStyle, parsed.fontWeight);
    };
    Font.default = undefined;
    return Font;
}());
exports.Font = Font;
function parseFontFamily(value) {
    var result = new Array();
    if (!value) {
        return result;
    }
    var split = value.split(",");
    for (var i = 0; i < split.length; i++) {
        var str = split[i].trim().replace(/['"]+/g, '');
        if (str) {
            result.push(str);
        }
    }
    return result;
}
exports.parseFontFamily = parseFontFamily;
var genericFontFamilies;
(function (genericFontFamilies) {
    genericFontFamilies.serif = "serif";
    genericFontFamilies.sansSerif = "sans-serif";
    genericFontFamilies.monospace = "monospace";
    genericFontFamilies.system = "system";
})(genericFontFamilies = exports.genericFontFamilies || (exports.genericFontFamilies = {}));
var styles = new Set();
["italic", "oblique"].forEach(function (val, i, a) { return styles.add(val); });
var weights = new Set();
["normal", "bold", "100", "200", "300", "400", "500", "600", "700", "800", "900"].forEach(function (val, i, a) { return weights.add(val); });
function parseFont(fontValue) {
    var result = {
        fontStyle: "normal",
        fontVariant: "normal",
        fontWeight: "normal",
    };
    var parts = fontValue.split(/\s+/);
    var part;
    while (part = parts.shift()) {
        if (part === "normal") {
        }
        else if (part === "small-caps") {
            result.fontVariant = part;
        }
        else if (styles.has(part)) {
            result.fontStyle = part;
        }
        else if (weights.has(part)) {
            result.fontWeight = part;
        }
        else if (!result.fontSize) {
            var sizes = part.split("/");
            result.fontSize = sizes[0];
            result.lineHeight = sizes.length > 1 ? sizes[1] : undefined;
        }
        else {
            result.fontFamily = part;
            if (parts.length) {
                result.fontFamily += " " + parts.join(" ");
            }
            break;
        }
    }
    return result;
}


text:
{% extends "base.html" %}
{% block title %}主页{% endblock %}
{% block link %}

{% endblock %}
{% block keydown %} onkeydown="keyDown()"{% endblock %}
{% block content %}

            {% for years, month_works in works.items %}
            {% for month, albums in month_works.items %}

{{ years }}年{{ month }}月

                {% for album in albums %}

 {{ album.title }}

                {% endfor %}

            {% endfor %}
            {% endfor %}

    ‹
    ›

{% endblock %}


text:
package org.intellij.lang.xpath.validation.inspections;

import com.intellij.codeInspection.InspectionManager;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.lang.Language;
import com.intellij.psi.xml.XmlElement;
import org.intellij.lang.xpath.XPathFileType;
import org.intellij.lang.xpath.context.ContextProvider;
import org.intellij.lang.xpath.context.NamespaceContext;
import org.intellij.lang.xpath.psi.PrefixedName;
import org.intellij.lang.xpath.psi.XPathNodeTest;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.xml.namespace.QName;
import java.text.MessageFormat;
import java.util.Set;

public class CheckNodeTest extends XPathInspection {
    @NonNls
    private static final String SHORT_NAME = "CheckNodeTest";

    @Override
    protected Visitor createVisitor(InspectionManager manager, boolean isOnTheFly) {
        return new MyVisitor(manager, isOnTheFly);
    }

    @Override
    @NotNull
    public String getDisplayName() {
        return "Check Node Test";
    }

    @Override
    @NotNull
    @NonNls
    public String getShortName() {
        return SHORT_NAME;
    }

    @Override
    public boolean isEnabledByDefault() {
        return true;
    }

    @Override
    protected boolean acceptsLanguage(Language language) {
      return language == XPathFileType.XPATH.getLanguage() || language == XPathFileType.XPATH2.getLanguage();
    }

    final static class MyVisitor extends Visitor {
        MyVisitor(InspectionManager manager, boolean isOnTheFly) {
            super(manager, isOnTheFly);
        }

        @Override
        protected void checkNodeTest(XPathNodeTest nodeTest) {
            final ContextProvider contextProvider = ContextProvider.getContextProvider(nodeTest.getContainingFile());
            final XmlElement contextNode = contextProvider.getContextElement();
            final NamespaceContext namespaceContext = contextProvider.getNamespaceContext();
            if (namespaceContext == null) return;

            if (nodeTest.isNameTest() && contextNode != null) {
                final PrefixedName prefixedName = nodeTest.getQName();
                assert prefixedName != null;
                if (!"*".equals(prefixedName.getLocalName()) && !"*".equals(prefixedName.getPrefix())) {
                    boolean found;

                    if (nodeTest.getPrincipalType() == XPathNodeTest.PrincipalType.ELEMENT) {
                        final Set<QName> elementNames = contextProvider.getElements(true);
                        if (elementNames != null) {
                            found = false;
                            for (QName pair : elementNames) {
                              if (matches(nodeTest.getQName(), pair, namespaceContext, contextNode, true)) {
                                    found = true;
                                    break;
                                }
                            }
                            if (!found) {
                                registerProblem(contextProvider, prefixedName, nodeTest, "element");
                            }
                        }
                    } else if (nodeTest.getPrincipalType() == XPathNodeTest.PrincipalType.ATTRIBUTE) {
                        final Set<QName> attributeNames = contextProvider.getAttributes(true);
                        if (attributeNames != null) {
                            found = false;
                            for (QName pair : attributeNames) {
                                if (matches(nodeTest.getQName(), pair, namespaceContext, contextNode, false)) {
                                    found = true;
                                    break;
                                }
                            }
                            if (!found) {
                                registerProblem(contextProvider, prefixedName, nodeTest, "attribute");
                            }
                        }
                    }
                }
            }
        }

        private void registerProblem(ContextProvider contextProvider, PrefixedName prefixedName, XPathNodeTest nodeTest, String type) {
            final QName qName = contextProvider.getQName(prefixedName, nodeTest);
            final String name;
            if (qName != null) {
                final String pattern;
                if (!"".equals(qName.getNamespaceURI())) {
                    pattern = "''{0}'' ({1})";
                } else {
                    pattern = "''{0}''";
                }
                name = MessageFormat.format(pattern, qName.getLocalPart(), qName.getNamespaceURI());
            } else {
                name = MessageFormat.format("''{0}''", prefixedName.getLocalName());
            }

            final LocalQuickFix[] fixes = contextProvider.getQuickFixFactory().createUnknownNodeTestFixes(nodeTest);
            addProblem(myManager.createProblemDescriptor(nodeTest, "Unknown " + type + " name " + name + "", myOnTheFly, fixes, ProblemHighlightType.GENERIC_ERROR_OR_WARNING));
        }

        private static boolean matches(@Nullable PrefixedName prefixedName,
                                       QName element,
                                       NamespaceContext namespaceContext,
                                       XmlElement context,
                                       boolean allowDefaultNamespace)
        {
            if (prefixedName == null) return false;

            boolean b = prefixedName.getLocalName().equals(element.getLocalPart()) || "*".equals(element.getLocalPart());

            final String prefix = prefixedName.getPrefix();
            if (prefix != null) {
              if (!"*".equals(prefix)) {
                final String namespaceURI = namespaceContext.getNamespaceURI(prefix, context);
                b = b && element.getNamespaceURI().equals(namespaceURI);
              }
            } else if (allowDefaultNamespace) {
              final String namespaceURI = namespaceContext.getDefaultNamespace(context);
              b = b && (element.getNamespaceURI().equals(namespaceURI) || (element.getNamespaceURI().length() == 0 && namespaceURI == null));
            } else {
              b = b && element.getNamespaceURI().length() == 0;
            }
          return b;
        }
    }
}


text:
<?php
/**
 * TestQueryBuilder.php at ld2.my
 * Created by Babenoff at 28.08.16 - 1:11
 * Maksim Babenko <mb.babenoff@yandex.ru>
 */

namespace Test;

use LD2\QueryBuilder\Additional\AndOp;
use LD2\QueryBuilder\Additional\Condition;
use LD2\QueryBuilder\Additional\Field;
use LD2\QueryBuilder\DeleteQuery;
use LogicException;
use PHPUnit\Framework\TestCase;

class QueryBuilderDeleteTest extends TestCase
{
    public function testDeleteSimple(){
        $deleteQuery = new DeleteQuery(["users"]);
        $this->assertEquals("DELETE FROM `users`", $deleteQuery->sql());
    }

    public function testOneOfMultiple(){
        $deleteQuery = new DeleteQuery(["users", "heroes", "locations"]);
        $this->assertEquals("DELETE FROM `t0` USING `users` AS `t0`, `heroes` AS `t1`, `locations` AS `t2`", $deleteQuery->sql());
    }
    public function testSeveralOfMultiple()
    {
        $deleteQuery = new DeleteQuery(['test', 'test2', 'test3'], array(0, 2));
        $this->assertEquals('DELETE FROM `t0`, `t2` USING `test` AS `t0`, `test2` AS `t1`, `test3` AS `t2`', $deleteQuery->sql());
    }
    public function testWhere()
    {
        $deleteQuery = new DeleteQuery([
            'test'
        ]);
        $deleteQuery->setWhere(new AndOp([
            new Condition('=', new Field('group'), 'test'),
            new Condition('=', new Field('author'), null)
        ]));
        $this->assertEquals('DELETE FROM `test` WHERE (`test`.`group` = :p1 AND `test`.`author` IS NULL)', $deleteQuery->sql());
    }
    public function testOrderLimit()
    {
        $deleteQuery = new DeleteQuery([
            'test'
        ]);
        $deleteQuery->setLimit(10);
        $deleteQuery->setOrderby([
            new Field('field1')
        ]);
        $this->assertEquals('DELETE FROM `test` ORDER BY `test`.`field1` ASC LIMIT 10', $deleteQuery->sql());
    }
    public function testOrderLimitOnMultiple()
    {
        try {
            $deleteQuery = new DeleteQuery([
                'test',
                'test2',
                'test3'
            ]);
            $deleteQuery->setLimit(10);
            $this->fail('LIMIT should not be allowed on multi-table queries');
        } catch (LogicException $e) {
        }
        try {
            $deleteQuery = new DeleteQuery([
                'test',
                'test2',
                'test3'
            ]);
            $deleteQuery->setOrderby([
                new Field('field1')
            ]);
            $this->fail('ORDER BY should not be allowed on multi-table queries');
        } catch (LogicException $e) {
        }
    }
}


text:
import Xml2js from 'xml2js';

export default Xml2js;


text:
⚠ Deprecated. See [j2js-compiler](https://github.com/decatur/j2js-compiler)

#j2js-agent

User Agent (Browser) specific code.

This project is part of the Java Bytecode to JavaScript cross-compiler at https://github.com/decatur/j2js-compiler.


text:
title: "Table Sources & Sinks"
nav-parent_id: tableapi
nav-pos: 40
---

A `TableSource` provides access to data which is stored in external systems (database, key-value store, message queue) or files. After a [TableSource is registered in a TableEnvironment](common.html#register-a-tablesource) it can accessed by [Table API](tableApi.html) or [SQL](sql.html) queries.

A TableSink [emits a Table](common.html#emit-a-table) to an external storage system, such as a database, key-value store, message queue, or file system (in different encodings, e.g., CSV, Parquet, or ORC).

Have a look at the [common concepts and API](common.html) page for details how to [register a TableSource](common.html#register-a-tablesource) and how to [emit a Table through a TableSink](common.html#emit-a-table).

* This will be replaced by the TOC
{:toc}

Provided TableSources
---------------------

**TODO: extend and complete**

Currently, Flink provides the `CsvTableSource` to read CSV files and a few table sources to read JSON or Avro data from Kafka.
A custom `TableSource` can be defined by implementing the `BatchTableSource` or `StreamTableSource` interface. See section on [defining a custom TableSource](#define-a-tablesource) for details.

| **Class name** | **Maven dependency** | **Batch?** | **Streaming?** | **Description**
| `CsvTableSource` | `flink-table` | Y | Y | A simple source for CSV files.
| `Kafka08JsonTableSource` | `flink-connector-kafka-0.8` | N | Y | A Kafka 0.8 source for JSON data.
| `Kafka08AvroTableSource` | `flink-connector-kafka-0.8` | N | Y | A Kafka 0.8 source for Avro data.
| `Kafka09JsonTableSource` | `flink-connector-kafka-0.9` | N | Y | A Kafka 0.9 source for JSON data.
| `Kafka09AvroTableSource` | `flink-connector-kafka-0.9` | N | Y | A Kafka 0.9 source for Avro data.
| `Kafka010JsonTableSource` | `flink-connector-kafka-0.10` | N | Y | A Kafka 0.10 source for JSON data.
| `Kafka010AvroTableSource` | `flink-connector-kafka-0.10` | N | Y | A Kafka 0.10 source for Avro data.

All sources that come with the `flink-table` dependency can be directly used by your Table programs. For all other table sources, you have to add the respective dependency in addition to the `flink-table` dependency.

{% top %}

### KafkaJsonTableSource

To use the Kafka JSON source, you have to add the Kafka connector dependency to your project:

  - `flink-connector-kafka-0.8` for Kafka 0.8,
  - `flink-connector-kafka-0.9` for Kafka 0.9, or
  - `flink-connector-kafka-0.10` for Kafka 0.10, respectively.

You can then create the source as follows (example for Kafka 0.8):

{% highlight java %}
// specify JSON field names and types
TypeInformation<Row> typeInfo = Types.ROW(
  new String[] { "id", "name", "score" },
  new TypeInformation<?>[] { Types.INT(), Types.STRING(), Types.DOUBLE() }
);

KafkaJsonTableSource kafkaTableSource = new Kafka08JsonTableSource(
    kafkaTopic,
    kafkaProperties,
    typeInfo);
{% endhighlight %}

{% highlight scala %}
// specify JSON field names and types
val typeInfo = Types.ROW(
  Array("id", "name", "score"),
  Array(Types.INT, Types.STRING, Types.DOUBLE)
)

val kafkaTableSource = new Kafka08JsonTableSource(
    kafkaTopic,
    kafkaProperties,
    typeInfo)
{% endhighlight %}

By default, a missing JSON field does not fail the source. You can configure this via:

```java
// Fail on missing JSON field
tableSource.setFailOnMissingField(true);
```

{% top %}

### KafkaAvroTableSource

The `KafkaAvroTableSource` allows you to read Avro's `SpecificRecord` objects from Kafka.

To use the Kafka Avro source, you have to add the Kafka connector dependency to your project:

  - `flink-connector-kafka-0.8` for Kafka 0.8,
  - `flink-connector-kafka-0.9` for Kafka 0.9, or
  - `flink-connector-kafka-0.10` for Kafka 0.10, respectively.

You can then create the source as follows (example for Kafka 0.8):

{% highlight java %}
// pass the generated Avro class to the TableSource
Class<? extends SpecificRecord> clazz = MyAvroType.class;

KafkaAvroTableSource kafkaTableSource = new Kafka08AvroTableSource(
    kafkaTopic,
    kafkaProperties,
    clazz);
{% endhighlight %}

{% highlight scala %}
// pass the generated Avro class to the TableSource
val clazz = classOf[MyAvroType]

val kafkaTableSource = new Kafka08AvroTableSource(
    kafkaTopic,
    kafkaProperties,
    clazz)
{% endhighlight %}

{% top %}

### CsvTableSource

The `CsvTableSource` is already included in `flink-table` without additional dependecies.

The easiest way to create a `CsvTableSource` is by using the enclosed builder `CsvTableSource.builder()`, the builder has the following methods to configure properties:

 - `path(String path)` Sets the path to the CSV file, required.
 - `field(String fieldName, TypeInformation<?> fieldType)` Adds a field with the field name and field type information, can be called multiple times, required. The call order of this method defines also the order of the fields in a row.
 - `fieldDelimiter(String delim)` Sets the field delimiter, `","` by default.
 - `lineDelimiter(String delim)` Sets the line delimiter, `"\n"` by default.
 - `quoteCharacter(Character quote)` Sets the quote character for String values, `null` by default.
 - `commentPrefix(String prefix)` Sets a prefix to indicate comments, `null` by default.
 - `ignoreFirstLine()` Ignore the first line. Disabled by default.
 - `ignoreParseErrors()` Skip records with parse error instead to fail. Throwing an exception by default.

You can create the source as follows:

{% highlight java %}
CsvTableSource csvTableSource = CsvTableSource
    .builder()
    .path("/path/to/your/file.csv")
    .field("name", Types.STRING())
    .field("id", Types.INT())
    .field("score", Types.DOUBLE())
    .field("comments", Types.STRING())
    .fieldDelimiter("#")
    .lineDelimiter("$")
    .ignoreFirstLine()
    .ignoreParseErrors()
    .commentPrefix("%");
{% endhighlight %}

{% highlight scala %}
val csvTableSource = CsvTableSource
    .builder
    .path("/path/to/your/file.csv")
    .field("name", Types.STRING)
    .field("id", Types.INT)
    .field("score", Types.DOUBLE)
    .field("comments", Types.STRING)
    .fieldDelimiter("#")
    .lineDelimiter("$")
    .ignoreFirstLine
    .ignoreParseErrors
    .commentPrefix("%")
{% endhighlight %}

{% top %}

Provided TableSinks
-------------------

**TODO**

{% top %}

Define a TableSource
--------------------

A `TableSource` is a generic interface to access to data stored in an external system as a table. It produces a `DataSet` or `DataStream` and provides the type information to derive the schema of the generated table. There are different table sources for batch tables and streaming tables.

Schema information consists of a data type, field names, and corresponding indexes of these names in the data type.

The general interface looks as follows:

{% highlight java %}
TableSource<T> {

  public TypeInformation<T> getReturnType();

  public String explainSource();
}
{% endhighlight %}

{% highlight scala %}
TableSource[T] {

  def getReturnType: TypeInformation[T]

  def explainSource: String

}
{% endhighlight %}

To define a `TableSource` one needs to implement `TableSource#getReturnType`. In this case field names and field indexes are derived from the returned type.

If the `TypeInformation` returned by `getReturnType` does not allow to specify custom field names, it is possible to implement the `DefinedFieldNames` interface in addition.

### BatchTableSource

Defines an external `TableSource` to create a batch table and provides access to its data.

The interface looks as follows:

{% highlight java %}
BatchTableSource<T> extends TableSource<T> {

  public DataSet<T> getDataSet(ExecutionEnvironment execEnv);
}
{% endhighlight %}

{% highlight scala %}
BatchTableSource[T] extends TableSource[T] {

  def getDataSet(execEnv: ExecutionEnvironment): DataSet[T]
}
{% endhighlight %}

{% top %}

### StreamTableSource

Defines an external `TableSource` to create a streaming table and provides access to its data.

The interface looks as follows:

{% highlight java %}
StreamTableSource<T> extends TableSource<T> {

  public DataSet<T> getDataStream(StreamExecutionEnvironment execEnv);
}
{% endhighlight %}

{% highlight scala %}
StreamTableSource[T] extends TableSource[T] {

  def getDataStream(execEnv: StreamExecutionEnvironment): DataSet[T]
}
{% endhighlight %}

**Note:** If a Table needs to be processed in event-time, the `DataStream` returned by the `getDataStream()` method must carry timestamps and watermarks. Please see the documentation on [timestamp and watermark assignment]({{ site.baseurl }}/dev/event_timestamps_watermarks.html) for details on how to assign timestamps and watermarks.

**Note:** Time-based operations on streaming tables such as windows in both the [Table API](tableApi.html#group-windows) and [SQL](sql.html#group-windows) require explicitly specified time attributes.

- `DefinedRowtimeAttribute` provides the `getRowtimeAttribute()` method to specify the name of the event-time time attribute.
- `DefinedProctimeAttribute` provides the `getProctimeAttribute()` method to specify the name of the processing-time time attribute.

Please see the documentation on [time attributes]({{ site.baseurl }}/dev/table/streaming.html#time-attributes) for details.

{% top %}

### ProjectableTableSource

The `ProjectableTableSource` interface adds support for projection push-down to a `TableSource`. A `TableSource` extending this interface is able to project the fields of the return table.

The interface looks as follows:

{% highlight java %}
ProjectableTableSource<T> {

  public TableSource<T> projectFields(int[] fields);
}
{% endhighlight %}

{% highlight scala %}
ProjectableTableSource[T] {

  def TableSource[T] projectFields(fields: Array[Int])
}
{% endhighlight %}

The `projectFields()` is called with an array that holds the indexes of the required fields. The method returns a new `TableSource` object that returns rows with the requested schema.

{% top %}

### NestedFieldsProjectableTableSource

The `NestedFieldsProjectableTableSource` interface adds support for projection push-down to a `TableSource` with nested fields. A `TableSource` extending this interface is able to project the nested fields of the returned table.

The interface looks as follows:

{% highlight java %}
NestedFieldsProjectableTableSource<T> {

  public TableSource<T> projectNestedFields(int[] fields, String[][] nestedFields);
}
{% endhighlight %}

{% highlight scala %}
NestedFieldsProjectableTableSource[T] {

  def projectNestedFields(fields: Array[Int], nestedFields: Array[Array[String]]): TableSource[T]
}
{% endhighlight %}

### FilterableTableSource

The `FilterableTableSource` interface adds support for filtering push-down to a `TableSource`. A `TableSource` extending this interface is able to filter records before returning.

The interface looks as follows:

{% highlight java %}
FilterableTableSource<T> {

  public TableSource<T> applyPredicate(List<Expression> predicates);

  public boolean isFilterPushedDown();
}
{% endhighlight %}

{% highlight scala %}
FilterableTableSource[T] {

  def applyPredicate(predicates: java.util.List[Expression]): TableSource[T]

  def isFilterPushedDown: Boolean
}
{% endhighlight %}

The optimizer pushes predicates down by calling the `applyPredicate()` method. The `TableSource` can evaluate which predicates to evaluate by itself and which to leave for the framework. Predicates which are evaluated by the `TableSource` must be removed from the `List`. All predicates which remain in the `List` after the method call returns are evaluated by the framework. The `applyPredicate()` method returns a new `TableSource` that evaluates all selected predicates.

The `isFilterPushedDown()` method tells the optimizer whether predicates have been pushed down or not.

{% top %}

Define a TableSink
------------------

A `TableSink` specifies how to emit a `Table` to an external system or location. The interface is generic such that it can support different storage locations and formats. There are different table sinks for batch tables and streaming tables.

The general interface looks as follows:

{% highlight java %}
TableSink<T> {

  public TypeInformation<T> getOutputType();

  public String[] getFieldNames();

  public TypeInformation[] getFieldTypes();

  public TableSink<T> configure(String[] fieldNames, TypeInformation[] fieldTypes);
}
{% endhighlight %}

{% highlight scala %}
TableSink[T] {

  def getOutputType: TypeInformation<T>

  def getFieldNames: Array[String]

  def getFieldTypes: Array[TypeInformation]

  def configure(fieldNames: Array[String], fieldTypes: Array[TypeInformation]): TableSink[T]
}
{% endhighlight %}

The `TableSink#configure` method is called to pass the schema of the Table (field names and types) to emit to the `TableSink`. The method must return a new instance of the TableSink which is configured to emit the provided Table schema.

### BatchTableSink

Defines an external `TableSink` to emit a batch table.

The interface looks as follows:

{% highlight java %}
BatchTableSink<T> extends TableSink<T> {

  public void emitDataSet(DataSet<T> dataSet);
}
{% endhighlight %}

{% highlight scala %}
BatchTableSink[T] extends TableSink[T] {

  def emitDataSet(dataSet: DataSet[T]): Unit
}
{% endhighlight %}

{% top %}

### AppendStreamTableSink

Defines an external `TableSink` to emit a streaming table with only insert changes.

The interface looks as follows:

{% highlight java %}
AppendStreamTableSink<T> extends TableSink<T> {

  public void emitDataStream(DataStream<T> dataStream);
}
{% endhighlight %}

{% highlight scala %}
AppendStreamTableSink[T] extends TableSink[T] {

  def emitDataStream(dataStream: DataStream<T>): Unit
}
{% endhighlight %}

If the table is also modified by update or delete changes, a `TableException` will be thrown.

{% top %}

### RetractStreamTableSink

Defines an external `TableSink` to emit a streaming table with insert, update, and delete changes.

The interface looks as follows:

{% highlight java %}
RetractStreamTableSink<T> extends TableSink<Tuple2<Boolean, T>> {

  public TypeInformation<T> getRecordType();

  public void emitDataStream(DataStream<Tuple2<Boolean, T>> dataStream);
}
{% endhighlight %}

{% highlight scala %}
RetractStreamTableSink[T] extends TableSink[Tuple2[Boolean, T]] {

  def getRecordType: TypeInformation[T]

  def emitDataStream(dataStream: DataStream[Tuple2[Boolean, T]]): Unit
}
{% endhighlight %}

The table will be converted into a stream of accumulate and retraction messages which are encoded as Java `Tuple2`. The first field is a boolean flag to indicate the message type (`true` indicates insert, `false` indicates delete). The second field holds the record of the requested type `T`.

{% top %}

### UpsertStreamTableSink

Defines an external `TableSink` to emit a streaming table with insert, update, and delete changes.

The interface looks as follows:

{% highlight java %}
UpsertStreamTableSink<T> extends TableSink<Tuple2<Boolean, T>> {

  public void setKeyFields(String[] keys);

  public void setIsAppendOnly(boolean isAppendOnly);

  public TypeInformation<T> getRecordType();

  public void emitDataStream(DataStream<Tuple2<Boolean, T>> dataStream);
}
{% endhighlight %}

{% highlight scala %}
UpsertStreamTableSink[T] extends TableSink[Tuple2[Boolean, T]] {

  def setKeyFields(keys: Array[String]): Unit

  def setIsAppendOnly(isAppendOnly: Boolean): Unit

  def getRecordType: TypeInformation[T]

  def emitDataStream(dataStream: DataStream[Tuple2[Boolean, T]]): Unit
}
{% endhighlight %}

The table must be have unique key fields (atomic or composite) or be append-only. If the table does not have a unique key and is not append-only, a `TableException` will be thrown. The unique key of the table is configured by the `UpsertStreamTableSink#setKeyFields()` method.

The table will be converted into a stream of upsert and delete messages which are encoded as a Java `Tuple2`. The first field is a boolean flag to indicate the message type. The second field holds the record of the requested type `T`.

A message with true boolean field is an upsert message for the configured key. A message with false flag is a delete message for the configured key. If the table is append-only, all messages will have a true flag and must be interpreted as insertions.

{% top %}


text:
#ifndef SUICIDE_TASK_H
#define SUICIDE_TASK_H

void vCreateSuicidalTasks( unsigned portBASE_TYPE uxPriority );
portBASE_TYPE xIsCreateTaskStillRunning( void );

#endif


text:
<!DOCTYPE HTML>

    <title></title>

    <meta name="google" value="notranslate">

    <link rel="stylesheet" href="chrome://resources/css/dialogs.css"></link>
    <link rel="stylesheet" href="chrome://resources/css/list.css"></link>
    <link rel="stylesheet" href="chrome://resources/css/tree.css"></link>
    <link rel="stylesheet" href="chrome://resources/css/table.css"></link>
    <link rel="stylesheet" href="chrome://resources/css/menu.css"></link>

    <link rel="stylesheet" href="css/combobutton.css"></link>
    <link rel="stylesheet" href="css/file_manager.css"></link>
    <link rel="stylesheet" href="css/file_types.css"></link>
    <link rel="stylesheet" href="css/common.css"></link>

    <if expr="0"></if>

    <if expr="0">

    </if>

    <commands>

      <command id="cut" i18n-values="label:CUT_BUTTON_LABEL"
               shortcut="U+0058-Ctrl">
      <command id="copy" i18n-values="label:COPY_BUTTON_LABEL"
               shortcut="U+0043-Ctrl">
      <command id="paste" i18n-values="label:PASTE_BUTTON_LABEL"
               shortcut="U+0056-Ctrl">
      <command id="rename" i18n-values="label:RENAME_BUTTON_LABEL"
               shortcut="Enter-Ctrl">
      <command id="delete" i18n-values="label:DELETE_BUTTON_LABEL"
               shortcut="U+007F">
      <command id="newfolder" i18n-values="label:NEW_FOLDER_BUTTON_LABEL"
               shortcut="U+0045-Ctrl">
      <command id="newwindow" i18n-values="label:NEW_WINDOW_BUTTON_LABEL">
      <command id="change-default-app"
               i18n-values="label:CHANGE_DEFAULT_APP_BUTTON_LABEL" hidden>

      <command id="search" shortcut="U+0046-Ctrl">

      <command id="unmount" i18n-values="label:UNMOUNT_DEVICE_BUTTON_LABEL">
      <command id="format" i18n-values="label:FORMAT_DEVICE_BUTTON_LABEL">
      <command id="import-photos" i18n-values="label:PHOTO_IMPORT_TITLE" hidden>

      <command id="volume-help" i18n-values="label:DRIVE_MENU_HELP">
      <command id="drive-buy-more-space"
               i18n-values="label:DRIVE_BUY_MORE_SPACE">
      <command id="drive-clear-local-cache"
               i18n-values="label:DRIVE_CLEAR_LOCAL_CACHE">
      <command id="drive-reload" i18n-values="label:DRIVE_RELOAD">
      <command id="drive-go-to-drive"
               i18n-values="label:DRIVE_VISIT_DRIVE_GOOGLE_COM">

      <command id="toggle-pinned" i18n-values="label:OFFLINE_COLUMN_LABEL">

      <command id="open-with" i18n-values="label:OPEN_WITH_BUTTON_LABEL">
      <command id="zip-selection"
               i18n-values="label:ZIP_SELECTION_BUTTON_LABEL">
    </commands>

    <menu id="file-context-menu" class="chrome-menu" showShortcuts>
      <menuitem id="default-action"
                visibleif="full-page" hidden></menuitem>
      <menuitem command="#open-with"
                visibleif="full-page" hidden></menuitem>

      <menuitem command="#toggle-pinned" checkable></menuitem>

      <menuitem command="#cut" visibleif="full-page"></menuitem>
      <menuitem command="#copy" visibleif="full-page"></menuitem>
      <menuitem command="#paste" visibleif="full-page"></menuitem>

      <menuitem command="#rename"></menuitem>
      <menuitem command="#delete"></menuitem>
      <menuitem command="#zip-selection"></menuitem>

      <menuitem command="#newfolder"
                visibleif="saveas-file full-page"></menuitem>
    </menu>
    <menu id="roots-context-menu" class="chrome-menu" >
      <menuitem command="#import-photos"></menuitem>
      <menuitem command="#unmount"></menuitem>
      <menuitem command="#format"></menuitem>
    </menu>

    <menu id="gear-menu" class="chrome-menu" showShortcuts>
      <menuitem command="#newwindow"></menuitem>
      <menuitem command="#newfolder"></menuitem>
      <menuitem command="#change-default-app"></menuitem>

      <menuitem id="drive-sync-settings"
                i18n-content=DRIVE_MOBILE_CONNECTION_OPTION></menuitem>
      <menuitem id="drive-hosted-settings"
                i18n-content=DRIVE_SHOW_HOSTED_FILES_OPTION></menuitem>

      <menuitem command="#drive-clear-local-cache"></menuitem>
      <menuitem command="#drive-reload"></menuitem>

      <menuitem command="#drive-buy-more-space"></menuitem>
      <menuitem command="#drive-go-to-drive"></menuitem>
      <menuitem command="#volume-help"></menuitem>
    </menu>

    <menu id="tasks-menu" class="chrome-menu">
    </menu>

    <menu id="text-context-menu" class="chrome-menu" showShortcuts>
        <menuitem command="#cut"></menuitem>
        <menuitem command="#copy"></menuitem>
        <menuitem command="#paste"></menuitem>
        <menuitem command="#delete"></menuitem>
    </menu>

        <tree id="directory-tree" tabindex="8"></tree>

          <input id="search-box" type="search" tabindex="9"
                 i18n-values="aria-label:SEARCH_TEXT_LABEL">

              <button class="left small" id="detail-view" tabindex="10"
                      i18n-values="aria-label:DETAIL_VIEW_TOOLTIP">
              </button>

              <button class="right small" id="thumbnail-view" tabindex="11"
                      i18n-values="aria-label:THUMBNAIL_VIEW_TOOLTIP">
              </button>

            <button class="menubutton" id="gear-button" tabindex="12"
                    menu="#gear-menu" visibleif="full-page">

            </button>

              <grid class=thumbnail-grid tabindex=1></grid>

              <button id="tasks" class="combobutton" menu="#tasks-menu"
                      tabindex="2">
              </button>
              <button id="delete-button" command="#delete" tabindex="3"></button>

              <button id="format-button" command="#format"></button>

      <button id="new-folder" i18n-content=NEW_FOLDER_BUTTON_LABEL
              visibleif="saveas-file folder" command="#newfolder" tabindex="4">
      </button>

        <input type=text spellcheck=false tabindex="5">

      <select id="file-type"></select>
      <button class=ok disabled tabindex="6"></button>

      <button class=cancel i18n-content=CANCEL_LABEL tabindex="7"></button>


text:
<?php

function add_order_reference_in_order_payment()
{
	$res = true;
	$payments = Db::getInstance()->query('
	SELECT op.id_order_payment, o.reference
	FROM `'._DB_PREFIX_.'order_payment` op
	INNER JOIN `'._DB_PREFIX_.'orders` o
	ON o.id_order = op.id_order');

	if (!is_resource($payments) || !$payments)
		return true;

	$errors = array();
	// Populate "order_reference"
	while ($payment = Db::getInstance()->nextRow($payments))
	{
		if(isset($payment['id_order_payment']) && $payment['id_order_payment'])
		{
			$res = Db::getInstance()->execute('
			UPDATE `'._DB_PREFIX_.'order_payment`
			SET order_reference = \''.pSQL($payment['reference']).'\'
			WHERE id_order_payment = '.(int)$payment['id_order_payment']);
			if (!$res)
				$errors[] = Db::getInstance()->getMsgError();
		}
	}

	if (count($errors))
		return array('error' => true, 'msg' => implode('<br/>', $errors));

	// Get lines to merge (with multishipping on, durring the payment one line was added by order, only one is necessary by cart)
	$duplicate_lines = Db::getInstance()->query('
	SELECT GROUP_CONCAT(id_order_payment) as id_order_payments
	FROM `'._DB_PREFIX_.'order_payment`
	GROUP BY order_reference, date_add
	HAVING COUNT(*) > 1');

	if (!is_resource($duplicate_lines) || !$duplicate_lines)
		return true;

	$order_payments_to_remove = array();
	while ($order_payments = Db::getInstance()->nextRow($duplicate_lines))
	{
		$order_payments_array = array();
		if(isset($order_payments['id_order_payments']))
			$order_payments_array = explode(',', $order_payments['id_order_payments']);
		// Remove the first item (we want to keep one line)
		$id_order_payment_keep = array_shift($order_payments_array);

		$res = Db::getInstance()->execute('
		UPDATE `'._DB_PREFIX_.'order_invoice_payment`
		SET id_order_payement = '.(int)$id_order_payment_keep.'
		WHERE id_order_payment IN ('.implode(',', $order_payments_array).')');

		$order_payments_to_remove = array_merge($order_payments_to_remove, $order_payments_array);
	}
	// Remove the duplicate lines (because of the multishipping)
	if (count($order_payments_to_remove))
		$res = Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'order_payment` WHERE id_order_payment IN ('.implode(',', $order_payments_to_remove).')');

	if (!$res)
		return array('errors' => true, 'msg' =>  Db::getInstance()->getMsgError());
	return true;
}


text:
<resources>
    <string name="app_name">GeekIT</string>

    <string name="title_section1">Section 1</string>
    <string name="title_section2">Section 2</string>
    <string name="title_section3">Section 3</string>

    <string name="hello_world">Hello world!</string>

    <string name="action_settings">Settings</string>
    <string name="grid_item_desc">Book Cover Image</string>
    <string name="book_cover_details_item">Book Cover Thumbnail Details View</string>
    <string name="button_download_text">Download</string>
    <string name="book_details_pages_count_header">Pages</string>
    <string name="book_details_year_header">Year</string>
    <string name="book_details_publisher_header">Publisher</string>
    <string name="book_details_author_header">Author</string>
    <string name="book_details_isbn_header">ISBN</string>
    <string name="book_details_description_header">Description</string>
    <string name="book_details_subtitle_header">Subtitle</string>
    <string name="book_details_title_header">Title</string>
    <string name="next_page_button_text">next</string>
    <string name="search_hint">Find Books</string>
    <string name="search_box_title">Search</string>

<!-- TODO: Remove or change this placeholder text -->
    <string name="hello_blank_fragment">Hello blank fragment</string>
</resources>


text:
export const TOKEN_RECEIVE = 'TOKEN_RECEIVE';
export const TOKEN_COOKIE_LOAD = 'TOKEN_COOKIE_LOAD';

export const USER_RECEIVE = 'USER_RECEIVE';
export const USER_SIGN_OUT = 'USER_SIGN_OUT';


text:
function [mn,s1,s3,s10]=runQAPs(problem_set)
%function [mn, s1,s3,s10]=runQAPs(problem_set)
% Run the QAP problem set using FW1, FW3, and FW10
% where
% FW1 is up to 30 iterations of Frank Wolf method with a single starting
%     point, the flat doubly stochastic matrix (the barycenter of the space
%     of doubly stochastic matrices.)
% FW3 is the minimum of FW1 and two starts near the barycenter of the space.
% FW10 is the minimum of FW1 and nine starts near the barycenter of the space.
% The input argument is one of the following:
% 'all' which will run all the QAP test problems in the QAPLIB as of
%       June 2012.
% 'path16' or 'lipa16' which will run the 16 QAPLIB test problems
%      that were run in the PATH paper and the 16 lipa[nn][a|b] problems.
% If no input or an unrecognized string is given then 'path16'
%    is the assumed default.
% A table summarizing the results will be produced.
% Also a structure, mn containing the output of the runs including the
%     runtime, number of iteration, as well as the approximate solutions found,
%     is returned.  Also, on output
% s1, s3, and s10 are given, which are the cost obtained using
%     1, 3, and 10 starts of the Frank Wolf method.
% John M. Conroy, June 2012
% IDA Center for Computing Sciences
% conroy@super.org
%  (c) 2012, Institute for Defense Analyses, 4850 Mark Center Drive,
%  Alexandria, Virginia, 22311-1882; 703-845-2500.
%  This material may be reproduced by or for the U.S.
%  Government pursuant to the copyright license under
%  the clauses at DFARS 252.227-7013 and 252.227-7014.
%
% To run this code, one must be in the /qaplib directory, with the /code/
% directory in the path.

rootDir='~/Research/projects/primary/FastApproximateQAP/qaplib/';
cd(rootDir)
path('../code/FAQ/',path)
path('../code/other/',path)

if nargin==0,
    problem_set='';
end
if iscell(problem_set)
    probs=problem_set;
else
    switch problem_set
        case'path16'
            fname=[rootDir, 'mat_files/problems16'];
            load(fname)
            probs=problems16;
        case 'lipa16'
            fname=[rootDir, 'mat_files/problems16_lip'];
            load(fname)
            probs=problems16_lip;
        case 'all'
            fname=[rootDir, 'mat_files/problems_all'];
            load(fname)
            probs=problems_all;
        otherwise
            fprintf('Default: runQAPs(''path16'')\n');
            fname=[rootDir, 'mat_files/problems16'];
            load(fname)
            probs=problems16;
    end
end
rand('seed',12345678);
% Loop over the starts
for i=1:10,
    display(['trial ', num2str(i)])
    % If it it the first start then start in the center of the space
    if i>1
        [mn(i).s,mn(i).p,mn(i).iters,mn(i).best,mn(i).time]=run_qaplib_problems(probs,30,-1);
        % otherwise pick a point near the center of the space.
    else
        [mn(i).s,mn(i).p,mn(i).iters,~,mn(i).time]=run_qaplib_problems(probs,30);
    end

end;
S=[mn.s]';
s1=S(1,:);
s10=min(S(1:10,:));
s3=min(S(1:3,:));
%s100=min(S)
fprintf(1,'%12s %12s %12s %12s\n','Problem','FW1','FW2','FW10');
for i=1:length(probs)
    fprintf(1,'%12s %12d %12d %12d \n',probs{i},s1(i),s3(i),s10(i));
end
% save([fname, '_results'])


text:
package org.koinkoin;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.GregorianCalendar;
import java.util.List;

import org.knowm.xchange.Exchange;
import org.knowm.xchange.ExchangeFactory;
import org.knowm.xchange.currency.Currency;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.marketdata.Ticker;
import org.knowm.xchange.kraken.KrakenExchange;
import org.knowm.xchange.kraken.dto.marketdata.KrakenTicker;
import org.knowm.xchange.kraken.service.KrakenMarketDataServiceRaw;
import org.knowm.xchange.poloniex.PoloniexExchange;
import org.knowm.xchange.service.marketdata.MarketDataService;
import org.koinkoin.bot.TradingBot;
import org.koinkoin.core.Fund;
import org.koinkoin.swarm.Swarm;
import org.koinkoin.trade.Position;
import org.koinkoin.trade.strategy.PercentageVariationTradingStrategy;

public class Main {
	public static final float MIN_PROFIT = 0.15f / 100.0f;

	/***
	 * Can I trade digital currencies other than Bitcoin?
	 *
	 * Yes. You can trade Bitcoin(XBT), Ethereum (ETH), Monero (XMR), Dash
	 * (DASH), Litecoin (LTC), Ripple (XRP), Stellar/Lumens (XLM), Ethereum
	 * Classic (ETC), Augur REP tokens (REP), ICONOMI (ICN), Melon (MLN), Zcash
	 * (ZEC), Dogecoin (XDG), Tether (USDT), Gnosis (GNO), and EOS (EOS).
	 *
	 */
	public static void main(String[] args) throws Exception {
		new Main().run();
	}

	public void run() throws Exception {
		// Use the factory to get Bitstamp exchange API using default settings
		Exchange kraken = ExchangeFactory.INSTANCE
				.createExchange(KrakenExchange.class.getName());
		Exchange poloniex = ExchangeFactory.INSTANCE
				.createExchange(PoloniexExchange.class.getName());

		// Interested in the public market data feed (no authentication)
		MarketDataService krakenMarketDataService = kraken
				.getMarketDataService();
		MarketDataService poloniexMarketDataService = poloniex
				.getMarketDataService();

		Fund fund = new Fund(new BigDecimal(800), Currency.USD);

		TradingBot tradingBot = new TradingBot(fund, krakenMarketDataService,
				new PercentageVariationTradingStrategy());
		TradingBot poloniexBot = new TradingBot(fund,
				poloniexMarketDataService,
				new PercentageVariationTradingStrategy());

		tradingBot.tradeWith(CurrencyPair.LTC_BTC, CurrencyPair.LTC_USD,
				CurrencyPair.BTC_USD, CurrencyPair.XRP_BTC,
				CurrencyPair.XRP_USD, new CurrencyPair(Currency.XMR,
						Currency.USD), new CurrencyPair("DASH", "USD"),
				new CurrencyPair("DASH", "BTC"), CurrencyPair.XMR_BTC);

		tradingBot.queue(Position.builder().withAmount(500f)
				.withCurrency(Currency.USD)
				.withPair(new CurrencyPair("BTC", "USD"))
				.withMinProfit(MIN_PROFIT).withMaxLoss(0.1f).sustained(true)
				.create());

		poloniexBot.queue(Position.builder().withAmount(500f)
				.withCurrency(Currency.USD)
				.withPair(new CurrencyPair("DASH", "USD"))
				.withMinProfit(MIN_PROFIT).withMaxLoss(0.1f).create());

		Swarm swarm = new Swarm();

		swarm.add(tradingBot);

		/**
		 * do something like
		 * MarketDefinition marketDefinition = MarketDefinition.builder().samePairsAs(bot);
		 * MarketLog marketLog = new MarketLog();
		 * do {
		 * MarketData marketData = new MarketData(marketDefinition);
		 *   swarm.trade(marketData);
		 *   marketLog.publish(marketData);
		 *   sleep(1000)
		 * } while (true)
		 */
		do {
			swarm.trade();

			try {
				Thread.sleep(1500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} while (true);
		// raw((KrakenMarketDataServiceRaw) marketDataService);
	}

	private void showPrices(String exchange, List<Ticker> tickers) {
		StringBuilder builder = new StringBuilder();
		builder.append(exchange);
		builder.append(": ");
		builder.append(GregorianCalendar.getInstance().getTime());
		builder.append(" | ");

		for (Ticker ticker : tickers) {
			builder.append(ticker.getCurrencyPair());
			builder.append(": ");
			builder.append(ticker.getAsk());
			builder.append(", ");
			builder.append(ticker.getBid());

			builder.append(" | ");
		}

		System.out.println(builder.toString());
	}

	private static void raw(KrakenMarketDataServiceRaw marketDataService)
			throws IOException {

		KrakenTicker krakenTicker = marketDataService
				.getKrakenTicker(CurrencyPair.BTC_EUR);

		System.out.println(krakenTicker.toString());
	}
}


text:
package org.chocosolver.solver.constraints.ternary;

import org.chocosolver.solver.Model;
import org.chocosolver.solver.Solver;
import org.chocosolver.solver.constraints.Constraint;
import org.chocosolver.solver.search.loop.monitors.IMonitorSolution;
import org.chocosolver.solver.variables.IntVar;
import org.testng.Assert;
import org.testng.annotations.Test;

import static org.chocosolver.solver.search.strategy.Search.randomSearch;
import static org.chocosolver.util.ESat.TRUE;

/**
 * <br/>
 *
 * @author Charles Prud'homme
 * @since 16/07/12
 */
public class DivTest extends AbstractTernaryTest {

    @Override
    protected int validTuple(int vx, int vy, int vz) {
        return vy != 0 && vz == vx / vy ? 1 : 0;
    }

    @Override
    protected Constraint make(IntVar[] vars, Model model) {
        return model.div(vars[0], vars[1], vars[2]);
    }

    @Test(groups="1s", timeOut=60000)
    public void testJL() {
        Model model = new Model();
        IntVar i = model.intVar("i", 0, 2, false);
        model.div(i, model.boolVar(true), model.boolVar(false)).getOpposite().post();
//        SMF.log(solver, true, false);
        while (model.getSolver().solve()) ;
    }

    @Test(groups="10s", timeOut=60000)
    public void testJL2() {
        for (int i = 0; i < 100000; i++) {
            final Model s = new Model();
            IntVar a = s.intVar("a", new int[]{0, 2, 3, 4});
            IntVar b = s.intVar("b", new int[]{-1, 1, 3, 4});
            IntVar c = s.intVar("c", new int[]{-3, 1, 4});
            s.div(a, b, c).post();
            Solver r = s.getSolver();
            r.setSearch(randomSearch(new IntVar[]{a, b, c}, i));
            //SMF.log(s, true, true);
            r.plugMonitor((IMonitorSolution) () -> {
                if (!TRUE.equals(r.isSatisfied())) {
                    throw new Error(s.toString());
                }
            });
            while (s.getSolver().solve()) ;
        }
    }

    @Test(groups="10s", timeOut=60000)
    public void testTP1(){
        final Model s = new Model();
        IntVar a = s.intVar("a", 0, 525000);
        IntVar b = s.intVar("b", 0, 5000);
        IntVar c = s.intVar("c", 0, 525000);
        s.div(a, b, c).post();
        Solver r = s.getSolver();
        r.solve();
        Assert.assertEquals(r.getSolutionCount(), 1);
    }
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const os_1 = require("os");
const loader_utils_1 = require("loader-utils");
const _1 = require(".");
const normalizePatterns = (patterns) => Array.isArray(patterns) ? patterns : [patterns];
const coerceContentEOL = (content) => (content.endsWith(os_1.EOL) ? content : `${content}${os_1.EOL}`);
const getResourceContent = ({ content }) => coerceContentEOL(content);
const normalizeInjector = (injector) => {
    if (typeof injector === 'undefined' || injector === 'prepend') {
        return (source, resources) => resources.map(getResourceContent).join('') + source;
    }
    if (injector === 'append') {
        return (source, resources) => source + resources.map(getResourceContent).join('');
    }
    return injector;
};
exports.normalizeOptions = (ctx) => {
    const options = loader_utils_1.getOptions(ctx) || {};
    _1.validateOptions(options);
    const { patterns, injector, globOptions = {}, resolveUrl = true } = options;
    return {
        patterns: normalizePatterns(patterns),
        injector: normalizeInjector(injector),
        globOptions,
        resolveUrl,
    };
};
//# sourceMappingURL=normalize-options.js.map


text:
package org.apache.metron;

public class TestConstants {

  public final static String SAMPLE_CONFIG_PATH = "../metron-integration-test/src/main/config/zookeeper/";
  public final static String PARSER_CONFIGS_PATH = "../metron-parsing/metron-parsers/src/main/config/zookeeper/";
  public final static String PARSER_COMMON_CONFIGS_PATH = "../metron-parsing/metron-parsers-common/src/main/config/zookeeper/";
  public final static String ENRICHMENTS_CONFIGS_PATH = "../metron-enrichment/src/main/config/zookeeper/";
  public final static String SAMPLE_DATA_PATH = "../metron-integration-test/src/main/sample/data/";
  public final static String SAMPLE_DATA_INPUT_PATH = "../metron-integration-test/src/main/sample/data/yaf/raw/";
  public final static String SAMPLE_DATA_PARSED_PATH = "../metron-integration-test/src/main/sample/data/test/parsed/";
  public final static String SAMPLE_DATA_INDEXED_PATH = "../metron-integration-test/src/main/sample/data/test/indexed/";
}