text:
FROM wegamekinglc/python:3.7-slim-stretch-aliyun

LABEL maintainer = "scrappedprince.li@gmail.com"
RUN apt-get update && apt-get install build-essential default-libmysqlclient-dev -y

WORKDIR /
COPY ./requirements.txt /requirements.txt
RUN pip install numpy cython -i https://pypi.douban.com/simple
RUN pip install -r /requirements.txt -i https://pypi.douban.com/simple
RUN pip install finance-python>=0.8.1 -i https://pypi.douban.com/simple

WORKDIR /
COPY ./alphamind /alphamind
COPY ./notebooks /notebooks

COPY ./setup.py /setup.py
COPY ./setup.cfg /setup.cfg

EXPOSE 8080
COPY ./entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh

WORKDIR /notebooks
ENTRYPOINT ["/entrypoint.sh"]
CMD []


text:
Internet hostname of this mail system

<tt>myhostname</tt>

This parameter specifies the internet hostname of this mail system. The default
is to use the fully-qualified domain name from <tt>gethostname()</tt>.

<tt>$myhostname</tt> is used as a default value for many other configuration
parameters.

redpajama_set_name: RedPajamaGithub


text:
@interface PodsDummy_ColorHSPicker : NSObject
@end
@implementation PodsDummy_ColorHSPicker
@end


text:
<?php

namespace Event\EventBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class EventEventBundle extends Bundle
{
}


text:
package br.com.m4u.commons.brazilian.library.validator.routines;

import java.util.regex.Pattern;

/**
 * Created by rodrigo.henriques on 04/03/15.
 */
public class MobilePhoneValidator {

    final String REG_EXP_MOBILE_PHONE = "\\(?((10)|([1-9][1-9]))\\)?\\s?9?[1-9]\\d{3}\\-?\\d{4}";

    Pattern pattern;

    public MobilePhoneValidator() {
        pattern = Pattern.compile(REG_EXP_MOBILE_PHONE);
    }

    public boolean validate(String value) {

        value = value.replaceAll("\\D+","");

        return pattern.matcher(value).matches();
    }
}


text:
package com.linecorp.armeria.internal.grpc;

import static java.util.Objects.requireNonNull;

import java.io.IOException;
import java.nio.channels.ClosedChannelException;

import com.linecorp.armeria.client.ResponseTimeoutException;

import io.grpc.Status;
import io.grpc.Status.Code;
import io.netty.handler.codec.http2.Http2Exception;
import io.netty.handler.codec.http2.Http2Exception.StreamException;

/**
 * Utilities for handling {@link Status} in Armeria.
 */
public final class GrpcStatus {

    /**
     * Converts the {@link Throwable} to a {@link Status}, taking into account exceptions specific to Armeria as
     * well.
     */
    public static Status fromThrowable(Throwable t) {
        requireNonNull(t, "t");
        Status s = Status.fromThrowable(t);
        if (s.getCode() != Code.UNKNOWN) {
            return s;
        }
        if (t instanceof StreamException) {
            StreamException streamException = (StreamException) t;
            if (streamException.getMessage() != null && streamException.getMessage().contains("RST_STREAM")) {
                return Status.CANCELLED;
            }
        }
        if (t instanceof ClosedChannelException) {
            // ClosedChannelException is used any time the Netty channel is closed. Proper error
            // processing requires remembering the error that occurred before this one and using it
            // instead.
            return Status.UNKNOWN.withCause(t);
        }
        if (t instanceof IOException) {
            return Status.UNAVAILABLE.withCause(t);
        }
        if (t instanceof Http2Exception) {
            return Status.INTERNAL.withCause(t);
        }
        if (t instanceof ResponseTimeoutException) {
            return Status.DEADLINE_EXCEEDED.withCause(t);
        }
        return s;
    }

    private GrpcStatus() {}
}


text:
// Definition lists

// Search `[:~][\n ]`, returns next pos after marker on success
// or -1 on fail.
function skipMarker(state, line) {
  var pos, marker,
      start = state.bMarks[line] + state.tShift[line],
      max = state.eMarks[line];

  if (start >= max) { return -1; }

  // Check bullet
  marker = state.src.charCodeAt(start++);
  if (marker !== 0x7E/* ~ */ && marker !== 0x3A/* : */) { return -1; }

  pos = state.skipSpaces(start);

  // require space after ":"
  if (start === pos) { return -1; }

  // no empty definitions, e.g. "  : "
  if (pos >= max) { return -1; }

  return pos;
}

function markTightParagraphs(state, idx) {
  var i, l,
      level = state.level + 2;

  for (i = idx + 2, l = state.tokens.length - 2; i < l; i++) {
    if (state.tokens[i].level === level && state.tokens[i].type === 'paragraph_open') {
      state.tokens[i + 2].tight = true;
      state.tokens[i].tight = true;
      i += 2;
    }
  }
}

export default function deflist(state, startLine, endLine, silent) {
  var contentStart,
      ddLine,
      dtLine,
      itemLines,
      listLines,
      listTokIdx,
      nextLine,
      oldIndent,
      oldDDIndent,
      oldParentType,
      oldTShift,
      oldTight,
      prevEmptyEnd,
      tight;

  if (silent) {
    // quirk: validation mode validates a dd block only, not a whole deflist
    if (state.ddIndent < 0) { return false; }
    return skipMarker(state, startLine) >= 0;
  }

  nextLine = startLine + 1;
  if (state.isEmpty(nextLine)) {
    if (++nextLine > endLine) { return false; }
  }

  if (state.tShift[nextLine] < state.blkIndent) { return false; }
  contentStart = skipMarker(state, nextLine);
  if (contentStart < 0) { return false; }

  if (state.level >= state.options.maxNesting) { return false; }

  // Start list
  listTokIdx = state.tokens.length;

  state.tokens.push({
    type: 'dl_open',
    lines: listLines = [ startLine, 0 ],
    level: state.level++
  });

  //
  // Iterate list items
  //

  dtLine = startLine;
  ddLine = nextLine;

  // One definition list can contain multiple DTs,
  // and one DT can be followed by multiple DDs.
  //
  // Thus, there is two loops here, and label is
  // needed to break out of the second one
  //
  /*eslint no-labels:0,block-scoped-var:0*/
  OUTER:
  for (;;) {
    tight = true;
    prevEmptyEnd = false;

    state.tokens.push({
      type: 'dt_open',
      lines: [ dtLine, dtLine ],
      level: state.level++
    });
    state.tokens.push({
      type: 'inline',
      content: state.getLines(dtLine, dtLine + 1, state.blkIndent, false).trim(),
      level: state.level + 1,
      lines: [ dtLine, dtLine ],
      children: []
    });
    state.tokens.push({
      type: 'dt_close',
      level: --state.level
    });

    for (;;) {
      state.tokens.push({
        type: 'dd_open',
        lines: itemLines = [ nextLine, 0 ],
        level: state.level++
      });

      oldTight = state.tight;
      oldDDIndent = state.ddIndent;
      oldIndent = state.blkIndent;
      oldTShift = state.tShift[ddLine];
      oldParentType = state.parentType;
      state.blkIndent = state.ddIndent = state.tShift[ddLine] + 2;
      state.tShift[ddLine] = contentStart - state.bMarks[ddLine];
      state.tight = true;
      state.parentType = 'deflist';

      state.parser.tokenize(state, ddLine, endLine, true);

      // If any of list item is tight, mark list as tight
      if (!state.tight || prevEmptyEnd) {
        tight = false;
      }
      // Item become loose if finish with empty line,
      // but we should filter last element, because it means list finish
      prevEmptyEnd = (state.line - ddLine) > 1 && state.isEmpty(state.line - 1);

      state.tShift[ddLine] = oldTShift;
      state.tight = oldTight;
      state.parentType = oldParentType;
      state.blkIndent = oldIndent;
      state.ddIndent = oldDDIndent;

      state.tokens.push({
        type: 'dd_close',
        level: --state.level
      });

      itemLines[1] = nextLine = state.line;

      if (nextLine >= endLine) { break OUTER; }

      if (state.tShift[nextLine] < state.blkIndent) { break OUTER; }
      contentStart = skipMarker(state, nextLine);
      if (contentStart < 0) { break; }

      ddLine = nextLine;

      // go to the next loop iteration:
      // insert DD tag and repeat checking
    }

    if (nextLine >= endLine) { break; }
    dtLine = nextLine;

    if (state.isEmpty(dtLine)) { break; }
    if (state.tShift[dtLine] < state.blkIndent) { break; }

    ddLine = dtLine + 1;
    if (ddLine >= endLine) { break; }
    if (state.isEmpty(ddLine)) { ddLine++; }
    if (ddLine >= endLine) { break; }

    if (state.tShift[ddLine] < state.blkIndent) { break; }
    contentStart = skipMarker(state, ddLine);
    if (contentStart < 0) { break; }

    // go to the next loop iteration:
    // insert DT and DD tags and repeat checking
  }

  // Finilize list
  state.tokens.push({
    type: 'dl_close',
    level: --state.level
  });
  listLines[1] = nextLine;

  state.line = nextLine;

  // mark paragraphs tight if needed
  if (tight) {
    markTightParagraphs(state, listTokIdx);
  }

  return true;
};


text:
<?php

namespace Esockets\Base\Exception;

final class ReadException extends \Exception
{
    const ERROR_EMPTY = 0; // nothing to read
    const ERROR_FAIL = 1; // not read to the end
    const ERROR_PROTOCOL = 2;

    /**
     * @param string $read
     * @param int $code
     */
    public function __construct($read, int $code)
    {
        parent::__construct($read, $code);
    }
}


text:
<comet color="blue"></comet><comet color="red"></comet>

<cover></cover>

<comet color="white"></comet>

<comet color="white"></comet>

        	<back-end></back-end>

<comet color="blue"></comet>

        <front-end></front-end>

<contact></contact>


text:
@interface UIStepper (TFEasyCoder)

-(UIStepper  *(^)(BOOL  continuous))set_continuous;
-(UIStepper  *(^)(BOOL  autorepeat))set_autorepeat;
-(UIStepper  *(^)(BOOL  wraps))set_wraps;
-(UIStepper  *(^)(double  value))set_value;
-(UIStepper  *(^)(double  minimumValue))set_minimumValue;
-(UIStepper  *(^)(double  maximumValue))set_maximumValue;
-(UIStepper  *(^)(double  stepValue))set_stepValue;
-(UIStepper  *(^)(UIColor *  tintColor))set_tintColor;

//superclass pros UIControl
-(UIStepper  *(^)(BOOL  enabled))set_enabled;
-(UIStepper  *(^)(BOOL  selected))set_selected;
-(UIStepper  *(^)(BOOL  highlighted))set_highlighted;
-(UIStepper  *(^)(long long  contentVerticalAlignment))set_contentVerticalAlignment;
-(UIStepper  *(^)(long long  contentHorizontalAlignment))set_contentHorizontalAlignment;
//superclass pros UIView
-(UIStepper  *(^)(UIView *  maskView))set_maskView;
-(UIStepper  *(^)(BOOL  userInteractionEnabled))set_userInteractionEnabled;
-(UIStepper  *(^)(long long  tag))set_tag;
-(UIStepper  *(^)(long long  semanticContentAttribute))set_semanticContentAttribute;
-(UIStepper  *(^)(CGPoint  center))set_center;
-(UIStepper  *(^)(CGRect  frame))set_frame;
-(UIStepper  *(^)(UIColor *  backgroundColor))set_backgroundColor;
//superclass pros UIResponder
-(UIStepper  *(^)(NSUserActivity *  userActivity))set_userActivity;
//superclass pros NSObject
-(UIStepper  *(^)(NSArray *  accessibilityElements))set_accessibilityElements;
-(UIStepper  *(^)(NSArray *  accessibilityCustomActions))set_accessibilityCustomActions;
-(UIStepper  *(^)(BOOL  isAccessibilityElement))set_isAccessibilityElement;
-(UIStepper  *(^)(NSString *  accessibilityLabel))set_accessibilityLabel;
-(UIStepper  *(^)(NSString *  accessibilityHint))set_accessibilityHint;
-(UIStepper  *(^)(NSString *  accessibilityValue))set_accessibilityValue;
-(UIStepper  *(^)(unsigned long long  accessibilityTraits))set_accessibilityTraits;
-(UIStepper  *(^)(UIBezierPath *  accessibilityPath))set_accessibilityPath;
-(UIStepper  *(^)(CGPoint  accessibilityActivationPoint))set_accessibilityActivationPoint;
-(UIStepper  *(^)(NSString *  accessibilityLanguage))set_accessibilityLanguage;
-(UIStepper  *(^)(BOOL  accessibilityElementsHidden))set_accessibilityElementsHidden;
-(UIStepper  *(^)(BOOL  accessibilityViewIsModal))set_accessibilityViewIsModal;
-(UIStepper  *(^)(BOOL  shouldGroupAccessibilityChildren))set_shouldGroupAccessibilityChildren;
-(UIStepper  *(^)(long long  accessibilityNavigationStyle))set_accessibilityNavigationStyle;

@end


text:
<?php

namespace Tests\Unit\Matchers;

use PHPKitchen\CodeSpecs\Expectation\Matcher\BooleanMatcher;
use Tests\Base\BaseMatcherTest;

/**
 * Unit test for {@link BooleanMatcher}
 *
 * @method BooleanMatcher createMatcherWithActualValue($actualValue)
 *
 * @coversDefaultClass \PHPKitchen\CodeSpecs\Expectation\Matcher\BooleanMatcher
 *
 * @package Tests\Expectation
 * @author Dmitry Kolodko <prowwid@gmail.com>
 */
class BooleanMatcherTest extends BaseMatcherTest {
    protected function initMatcherClass() {
        $this->matcherClass = BooleanMatcher::class;
    }

    /**
     * @covers ::__construct
     */
    public function testCreate() {
        try {
            $this->createMatcherWithActualValue(true);
            $matcherCreated = true;
        } catch (\Exception $e) {
            $matcherCreated = false;
        }
        $this->assertTrue($matcherCreated, 'Unable to instantiate ' . BooleanMatcher::class);
    }

    /**
     * @covers ::isTrue
     */
    public function testIsTrue() {
        $bool = $this->createMatcherWithActualValue(true);
        $bool->isTrue();
    }

    /**
     * @covers ::isFalse
     */
    public function testIsFalse() {
        $bool = $this->createMatcherWithActualValue(false);
        $bool->isFalse();
    }

    /**
     * @covers ::isNotTrue
     */
    public function testIsNotTrue() {
        $bool = $this->createMatcherWithActualValue(1);
        $bool->isNotTrue();
    }

    /**
     * @covers ::isNotFalse
     */
    public function testIsNotFalse() {
        $bool = $this->createMatcherWithActualValue(0);
        $bool->isNotFalse();
    }
}


text:
package org.elasticsearch.search.aggregations.bucket.terms;

import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.aggregations.Aggregator;
import org.elasticsearch.search.aggregations.AggregatorFactories;
import org.elasticsearch.search.aggregations.bucket.terms.heuristic.SignificanceHeuristic;
import org.elasticsearch.search.aggregations.support.AggregatorSupplier;
import org.elasticsearch.search.aggregations.support.ValuesSource;
import org.elasticsearch.search.internal.SearchContext;

import java.io.IOException;
import java.util.Map;

interface SignificantTermsAggregatorSupplier extends AggregatorSupplier {
    Aggregator build(String name,
                     AggregatorFactories factories,
                     ValuesSource valuesSource,
                     DocValueFormat format,
                     TermsAggregator.BucketCountThresholds bucketCountThresholds,
                     IncludeExclude includeExclude,
                     String executionHint,
                     SearchContext context,
                     Aggregator parent,
                     SignificanceHeuristic significanceHeuristic,
                     SignificanceLookup lookup,
                     boolean collectsFromSingleBucket,
                     Map<String, Object> metadata) throws IOException;
}


text:
public class Tower {
    public UnityEngine.GameObject Entity;
    public Tower() {
        Entity = UnityEngine.GameObject.Instantiate<UnityEngine.GameObject>(Game.TowerPrefab);
    }
}


text:
package pro.anton.averin.android.skeleton.data.prefs;

import pro.anton.averin.android.skeleton.BaseContext;

/**
 * Created by AAverin on 24.05.2014.
 */
public class PermanentCache extends BaseCache {

    public String sample = "";
    public String locale_lang = "ru";
    public String locale_country = "RUS";
    public String locale_variant = "";

    private SharedPreferencesCache preferencesCache;

    public static PermanentCache instance = null;

    public static PermanentCache getInstance(BaseContext context) {
        if (instance == null) {
            instance = new PermanentCache(context);
        }
        return instance;
    }

    private PermanentCache(BaseContext baseContext) {
        preferencesCache = SharedPreferencesCache.getInstance(baseContext);
    }

    @Override
    public AppSharedPreferences getPreferences() {
        return preferencesCache.prefCache;
    }

    @Override
    public void save() {
        preferencesCache.prefCache.setStringSetting(SharedPreferencesCache.SHARED_OPTIONS.SAMPLE, sample);
        preferencesCache.prefCache.setStringSetting(SharedPreferencesCache.SHARED_OPTIONS.LOCALE_LANG, locale_lang);
        preferencesCache.prefCache.setStringSetting(SharedPreferencesCache.SHARED_OPTIONS.LOCALE_COUNTRY, locale_country);
        preferencesCache.prefCache.setStringSetting(SharedPreferencesCache.SHARED_OPTIONS.LOCALE_VARIANT, locale_variant);
    }

    @Override
    public void restore() {
        sample = preferencesCache.prefCache.getStringSetting(SharedPreferencesCache.SHARED_OPTIONS.SAMPLE);
        locale_lang = preferencesCache.prefCache.getStringSetting(SharedPreferencesCache.SHARED_OPTIONS.LOCALE_LANG);
        locale_country = preferencesCache.prefCache.getStringSetting(SharedPreferencesCache.SHARED_OPTIONS.LOCALE_COUNTRY);
        locale_variant = preferencesCache.prefCache.getStringSetting(SharedPreferencesCache.SHARED_OPTIONS.LOCALE_VARIANT);
    }

    @Override
    public void reset() {
        sample = "";
        locale_lang = "";
        locale_country = "";
        locale_variant = "";
        save();
    }
}


text:
package com.redhat.ceylon.compiler.typechecker.tree;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.antlr.runtime.CommonToken;
import org.antlr.runtime.Token;

import com.redhat.ceylon.common.Backend;
import com.redhat.ceylon.compiler.typechecker.analyzer.AnalysisError;
import com.redhat.ceylon.compiler.typechecker.analyzer.UnsupportedError;
import com.redhat.ceylon.compiler.typechecker.analyzer.UsageWarning;
import com.redhat.ceylon.compiler.typechecker.parser.LexError;
import com.redhat.ceylon.compiler.typechecker.parser.ParseError;
import com.redhat.ceylon.compiler.typechecker.util.PrintVisitor;
import com.redhat.ceylon.model.typechecker.model.Scope;
import com.redhat.ceylon.model.typechecker.model.Unit;

public abstract class Node {

    private String text;
    private Token token;
    private Token endToken;
    private Token firstChildToken;
    private Token lastChildToken;
    private Scope scope;
    private Unit unit;
    private List<Message> errors = null;

    protected Node(Token token) {
        this.token = token;
    }

    /**
     * The scope within which the node occurs.
     */
    public Scope getScope() {
        return scope;
    }

    public void setScope(Scope scope) {
        this.scope = scope;
    }

    /**
     * The compilation unit in which the node
     * occurs.
     */
    public Unit getUnit() {
        return unit;
    }

    public void setUnit(Unit unit) {
        this.unit = unit;
    }

    /**
     * The text of the corresponding ANTLR node.
     */
    public String getText() {
    	if (text!=null) {
    		return text;
    	}
    	else if (token==null) {
    		return "";
    	}
    	else if (endToken==null) {
    		return token.getText();
    	}
    	else {
    		return token.getText() +
    		        endToken.getText();
    	}
    }

    public void setText(String text) {
        this.text = text;
    }

    /**
     * The text of the corresponding ANTLR tree node. Never null,
     * since the two trees are isomorphic.
     */
    public Token getToken() {
    	return getFirstChildToken();
    }

    public Token getMainToken() {
        return token;
    }

    public Token getMainEndToken() {
        return endToken;
    }

    public String getLocation() {
    	Token token = getToken();
    	Token endToken = getEndToken();
		if (token==null) {
    		return "unknown location";
    	}
    	else if (endToken==null) {
    		return toLocation(token);
    	}
    	else {
    		return toLocation(token) + "-" +
    				toEndLocation(endToken);
    	}
    }

    /**
     * The index of the first character belonging to this node.
     */
    public Integer getStartIndex() {
    	Token token = getToken();
    	if (token==null) {
    		return null;
    	}
    	else {
    		CommonToken ct = (CommonToken) token;
            return ct.getStartIndex();
    	}
    }

    /**
     * The index of the last character belonging to this node.
     *
     * @returns an index one less than the end index of the node!
     * @see #getEndIndex()
     */
    public Integer getStopIndex() {
    	Token token = getEndToken();
    	if (token==null) {
    		token = getToken();
    	}
    	if (token==null) {
    		return null;
    	}
    	else {
    		CommonToken ct = (CommonToken) token;
            return ct.getStopIndex();
    	}
    }

    /**
     * The index of the first character after this node.
     */
    public Integer getEndIndex() {
        Token token = getEndToken();
        if (token==null) {
            token = getToken();
        }
        if (token==null) {
            return null;
        }
        else {
            CommonToken ct = (CommonToken) token;
            return ct.getStopIndex()+1;
        }
    }

    /**
     * The distance between {@link #getStartIndex()} and {@link #getEndIndex()},
     * that is, loosely speaking, the length of this node.
     */
    public Integer getDistance() {
        Integer start = getStartIndex();
        Integer end = getEndIndex();
        if (start!=null && end!=null) {
            return end - start;
        }
        else {
            return null;
        }
    }

	private static String toLocation(Token token) {
		return token.getLine() + ":" +
				token.getCharPositionInLine();
	}

	private static String toEndLocation(Token token) {
		return token.getLine() + ":" +
				(token.getCharPositionInLine()
				+ token.getText().length()-1);
	}

    private static boolean isMissingToken(Token t) {
        return t instanceof MissingToken;
    }

    public boolean isMissingToken() {
        return isMissingToken(token);
    }

    private Token getFirstChildToken() {
        Token token = this.token==null ||
                //the tokens ANTLR inserts to represent missing tokens
                //don't come with useful offset information
                isMissingToken(this.token) ?
                null : this.token;
        if (firstChildToken!=null &&
                (token==null ||
                firstChildToken.getTokenIndex()<token.getTokenIndex())) {
            token = firstChildToken;
        }
		return token;
    }

    private Token getLastChildToken() {
		Token token=this.endToken==null ||
		        //the tokens ANTLR inserts to represent missing tokens
		        //don't come with useful offset information
		        isMissingToken(endToken) ?
				this.token : this.endToken;
        if (lastChildToken!=null &&
                (token==null ||
                lastChildToken.getTokenIndex()>token.getTokenIndex())) {
            token = lastChildToken;
        }
		return token;
    }

    public Token getEndToken() {
    	return getLastChildToken();
	}

    public void setToken(Token token) {
        this.token = token;
    }

    public void setEndToken(Token endToken) {
        //the tokens ANTLR inserts to represent missing tokens
        //don't come with useful offset information
        if (endToken==null || !isMissingToken(endToken)) {
            this.endToken = endToken;
        }
	}

    /**
     * The compilation errors belonging to this node.
     */
    public List<Message> getErrors() {
        return errors != null ?
                errors : Collections.<Message>emptyList();
    }

    public void addError(Message error){
        if (errors == null) {
            errors = new ArrayList<Message>(2);
        }
        errors.add(error);
    }

    public void addError(String message) {
        addError( new AnalysisError(this, message) );
    }

    public void addError(String message, Backend backend) {
        addError( new AnalysisError(this, message, backend) );
    }

    public void addError(String message, int code) {
        addError( new AnalysisError(this, message, code) );
    }

    public void addError(String message, int code, Backend backend) {
        addError( new AnalysisError(this, message, code, backend) );
    }

    public void addUnexpectedError(String message) {
        addError( new UnexpectedError(this, message) );
    }

    public void addUnexpectedError(String message, Backend backend) {
        addError( new UnexpectedError(this, message, backend) );
    }

    public void addUnsupportedError(String message) {
        addError( new UnsupportedError(this, message) );
    }

    public void addUnsupportedError(String message, Backend backend) {
        addError( new UnsupportedError(this, message, backend) );
    }

    public <E extends Enum<E>> void addUsageWarning
            (E warningName, String message) {
        addError( new UsageWarning(this, message,
                warningName.toString()) );
    }

    public <E extends Enum<E>> void addUsageWarning
            (E warningName, String message, Backend backend) {
        addError( new UsageWarning(this, message,
                warningName.toString(), backend) );
    }

    public void addParseError(ParseError error) {
        addError(error);
    }

    public void addLexError(LexError error) {
        addError(error);
    }

    public abstract void visit(Visitor visitor);

    public abstract void visitChildren(Visitor visitor);

    @Override
    public String toString() {
        StringWriter w = new StringWriter();
        PrintVisitor pv = new PrintVisitor(w);
        pv.visitAny(this);
        return w.toString();
        //return getClass().getSimpleName() + "(" + text + ")";
    }

    public String getNodeType() {
        return getClass().getSimpleName();
    }

    public void handleException(Exception e, Visitor visitor) {
        addUnexpectedError(getMessage(e, visitor));
    }

    public String getMessage(Exception e, Visitor visitor) {
		return "the '" + visitor.getClass().getSimpleName() +
		        "' caused an exception visiting a '" +
		        getNodeType() + "' node: '\"" + e + "\"'" +
		        getLocationInfo(e);
	}

	private String getLocationInfo(Exception e) {
		return e.getStackTrace().length==0 ? "" :
		    " at '" + e.getStackTrace()[0].toString() + "'";
	}

	public void connect(Node child) {
		if (child!=null) {
			Token childFirstChildToken = child.getFirstChildToken();
            if (childFirstChildToken!=null &&
                    (firstChildToken==null ||
			        childFirstChildToken.getTokenIndex()<firstChildToken.getTokenIndex())) {
			    firstChildToken = childFirstChildToken;
			}
            Token childLastChildToken = child.getLastChildToken();
            if (childLastChildToken!=null &&
                    (lastChildToken==null ||
                    childLastChildToken.getTokenIndex()>lastChildToken.getTokenIndex())) {
                lastChildToken = childLastChildToken;
            }
		}
	}

}


text:
namespace LemonStorage.Classes.Mobiles
{
    using LemonStorage.Interfaces;
    using System;

    public abstract class Mobile : Product, IMobiles, IProduct, ISavable
    {
        private string processor;
        private double displaySize;
        private double camInMPix;
        private uint ram;
        private uint rom;

        //constructor
        public Mobile(decimal price, string brand, string model, string color, string processor,
                      double displaySize, double camInMPix, uint ram, uint rom)
            : base(price, brand, model, color)
        {
            this.Processor = processor;
            this.DisplaySize = displaySize;
            this.CamInMPix = camInMPix;
            this.Ram = ram;
            this.Rom = rom;
        }

        //properties
        public string Processor
        {
            get
            {
                return this.processor;
            }
            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    throw new System.ArgumentException("Processor can not be empty");
                }
                this.processor = value;
            }
        }

        public double DisplaySize
        {
            get
            {
                return this.displaySize;
            }
            set
            {
                if (value <= 0)
                {
                    throw new System.ArgumentException("Display size can not be less or equal to zero");
                }
                this.displaySize = value;
            }
        }

        public double CamInMPix
        {
            get
            {
                return this.camInMPix;
            }
            set
            {
                if (value <= 0)
                {
                    throw new System.ArgumentException("Camera megapixels can not be less or equal to zero");
                }
                this.camInMPix = value;
            }
        }

        public uint Ram
        {
            get
            {
                return this.ram;
            }
            set
            {
                if (value <= 0)
                {
                    throw new System.ArgumentException("Ram memory can not be less or equal to zero");
                }
                this.ram = value;
            }
        }

        public uint Rom
        {
            get
            {
                return this.rom;
            }
            set
            {
                if (value <= 0)
                {
                    throw new System.ArgumentException("Rom memory can not be less or equal to zero");
                }
                this.rom = value;
            }
        }
    }
}


text:
/* ******************* Our very own fake ticket ******************* */
typedef struct fake_ticket
	{
	char	szNetID[40]	;			// Net ID
	char	szTicket[256] ;		// NetID and password, separated by a ','
	long	lTimeAcquired ;		// time ticket was acquired
	long	lTimeExpires ;			// time ticket expires
	WORD	iLifeTime ;				// lifetime of ticket
	BOOL	bAuthenticated ;		// did we pass the authentication test?
	}	FAKETICKET ;

typedef  FAKETICKET FAR * LPFAKETICKET ;

/* ******************* Kerberos specific typdefs ******************* */
#define	RET_TKFIL		21       /* Can't read ticket file */
#define	ANAME_SZ			40
#define	REALM_SZ       40
#define	SNAME_SZ       40
#define	INST_SZ        40
#define	MAX_KTXT_LEN 1250
#define	MAX_K_NAME_SZ	(ANAME_SZ + INST_SZ + REALM_SZ + 2)

typedef unsigned char des_cblock[8];    /* crypto-block size */
#define C_Block des_cblock

typedef struct ktext
	{
	WORD	length ;								/* Length of the text */
	unsigned char dat[MAX_KTXT_LEN] ;	/* The data itself */
	unsigned long mbz ;						/* zero to catch runaway strings */
	} KTEXT_ST ;

typedef struct ktext FAR * KTEXT ;

typedef struct credentials
	{
   char	service[ANAME_SZ] ;	/* Service name */
   char	instance[INST_SZ] ;  /* Instance */
   char	realm[REALM_SZ] ;    /* Auth domain */
   C_Block session ;          /* Session key */
   WORD	lifetime ;           /* Lifetime */
   WORD		kvno ;               /* Key version number */
   KTEXT_ST ticket_st ;       /* The ticket itself */
   long	issue_date ;         /* The issue time */
   char	pname[ANAME_SZ] ;    /* Principal's name */
   char 	pinst[INST_SZ] ;     /* Principal's instance */
	} CREDENTIALS ;

typedef CREDENTIALS FAR * LPCREDENTIALS ;

typedef struct ticketinfo
	{
	char	principal[MAX_K_NAME_SZ] ;	/* Principal name/instance/realm */
	WORD	btickets ;				 		/* Do we have tickets? */
	long	lifetime ;						/* Lifetime -- needs to have room for 255 5-minute periods * 5 * 60 */
	long	issue_date ;					/* The issue time */
	} TICKETINFO ;

#if defined(_WIN32)
/* unfortunately the 32-bit compiler doesn't allow a function */
/* to be declared as __stdcall AND __declspec(dllexport), so  */
/* I have to use a .def file for the export part */
#define KL_CALLTYPE __stdcall
#define KL_EXPORT
#else
#define KL_CALLTYPE WINAPI
#define KL_EXPORT _export
#endif

#if defined(_WIN32)
#define _fstrcspn  strcspn
#define _fstrnicmp  strnicmp
#define _fstrlen  strlen
#define _fstrncat strncat
#define _fstricmp stricmp
#define _fstrcmp strcmp
#define _fstrcpy strcpy
#define _fstrcat strcat
#define _fstrchr strchr
#define _fmemmove memmove
#define _fmemset memset
#define _fmemcpy memcpy
#endif


text:
package de.knightsoftnet.validators.shared;

import de.knightsoftnet.validators.shared.impl.IbanValidator;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.OverridesAttribute;
import javax.validation.Payload;

/**
 * The annotated element must be a valid International Bank Account Number.

 * Supported types are Strings, other Objects are transfered to Strings, null elements
 * are considered valid. Whitespaces as separators are allowed when ignoreWhitspaces is
 * set to true.

 * There are format, size, SEPA country and checksum tests by apache commons validation routines.
 *
 * @author Manfred Tremmel
 *
 */
@Documented
@Constraint(validatedBy = IbanValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE,
    ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@SizeWithoutSeparators(min = IbanValidator.IBAN_LENGTH_MIN, max = IbanValidator.IBAN_LENGTH_MAX)
public @interface Iban {
  /**
   * localized message.
   *
   * @return localized validation message
   */
  String message() default "{deKnightsoftnetValidatorsSharedValidationIbanMessage}";

  /**
   * groups to use.
   *
   * @return array of validation groups
   */
  Class<?>[] groups() default {};

  /**
   * payload whatever.
   *
   * @return payload class
   */
  Class<? extends Payload>[] payload() default {};

  /**
   * should whitespaces be ignored (true/false).
   *
   * @return true if separators should be ignored
   */
  @OverridesAttribute(constraint = SizeWithoutSeparators.class, name = "ignoreWhiteSpaces")
  boolean ignoreWhitspaces() default false;

  /**
   * Defines several {@code @Iban} annotations on the same element.
   */
  @Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE,
      ElementType.CONSTRUCTOR, ElementType.PARAMETER})
  @Retention(RetentionPolicy.RUNTIME)
  @Documented
  @interface List {
    /**
     * iban value.
     *
     * @return value
     */
    Iban[] value();
  }
}


text:
<include file="Public:head"/>

<link rel="stylesheet" type="text/css" href="{Saivi::RES}/css/cymain.css" />

 <link rel="stylesheet" href="{Saivi::STATICS}/kindeditor/themes/default/default.css" />

<link rel="stylesheet" href="{Saivi::STATICS}/kindeditor/plugins/code/prettify.css" />

店铺信息

<form method="post" action="">

<if condition="($parentid neq  '0') and ($parentid neq '')">$token,'parentid'=>$parentCat['parentid']))}" class="btnGreen" style="margin-top:-27px">返回上</if>

</form>

<if condition="$set.catid neq ''">
$token))}">更新信息
</if>

$token))}">店铺信息

$token,'dining'=>1))}">菜品管理

$token,'dining'=>1))}">菜品分类管理

$token,'dining'=>1))}">订单管理

$token,'dining'=>1))}">桌台管理

$token,'infotype'=>'Dining'))}">订餐回复配置

 <form class="form" method="post" id="form" action="">

<if condition="$set.catid neq ''">

<input type="hidden" name="id" value="{Saivi:$set.id}" />

</if>

<input type="hidden" name="discount" id="discount" value="{Saivi:$set.discount}" />

        *店铺选择:

          <select name="catid" class="px require" style="width:400px;" >

         <volist name="Company" id="t">

        <option  value="{Saivi:$t.id}">{Saivi:$t.name}</option>

        </volist>

        </select>

        店铺公告:

        <input type="text" id="bulletin" name="bulletin" value="{Saivi:$set.bulletin}" placeholder="如:店铺最新优惠:买10元送1元 " class="px require" style="width:400px;" />

        店铺状态:

        <select name="status" class="px require" style="width:400px;" >

        <option value="0" <if condition="$set.status eq 0">selected</if>>营业中</option>

        <option value="1" <if condition="$set.status eq 1"> selected</if>>未营业</option></select>

        店铺类型:

        <input type="text" id="category" name="category" value="{Saivi:$set.category}" placeholder="如:小吃、快餐 " class="px require" style="width:400px;" />

        营业时间:

        <input type="text" id="time" name="time" value="{Saivi:$set.time}" placeholder="如:8:00~22:00 " class="px require" style="width:400px;" />

        起送价格:

        <input type="text" id="money" name="money" value="{Saivi:$set.money}" placeholder="请填写数字,如50,仅保留小数点后2位 " class="px require" style="width:400px;" />

        服务半径:

        <input type="text" id="radius" name="radius" value="{Saivi:$set.radius}" placeholder="如:3公里   "  class="px require" style="width:400px;" />

        配送区域:

        <input type="text" id="scope" name="scope" value="{Saivi:$set.scope}" placeholder="如:置地大道等   "   class="px require" style="width:400px;" />

       <if condition="$isBranch eq 1">

      <input type="hidden" name="isbranch" value="1" />

      </if>

      <input type="hidden" name="token" value="{Saivi::$token}" />

       <button type="submit" name="button" class="btnGreen">保存</button>

   </form>

<include file="Public:footer"/>


text:
package com.kaidad.test;

import android.test.ActivityInstrumentationTestCase2;
import com.kaidad.geo.Geo;

public class GeoAndroidActivityTest extends ActivityInstrumentationTestCase2<Geo> {

    public GeoAndroidActivityTest() {
        super(Geo.class);
    }

    public void testActivity() {
        Geo activity = getActivity();
        assertNotNull(activity);
    }
}


text:
package de.mirkosertic.bytecoder.maven;

import de.mirkosertic.bytecoder.allocator.Allocator;
import de.mirkosertic.bytecoder.backend.CompileOptions;
import de.mirkosertic.bytecoder.backend.CompileResult;
import de.mirkosertic.bytecoder.backend.CompileTarget;
import de.mirkosertic.bytecoder.backend.LLVMOptimizationLevel;
import de.mirkosertic.bytecoder.core.BytecodeArrayTypeRef;
import de.mirkosertic.bytecoder.core.BytecodeMethodSignature;
import de.mirkosertic.bytecoder.core.BytecodeObjectTypeRef;
import de.mirkosertic.bytecoder.core.BytecodePrimitiveTypeRef;
import de.mirkosertic.bytecoder.core.BytecodeTypeRef;
import de.mirkosertic.bytecoder.optimizer.KnownOptimizer;
import de.mirkosertic.bytecoder.unittest.Slf4JLogger;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;

import java.io.File;
import java.io.FileOutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

/**
 * Plugin to run Bytecoder using Maven.
 */
@Mojo(name = "compile", defaultPhase = LifecyclePhase.PROCESS_CLASSES, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME,
    requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME)
public class BytecoderMavenMojo extends AbstractMojo {

    @Parameter( defaultValue = "${project}", readonly = true )
    protected MavenProject project;

    @Parameter(defaultValue = "${project.build.outputDirectory}")
    protected File classFiles;

    /**
     * Classname with the main class to be compiled.
     */
    @Parameter(required = true)
    protected String mainClass;

    /**
     * Backend to be used, can be either js,wasm or wasm_llvm.
     */
    @Parameter(required = true, defaultValue = "js")
    protected String backend;

    /**
     * The build target directory.
     */
    @Parameter(defaultValue = "${project.build.directory}")
    protected String buildDirectory;

    /**
     * Shall debug output be generated?
     */
    @Parameter(required = false, defaultValue = "false")
    protected boolean debugOutput;

    /**
     * Shall Exception-Handling be activated?
     */
    @Parameter(required = false, defaultValue = "false")
    protected boolean enableExceptionHandling;

    /**
     * Which kind of optimization should be applied? Can be NONE, ALL or EXPERIMENTAL.
     */
    @Parameter(required = false, defaultValue = "ALL")
    protected String optimizationLevel;

    /**
     * Prefix of the generated files.
     */
    @Parameter(required = false, defaultValue = "bytecoder")
    protected String filenamePrefix;

    /**
     * Minimum number of pages for WASM memory.
     */
    @Parameter(required = false, defaultValue = "512")
    protected int wasmInitialPages;

    /**
     * Maximum number of pages for WASM memory.
     */
    @Parameter(required = false, defaultValue = "1024")
    protected int wasmMaximumPages;

    /**
     * Shall the compile result be minified?
     */
    @Parameter(required = false, defaultValue = "true")
    protected boolean minifyCompileResult;

    /**
     * Shall the Stackifier be used and the Relooper as fallback?
     */
    @Parameter(required = false, defaultValue = "false")
    protected boolean preferStackifier;

    /**
     * Which register allocator should be used? Can be linear or passthru.
     */
    @Parameter(required = false, defaultValue = "linear")
    protected String registerAllocator;

    /**
     * List of full qualified class names to be linked beside the statically referenced ones.
     */
    @Parameter(required = false)
    protected String[] additionalClassesToLink = new String[0];

    /**
     * A list of classpath resources to be included into the build.
     */
    @Parameter(required = false)
    protected String[] additionalResources = new String[0];

    /**
     * Optimization level for the LLVM backend. Generate code at different optimization levels. These correspond to the -O0, -O1, -O2, and -O3 optimization levels used by clang.
     */
    @Parameter(required = false, defaultValue = "O2")
    protected String llvmOptimizationLevel = LLVMOptimizationLevel.defaultValue().name();

    /**
     * Shall the escape analysis be enabled? Defaults to 'false'.
     */
    @Parameter(required = false, defaultValue = "false")
    protected boolean escapeAnalysisEnabled = false;

    @Override
    public void execute() throws MojoExecutionException {
        final File theBaseDirectory = new File(buildDirectory);
        final File theBytecoderDirectory = new File(theBaseDirectory, "bytecoder");
        theBytecoderDirectory.mkdirs();

        try {
            final ClassLoader theLoader = prepareClassLoader();
            final Class<?> theTargetClass = theLoader.loadClass(mainClass);

            final CompileTarget theCompileTarget = new CompileTarget(theLoader, CompileTarget.BackendType.valueOf(backend));

            final BytecodeMethodSignature theSignature = new BytecodeMethodSignature(BytecodePrimitiveTypeRef.VOID,
                    new BytecodeTypeRef[] { new BytecodeArrayTypeRef(BytecodeObjectTypeRef.fromRuntimeClass(String.class), 1) });

            final CompileOptions theOptions = new CompileOptions(new Slf4JLogger(), debugOutput, KnownOptimizer.valueOf(optimizationLevel), enableExceptionHandling, filenamePrefix, wasmInitialPages, wasmMaximumPages, minifyCompileResult, preferStackifier, Allocator.valueOf(registerAllocator), additionalClassesToLink, additionalResources, LLVMOptimizationLevel.valueOf(llvmOptimizationLevel), escapeAnalysisEnabled);
            final CompileResult theCode = theCompileTarget.compile(theOptions, theTargetClass, "main", theSignature);
            for (final CompileResult.Content content : theCode.getContent()) {
                final File theBytecoderFileName = new File(theBytecoderDirectory, content.getFileName());
                try (final FileOutputStream theFos = new FileOutputStream(theBytecoderFileName)) {
                    content.writeTo(theFos);
                }
            }

        } catch (final Exception e) {
            throw new MojoExecutionException("Error running bytecoder", e);
        }
    }

    protected boolean isSupportedScope(final String scope) {
        switch (scope) {
        case Artifact.SCOPE_COMPILE:
        case Artifact.SCOPE_PROVIDED:
        case Artifact.SCOPE_SYSTEM:
            return true;
        default:
            return false;
        }
    }

    protected final ClassLoader prepareClassLoader() throws MojoExecutionException {
        try {
            final List<URL> theURLs = new ArrayList<>();
            for (final Artifact artifact : project.getArtifacts()) {
                if (!isSupportedScope(artifact.getScope())) {
                    continue;
                }
                final File file = artifact.getFile();
                theURLs.add(file.toURI().toURL());
            }
            theURLs.add(classFiles.toURI().toURL());

            return new URLClassLoader(theURLs.toArray(new URL[0]),
                    getClass().getClassLoader());
        } catch (final MalformedURLException e) {
            throw new MojoExecutionException("Cannot create classloader", e);
        }
    }
}


text:
<?php

	$btThemeObj->addHeadItem("twitch-css", "<link rel='stylesheet' type='text/css' href='".MAIN_ROOT."plugins/twitch/twitch.css.php'>");

	function setupStreamPage() {
		global $mysqli, $hooksObj;
		$memberObj = new Member($mysqli);
		$returnVal = false;
		if($memberObj->select($_GET['user'])) {

			$streamTitle = $memberObj->get_info_filtered("username")."'s Stream";
			$hooksObj->addHook("breadcrumb", "setStreamPageBreadcrumb", array($streamTitle));
			$returnVal = true;
		}

		return $returnVal;
	}

	function setStreamPageBreadcrumb($breadcrumbTitle) {
		global $breadcrumbObj;

		$breadcrumbObj->setTitle($breadcrumbTitle);

		$breadcrumbObj->popCrumb();
		$breadcrumbObj->addCrumb("Twitch Streams", MAIN_ROOT."plugins/twitch");
		$breadcrumbObj->addCrumb($breadcrumbTitle);

	}

?>


text:
using System;

namespace Jasper.Http.Routing
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
    public class RouteNameAttribute : Attribute
    {
        public RouteNameAttribute(string name)
        {
            Name = name;
        }

        public string Name { get; }
    }
}


text:
using namespace llvm;

#define DEBUG_TYPE "divergence"

// transparently use the GPUDivergenceAnalysis
static cl::opt<bool> UseGPUDA("use-gpu-divergence-analysis", cl::init(false),
                              cl::Hidden,
                              cl::desc("turn the LegacyDivergenceAnalysis into "
                                       "a wrapper for GPUDivergenceAnalysis"));

namespace {

class DivergencePropagator {
public:
  DivergencePropagator(Function &F, TargetTransformInfo &TTI, DominatorTree &DT,
                       PostDominatorTree &PDT, DenseSet<const Value *> &DV,
                       DenseSet<const Use *> &DU)
      : F(F), TTI(TTI), DT(DT), PDT(PDT), DV(DV), DU(DU) {}
  void populateWithSourcesOfDivergence();
  void propagate();

private:
  // A helper function that explores data dependents of V.
  void exploreDataDependency(Value *V);
  // A helper function that explores sync dependents of TI.
  void exploreSyncDependency(Instruction *TI);
  // Computes the influence region from Start to End. This region includes all
  // basic blocks on any simple path from Start to End.
  void computeInfluenceRegion(BasicBlock *Start, BasicBlock *End,
                              DenseSet<BasicBlock *> &InfluenceRegion);
  // Finds all users of I that are outside the influence region, and add these
  // users to Worklist.
  void findUsersOutsideInfluenceRegion(
      Instruction &I, const DenseSet<BasicBlock *> &InfluenceRegion);

  Function &F;
  TargetTransformInfo &TTI;
  DominatorTree &DT;
  PostDominatorTree &PDT;
  std::vector<Value *> Worklist; // Stack for DFS.
  DenseSet<const Value *> &DV;   // Stores all divergent values.
  DenseSet<const Use *> &DU;   // Stores divergent uses of possibly uniform
                               // values.
};

void DivergencePropagator::populateWithSourcesOfDivergence() {
  Worklist.clear();
  DV.clear();
  DU.clear();
  for (auto &I : instructions(F)) {
    if (TTI.isSourceOfDivergence(&I)) {
      Worklist.push_back(&I);
      DV.insert(&I);
    }
  }
  for (auto &Arg : F.args()) {
    if (TTI.isSourceOfDivergence(&Arg)) {
      Worklist.push_back(&Arg);
      DV.insert(&Arg);
    }
  }
}

void DivergencePropagator::exploreSyncDependency(Instruction *TI) {
  // Propagation rule 1: if branch TI is divergent, all PHINodes in TI's
  // immediate post dominator are divergent. This rule handles if-then-else
  // patterns. For example,
  //
  // if (tid < 5)
  //   a1 = 1;
  // else
  //   a2 = 2;
  // a = phi(a1, a2); // sync dependent on (tid < 5)
  BasicBlock *ThisBB = TI->getParent();

  // Unreachable blocks may not be in the dominator tree.
  if (!DT.isReachableFromEntry(ThisBB))
    return;

  // If the function has no exit blocks or doesn't reach any exit blocks, the
  // post dominator may be null.
  DomTreeNode *ThisNode = PDT.getNode(ThisBB);
  if (!ThisNode)
    return;

  BasicBlock *IPostDom = ThisNode->getIDom()->getBlock();
  if (IPostDom == nullptr)
    return;

  for (auto I = IPostDom->begin(); isa<PHINode>(I); ++I) {
    // A PHINode is uniform if it returns the same value no matter which path is
    // taken.
    if (!cast<PHINode>(I)->hasConstantOrUndefValue() && DV.insert(&*I).second)
      Worklist.push_back(&*I);
  }

  // Propagation rule 2: if a value defined in a loop is used outside, the user
  // is sync dependent on the condition of the loop exits that dominate the
  // user. For example,
  //
  // int i = 0;
  // do {
  //   i++;
  //   if (foo(i)) ... // uniform
  // } while (i < tid);
  // if (bar(i)) ...   // divergent
  //
  // A program may contain unstructured loops. Therefore, we cannot leverage
  // LoopInfo, which only recognizes natural loops.
  //
  // The algorithm used here handles both natural and unstructured loops.  Given
  // a branch TI, we first compute its influence region, the union of all simple
  // paths from TI to its immediate post dominator (IPostDom). Then, we search
  // for all the values defined in the influence region but used outside. All
  // these users are sync dependent on TI.
  DenseSet<BasicBlock *> InfluenceRegion;
  computeInfluenceRegion(ThisBB, IPostDom, InfluenceRegion);
  // An insight that can speed up the search process is that all the in-region
  // values that are used outside must dominate TI. Therefore, instead of
  // searching every basic blocks in the influence region, we search all the
  // dominators of TI until it is outside the influence region.
  BasicBlock *InfluencedBB = ThisBB;
  while (InfluenceRegion.count(InfluencedBB)) {
    for (auto &I : *InfluencedBB) {
      if (!DV.count(&I))
        findUsersOutsideInfluenceRegion(I, InfluenceRegion);
    }
    DomTreeNode *IDomNode = DT.getNode(InfluencedBB)->getIDom();
    if (IDomNode == nullptr)
      break;
    InfluencedBB = IDomNode->getBlock();
  }
}

void DivergencePropagator::findUsersOutsideInfluenceRegion(
    Instruction &I, const DenseSet<BasicBlock *> &InfluenceRegion) {
  for (Use &Use : I.uses()) {
    Instruction *UserInst = cast<Instruction>(Use.getUser());
    if (!InfluenceRegion.count(UserInst->getParent())) {
      DU.insert(&Use);
      if (DV.insert(UserInst).second)
        Worklist.push_back(UserInst);
    }
  }
}

// A helper function for computeInfluenceRegion that adds successors of "ThisBB"
// to the influence region.
static void
addSuccessorsToInfluenceRegion(BasicBlock *ThisBB, BasicBlock *End,
                               DenseSet<BasicBlock *> &InfluenceRegion,
                               std::vector<BasicBlock *> &InfluenceStack) {
  for (BasicBlock *Succ : successors(ThisBB)) {
    if (Succ != End && InfluenceRegion.insert(Succ).second)
      InfluenceStack.push_back(Succ);
  }
}

void DivergencePropagator::computeInfluenceRegion(
    BasicBlock *Start, BasicBlock *End,
    DenseSet<BasicBlock *> &InfluenceRegion) {
  assert(PDT.properlyDominates(End, Start) &&
         "End does not properly dominate Start");

  // The influence region starts from the end of "Start" to the beginning of
  // "End". Therefore, "Start" should not be in the region unless "Start" is in
  // a loop that doesn't contain "End".
  std::vector<BasicBlock *> InfluenceStack;
  addSuccessorsToInfluenceRegion(Start, End, InfluenceRegion, InfluenceStack);
  while (!InfluenceStack.empty()) {
    BasicBlock *BB = InfluenceStack.back();
    InfluenceStack.pop_back();
    addSuccessorsToInfluenceRegion(BB, End, InfluenceRegion, InfluenceStack);
  }
}

void DivergencePropagator::exploreDataDependency(Value *V) {
  // Follow def-use chains of V.
  for (User *U : V->users()) {
    if (!TTI.isAlwaysUniform(U) && DV.insert(U).second)
      Worklist.push_back(U);
  }
}

void DivergencePropagator::propagate() {
  // Traverse the dependency graph using DFS.
  while (!Worklist.empty()) {
    Value *V = Worklist.back();
    Worklist.pop_back();
    if (Instruction *I = dyn_cast<Instruction>(V)) {
      // Terminators with less than two successors won't introduce sync
      // dependency. Ignore them.
      if (I->isTerminator() && I->getNumSuccessors() > 1)
        exploreSyncDependency(I);
    }
    exploreDataDependency(V);
  }
}

} // namespace

// Register this pass.
char LegacyDivergenceAnalysis::ID = 0;
INITIALIZE_PASS_BEGIN(LegacyDivergenceAnalysis, "divergence",
                      "Legacy Divergence Analysis", false, true)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
INITIALIZE_PASS_END(LegacyDivergenceAnalysis, "divergence",
                    "Legacy Divergence Analysis", false, true)

FunctionPass *llvm::createLegacyDivergenceAnalysisPass() {
  return new LegacyDivergenceAnalysis();
}

void LegacyDivergenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
  AU.addRequired<DominatorTreeWrapperPass>();
  AU.addRequired<PostDominatorTreeWrapperPass>();
  if (UseGPUDA)
    AU.addRequired<LoopInfoWrapperPass>();
  AU.setPreservesAll();
}

bool LegacyDivergenceAnalysis::shouldUseGPUDivergenceAnalysis(
    const Function &F) const {
  if (!UseGPUDA)
    return false;

  // GPUDivergenceAnalysis requires a reducible CFG.
  auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  using RPOTraversal = ReversePostOrderTraversal<const Function *>;
  RPOTraversal FuncRPOT(&F);
  return !containsIrreducibleCFG<const BasicBlock *, const RPOTraversal,
                                 const LoopInfo>(FuncRPOT, LI);
}

bool LegacyDivergenceAnalysis::runOnFunction(Function &F) {
  auto *TTIWP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
  if (TTIWP == nullptr)
    return false;

  TargetTransformInfo &TTI = TTIWP->getTTI(F);
  // Fast path: if the target does not have branch divergence, we do not mark
  // any branch as divergent.
  if (!TTI.hasBranchDivergence())
    return false;

  DivergentValues.clear();
  DivergentUses.clear();
  gpuDA = nullptr;

  auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();

  if (shouldUseGPUDivergenceAnalysis(F)) {
    // run the new GPU divergence analysis
    auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
    gpuDA = std::make_unique<GPUDivergenceAnalysis>(F, DT, PDT, LI, TTI);

  } else {
    // run LLVM's existing DivergenceAnalysis
    DivergencePropagator DP(F, TTI, DT, PDT, DivergentValues, DivergentUses);
    DP.populateWithSourcesOfDivergence();
    DP.propagate();
  }

  LLVM_DEBUG(dbgs() << "\nAfter divergence analysis on " << F.getName()
                    << ":\n";
             print(dbgs(), F.getParent()));

  return false;
}

bool LegacyDivergenceAnalysis::isDivergent(const Value *V) const {
  if (gpuDA) {
    return gpuDA->isDivergent(*V);
  }
  return DivergentValues.count(V);
}

bool LegacyDivergenceAnalysis::isDivergentUse(const Use *U) const {
  if (gpuDA) {
    return gpuDA->isDivergentUse(*U);
  }
  return DivergentValues.count(U->get()) || DivergentUses.count(U);
}

void LegacyDivergenceAnalysis::print(raw_ostream &OS, const Module *) const {
  if ((!gpuDA || !gpuDA->hasDivergence()) && DivergentValues.empty())
    return;

  const Function *F = nullptr;
  if (!DivergentValues.empty()) {
    const Value *FirstDivergentValue = *DivergentValues.begin();
    if (const Argument *Arg = dyn_cast<Argument>(FirstDivergentValue)) {
      F = Arg->getParent();
    } else if (const Instruction *I =
                   dyn_cast<Instruction>(FirstDivergentValue)) {
      F = I->getParent()->getParent();
    } else {
      llvm_unreachable("Only arguments and instructions can be divergent");
    }
  } else if (gpuDA) {
    F = &gpuDA->getFunction();
  }
  if (!F)
    return;

  // Dumps all divergent values in F, arguments and then instructions.
  for (auto &Arg : F->args()) {
    OS << (isDivergent(&Arg) ? "DIVERGENT: " : "           ");
    OS << Arg << "\n";
  }
  // Iterate instructions using instructions() to ensure a deterministic order.
  for (auto BI = F->begin(), BE = F->end(); BI != BE; ++BI) {
    auto &BB = *BI;
    OS << "\n           " << BB.getName() << ":\n";
    for (auto &I : BB.instructionsWithoutDebug()) {
      OS << (isDivergent(&I) ? "DIVERGENT:     " : "               ");
      OS << I << "\n";
    }
  }
  OS << "\n";
}


text:
package io.smartlogic.smartchat.data;

import android.content.UriMatcher;
import android.net.Uri;

import io.smartlogic.smartchat.Constants;

public class DataUriManager {
    public static final Uri CONTENT_URI = Uri.parse("content://" + Constants.AUTHORITY + "/");

    protected static final int FRIENDS = 1;
    protected static final int FRIENDS_ID = 2;

    protected static final int NOTIFICATIONS = 3;
    protected static final int NOTIFICATIONS_ID = 4;

    private static final UriMatcher uriMatcher;

    static {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

        uriMatcher.addURI(Constants.AUTHORITY, "friends", FRIENDS);
        uriMatcher.addURI(Constants.AUTHORITY, "friends/#", FRIENDS_ID);

        uriMatcher.addURI(Constants.AUTHORITY, "notifications/", NOTIFICATIONS);
        uriMatcher.addURI(Constants.AUTHORITY, "notifications/#", NOTIFICATIONS_ID);
    }

    public static int match(Uri uri) {
        return uriMatcher.match(uri);
    }

    public static Uri getFriendsUri() {
        Uri.Builder builder = CONTENT_URI.buildUpon();
        builder.appendPath("friends");
        return builder.build();
    }

    public static Uri getFriendUri(long id) {
        Uri.Builder builder = getFriendsUri().buildUpon();
        builder.appendPath(String.valueOf(id));
        return builder.build();
    }

    public static Uri getNotificationsUri() {
        Uri.Builder builder = CONTENT_URI.buildUpon();
        builder.appendPath("notifications");
        return builder.build();
    }

    public static Uri getNotificationUri(long id) {
        Uri.Builder builder = getNotificationsUri().buildUpon();
        builder.appendPath(String.valueOf(id));
        return builder.build();
    }
}


text:
#import <Cocoa/Cocoa.h>

extern NSString *NSStringFromDragOperation(NSDragOperation operation);

@interface NSArrayController (ObjectExchange)

- (NSDictionary *) optionsWithEntityNameFromOptions: (NSDictionary *) options;

- (NSArray *) objectExchangeUTIsWithOptions: (NSDictionary *) options;

- (BOOL) isSortedByDescendingKey: (NSString *) key;

- (BOOL) writeObjectsAtIndexes: (NSIndexSet *) indexes toPasteboard: (NSPasteboard *) pasteboard options: (NSDictionary *) options;
- (BOOL) writeSelectionToPasteboard: (NSPasteboard *) pasteboard options: (NSDictionary *) options;

#if UNTESTED_CODE
- (BOOL) setValuesForKeyPaths: (NSArray *) keyPaths fromPasteboard: (NSPasteboard *) pboard options: (NSDictionary *) options error: (NSError **) outError;
#endif

- (BOOL) insertFromPasteboard: (NSPasteboard *) pboard options: (NSDictionary *) options error: (NSError **) outError;

- (BOOL) performDragOperation: (NSDragOperation) dragOperation fromPasteboard: (NSPasteboard *) pboard beforeIndex: (NSInteger) destinationIndex options: (NSDictionary *) options error: (NSError **) outError;

// triggered by kObjectExchangeViewPositionKeyPath in options to performDragOperation
- (void) updateViewPositionsOfObjects: (NSArray *) array usingKeyPath: (NSString *) keyPath;

// triggered by kObjectExchangeNameToChangeOnCopyKeyPath in options to performDragOperation
- (void) updateNamesOfObjects: (NSArray *) newObjects usingKeyPath: (NSString *) keyPath avoidingCollisionsWithExistingObjects: (NSArray *) existingObjects;

@end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.16"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Wizard Parser: Пространство имен thewizardplusplus::wizard_parser::exceptions</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Wizard Parser
    v4.4

LL(*)-парсер на C++ с поддержкой DSL для описания грамматики в EBNF непосредственно в коде программы

thewizardplusplus

wizard_parser

exceptions

Классы |
Определения типов

Пространство имен thewizardplusplus::wizard_parser::exceptions

Классы

struct  	base_unexpected_entity_exception

struct  	positional_exception

Определения типов

template<entity_type::_integral type>

using 	unexpected_entity_exception = base_unexpected_entity_exception< entity_type, type >

Типы

◆ unexpected_entity_exception

template<entity_type::_integral type>

          using thewizardplusplus::wizard_parser::exceptions::unexpected_entity_exception = typedef base_unexpected_entity_exception<entity_type, type>

<address class="footer">
Документация по Wizard Parser. Последние изменения: Вт 25 Июн 2019 04:16:35. Создано системой

 1.8.16
</address>


text:
using System.Diagnostics;
using System.Dynamic.Utils;

namespace System.Linq.Expressions.Interpreter
{
    internal abstract class DivInstruction : Instruction
    {
        private static Instruction s_Int16, s_Int32, s_Int64, s_UInt16, s_UInt32, s_UInt64, s_Single, s_Double;

        public override int ConsumedStack => 2;
        public override int ProducedStack => 1;
        public override string InstructionName => "Div";

        private DivInstruction() { }

        private sealed class DivInt16 : DivInstruction
        {
            public override int Run(InterpretedFrame frame)
            {
                int index = frame.StackIndex;
                object[] stack = frame.Data;
                object left = stack[index - 2];
                if (left != null)
                {
                    object right = stack[index - 1];
                    stack[index - 2] = right == null ? null : (object)unchecked((short)((short)left / (short)right));
                }

                frame.StackIndex = index - 1;
                return 1;
            }
        }

        private sealed class DivInt32 : DivInstruction
        {
            public override int Run(InterpretedFrame frame)
            {
                int index = frame.StackIndex;
                object[] stack = frame.Data;
                object left = stack[index - 2];
                if (left != null)
                {
                    object right = stack[index - 1];
                    stack[index - 2] = right == null ? null : ScriptingRuntimeHelpers.Int32ToObject((int)left / (int)right);
                }

                frame.StackIndex = index - 1;
                return 1;
            }
        }

        private sealed class DivInt64 : DivInstruction
        {
            public override int Run(InterpretedFrame frame)
            {
                int index = frame.StackIndex;
                object[] stack = frame.Data;
                object left = stack[index - 2];
                if (left != null)
                {
                    object right = stack[index - 1];
                    stack[index - 2] = right == null ? null : (object)((long)left / (long)right);
                }

                frame.StackIndex = index - 1;
                return 1;
            }
        }

        private sealed class DivUInt16 : DivInstruction
        {
            public override int Run(InterpretedFrame frame)
            {
                int index = frame.StackIndex;
                object[] stack = frame.Data;
                object left = stack[index - 2];
                if (left != null)
                {
                    object right = stack[index - 1];
                    stack[index - 2] = right == null ? null : (object)unchecked((ushort)((ushort)left / (ushort)right));
                }

                frame.StackIndex = index - 1;
                return 1;
            }
        }

        private sealed class DivUInt32 : DivInstruction
        {
            public override int Run(InterpretedFrame frame)
            {
                int index = frame.StackIndex;
                object[] stack = frame.Data;
                object left = stack[index - 2];
                if (left != null)
                {
                    object right = stack[index - 1];
                    stack[index - 2] = right == null ? null : (object)((uint)left / (uint)right);
                }

                frame.StackIndex = index - 1;
                return 1;
            }
        }

        private sealed class DivUInt64 : DivInstruction
        {
            public override int Run(InterpretedFrame frame)
            {
                int index = frame.StackIndex;
                object[] stack = frame.Data;
                object left = stack[index - 2];
                if (left != null)
                {
                    object right = stack[index - 1];
                    stack[index - 2] = right == null ? null : (object)((ulong)left / (ulong)right);
                }

                frame.StackIndex = index - 1;
                return 1;
            }
        }

        private sealed class DivSingle : DivInstruction
        {
            public override int Run(InterpretedFrame frame)
            {
                int index = frame.StackIndex;
                object[] stack = frame.Data;
                object left = stack[index - 2];
                if (left != null)
                {
                    object right = stack[index - 1];
                    stack[index - 2] = right == null ? null : (object)((float)left / (float)right);
                }

                frame.StackIndex = index - 1;
                return 1;
            }
        }

        private sealed class DivDouble : DivInstruction
        {
            public override int Run(InterpretedFrame frame)
            {
                int index = frame.StackIndex;
                object[] stack = frame.Data;
                object left = stack[index - 2];
                if (left != null)
                {
                    object right = stack[index - 1];
                    stack[index - 2] = right == null ? null : (object)((double)left / (double)right);
                }

                frame.StackIndex = index - 1;
                return 1;
            }
        }

        public static Instruction Create(Type type)
        {
            Debug.Assert(!type.IsEnum);
            return type.GetNonNullableType().GetTypeCode() switch
            {
                TypeCode.Int16 => s_Int16 ?? (s_Int16 = new DivInt16()),
                TypeCode.Int32 => s_Int32 ?? (s_Int32 = new DivInt32()),
                TypeCode.Int64 => s_Int64 ?? (s_Int64 = new DivInt64()),
                TypeCode.UInt16 => s_UInt16 ?? (s_UInt16 = new DivUInt16()),
                TypeCode.UInt32 => s_UInt32 ?? (s_UInt32 = new DivUInt32()),
                TypeCode.UInt64 => s_UInt64 ?? (s_UInt64 = new DivUInt64()),
                TypeCode.Single => s_Single ?? (s_Single = new DivSingle()),
                TypeCode.Double => s_Double ?? (s_Double = new DivDouble()),
                _ => throw ContractUtils.Unreachable,
            };
        }
    }
}


text:
module Backup
  module Syncer
    module RSync
      class Base < Syncer::Base
        ##
        # Additional options for the rsync cli
        attr_accessor :additional_options

        ##
        # Instantiates a new RSync Syncer object
        # and sets the default configuration
        def initialize
          super

          @additional_options ||= Array.new
        end

        private

        ##
        # Returns the @directories as a space-delimited string of
        # single-quoted values for use in the `rsync` command line.
        # Each path is expanded, since these refer to local paths
        # for both RSync::Local and RSync::Push.
        # RSync::Pull does not use this method.
        def directories_option
          @directories.map do |directory|
            "'#{ File.expand_path(directory) }'"
          end.join(' ')
        end

        ##
        # Returns Rsync syntax for enabling mirroring
        def mirror_option
          '--delete' if @mirror
        end

        ##
        # Returns Rsync syntax for invoking "archive" mode
        def archive_option
          '--archive'
        end

      end
    end
  end
end


text:
qx.Class.define("qookery.internal.components.ComboBoxComponent", {

	extend: qookery.internal.components.AbstractSelectBoxComponent,

	construct: function(parentComponent) {
		this.base(arguments, parentComponent);
	},

	members: {

		// Metadata

		getAttributeType: function(attributeName) {
			switch(attributeName) {
			case "placeholder": return "ReplaceableString";
			case "text-align": return "String";
			}
			return this.base(arguments, attributeName);
		},

		// Construction

		_createMainWidget: function() {
			var comboBox = new qx.ui.form.ComboBox();
			this._applySelectBoxAttributes(comboBox);
			this._applyAttribute("placeholder", comboBox, "placeholder");
			var textField = comboBox.getChildControl("textfield");
			textField.addListener("changeValue", function(event) {
				if(this._disableValueEvents)
					return;
				var text = event.getData();
				if(text != null && text.trim().length === 0)
					text = null;
				var format = this.getFormat();
				var value = format != null ? format.parse(text) : text;
				this.getEditableWidget().setValue(this._getLabelOf(value));
				this._setValueSilently(value);
			}, this);
			this._applyAttribute("text-align", textField, "textAlign");
			return comboBox;
		},

		// Behavior

		_updateUI: function(value) {
			this.getEditableWidget().setValue(this._getLabelOf(value));
		}
	}
});


text:
export default {
  div: function(role){
    var div = document.createElement("div");
    div.dataset.role = role;
    div.classList.add(role);
    return div;
  }
}


text:
/*
 Show a simple star chart.
 If a location is present, then topocentric parallax is calculated for the Moon (and no other object).
*/
var show = function(input){

  //constants
  var NL = '\r\n'; // new line
  var DEG = '°';
  var WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  //indices into the star-messier data structure (array of items)
  var mag = 3;
  var α = 1
  var δ = 2;
  var name = 0;
  var gap = 14; //between object and associated text
  var MARGIN_DEGS = 10; //marginal stars need positions, in order to plot constellation lines that go off-canvas

  var when;
  if (input.time_scale && input.date_time && input.date_time.length > 0){
    when = EPH.when(input.time_scale + ' ' + input.date_time);
  }
  else {
    when = EPH.when_now();
  }

  /* The 'when' as input by the user in the date-time control, and as it appears in the URL. */
  var when_as_input_str = function(){
    var result = '';
    if (input.time_scale === 'LT'){
      result = when.toStringLT();
    }
    else if (input.time_scale === 'UT'){
      result = when.toStringUT();
    }
    else if (input.time_scale === 'TT'){
      result = when.toStringTT();
    }
    return result.substring(3);
  };

  var default_setting = function(name, val){
    if (typeof input[name] === "undefined" || input[name].length === 0){
      input[name] = val;
    }
  };
  var apply_default_settings_if_absent = function(){
    default_setting('place_at_top', 'north');
    default_setting('date_time', when_as_input_str());
    default_setting('time_scale', 'LT');
    default_setting('location_name', '');
    default_setting('latitude', '0');
    default_setting('longitude', '0');
    default_setting('limiting_mag', '8.0');
    default_setting('chart_width', '30');
    //default_setting('show_identifiers', ['bayer']);
    default_setting('style', 'regular');
  };
  apply_default_settings_if_absent();

  var star_positions = [];

  var opts_topocentric = {}; //the Moon needs a topocentric position, because of its parallax
  opts_topocentric.where = EPH.where(
    parseFloat(input.latitude),
    parseFloat(input.longitude),
    parseFloat(input.limiting_mag),
    true
  );
  opts_topocentric.units = 'rads';
  opts_topocentric.equinox = when; //equinox of date

  /*
   The two center-on styles, ra-decl versus object, are somewhat at odds with each other.
   When centering on an object, we need to calculate the initial center-on ra and decl, in order to play nice with controls
   that tweak the position of the center by a few degrees. Once the tweak-center controls are activated, the user has
   implicitly (and irreversibly) moved from a center-on-object style to a center-on-ra-decl style.
   SIDE-EFFECT: can override input.center_ra and input.center_dec.
  */
  var initialize_center = function(){
    var result = {}, object_found = false;
    if (input.center_object){
      ephem = EPH.position(input.center_object, when, opts_topocentric); //fails if the name is unknown
      if (ephem){
        object_found = true;
        if (input.center_object === 'Moon'){
          //needed only because the chart projection relies on ra-dec, not-alt-az
          EPH.apply_parallax_to_αδ(ephem, opts_topocentric.where);
        }
        result.α = ephem.α;
        result.δ = ephem.δ;
        input.center_ra = EPH.degs(result.α); //side-effect: keep the data 100% consistent; needed for the tweak-center controls
        input.center_dec = EPH.degs(result.δ);
      }
    }
    if (! object_found) {
      result.α = EPH.rads(parseFloat(input.center_ra));
      result.δ = EPH.rads(parseFloat(input.center_dec));
    }
    return result;
  }
  var ctr = initialize_center();

  var add_summary_blurb = function(){
    var summary = document.getElementById('summary');
    summary.innerHTML = summary.innerHTML + NL +
      '   <tr><td>' + UTIL.escapeHtml(input.location_name) +
      '<td>' + UTIL.escapeHtml(input.time_scale) + ' ' + UTIL.escapeHtml(input.date_time) +
      '<td>' +  UTIL.escapeHtml(input.latitude) + DEG +
      '<td>' +  UTIL.escapeHtml(input.longitude) + DEG +
      '<td>' +  new Date().getTimezoneOffset() + 'm'
    ;
  };
  add_summary_blurb();

  /* Needed since there's more than 1 form, whose items share names. Return the dom node under the form, whose name matches. */
  var form_child_element_by_name = function(form /*dom node*/, control_name){
    var result, i;
    for(i=0; i < form.children.length; ++i){
      if (form.children[i].name === control_name){
        result = form.children[i];
        break;
      }
    }
    return result;
  };

  var array_includes = function(item, items){
    var result = false;
    for(var i = 0; i < items.length; ++i){
      if (items[i] === item){
        result = true;
        break;
      }
    }
    return result;
  };

  /* Tweaker-controls/properties are used to tweak the URL. */
  var is_tweaker_param = function(item, tweakers){
    return array_includes(item, tweakers);
  };

  var is_array = function(value){ //Crockford p61
    return value && typeof value === 'object' && value.constructor === Array;
  };
  var add_hidden_item = function(name, form, value){
    var hidden_input = document.createElement('input');
    hidden_input.type = 'hidden';
    hidden_input.name = name; //use name, not id! there are N such forms on the page, whose items share these names
    hidden_input.value = value; //input[prop];
    form.appendChild(hidden_input);
  };
  var put_hidden_controls_into = function(form, tweakers){
    for (var prop in input){
      if (input.hasOwnProperty(prop)){
        if (!is_tweaker_param(prop, tweakers)){
          if (is_array(input[prop])){ //for a multivalued request param
            for(var i = 0; i < input[prop].length; ++i){
              add_hidden_item(prop, form, input[prop][i]);
            }
          }
          else {
            add_hidden_item(prop, form, input[prop]);
          }
        }
      }
    }
  };

  /*  Tweak the date-time of the URL. */
  var date_time_controls_init = function(){
    var form = document.getElementById('date_time_controls');
    var hidden_input, date_time_unit, num_steps, i, option, when_str, hidden_date_time, sign;
    var tweakers = ['go', 'num_steps', 'date_time_unit'];
    put_hidden_controls_into(form, tweakers);
    //prepopulate date-time controls that modify the URL by recycling req params, if present
    if (input.num_steps){
      document.getElementById('num_steps').value = input.num_steps;
    }
    if (input.date_time_unit){
       date_time_unit = document.getElementById('date_time_unit');
       for(i=0; i < date_time_unit.options.length ; ++i){
         option = date_time_unit.options[i];
         if (option.value === input.date_time_unit){
           option.selected = true;
         }
       }
    }
    form.onsubmit = function(){
      hidden_date_time = form_child_element_by_name(form, 'date_time');
      date_time_unit = document.getElementById('date_time_unit');
      num_steps = document.getElementById('num_steps');
      sign = go_plus ? 1 : -1;
      //alter the hidden date_time control to some new value
      hidden_date_time.value = EPH.date_time_odometer(hidden_date_time.value, date_time_unit.value, sign * num_steps.value);
      return true; //continue with regular form processing
    };
  };
  date_time_controls_init();

  /* Stay in range 0..360. */
  var ra_degs_constraint = function(α){
    var result = α % 360; // range -360..360
    if (result < 0) result = result + 360; // range 0..360
    return result;
  };
  /* Stop at the poles; stay in range -90..90. */
  var dec_degs_constraint = function(δ){
    var result  = Math.min(δ, 90); //stop at the poles; stay in range -90..90
    result = Math.max(result, -90);
    return result;
  };

  /*
   Tweak the center of the chart.
   If the user initially centered on an object, then that is discarded by this action, and it reverts to centering on the object's ra and decl.
   That means that the center-on-object case needs to remember the center as ra, decl, and store those numbers in the forms.
  */
  var direction_controls_init = function(){
    var form = document.getElementById('direction_controls');
    var num_degs, hidden_center_ra, hidden_center_dec, sign, op_code, num_degs_input, new_dec, new_ra;
    var tweakers = ['go', 'num_degs'];
    put_hidden_controls_into(form, tweakers);
    //if present, center_object overrides center-on-ra-dec; this form negates center_object, and reverts to center-ra-dec,
    //so we want to make sure center_object is empty
    form_child_element_by_name(form, 'center_object').value = '';
    //prepopulate controls that modify the URL by recycling req params, if present
    if (input.num_degs){
      document.getElementById('num_degs').value = input.num_degs;
    }
    form.onsubmit = function(){
      hidden_center_ra = form_child_element_by_name(form, 'center_ra');
      hidden_center_dec = form_child_element_by_name(form, 'center_dec');
      num_degs_input = document.getElementById('num_degs').value;
      num_degs = num_degs_input ? parseFloat(num_degs_input) : 0.15 * parseFloat(input.chart_width);
      op_code = go_op;
      sign = op_code % 2 ? 1 : -1;
      if (op_code <= 2){
        new_ra = parseFloat(hidden_center_ra.value)  + sign * num_degs;
        new_ra = ra_degs_constraint(new_ra);
        hidden_center_ra.value = new_ra;
      }
      else {
        new_dec = parseFloat(hidden_center_dec.value)  + sign * num_degs;
        new_dec = dec_degs_constraint(new_dec);
        hidden_center_dec.value = new_dec;
      }
      return true; //continue with regular form processing (a GET to the altered URL)
    };
  };
  direction_controls_init();

  var zoom_controls_init = function(){
    var form = document.getElementById('zoom_controls');
    var tweakers = ['go'];
    put_hidden_controls_into(form, tweakers);
    form.onsubmit = function(){
      var val, FACTOR=1.25, MIN=1, MAX=90, ABANDON=false, SUBMIT_FORM=true;
      var hidden_chart_width = form_child_element_by_name(form, 'chart_width');
      if (zoom_go_op === 1){
        val = parseFloat(hidden_chart_width.value) * FACTOR;
        val = Math.min(MAX, val);
      }
      else {
        val = parseFloat(hidden_chart_width.value) / FACTOR;
        val = Math.max(MIN, val);
      }
      if (MIN <= val && val <= MAX){
        hidden_chart_width.value = val;
        return SUBMIT_FORM; //continue with regular form processing (a GET to the altered URL)
      }
      return ABANDON;
    };
  };
  zoom_controls_init();

  var click_on = function(id){
    var item = document.getElementById(id);
    item.click();
  };
  /* Change the center of the chart using the arrow keys, in addition to a click. */
  var use_special_keys = function(){
      document.onkeydown = function(e) {
        switch (e.keyCode) {
          //arrow keys for change of center
          case 37:
              click_on('incr_w');
              break;
          case 38:
              click_on('incr_n');
              break;
          case 39:
              click_on('incr_e');
              break;
          case 40:
              click_on('incr_s');
              break;
          //page up-down for zoom in-out
          case 33:
              click_on('zoom_plus');
              break;
          case 34:
              click_on('zoom_minus');
              break;
        }
    };
  };
  use_special_keys();

  var use_scroll_wheel = function(){
    //http://stackoverflow.com/questions/14926366/mousewheel-event-in-modern-browsers
    var change_zoom = function(e){
      // cross-browser wheel delta
      var e = window.event || e; // old IE support
      var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
      if (delta > 0) {
        click_on('zoom_plus');
      }
      else {
       click_on('zoom_minus');
      }
    };
    document.addEventListener("wheel", change_zoom, false);
  };
  use_scroll_wheel();

  /* Near poles this is very sensitive to the motion, and the experience degrades a bit. */
  var use_drag_and_drop_to_recenter = function(chart){
    var canvas = document.getElementById('star_chart');
    var start = {};
    var is_down = false;
    var current_pos = function(e){
      var pos = {};
      pos.x = parseInt(e.clientX - canvas.offsetLeft);
      pos.y = parseInt(e.clientY - canvas.offsetTop);
      return pos;
    };
    var mouse_down = function(e){
      e.preventDefault();
      if (!is_down) {
        is_down = true;
        start = current_pos(e);
      }
    };
    var mouse_up = function(e){
      if (is_down){
        is_down = false;
        var stop = current_pos(e);
        var displacement = {};
        displacement.x = stop.x - start.x;
        displacement.y = stop.y - start.y;
        //console.log('Displacement ' + displacement.x + ' ' + displacement.y);
        var new_center = {}; //calc the new center coords ra-dec, and stay in range
        new_center.ra = parseFloat(input.center_ra) + EPH.degs(displacement.x / chart.pixels_per_rad);
        new_center.ra = ra_degs_constraint(new_center.ra);
        new_center.dec = parseFloat(input.center_dec) + EPH.degs(displacement.y / chart.pixels_per_rad);
        new_center.dec = dec_degs_constraint(new_center.dec);
        //somewhat dangerously, I overwrite the input object; this is reasonably safe since the page is about to be reloaded
        input.center_ra = new_center.ra;
        input.center_dec = new_center.dec;
        input.center_object = ''; // no longer centered on an object
        var new_url =  'graphic.sky' + build_href_to_form([]);
        document.location = new_url;
      }
    };
    canvas.onmousedown = mouse_down;
    canvas.onmouseup = mouse_up;
    canvas.onmouseout = mouse_up;
  };

  var append_item_to_href = function(href, name, value){
    return href + name + '=' + encodeURIComponent(value) + '&';
  };
  var build_href_to_form = function(tweakers){
    var href = '?';
    for (var prop in input){
      if (input.hasOwnProperty(prop)){
        if (!is_tweaker_param(prop, tweakers)){
          if (is_array(input[prop])){ //for a multivalued request param
            for(var i = 0; i < input[prop].length; ++i){
              href = append_item_to_href(href, prop, input[prop][i]);
            }
          }
          else {
            href = append_item_to_href(href, prop, input[prop]);
          }
        }
      }
    }
    return href;
  };
  /*
   Link back to the main form, such that current settings are preserved.
   Tweaker params are ignored. Multivalued params have special handling.
  */
  var link_back_to_main_form = function(tweakers){
    var link = document.getElementById('link_back');
    link.href = link.href + build_href_to_form(tweakers);
  };
  link_back_to_main_form(['go', 'num_degs', 'num_steps', 'date_time_unit']);

  var standard_canvas_appearance = function(ctx, use_big_font){
    if (use_big_font){
      GRAPH.myBigFont(ctx);
    }
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
  };

  var canvas_colors = function(is_regular, ctx, canvas){
    if (is_regular){ //screen-friendly, white on deep blue
      ctx.fillStyle = 'rgb(36,55,114)';
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.fillStyle = 'white';
      ctx.strokeStyle = 'white';
    }
    else { //print-friendly, black on white
      ctx.fillStyle = 'black';
      ctx.strokeStyle = 'black';
    }
  };

  //SAME
  var star_size = function(mag){
    var A0 = 3.5; //the max
    var result;
    var limiting_mag = parseFloat(input.limiting_mag);
    if (mag > limiting_mag){
      result = -1; //won't be drawn; error if even attempted
    }
    else if (mag <= 1.25){
      result = A0; //capped
    }
    else if (mag <= 5.0){
      result = A0*Math.exp(-mag/2.5);
    }
    else {
      result = 0.1;
    }
    return result;
  };

  /* Find the pos on Earth where the object is in the zenith (for the given when; geocentric). */
  var find_sub_star_point = function(thing){
    var result = {}; // a 'where' object
    result.φ = thing.δ;
    result.λ = EPH.in2pi(thing.α - when.gmst);
    //corrections for parallax don't apply here! they apply only for the 'real' position.
    //the idea is that for the real position, parallax is already applied before this code is reached,
    //AND that the parallax is applied to alter ra and dec (not just a, A).
    //the sub-star point then uses that ra and dec to calc it's (non-topocentric) a,A.
    result.is_topocentric = false;
    return result;
  };

  /*
   Project from a given center. Use elongation from the center, and the polar angle to the object (wrt the center).
   If the center is near a celestial pole, then use the pole as the center, along with a plain 'rθ projection'.
  */
  var chart_projection = function(ephem, chart /*.ctr.α,ctr.δ in rads*/){
    var result;
      if (Math.abs(ctr.δ) < EPH.rads(88)){
      result = project_from_center(ephem, chart);
    }
    else {
      result = project_from_pole(ephem, chart);
    }
    return result;
  };
  var project_from_center = function(ephem, chart/*.ctr.α,ctr.δ in rads*/){
    var pos = {};
    var elong = EPH.elongation_between(chart.ctr, ephem);
    var θ = EPH.position_angle_between(chart.ctr, ephem); //NCP-ctr-ephem
    if (input.place_at_top === 'south') {
      θ = θ + Math.PI;
    }
    var r = elong * chart.pixels_per_rad;
    pos.x = chart.ctr.x - r * Math.sin(θ);
    pos.y = chart.ctr.y - r * Math.cos(θ);
    return pos;
  };
  var project_from_pole = function(ephem, chart/*.ctr.α,ctr.δ in rads*/){
    var pos = {}, elong;
    var halfpi = 0.5*Math.PI;
    var θ = ephem.α;
    if (chart.ctr.δ > 0){ //north celestial pole
      elong = halfpi - ephem.δ;
    }
    else { //south celestial pole
      elong = halfpi + ephem.δ;
    }
    var r = elong * chart.pixels_per_rad;
    pos.x = chart.ctr.x + r * Math.sin(θ);
    pos.y = chart.ctr.y - r * Math.cos(θ);
    return pos;
  };

  /* Remember later, so that stars and constellation lines can be plotted in the desired order. */
  var remember_star_position = function(i, x, y, size){
    star_positions[i] = {x:x, y:y, size:size}; //not an array: the index is sparse, non-contiguous
  };

  var find_star = function(star, chart, ctx, i){
    var size = star_size(star[mag]);
    var pos = chart_projection({α: star[α], δ:star[δ]}, chart);
    if (size > 0){
      remember_star_position(i, pos.x, pos.y, size);
    }
  };

  var plot_star = function(ctx, star_position){
    GRAPH.spot(ctx, star_position.x, star_position.y, star_position.size);
  };

  var plot_star_name = function(ctx, star_position, i){
    var star_name = EPH.stars[i][name];
    if (star_name.length > 0){
      if (star_name.indexOf(' ') !== -1){
        star_name = star_name.split(" ")[0]; //chop off the constellation abbr
      }
      var show_star_name = false;
      if (/^\d+$/.test(star_name)){ //numbers only
        if (array_includes('flamsteed', input.show_identifiers)){
          show_star_name = true;
        }
      }
      else {
        if (array_includes('bayer', input.show_identifiers)){
          show_star_name = true;
        }
      }
      if (show_star_name){
        GRAPH.text(ctx, star_name, star_position.x, star_position.y + gap);
      }
    }
  };

  var find_stars = function(chart, ctx){
    var i, star;
    var limiting_mag = parseFloat(input.limiting_mag);
    for (i=0; i < EPH.stars.length; ++i){
      star = EPH.stars[i];
      if (star[mag] <= limiting_mag){
        if (EPH.elongation_between(chart.ctr, {α: star[α], δ: star[δ]}) <= chart.width + EPH.rads(MARGIN_DEGS)){
          find_star(star, chart, ctx, i);
        }
      }
    }
  };

  var draw_polyline = function(ctx, points){
    var i;
    ctx.save();
    ctx.strokeStyle='rgb(125,125,125)';
    //ctx.strokeStyle='rgb(177,156,217)';
    ctx.beginPath();
    ctx.moveTo(points[0].x,points[0].y);
    for (i=1;i<points.length;i++){
      ctx.lineTo(points[i].x,points[i].y);
    }
    ctx.stroke();
    ctx.closePath();
    ctx.restore();
  };

  /* Join up sets of star positions, to show the usual lines denoting a constellation. */
  var connect_the_star_positions = function(ctx){
    var polylines, i, count, polyline, j, points;
    //for all possible polylines
    for (constell in EPH.constellation_lines){
      if (EPH.constellation_lines.hasOwnProperty(constell)){
        polylines = EPH.constellation_lines[constell]; //array of arrays
        for(i=0; i<polylines.length; ++i){
          polyline = polylines[i];
          points = [];
          //find the points that have a corresponding calculated position
          for(j=0; j<polyline.length; ++j){
            if (star_positions[polyline[j]]){
              points.push(star_positions[polyline[j]]);
            }
          }
          if (points.length >= 2){
            //lines(ctx, points);
            draw_polyline(ctx, points);
          }
        }
      }
    }
  };

  /* Do this after the constellation lines, such that the spots overwrite the lines. */
  var show_stars = function(ctx){
    var i;
    for (i in star_positions){
      if (star_positions.hasOwnProperty(i)){
        plot_star(ctx, star_positions[i]);
        plot_star_name(ctx, star_positions[i], i);
      }
    }
  };

  var plot_messier = function(thing, chart, ctx){
    var pos = chart_projection({α: thing[α], δ:thing[δ]}, chart);
    var tiny_gap = 2;
    GRAPH.point(ctx, pos.x+tiny_gap, pos.y+tiny_gap);
    GRAPH.point(ctx, pos.x+tiny_gap, pos.y-tiny_gap);
    GRAPH.point(ctx, pos.x-tiny_gap, pos.y+tiny_gap);
    GRAPH.point(ctx, pos.x-tiny_gap, pos.y-tiny_gap);
    ctx.save();
    ctx.font = '10px Verdana';
    GRAPH.text(ctx, thing[name], pos.x, pos.y+gap);
    ctx.restore();
  };

  var show_deep_sky_objects = function(list, chart, ctx){
    var i, dso;
    for (i=0; i < list.length; ++i){
      dso = list[i];
      if (EPH.elongation_between(chart.ctr, {α: dso[α], δ: dso[δ]}) <= chart.width){
          plot_messier(dso, chart, ctx);
      }
    }
  };

  var show_comets = function(chart, ctx){
     var comets = EPH.as_array(EPH.comets);
     for(var i=0; i < comets.length; ++i){
       var ephem = EPH.position(comets[i].name, when, opts_topocentric);
        if (EPH.elongation_between(chart.ctr, ephem) <= chart.width){
          var pos = chart_projection(ephem, chart);
          GRAPH.circle(ctx,pos.x, pos.y,3);
          GRAPH.text(ctx, comets[i].alt_name, pos.x, pos.y+gap);
        }
     }
  };

  var show_minor_planets = function(chart, ctx){
     var items = EPH.as_array(EPH.minor_planets);
     for(var i=0; i < items.length; ++i){
       var ephem = EPH.position(items[i].name, when, opts_topocentric);
        if (EPH.elongation_between(chart.ctr, ephem) <= chart.width){
          var pos = chart_projection(ephem, chart);
          GRAPH.square(ctx, pos.x, pos.y,6);
          GRAPH.text(ctx, items[i].name, pos.x, pos.y+gap);
        }
     }
  };

  /* Use brightness by default, but apparent angular size IF that would result in a bigger dot. */
  var planet_size = function(planet, chart){
    var result = star_size(planet.mag);
    var size_as_fraction_of_chart_width = planet.size / chart.width; // both in rads
    var size_in_pixels = Math.floor(size_as_fraction_of_chart_width * chart.w); // pixels
    if (size_in_pixels > result){
      result = size_in_pixels;
    }
    return result;
  };

  var plot_planet = function(planet, chart, ctx){
    var size = planet_size(planet, chart);
    //override the case in which the planet is dimmer than the input limiting stellar magnitude, to always show the planet
    if (size === -1){
      size = 0.1;
    }
    var pos = chart_projection(planet, chart);
    GRAPH.spot(ctx, pos.x, pos.y, size);
    GRAPH.text(ctx, planet.symbol, pos.x, pos.y+size+gap);
  };

  var show_planets_etc = function(chart, ctx){
      var planets = EPH.as_array(EPH.planets);
      var planet;
      for (var i=0; i < planets.length; ++i){
        planet = EPH.position(planets[i].name, when, opts_topocentric);
        if (planets[i].name === 'Moon'){
          //needed only because the chart projection relies on ra-dec, not-alt-az
          EPH.apply_parallax_to_αδ(planet, opts_topocentric.where);
        }
        planet.symbol = planets[i].symbol; //add it here for the sake of convenience
        if (EPH.elongation_between(chart.ctr, planet) <= chart.width){
            plot_planet(planet, chart, ctx);
        }
      }
  };

  var show_star_chart = function(){
    var chart = {}, ephem;
    chart.width = EPH.rads(parseInt(input.chart_width));
    var canvas = document.getElementById('star_chart');
    canvas.width = window.innerWidth*0.95;
    canvas.height = window.innerHeight*.85;
    var ctx = canvas.getContext('2d');
    //ctx.fillStyle = 'rgb(36,55,114)'; //blue background
    //ctx.fillRect(0, 0, canvas.width, canvas.height);
    standard_canvas_appearance(ctx, true);
    canvas_colors(input.style === 'regular', ctx, canvas);
    h = canvas.height;
    w = canvas.width;
    ctr.x = w/2;
    ctr.y = h/2;
    chart.ctr = ctr;
    chart.ctr.α = EPH.rads(input.center_ra);
    chart.ctr.δ = EPH.rads(input.center_dec);
    chart.w = w;
    chart.h = h;
    chart.pixels_per_rad = chart.w / chart.width;
    find_stars(chart, ctx);
    connect_the_star_positions(ctx);
    show_stars(ctx);
    show_deep_sky_objects(EPH.messiers, chart, ctx);
    show_deep_sky_objects(EPH.caldwells, chart, ctx);
    show_planets_etc(chart, ctx);
    show_comets(chart, ctx);
    show_minor_planets(chart, ctx);
    use_drag_and_drop_to_recenter(chart);
  };

  /* The top-level call. */
  show_star_chart();

  // animation, over time or space
  //   with optional trailing path, tick marks ever N days, single object
  //   nice for planets, comets, asteroids, moon
  //   printable version for the whole year
  //
  // moon with correct phase, and position angle wrt NCP
  //    this needed for better charting of zoomed-in cases, especially for occultations
  //
  // projection appropriate for horizon views
  //    calc a, A
  //    show the horizon as a straight horizontal line
  //    restrict up-down navigation in some way (max altitude)?  or better: just cut off showing alt < 0 items
  //    probably replace center-on ra, dec with center an alt-az
  //    probably add an option for the projection: regular, near-horizon only
  //    allow zoom
  //
  // center-object:
  //    constellation names?
  //       the abbr is already in ephem.js
  //       in that case, I would need to input the ra-decl of each constellation manually somewhere; maybe directly in ephem.js
  //       the IMCEE French data may be useful here
  //
  // colors control (html color picker not supported universally)
  // colors for printing: need to re-draw the canvas, with different colors!
  // very useful: pop-up window to describe object x; store object coords and details in memory; when within x pixels, show its data
  //   what if 2 things are very close? pick the closest one to the pointer; or maybe show N, not just 1
};


text:
using System;
using System.Collections.Generic;
using System.Text;
using CAPLab;
[assembly: Xamarin.Forms.Dependency(typeof(ICloseApplication))]

/*
* This class makes ues of the dependency service.More info here: https://developer.xamarin.com/guides/xamarin-forms/dependency-service/introduction/
 */

namespace CAPLab.iOS
{
    public class CloseApplication : ICloseApplication
    {
        public void CloseApp()
        {
            System.Threading.Thread.CurrentThread.Abort();
        }
    }
}