text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;

namespace EmbedIndex
{
    public class Program
    {
        public static void Main(string[] args)
        {
            if(args.Length != 2)
            {
                PrintUsage();
                return;
            }

            if(Directory.Exists(args[0]))
            {
                string inputDir = args[0];
                string outputDir = args[1];
                Directory.CreateDirectory(outputDir);
                foreach(string nugetPath in Directory.EnumerateFiles(inputDir, "*.nupkg", SearchOption.AllDirectories))
                {
                    Console.WriteLine(nugetPath);
                    string indexedNugetPath = Path.Combine(outputDir, Path.GetFileName(nugetPath));
                    File.Copy(nugetPath, indexedNugetPath, true);
                    IndexPackage(indexedNugetPath, GetIndexers());
                }
            }
            else
            {
                string nugetPackagePath = args[0];
                string nugetPackageOutputPath = args[1];
                Directory.CreateDirectory(Path.GetDirectoryName(nugetPackageOutputPath));
                File.Copy(nugetPackagePath, nugetPackageOutputPath, true);
                IndexPackage(nugetPackageOutputPath, GetIndexers());
            }
        }

        private static void PrintUsage()
        {
            Console.WriteLine("Either:");
            Console.WriteLine("  EmbedIndex <path_to_existing_nuget_package> <output_path_to_indexed_nuget_package>");
            Console.WriteLine("  EmbedIndex <path_to_directory_of_nuget_packages> <output_path_to_directory_of_indexed_nuget_packages>");
        }

        private static IEnumerable<IFileFormatIndexer> GetIndexers()
        {
            yield return new PETimestampSizeIndexer();
            yield return new PDBSignatureAgeIndexer();
            yield return new SHA1Indexer();
            yield return new ELFBuildIdIndexer();
            yield return new MachOUuidIndexer();
        }

        private static void IndexPackage(string nugetPackagePath, IEnumerable<IFileFormatIndexer> indexers)
        {
            using (FileStream packageStream = File.Open(nugetPackagePath, FileMode.Open))
            {
                using (ZipArchive archive = new ZipArchive(packageStream, ZipArchiveMode.Update))
                {
                    List<Tuple<string, string>> indexEntries = ComputeIndexEntries(archive, indexers);

                    ZipArchiveEntry symbolIndexEntry = archive.GetEntry("symbol_index.json");
                    if (symbolIndexEntry != null)
                    {
                        symbolIndexEntry.Delete();
                    }
                    symbolIndexEntry = archive.CreateEntry("symbol_index.json");
                    using (Stream indexStream = symbolIndexEntry.Open())
                    {
                        SerializeIndex(indexEntries, indexStream);
                    }
                }
            }
        }

        private static List<Tuple<string, string>> ComputeIndexEntries(ZipArchive archive, IEnumerable<IFileFormatIndexer> indexers)
        {
            List<Tuple<string, string>> indexEntries = new List<Tuple<string, string>>();
            foreach (ZipArchiveEntry entry in archive.Entries)
            {
                if (!ShouldIndexEntry(entry.FullName))
                {
                    continue;
                }
                using (Stream zipFileStream = entry.Open())
                {
                    IEnumerable<string> keys = ComputeIndexEntries(entry.FullName, zipFileStream, indexers);
                    indexEntries.AddRange(keys.Select(k => new Tuple<string, string>(k, entry.FullName)));
                }
            }

            return indexEntries;
        }

        private static bool ShouldIndexEntry(string archiveRelativePath)
        {
            if (archiveRelativePath.EndsWith("/"))
                return false;
            if (archiveRelativePath.StartsWith("_rels/"))
                return false;
            if (archiveRelativePath.StartsWith("package/"))
                return false;
            if (archiveRelativePath == "[Content_Types].xml")
                return false;
            if (archiveRelativePath == "symbol_index.json")
                return false;
            if (!archiveRelativePath.Contains("/") && archiveRelativePath.EndsWith(".nuspec"))
                return false;

            return true;
        }

        private static void SerializeIndex(List<Tuple<string, string>> indexEntries, Stream indexStream)
        {
            TextWriter writer = new StreamWriter(indexStream);
            writer.WriteLine("[");
            for (int i = 0; i < indexEntries.Count; i++)
            {
                Tuple<string, string> entry = indexEntries[i];
                writer.WriteLine("    {");
                writer.WriteLine("        \"clientKey\" : \"{0}\",", entry.Item1);
                writer.WriteLine("        \"blobPath\" : \"{0}\"", entry.Item2);

                if (i != indexEntries.Count - 1)
                {
                    writer.WriteLine("    },");
                }
                else
                {
                    writer.WriteLine("    }");
                }
            }
            writer.WriteLine("]");
            writer.Flush();
        }

        public static IEnumerable<string> ComputeIndexEntries(string archiveRelativePath, Stream fileStream, IEnumerable<IFileFormatIndexer> indexers)
        {
            List<string> keys = new List<string>();

            //the indexers can handle this, but it wastes time and makes debugging worse to throw and
            //catch the exceptions
            if (fileStream.Length == 0)
            {
                return keys;
            }

            foreach (IFileFormatIndexer indexer in indexers)
            {
                fileStream.Position = 0;
                string key = indexer.ComputeIndexKey(archiveRelativePath, fileStream);
                if (key != null)
                {
                    keys.Add(key);
                }
            }
            return keys;
        }
    }
}


text:
package com.example.tetianapriadko.myapplication;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

public class Lesson141 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new DrawView(this));
    }

//    class DrawView extends View {
//
//        public DrawView(Context context) {
//            super(context);
//        }
//
//        @Override
//        protected void onDraw(Canvas canvas) {
//            canvas.drawColor(Color.GREEN);
//        }
//
//    }

    class DrawView extends SurfaceView implements SurfaceHolder.Callback {

        private DrawThread drawThread;

        public DrawView(Context context) {
            super(context);
            getHolder().addCallback(this);
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                                   int height) {

        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            drawThread = new DrawThread(getHolder());
            drawThread.setRunning(true);
            drawThread.start();
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            boolean retry = true;
            drawThread.setRunning(false);
            while (retry) {
                try {
                    drawThread.join();
                    retry = false;
                } catch (InterruptedException e) {
                }
            }
        }

        class DrawThread extends Thread {

            private boolean running = false;
            private SurfaceHolder surfaceHolder;

            public DrawThread(SurfaceHolder surfaceHolder) {
                this.surfaceHolder = surfaceHolder;
            }

            public void setRunning(boolean running) {
                this.running = running;
            }

            @Override
            public void run() {
                Canvas canvas;
                while (running) {
                    canvas = null;
                    try {
                        canvas = surfaceHolder.lockCanvas(null);
                        if (canvas == null)
                            continue;
                        canvas.drawColor(Color.GREEN);
                    } finally {
                        if (canvas != null) {
                            surfaceHolder.unlockCanvasAndPost(canvas);
                        }
                    }
                }
            }
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.lib.query2;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Throwables;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.SetMultimap;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.concurrent.AbstractQueueVisitor;
import com.google.devtools.build.lib.concurrent.ErrorClassifier;
import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadSafe;
import com.google.devtools.build.lib.events.ExtendedEventHandler;
import com.google.devtools.build.lib.packages.AggregatingAttributeMapper;
import com.google.devtools.build.lib.packages.AspectDefinition;
import com.google.devtools.build.lib.packages.Attribute;
import com.google.devtools.build.lib.packages.AttributeMap;
import com.google.devtools.build.lib.packages.BuildType;
import com.google.devtools.build.lib.packages.DependencyFilter;
import com.google.devtools.build.lib.packages.InputFile;
import com.google.devtools.build.lib.packages.NoSuchThingException;
import com.google.devtools.build.lib.packages.OutputFile;
import com.google.devtools.build.lib.packages.Package;
import com.google.devtools.build.lib.packages.PackageGroup;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.packages.RuleClass;
import com.google.devtools.build.lib.packages.Target;
import com.google.devtools.build.lib.pkgcache.TargetEdgeObserver;
import com.google.devtools.build.lib.pkgcache.TargetProvider;
import java.util.Collection;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 *
Visit the transitive closure of a label. Primarily used to "fault in"
 * packages to the packageProvider and ensure the necessary targets exists, in
 * advance of the configuration step, which is intolerant of missing
 * packages/targets.
 *
 *
LabelVisitor loads packages concurrently where possible, to increase I/O
 * parallelism.  However, the public interface is not thread-safe: calls to
 * public methods should not be made concurrently.
 *
 *
LabelVisitor is stateful: It remembers the previous visitation and can
 * check its validity on subsequent calls to sync() instead of doing the normal
 * visitation.
 *
 *
TODO(bazel-team): (2009) a small further optimization could be achieved if we
 * create tasks at the package (not individual label) level, since package
 * loading is the expensive step.  This would require additional bookkeeping to
 * maintain the list of labels that we need to visit once a package becomes
 * available.  Profiling suggests that there is still a potential benefit to be
 * gained: when the set of packages is known a-priori, loading a set of packages
 * that took 20 seconds can be done under 5 in the sequential case or 7 in the
 * current (parallel) case.
 *
 *
Concurrency

 *
 *
The sync() methods of this class is thread-compatible. The accessor
 * ({@link #hasVisited} and similar must not be called until the concurrent phase
 * is over, i.e. all external calls to visit() methods have completed.
 */
final class LabelVisitor {

  /**
   * Attributes of a visitation which determine whether it is up-to-date or not.
   */
  private class VisitationAttributes {
    private Collection<Target> targetsToVisit;
    private boolean success = false;
    private int maxDepth = 0;

    /**
     * Returns true if and only if this visitation attribute is still up-to-date.
     */
    boolean current() {
      return targetsToVisit.equals(lastVisitation.targetsToVisit)
          && maxDepth <= lastVisitation.maxDepth;
    }
  }

  /*
   * Interrupts during the loading phase ===================================
   *
   * Bazel can be interrupted in the middle of the loading phase. The mechanics
   * of this are far from trivial, so there is an explanation of how they are
   * supposed to work. For a description how the same thing works in the
   * execution phase, see ParallelBuilder.java .
   *
   * The sequence of events that happen when the user presses Ctrl-C is the
   * following:
   *
   * 1. A SIGINT gets delivered to the Bazel client process.
   *
   * 2. The client process delivers the SIGINT to the server process.
   *
   * 3. The interruption state of the main thread is set to true.
   *
   * 4. Sooner or later, this results in an InterruptedException being thrown.
   * Usually this takes place because the main thread is interrupted during
   * AbstractQueueVisitor.awaitTermination(). The only exception to this is when
   * the interruption occurs during the loading of a package of a label
   * specified on the command line; in this case, the InterruptedException is
   * thrown during the loading of an individual package (see below where this
   * can occur)
   *
   * 5. The main thread calls ThreadPoolExecutor.shutdown(), which in turn
   * interrupts every worker thread. Then the main thread waits for their
   * termination.
   *
   * 6. An InterruptedException is thrown during the loading of an individual
   * package in the worker threads.
   *
   * 7. All worker threads terminate.
   *
   * 8. An InterruptedException is thrown from
   * AbstractQueueVisitor.awaitTermination()
   *
   * 9. This exception causes the execution of the currently running command to
   * terminate prematurely.
   *
   * The interruption of the loading of an individual package happens as follow:
   *
   * 1. We periodically check the interruption state of the thread in
   * UnixGlob.reallyGlob(). If it is interrupted, an InterruptedException is
   * thrown.
   *
   * 2. The stack is unwound until we are out of the part of the call stack
   * responsible for package loading. This either means that the worker thread
   * terminates or that the label parsing terminates if the package that is
   * being loaded was specified on the command line.
   */
  private final TargetProvider targetProvider;
  private final DependencyFilter edgeFilter;
  private final SetMultimap<Package, Target> visitedMap =
      Multimaps.synchronizedSetMultimap(HashMultimap.<Package, Target>create());
  private final ConcurrentMap visitedTargets = new ConcurrentHashMap<>();

  private VisitationAttributes lastVisitation;

  /**
   * Constant for limiting the permitted depth of recursion.
   */
  private static final int RECURSION_LIMIT = 100;

  /**
   * Construct a LabelVisitor.
   *
   * @param targetProvider how to resolve labels to targets
   * @param edgeFilter which edges may be traversed
   */
  public LabelVisitor(TargetProvider targetProvider, DependencyFilter edgeFilter) {
    this.targetProvider = targetProvider;
    this.lastVisitation = new VisitationAttributes();
    this.edgeFilter = edgeFilter;
  }

  boolean syncWithVisitor(
      ExtendedEventHandler eventHandler,
      Collection<Target> targetsToVisit,
      boolean keepGoing,
      int parallelThreads,
      int maxDepth,
      TargetEdgeObserver... observers)
      throws InterruptedException {
    VisitationAttributes nextVisitation = new VisitationAttributes();
    nextVisitation.targetsToVisit = targetsToVisit;
    nextVisitation.maxDepth = maxDepth;

    if (!lastVisitation.success || !nextVisitation.current()) {
      try {
        nextVisitation.success = redoVisitation(eventHandler, nextVisitation, keepGoing,
            parallelThreads, maxDepth, observers);
        return nextVisitation.success;
      } finally {
        lastVisitation = nextVisitation;
      }
    } else {
      return true;
    }
  }

  // Does a bounded transitive visitation starting at the given top-level targets.
  private boolean redoVisitation(
      ExtendedEventHandler eventHandler,
      VisitationAttributes visitation,
      boolean keepGoing,
      int parallelThreads,
      int maxDepth,
      TargetEdgeObserver... observers)
      throws InterruptedException {
    visitedMap.clear();
    visitedTargets.clear();

    Visitor visitor = new Visitor(eventHandler, keepGoing, parallelThreads, maxDepth, observers);

    Throwable uncaught = null;
    boolean result;
    try {
      visitor.visitTargets(visitation.targetsToVisit);
    } catch (Throwable t) {
      visitor.stopNewActions();
      uncaught = t;
    } finally {
      // Run finish() in finally block to ensure we don't leak threads on exceptions.
      result = visitor.finish();
    }
    Throwables.propagateIfPossible(uncaught);
    return result;
  }

  boolean hasVisited(Label target) {
    return visitedTargets.containsKey(target);
  }

  @VisibleForTesting class Visitor extends AbstractQueueVisitor {

    private final static String THREAD_NAME = "LabelVisitor";

    private final ExtendedEventHandler eventHandler;
    private final boolean keepGoing;
    private final int maxDepth;
    private final Iterable<TargetEdgeObserver> observers;
    private final TargetEdgeErrorObserver errorObserver;
    private final AtomicBoolean stopNewActions = new AtomicBoolean(false);

    public Visitor(
        ExtendedEventHandler eventHandler,
        boolean keepGoing,
        int parallelThreads,
        int maxDepth,
        TargetEdgeObserver... observers) {
      // Observing the loading phase of a typical large package (with all subpackages) shows
      // maximum thread-level concurrency of ~20. Limiting the total number of threads to 200 is
      // therefore conservative and should help us avoid hitting native limits.
      super(
          parallelThreads,
          1L,
          TimeUnit.SECONDS,
          !keepGoing,
          THREAD_NAME,
          AbstractQueueVisitor.EXECUTOR_FACTORY,
          ErrorClassifier.DEFAULT);
      this.eventHandler = eventHandler;
      this.maxDepth = maxDepth;
      this.errorObserver = new TargetEdgeErrorObserver();
      ImmutableList.Builder<TargetEdgeObserver> builder = ImmutableList.builder();
      builder.add(observers);
      builder.add(errorObserver);
      this.observers = builder.build();
      this.keepGoing = keepGoing;
    }

    /**
     * Visit the specified labels and follow the transitive closure of their outbound dependencies.
     *
     * @param targets the targets to visit
     */
    @ThreadSafe
    public void visitTargets(Iterable<Target> targets) throws InterruptedException {
      for (Target target : targets) {
        visit(null, null, target, 0, 0);
      }
    }

    @ThreadSafe
    public boolean finish() throws InterruptedException {
      awaitQuiescence(/*interruptWorkers=*/ true);
      return !errorObserver.hasErrors();
    }

    @Override
    protected boolean blockNewActions() {
      return (!keepGoing && errorObserver.hasErrors()) || super.blockNewActions() ||
          stopNewActions.get();
    }

    public void stopNewActions() {
      stopNewActions.set(true);
    }

    private void enqueueTarget(
        final Target from, final Attribute attr, final Label label, final int depth,
        final int count) {
      // Don't perform the targetProvider lookup if at the maximum depth already.
      if (depth >= maxDepth) {
        return;
      }

      // Avoid thread-related overhead when not crossing packages.
      // Can start a new thread when count reaches 100, to prevent infinite recursion.
      if (from != null && from.getLabel().getPackageFragment() == label.getPackageFragment() &&
          !blockNewActions() && count < RECURSION_LIMIT) {
        newVisitRunnable(from, attr, label, depth, count + 1).run();
      } else {
        execute(newVisitRunnable(from, attr, label, depth, 0));
      }
    }

    private Runnable newVisitRunnable(final Target from, final Attribute attr, final Label label,
        final int depth, final int count) {
      return new Runnable() {
        @Override
        public void run() {
          try {
            try {
              visit(from, attr, targetProvider.getTarget(eventHandler, label), depth + 1, count);
            } catch (NoSuchThingException e) {
              observeError(from, label, e);
            }
          } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
          }
        }
      };
    }

    private void visitTargetVisibility(Target target, int depth, int count) {
      Attribute attribute = null;
      if (target instanceof Rule) {
        Rule rule = (Rule) target;
        RuleClass ruleClass = rule.getRuleClassObject();
        if (!ruleClass.hasAttr("visibility", BuildType.NODEP_LABEL_LIST)) {
          return;
        }
        attribute = ruleClass.getAttributeByName("visibility");
        if (!edgeFilter.apply(rule, attribute)) {
          return;
        }
      }

      for (Label label : target.getVisibility().getDependencyLabels()) {
        enqueueTarget(target, attribute, label, depth, count);
      }
    }

    /**
     * Visit all the labels in a given rule.
     *
     *
Called in a worker thread if CONCURRENT.
     *
     * @param rule the rule to visit
     */
    @ThreadSafe
    private void visitRule(final Rule rule, final int depth, final int count)
        throws InterruptedException {
      // Follow all labels defined by this rule:
      AggregatingAttributeMapper.of(rule).visitLabels(new AttributeMap.AcceptsLabelAttribute() {
        @Override
        public void acceptLabelAttribute(Label label, Attribute attribute) {
          if (!edgeFilter.apply(rule, attribute)) {
            return;
          }
          enqueueTarget(rule, attribute, label, depth, count);
        }
      });
    }

    @ThreadSafe
    private void visitPackageGroup(PackageGroup packageGroup, int depth, int count) {
      for (final Label include : packageGroup.getIncludes()) {
        enqueueTarget(packageGroup, null, include, depth, count);
      }
    }

    /**
     * Visits the target and its package.
     *
     *
Potentially blocking invocations into the package cache are enqueued in the worker pool if
     * CONCURRENT.
     */
    private void visit(Target from, Attribute attribute, final Target target, int depth, int count)
        throws InterruptedException {
      if (target == null) {
        throw new NullPointerException(
            String.format("'%s' attribute '%s'",
              from == null ? "(null)" : from.getLabel().toString(),
              attribute == null ? "(null)" : attribute.getName()));
      }
      if (depth > maxDepth) {
        return;
      }

      if (from != null) {
        observeEdge(from, attribute, target);
        visitAspectsIfRequired(from, attribute, target, depth, count);
      }

      visitedMap.put(target.getPackage(), target);
      visitTargetNode(target, depth, count);
    }

    private void visitAspectsIfRequired(
        Target from, Attribute attribute, final Target to, int depth, int count) {
      ImmutableMultimap<Attribute, Label> labelsFromAspects =
          AspectDefinition.visitAspectsIfRequired(from, attribute, to, edgeFilter);
      // Create an edge from target to the attribute value.
      for (Entry<Attribute, Label> entry : labelsFromAspects.entries()) {
        enqueueTarget(from, entry.getKey(), entry.getValue(), depth, count);
      }
    }

    /**
     * Visit the specified target. Called in a worker thread if CONCURRENT.
     *
     * @param target the target to visit
     */
    private void visitTargetNode(Target target, int depth, int count) throws InterruptedException {
      Integer minTargetDepth = visitedTargets.putIfAbsent(target.getLabel(), depth);
      if (minTargetDepth != null) {
        // The target was already visited at a greater depth.
        // The closure we are about to build is therefore a subset of what
        // has already been built, and we can skip it.
        // Also special case MAX_VALUE, where we never want to revisit targets.
        // (This avoids loading phase overhead outside of queries).
        if (maxDepth == Integer.MAX_VALUE || minTargetDepth <= depth) {
          return;
        }
        // Check again in case it was overwritten by another thread.
        synchronized (visitedTargets) {
          if (visitedTargets.get(target.getLabel()) <= depth) {
            return;
          }
          visitedTargets.put(target.getLabel(), depth);
        }
      }

      observeNode(target);
      if (target instanceof OutputFile) {
        Rule rule = ((OutputFile) target).getGeneratingRule();
        observeEdge(target, null, rule);
        // This is the only recursive call to visit which doesn't pass through enqueueTarget().
        visit(null, null, rule, depth + 1, count + 1);
        visitTargetVisibility(target, depth, count);
      } else if (target instanceof InputFile) {
        visitTargetVisibility(target, depth, count);
      } else if (target instanceof Rule) {
        visitTargetVisibility(target, depth, count);
        visitRule((Rule) target, depth, count);
      } else if (target instanceof PackageGroup) {
        visitPackageGroup((PackageGroup) target, depth, count);
      }
    }

    private void observeEdge(Target from, Attribute attribute, Target to) {
      for (TargetEdgeObserver observer : observers) {
        observer.edge(from, attribute, to);
      }
    }

    private void observeNode(Target target) {
      for (TargetEdgeObserver observer : observers) {
        observer.node(target);
      }
    }

    private void observeError(Target from, Label label, NoSuchThingException e)
        throws InterruptedException {
      for (TargetEdgeObserver observer : observers) {
        observer.missingEdge(from, label, e);
      }
    }
  }
}


text:
/**
 *
 */
package com.domker.marmot;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager.WakeLock;

import com.domker.marmot.core.AsyncHandler;
import com.domker.marmot.core.CpuWakeLock;
import com.domker.marmot.core.Watcher;

/**
 * 系统启动之后的广播
 *
 * @author wanlipeng
 * @date 2017年1月5日 下午5:49:41
 */
public class BootCompletedReceiver extends BroadcastReceiver {
	private ActivityManager am = null;
	private String processName = null;

	/*
	 * (non-Javadoc)
	 *
	 * @see android.content.BroadcastReceiver#onReceive(android.content.Context,
	 * android.content.Intent)
	 */
	@Override
	public void onReceive(final Context context, Intent intent) {
		if (isServiceProcessAlive(context)) {
			// 如果进程存在,则返回
			return;
		}
		final PendingResult result = goAsync();
		final WakeLock wl = CpuWakeLock.createPartialWakeLock(context);
		wl.acquire();

		AsyncHandler.post(new Runnable() {

			@Override
			public void run() {
				handleBoot(context);
				wl.release();
				result.finish();
			}
		});
	}

	/**
	 * 判断服务进程是否存在
	 *
	 * @param context
	 * @return
	 */
	private boolean isServiceProcessAlive(Context context) {
		if (am == null) {
			am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
			processName = context.getString(R.string.watcher_process);
		}
		for (RunningAppProcessInfo p : am.getRunningAppProcesses()) {
			if (p.processName.equals(processName)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 启动之后执行的操作
	 */
	private void handleBoot(Context context) {
		Intent intent = Watcher.createIntent(context, WatcherService.class);
		Watcher.startService(context, intent);
		Watcher.toast(context, "Service WatcherService start");
	}
}


text:
import React from 'react';
import { FormattedMessage } from 'react-intl';
import { useDispatch } from 'react-redux';
import styled from 'styled-components';
import Navbar from '../components/Navbar';
import Footer from '../components/Footer';
import LanguageSelector from '../components/LanguageSelector';
import { changeLanguage } from '../actions/language';
import * as constants from '../constants';

const languages = [
  {
    id: constants.LANGUAGE_SPANISH,
    locale: 'es',
    text: <FormattedMessage id="language.spanish" />,
  },
  {
    id: constants.LANGUAGE_ENGLISH,
    locale: 'en',
    text: <FormattedMessage id="language.english" />,
  },
];

const MainLayout = styled.div`
  margin-top: 5rem;
  padding-bottom: 6rem;
  flex: 1 0 auto;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;

  @media only screen and (min-width: 80rem) { /* width < 80rem (OK) */
    margin: 4rem 0 0 0; /* margin: 4rem 1rem 0 1rem; */
  }
`;

const Container = styled.div`
  flex: 1 0 auto;
  max-width: 76rem;
  width: 100%;

  & p {
    text-align: justify;
  }

  @media only screen and (max-width: 79.999rem) { /* width < 80rem */
    margin: 0 1rem;
    width: auto;
  }
`;

const Wrapper = ({ children }) => {
  const dispatch = useDispatch();
  const onChangeLanguage = (lang, locale) => {
    dispatch(changeLanguage(lang, locale));
  };

  return (
    <MainLayout>
      <Navbar brandText={<FormattedMessage id="app.brand-text" />} />
      <Container>
        {children}
      </Container>
      <Footer>
        <LanguageSelector
          languages={languages}
          onChangeLanguage={onChangeLanguage}
        />
      </Footer>
    </MainLayout>
  );
}

// export default connect(state => ({
//   selectedLanguage: state.language.selected,
// }), {
//   changeLanguage: _changeLanguage,
// })(MainLayout);

export default Wrapper;


text:
import DS from "ember-data";

export default DS.Model.extend({
  modelName:     DS.attr('string'),
  serialized:    DS.attr(),
  operation:     DS.attr('string'),
  createdAt:     DS.attr('string'),
});


text:
/*
 * Setting-up global variables.
 */

var operations = '.wr-operations',
    modalPopup = '.modal',
    modalPopupContent = modalPopup + ' .modal-content',
    navHeight = $('#nav').height(),
    headerHeight = $('header').height(),
    offset = (headerHeight + navHeight),
    deviceSelection = '.device-select',
    platformTypeConstants = {
        "ANDROID": "android",
        "IOS": "ios",
        "WINDOWS": "windows"
    },
    ownershipTypeConstants = {
        "BYOD": "BYOD",
        "COPE": "COPE"
    },
    operationBarModeConstants = {
        "BULK": "BULK_OPERATION_MODE",
        "SINGLE": "SINGLE_OPERATION_MODE"
    };

/*
 * Function to get selected devices ID's
 */
function getSelectedDeviceIds() {
    var deviceIdentifierList = [];
    $(deviceSelection).each(function (index) {
        var device = $(this);
        var deviceId = device.data('deviceid');
        var deviceType = device.data('type');
        deviceIdentifierList.push({
                                      "id": deviceId,
                                      "type": deviceType
                                  });
    });
    if (deviceIdentifierList.length == 0) {
        var thisTable = $(".DTTT_selected").closest('.dataTables_wrapper').find('.dataTable').dataTable();
        thisTable.api().rows().every(function () {
            if ($(this.node()).hasClass('DTTT_selected')) {
                var deviceId = $(thisTable.api().row(this).node()).data('deviceid');
                var deviceType = $(thisTable.api().row(this).node()).data('devicetype');
                deviceIdentifierList.push({
                                              "id": deviceId,
                                              "type": deviceType
                                          });
            }
        });
    }

    return deviceIdentifierList;
}

/*
 * On operation click function.
 * @param selection: Selected operation
 */
function operationSelect(selection) {
    var deviceIdList = getSelectedDeviceIds();
    if (deviceIdList == 0) {
        $(modalPopupContent).html($("#errorOperations").html());
    } else {
        $(modalPopupContent).addClass("operation-data");
        $(modalPopupContent).html($(operations + " .operation[data-operation-code=" + selection + "]").html());
        $(modalPopupContent).data("operation-code", selection);
    }
    showPopup();
}

function getDevicesByTypes(deviceList) {
    var deviceTypes = {};
    $.each(deviceList, function (index, item) {
        if (!deviceTypes[item.type]) {
            deviceTypes[item.type] = [];
        }
        if (item.type == platformTypeConstants.ANDROID ||
            item.type == platformTypeConstants.IOS || item.type == platformTypeConstants.WINDOWS) {
            deviceTypes[item.type].push(item.id);
        }
    });
    return deviceTypes;
}

//function unloadOperationBar() {
//    $("#showOperationsBtn").addClass("hidden");
//    $(".wr-operations").html("");
//}

function loadOperationBar(deviceType, ownership, mode) {
    var operationBar = $("#operations-bar");
    var operationBarSrc = operationBar.attr("src");

    $.template("operations-bar", operationBarSrc, function (template) {
        var serviceURL = "/api/device-mgt/v1.0/devices/" + deviceType + "/*/features";
        invokerUtil.get(
            serviceURL,
            // success callback
            function (data) {
                var permittedOperations = [];
                var i;
                var permissionList = $("#operations-mod").data("permissions");
                var totalFeatures = JSON.parse(data);
                for (i = 0; i < permissionList[deviceType].length; i++) {
                    var j;
                    for (j = 0; j < totalFeatures.length; j++) {
                        if (permissionList[deviceType][i] == totalFeatures[j]["code"]) {
                            if (deviceType == platformTypeConstants.ANDROID) {
                                if (totalFeatures[j]["code"] == "DEVICE_UNLOCK") {
                                    if (ownership == ownershipTypeConstants.COPE) {
                                        permittedOperations.push(totalFeatures[j]);
                                    }
                                } else if (totalFeatures[j]["code"] == "WIPE_DATA") {
                                    if (mode == operationBarModeConstants.BULK) {
                                        if (ownership == ownershipTypeConstants.COPE) {
                                            permittedOperations.push(totalFeatures[j]);
                                        }
                                    } else {
                                        permittedOperations.push(totalFeatures[j]);
                                    }
                                } else {
                                    permittedOperations.push(totalFeatures[j]);
                                }
                            } else {
                                permittedOperations.push(totalFeatures[j]);
                            }
                        }
                    }
                }

                var viewModel = {};
                permittedOperations = permittedOperations.filter(function (current) {
                    var iconName;
                    switch (deviceType) {
                        case platformTypeConstants.ANDROID:
                            iconName = operationModule.getAndroidIconForFeature(current.code);
                            break;
                        case platformTypeConstants.WINDOWS:
                            iconName = operationModule.getWindowsIconForFeature(current.code);
                            break;
                        case platformTypeConstants.IOS:
                            iconName = operationModule.getIOSIconForFeature(current.code);
                            break;
                    }

                    /* adding ownership in addition to device-type
                     as it's vital in cases where UI for the same feature should change
                     according to ownership
                      */
                    if (ownership) {
                        current.ownership = ownership;
                    }

                    if (iconName) {
                        current.icon = iconName;
                    }

                    return current;
                });

                viewModel.features = permittedOperations;
                var content = template(viewModel);
                $(".wr-operations").html(content);
            },
            // error callback
            function (message) {
                $(".wr-operations").html(message);
            });
    });
}

function runOperation(operationName) {
    var deviceIdList = getSelectedDeviceIds();
    var list = getDevicesByTypes(deviceIdList);

    var successCallback = function (data) {
        if (operationName == "NOTIFICATION") {
            $(modalPopupContent).html($("#messageSuccess").html());
        } else {
            $(modalPopupContent).html($("#operationSuccess").html());
        }
        showPopup();
    };
    var errorCallback = function (data) {
        $(modalPopupContent).html($("#errorOperationUnexpected").html());
        showPopup();
    };

    var payload, serviceEndPoint;
    if (list[platformTypeConstants.IOS]) {
        payload =
            operationModule.generatePayload(platformTypeConstants.IOS, operationName, list[platformTypeConstants.IOS]);
        serviceEndPoint = operationModule.getIOSServiceEndpoint(operationName);
    } else if (list[platformTypeConstants.ANDROID]) {
        payload = operationModule
            .generatePayload(platformTypeConstants.ANDROID, operationName, list[platformTypeConstants.ANDROID]);
        serviceEndPoint = operationModule.getAndroidServiceEndpoint(operationName);
    } else if (list[platformTypeConstants.WINDOWS]) {
        payload = operationModule.generatePayload(platformTypeConstants.WINDOWS, operationName,
                                                  list[platformTypeConstants.WINDOWS]);
        serviceEndPoint = operationModule.getWindowsServiceEndpoint(operationName);
    }
    if (operationName == "NOTIFICATION") {
        var errorMsgWrapper = "#notification-error-msg";
        var errorMsg = "#notification-error-msg span";
        var messageTitle = $("#messageTitle").val();
        var messageText = $("#messageText").val();
        if (!(messageTitle && messageText)) {
            $(errorMsg).text("Enter a message. It cannot be empty.");
            $(errorMsgWrapper).removeClass("hidden");
        } else {
            invokerUtil.post(serviceEndPoint, payload, successCallback, errorCallback);
            $(modalPopupContent).removeData();
            hidePopup();
        }
    } else {
        invokerUtil.post(serviceEndPoint, payload, successCallback, errorCallback);
        $(modalPopupContent).removeData();
        hidePopup();
    }
}

/*
 * DOM ready functions.
 */
$(document).ready(function () {
    $(operations).show();
});


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

 Copyright 2013 Anis Kadri

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.

-->

<plugin xmlns="http://cordova.apache.org/ns/plugins/1.0"
    xmlns:android="http://schemas.android.com/apk/res/android"
    id="com.phonegap.plugins.faultyplugin"
    version="0.6.0">

    <name>Faulty Plugin</name>

	<access origin="build.phonegap.com" />
	<access origin="s3.amazonaws.com" />
    <!-- file doesn't exist -->

    <config-file target="config.xml" parent="/widget">
        <asset src="www/main.js" target="faultyplugin/main.js" />
        <asset src="www/index.js" target="faultyplugin/index.js" />
    </config-file>

    <!-- android -->
    <platform name="android">
        <config-file target="AndroidManifest.xml" parent="/manifest/application">
            <activity android:name="com.phonegap.plugins.faultyplugin.FaultyPlugin"
                      android:label="@string/app_name">
                <intent-filter>
                </intent-filter>
            </activity>
        </config-file>

        <!-- CDV < 2.0 -->
        <config-file target="res/xml/plugins.xml" parent="/plugins">
            <plugin name="FaultyPlugin"
                value="com.phonegap.plugins.faultyplugin.FaultyPlugin"/>
        </config-file>

        <!-- CDV 2.0+ (for now) -->
        <config-file target="res/xml/config.xml" parent="/cordova/plugins">
            <plugin name="FaultyPlugin"
                value="com.phonegap.plugins.faultyplugin.FaultyPlugin"/>
        </config-file>

        <!-- this file doesn't exist -->
        <source-file src="src/android/NotHere.java"
                target-dir="src/com/phonegap/plugins/faultyplugin" />
    </platform>

    <!-- ios -->
    <platform name="ios">
        <!-- /cordova/plugins no longer exists, it is now /widget/plugins -->
        <!-- this should fail to install on ios -->
        <config-file target="config.xml" parent="/cordova/plugins">
            <plugin name="FaultyPlugin"
                value="FaultyPlugin"/>
        </config-file>

        <header-file src="src/ios/FaultyPlugin.h" />
        <source-file src="src/ios/FaultyPlugin.m" />
        <!-- these files don't exist -->
        <header-file src="src/ios/FaultyPluginCommand.h" />
        <source-file src="src/ios/FaultyPluginCommand.m" />
        <resource-file src="src/ios/IDontExist.bundle" />
        <framework src="src/ios/Nopers.lib" />
    </platform>
    <platform name="blackberry10">
        <config-file target="config.xml" parent="/widget">
            <feature id="cordova.echo" required="true" version="1.0.0.0"/>
        </config-file>

        <source-file src="src/blackberry10/index.js" target-dir="ext-qnx/cordova.echo" />
        <!-- these dont exist -->
        <lib-file src="src/blackberry10/device/echoJnext.so" target-dir="ext-qnx/cordova.echo/device" />
        <lib-file src="src/blackberry10/simulator/echoJnext.so" target-dir="ext-qnx/cordova.echo/simulator" />
    </platform>

    <!-- wp7 -->
    <platform name="wp7">
        <config-file target="config.xml" parent="/*">
            <feature name="FaultyPlugin">
                <param name="wp-package" value="FaultyPlugin"/>
            </feature>
        </config-file>

        <source-file src="src/wp7/FaultyPlugin.cs" />

        <!-- this desn't exist -->
        <source-file src="src/wp7/NotHere.cs" />
    </platform>

    <!-- wp8 -->
    <platform name="wp8">
        <config-file target="config.xml" parent="/*">
            <feature name="FaultyPlugin">
                <param name="wp-package" value="FaultyPlugin"/>
            </feature>
        </config-file>

        <source-file src="src/wp8/FaultyPlugin.cs" />

        <!-- this desn't exist -->
        <source-file src="src/wp8/NotHere.cs" />
    </platform>

    <!-- wp8 -->
    <platform name="windows8">
        <config-file target="config.xml" parent="/*">
            <feature name="FaultyPlugin">
                <param name="windows8-package" value="FaultyPlugin"/>
            </feature>
        </config-file>

        <source-file src="src/windows8/faultyPlugin.js" />

        <!-- does not exist -->
        <source-file src="src/windows8/NotHere.js" />
    </platform>
</plugin>


text:
var util         = require("util");
var EventEmitter = require("events").EventEmitter;
var id = 1;
var database = {
    users: [
        { id: id++, name: "Joe Smith",  occupation: "developer"    },
        { id: id++, name: "Jane Doe",   occupation: "data analyst" },
        { id: id++, name: "John Henry", occupation: "designer"     }
    ]
};
function UserList () {
    EventEmitter.call(this);
}
util.inherits(UserList, EventEmitter);
UserList.prototype.save = function (obj) {
    obj.id = id++;
    database.users.push(obj);
    this.emit("saved-user", obj);
};
module.exports = UserList;


text:
package es.minetsii.eggwars.enums;

public enum EnumArenaStatus {

	lobby, starting, startingGame, setting, ingame, finish;

	@Override
	public String toString(){
		switch (name()) {
		case "lobby":
		case "ingame":
		case "finish":
		case "starting":
		case "setting":
			return name();
		case "startingGame":
			return "ingame";
		default:
			return "";
		}

	}
}


text:
"""
This script should only be executed by the news-please initial script itself.

This script starts a crawler.
"""

import hashlib
import logging
import shutil
import sys
from ast import literal_eval

import os
from scrapy.crawler import CrawlerProcess
from scrapy.settings import Settings
from scrapy.spiderloader import SpiderLoader
from scrapy.utils.log import configure_logging

cur_path = os.path.dirname(os.path.realpath(__file__))
par_path = os.path.dirname(cur_path)
sys.path.append(cur_path)
sys.path.append(par_path)
from newsplease.config import CrawlerConfig
from newsplease.config import JsonConfig
from newsplease.helper import Helper
from newsplease.helper_classes.class_loader import ClassLoader
from newsplease.crawler.items import NewscrawlerItem

try:
    from _thread import start_new_thread
except ImportError:
    from thread import start_new_thread
from twisted.internet.error import ReactorAlreadyRunning

class SingleCrawler(object):
    """
    This class is called when this script is executed.

    It starts a single crawler, that is passed along to this script.
    """
    cfg = None
    json = None
    log = None
    crawler_name = None
    process = None
    helper = None
    cfg_file_path = None
    json_file_path = None
    cfg_crawler = None
    __scrapy_options = None
    __crawer_module = "newsplease.crawler.spiders"
    site_number = None
    shall_resume = False
    daemonize = False

    @classmethod
    def create_as_library(cls, url):
        """
        Creates a single crawler as in library mode. Crawling will start immediately.
        :param url:
        :return:
        """
        site = {
            "crawler": "Download",
            "url": url
        }
        cfg_file_path = os.path.dirname(__file__) + os.path.sep + 'config' + os.path.sep + 'config_lib.cfg'
        return cls(cfg_file_path, site, 0, False, False, True)

    def __init__(self, cfg_file_path, json_file_path,
                 site_index, shall_resume, daemonize, library_mode=False):
        # set up logging before it's defined via the config file,
        # this will be overwritten and all other levels will be put out
        # as well, if it will be changed.
        configure_logging({"LOG_LEVEL": "CRITICAL"})
        self.log = logging.getLogger(__name__)

        self.cfg_file_path = cfg_file_path
        self.json_file_path = json_file_path
        self.site_number = int(site_index)
        self.shall_resume = shall_resume \
            if isinstance(shall_resume, bool) else literal_eval(shall_resume)
        self.daemonize = daemonize \
            if isinstance(daemonize, bool) else literal_eval(daemonize)

        # set up the config file
        self.cfg = CrawlerConfig.get_instance()
        self.cfg.setup(self.cfg_file_path)
        self.log.debug("Config initialized - Further initialisation.")

        self.cfg_crawler = self.cfg.section("Crawler")

        # load the URL-input-json-file or - if in library mode - take the json_file_path as the site information (
        # kind of hacky..)
        if not library_mode:
            self.json = JsonConfig.get_instance()
            self.json.setup(self.json_file_path)
            sites = self.json.get_site_objects()
            site = sites[self.site_number]
        else:
            sites = [json_file_path]
            site = json_file_path

        if "ignore_regex" in site:
            ignore_regex = "(%s)|" % site["ignore_regex"]
        else:
            ignore_regex = "(%s)|" % \
                           self.cfg.section('Crawler')['ignore_regex']

        # Get the default crawler. The crawler can be overwritten by fallbacks.
        if "additional_rss_daemon" in site and self.daemonize:
            self.crawler_name = "RssCrawler"
        elif "crawler" in site:
            self.crawler_name = site["crawler"]
        else:
            self.crawler_name = self.cfg.section("Crawler")["default"]
        # Get the real crawler-class (already "fallen back")
        crawler_class = self.get_crawler(self.crawler_name, site["url"])

        if not self.cfg.section('Files')['relative_to_start_processes_file']:
            relative_to_path = os.path.dirname(self.cfg_file_path)
        else:
            # absolute dir this script is in
            relative_to_path = os.path.dirname(__file__)

        news_item_class_name = self.cfg.section("Scrapy").get("item_class", None)
        if not news_item_class_name:
            news_item_class = NewscrawlerItem
        else:
            news_item_class = ClassLoader.from_string(news_item_class_name)
            if not issubclass(news_item_class, NewscrawlerItem):
                raise ImportError("ITEM_CLASS must be a subclass of NewscrawlerItem")

        self.helper = Helper(self.cfg.section('Heuristics'),
                             self.cfg.section("Files")["local_data_directory"],
                             relative_to_path,
                             self.cfg.section('Files')['format_relative_path'],
                             sites,
                             crawler_class,
                             news_item_class,
                             self.cfg.get_working_path())

        self.__scrapy_options = self.cfg.get_scrapy_options()

        self.update_jobdir(site)

        # make sure the crawler does not resume crawling
        # if not stated otherwise in the arguments passed to this script
        self.remove_jobdir_if_not_resume()

        self.load_crawler(crawler_class,
                          site["url"],
                          ignore_regex)

        # start the job. if in library_mode, do not stop the reactor and so on after this job has finished
        # so that further jobs can be executed. it also needs to run in a thread since the reactor.run method seems
        # to not return. also, scrapy will attempt to start a new reactor, which fails with an exception, but
        # the code continues to run. we catch this excepion in the function 'start_process'.
        if library_mode:
            start_new_thread(start_process, (self.process, False,))
        else:
            self.process.start()

    def update_jobdir(self, site):
        """
        Update the JOBDIR in __scrapy_options for the crawler,
        so each crawler gets its own jobdir.

        :param object site: a site dict extracted from the json file
        """
        working_path = self.cfg.get_working_path()
        if not working_path.endswith("/"):
            working_path += "/"
        jobdirname = self.__scrapy_options["JOBDIRNAME"]
        if not jobdirname.endswith("/"):
            jobdirname += "/"

        site_string = ''.join(site["url"]) + self.crawler_name
        hashed = hashlib.md5(site_string.encode('utf-8'))

        self.__scrapy_options["JOBDIR"] = working_path + jobdirname + hashed.hexdigest()

    def get_crawler(self, crawler, url):
        """
        Checks if a crawler supports a website (the website offers e.g. RSS
        or sitemap) and falls back to the fallbacks defined in the config if
        the site is not supported.

        :param str crawler: Crawler-string (from the crawler-module)
        :param str url: the url this crawler is supposed to be loaded with
        :rtype: crawler-class or None
        """
        checked_crawlers = []
        while crawler is not None and crawler not in checked_crawlers:
            checked_crawlers.append(crawler)
            current = self.get_crawler_class(crawler)
            if hasattr(current, "supports_site"):
                supports_site = getattr(current, "supports_site")
                if callable(supports_site):
                    try:
                        crawler_supports_site = supports_site(url)
                    except Exception as e:
                        self.log.info(f'Crawler not supported due to: {str(e)}',
                                      exc_info=True)
                        crawler_supports_site = False

                    if crawler_supports_site:
                        self.log.debug("Using crawler %s for %s.",
                                       crawler, url)
                        return current
                    elif (crawler in self.cfg_crawler["fallbacks"] and
                                  self.cfg_crawler["fallbacks"][crawler] is not None):
                        self.log.warn("Crawler %s not supported by %s. "
                                      "Trying to fall back.", crawler, url)
                        crawler = self.cfg_crawler["fallbacks"][crawler]
                    else:
                        self.log.error("No crawlers (incl. fallbacks) "
                                       "found for url %s.", url)
                        raise RuntimeError("No crawler found. Quit.")
            else:
                self.log.warning("The crawler %s has no "
                                 "supports_site-method defined", crawler)
                return current
        self.log.error("Could not fall back since you created a fall back "
                       "loop for %s in the config file.", crawler)
        sys.exit(1)

    def get_crawler_class(self, crawler):
        """
        Searches through the modules in self.__crawer_module for a crawler with
        the name passed along.

        :param str crawler: Name of the crawler to load
        :rtype: crawler-class
        """
        settings = Settings()
        settings.set('SPIDER_MODULES', [self.__crawer_module])
        spider_loader = SpiderLoader(settings)
        return spider_loader.load(crawler)

    def load_crawler(self, crawler, url, ignore_regex):
        """
        Loads the given crawler with the given url.

        :param class crawler: class of the crawler to load
        :param str url: url to start the crawler with
        :param regex ignore_regex: to be able to ignore urls that match this
                                   regex code
        """
        self.process = CrawlerProcess(self.cfg.get_scrapy_options())
        self.process.crawl(
            crawler,
            self.helper,
            url=url,
            config=self.cfg,
            ignore_regex=ignore_regex)

    def remove_jobdir_if_not_resume(self):
        """
        This method ensures that there's no JOBDIR (with the name and path
        stated in the config file) any crawler would automatically resume
        crawling with if '--resume' isn't passed to this script.
        """
        jobdir = self.__scrapy_options["JOBDIR"]

        if (not self.shall_resume or self.daemonize) \
                and os.path.exists(jobdir):
            shutil.rmtree(jobdir)

            self.log.info("Removed " + jobdir + " since '--resume' was not passed to"
                                                " initial.py or this crawler was daemonized.")

def start_process(process, stop_after_job):
    try:
        process.start(stop_after_job)
    except ReactorAlreadyRunning:
        pass

if __name__ == "__main__":
    SingleCrawler(cfg_file_path=sys.argv[1],
                  json_file_path=sys.argv[2],
                  site_index=sys.argv[3],
                  shall_resume=sys.argv[4],
                  daemonize=sys.argv[5])


text:
pkmn::animation::animation() = default;
pkmn::animation::animation(geometry &container, const sequence &seq, std::size_t i) : frames(&seq), index(i), m_geometry(&container) {}
void pkmn::animation::operator()(timer &t) {
    index = (index + 1) % frames->count();
    m_geometry->value = &frames->at(index);
}

void pkmn::animation::reset(bool resetindex) {
    if (resetindex) {
        index = 0;
    }
    m_geometry->value = &frames->at(index);
}


text:
class Forum::AdminController < ModuleController
  before_filter :find_forum_category, :only => ['category', 'delete']

  helper 'forum/path'

  permit 'forum_config'

  component_info 'Forum', :description => 'Add Forums to your website',
                          :access => :private

  content_model :forums

  content_action  'Create a new Forum Category', { :controller => '/forum/admin', :action => 'category' }, :permit => 'forum_config'

  register_permission_category :forum, "Forum" ,"Permissions for Writing to and Managing Forums"

  register_permissions :forum, [[ :manage, 'Forum Management', 'Can Manage forums and posts' ],
                                [ :config, 'Forum Configuration', 'Can Create, Delete and Configure Forums'],
                                [ :post, 'Can Post', 'Can Post to Forums'],
                                [ :search, 'Can Search', 'Can Search Forums' ]
                             ]

  cms_admin_paths "options",
                  'Content' => { :controller => '/content' },
                  'Options' =>   { :controller => '/options' },
                  'Modules' =>  { :controller => '/modules' },
                  'Forum Options' => { :action => 'options' }

  register_action '/forum/new_post', :description => 'Forum New Post', :level => 3
  register_action '/forum/new_topic', :description => 'Forum New Topic', :level => 3

  register_handler :structure, :wizard, "Forum::WizardController"
  register_handler :webiva, :widget, "ForumWidget"

  public

  def self.get_forums_info
    ForumCategory.find(:all, :order => 'weight, name').collect do |category|
      {:name => "%s Forums" / category.name,
	:url => { :controller => '/forum/manage', :action=>'category', :path => category.id } ,
	:permission => { :model => category, :permission => :admin_permission, :base => :forum_manage },
	:icon => 'icons/content/forms_icon.png' }
    end
  end

  def options
    cms_page_path ['Options','Modules'], 'Forum Options'

    @options = self.class.module_options(params[:options])

    if request.post? && @options.valid?
      Configuration.set_config_model(@options)
      flash[:notice] = "Updated forum module options".t
      redirect_to :controller => '/modules'
      return
    end
  end

  def category
    if @forum_category.nil?
      @forum_category = ForumCategory.new(params[:forum_category] || { :add_to_site => true })
      cms_page_path ['Content'], 'Create a new Forum Category'
    else
      cms_page_path ['Content'], ['%s Forums', forum_category_url_for, @forum_category.name]
    end

    if request.post? && params[:forum_category]
      if @forum_category.update_attributes(params[:forum_category])
	flash[:notice] = params[:path][0] ? 'Updated Forum Category Configuration'.t : 'Created a new Forum Category'.t
	if @forum_category.add_to_site
	  redirect_to :controller => '/forum/wizard', :forum_category_id => @forum_category.id
	else
	  redirect_to forum_category_url_for
	end
      end
    end
  end

  def delete
    cms_page_path ['Content', ['%s Forums', forum_category_url_for, @forum_category.name]], 'Delete Forum Category'

    if request.post? && params[:destroy] == 'yes'
      @forum_category.destroy
      flash[:notice] = 'Deleted "%s" Forum Category' / @forum_category.name
      redirect_to :controller => '/content', :action => 'index'
    end
  end

  def self.module_options(vals=nil)
    Configuration.get_config_model(Options,vals)
  end

  class Options < HashModel
    attributes :subscription_template_id => nil

    integer_options :subscription_template_id
  end

  module AdminModule
    include Forum::PathHelper

    def find_forum_category
      @forum_category ||= ForumCategory.find(params[:path][0]) if params[:path][0]
    end
  end

  include AdminModule
end


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

<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<Title>The Boost Graph Library</Title>

The Boost Graph Library (BGL)

Graphs are mathematical abstractions that are useful for solving many
types of problems in computer science. Consequently, these
abstractions must also be represented in computer programs.  A
standardized generic interface for traversing graphs is of utmost
importance to encourage reuse of graph algorithms and data structures.
Part of the Boost Graph Library is a generic interface that allows
access to a graph's structure, but hides the details of the
implementation.  This is an “open” interface in the sense that any
graph library that implements this interface will be interoperable
with the BGL generic algorithms and with other algorithms that also
use this interface. The BGL provides some general purpose graph classes
that conform to this interface, but they are not meant to be the
“only” graph classes; there certainly will be other graph classes
that are better for certain situations.  We believe that the main
contribution of the The BGL is the formulation of this interface.

The BGL graph interface and graph components are generic, in the
same sense as the Standard Template Library (STL) [2].

In the following sections, we review the role that generic programming
plays in the STL and compare that to how we applied generic
programming in the context of graphs.

Of course, if you are already familiar with generic programming,
please dive right in! Here's the Table of Contents.  For distributed-memory
parallelism, you can also look at the Parallel BGL.

The source for the BGL is available as part of the Boost distribution,
which you can
download from here.

How to Build the BGL

DON'T! The Boost Graph Library is a header-only library and
does not need to be built to be used. The only exceptions are the GraphViz input parser and the GraphML parser.

When compiling programs that use the BGL, be sure to compile
with optimization. For instance, select “Release” mode with
Microsoft Visual C++ or supply the flag <tt>-O2</tt> or <tt>-O3</tt>
to GCC.

Genericity in STL

There are three ways in which the STL is generic.

Algorithm/Data-Structure Interoperability

First, each algorithm is written in a data-structure neutral way,
allowing a single template function to operate on many different
classes of containers. The concept of an iterator is the key
ingredient in this decoupling of algorithms and data-structures.  The
impact of this technique is a reduction in the STL's code size from
O(M*N) to O(M+N), where M is the number of
algorithms and N is the number of containers. Considering a
situation of 20 algorithms and 5 data-structures, this would be the
difference between writing 100 functions versus only 25 functions! And
the differences continues to grow faster and faster as the number of
algorithms and data-structures increase.

Extension through Function Objects

The second way that STL is generic is that its algorithms and containers
are extensible. The user can adapt and customize the STL through the
use of function objects. This flexibility is what makes STL such a
great tool for solving real-world problems. Each programming problem
brings its own set of entities and interactions that must be
modeled. Function objects provide a mechanism for extending the STL to
handle the specifics of each problem domain.

Element Type Parameterization

The third way that STL is generic is that its containers are
parameterized on the element type. Though hugely important, this is
perhaps the least “interesting” way in which STL is generic.
Generic programming is often summarized by a brief description of
parameterized lists such as <TT>std::list<T></TT>. This hardly scratches
the surface!

Genericity in the Boost Graph Library

Like the STL, there are three ways in which the BGL is generic.

Algorithm/Data-Structure Interoperability

First, the graph algorithms of the BGL are written to an interface that
abstracts away the details of the particular graph data-structure.
Like the STL, the BGL uses iterators to define the interface for
data-structure traversal. There are three distinct graph traversal
patterns: traversal of all vertices in the graph, through all of the
edges, and along the adjacency structure of the graph (from a vertex
to each of its neighbors). There are separate iterators for each
pattern of traversal.

This generic interface allows template functions such as <TT>breadth_first_search()</TT>
to work on a large variety of graph data-structures, from graphs
implemented with pointer-linked nodes to graphs encoded in
arrays. This flexibility is especially important in the domain of
graphs. Graph data-structures are often custom-made for a particular
application. Traditionally, if programmers want to reuse an
algorithm implementation they must convert/copy their graph data into
the graph library's prescribed graph structure.  This is the case with
libraries such as LEDA, GTL, Stanford GraphBase; it is especially true
of graph algorithms written in Fortran. This severely limits the reuse
of their graph algorithms.

In contrast, custom-made (or even legacy) graph structures can be used
as-is with the generic graph algorithms of the BGL, using external
adaptation (see Section How to
Convert Existing Graphs to the BGL).  External adaptation wraps a new
interface around a data-structure without copying and without placing
the data inside adaptor objects.  The BGL interface was carefully
designed to make this adaptation easy. To demonstrate this, we have
built interfacing code for using a variety of graph dstructures (LEDA
graphs, Stanford GraphBase graphs, and even Fortran-style arrays) in
BGL graph algorithms.

Extension through Visitors

Second, the graph algorithms of the BGL are extensible. The BGL introduces the
notion of a visitor, which is just a function object with
multiple methods.  In graph algorithms, there are often several key
“event points” at which it is useful to insert user-defined
operations. The visitor object has a different method that is invoked
at each event point. The particular event points and corresponding
visitor methods depend on the particular algorithm.  They often
include methods like <TT>start_vertex()</TT>,
<TT>discover_vertex()</TT>, <TT>examine_edge()</TT>,
<tt>tree_edge()</tt>, and <TT>finish_vertex()</TT>.

Vertex and Edge Property Multi-Parameterization

The third way that the BGL is generic is analogous to the parameterization
of the element-type in STL containers, though again the story is a bit
more complicated for graphs. We need to associate values (called
“properties”) with both the vertices and the edges of the graph.
In addition, it will often be necessary to associate
multiple properties with each vertex and edge; this is what we mean
by multi-parameterization.
The STL <tt>std::list<T></tt> class has a parameter <tt>T</tt>
for its element type. Similarly, BGL graph classes have template
parameters for vertex and edge “properties”. A
property specifies the parameterized type of the property and also assigns
an identifying tag to the property. This tag is used to distinguish
between the multiple properties which an edge or vertex may have. A
property value that is attached to a
particular vertex or edge can be obtained via a property
map. There is a separate property map for each property.

Traditional graph libraries and graph structures fall down when it
comes to the parameterization of graph properties. This is one of the
primary reasons that graph data-structures must be custom-built for
applications. The parameterization of properties in the  BGL graph
classes makes them well suited for re-use.

Algorithms

The BGL algorithms consist of a core set of algorithm patterns
(implemented as generic algorithms) and a larger set of graph
algorithms. The core algorithm patterns are

Breadth First Search

Depth First Search

Uniform Cost Search

By themselves, the algorithm patterns do not compute any meaningful
quantities over graphs; they are merely building blocks for
constructing graph algorithms. The graph algorithms in the BGL currently
include

Dijkstra's Shortest Paths

Bellman-Ford Shortest Paths

Johnson's All-Pairs Shortest Paths

Kruskal's Minimum Spanning Tree

Prim's Minimum Spanning Tree

Connected Components

Strongly Connected Components

Dynamic Connected Components (using Disjoint Sets)

Topological Sort

Transpose

Reverse Cuthill Mckee Ordering

Smallest Last Vertex Ordering

Sequential Vertex Coloring

Data Structures

The BGL currently provides two graph classes and an edge list adaptor:

<TT>adjacency_list</TT>

<TT>adjacency_matrix</TT>

<TT>edge_list</TT>

The <TT>adjacency_list</TT> class is the general purpose “swiss army
knife” of graph classes. It is highly parameterized so that it can be
optimized for different situations: the graph is directed or
undirected, allow or disallow parallel edges, efficient access to just
the out-edges or also to the in-edges, fast vertex insertion and
removal at the cost of extra space overhead, etc.

The <tt>adjacency_matrix</tt> class stores edges in a |V| x |V|
matrix (where |V| is the number of vertices). The elements of
this matrix represent edges in the graph. Adjacency matrix
representations are especially suitable for very dense graphs, i.e.,
those where the number of edges approaches |V|2.

The <TT>edge_list</TT> class is an adaptor that takes any kind of edge
iterator and implements an Edge List Graph.

Copyright © 2000-2001
Jeremy Siek,
Indiana University (jsiek@osl.iu.edu)

Lie-Quan Lee, Indiana University (llee@cs.indiana.edu)

Andrew Lumsdaine,
Indiana University (lums@osl.iu.edu)


text:
#ifndef _QCAR_OBB3D_H_
#define _QCAR_OBB3D_H_

#include "QCAR.h"
#include "Vectors.h"

namespace QCAR
{

/// An Obb3D represents a 3D bounding box oriented along z-direction
class QCAR_API Obb3D
{
public:

    /// Constructor.
    Obb3D();

    /// Copy constructor.
    Obb3D(const Obb3D& other);

    /// Construct from center, half extents and rotation.
    Obb3D(const Vec3F& nCenter, const Vec3F& nHalfExtents,
        float nRotationZ);

    /// Returns the center of the bounding box.
    virtual const Vec3F& getCenter() const;

    /// Returns the half width, depth, and height of the bounding box.
    virtual const Vec3F& getHalfExtents() const;

    /// Returns the counter-clock-wise rotation angle (in radians)
    /// of the bounding box with respect to the Z axis.
    virtual float getRotationZ() const;

    virtual ~Obb3D();

protected:
    Vec3F center;
    Vec3F halfExtents;
    float rotation;
};

} // namespace QCAR

#endif // _QCAR_OBB3D_H_


text:
package kafka.serializer;

import kafka.utils.VerifiableProperties;

/**
 * The default implementation is a no-op, it just returns the same array it takes in
 */
public class DefaultEncoder implements Encoder<byte[]> {
    public VerifiableProperties props;

    public DefaultEncoder() {

    }

    public DefaultEncoder(VerifiableProperties props) {
        this.props = props;
    }

    @Override
    public byte[] toBytes(byte[] bytes) {
        return bytes;
    }
}


text:
package org.spongepowered.api.data.types;

import org.spongepowered.api.CatalogType;
import org.spongepowered.api.util.annotation.CatalogedBy;

@CatalogedBy(TreeTypes.class)
public interface TreeType extends CatalogType {

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Uredo celastrineae Cooke & Massee

### Remarks
null


text:
package cz.hrnr.matroskabatch.muxing;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import cz.hrnr.matroskabatch.track.Container;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.value.ObservableDoubleValue;

/**
 * Executing service which muxes provided muxing data
 * into Matroska containers.
 *
 * Tasks may be executed in any order.
 *
 * Methods are not generally guaranteed to be thread-safe.
 * However implementations may guarantee thread-safety of some methods.
 *
 */
public abstract class AbstractMuxingService {
	protected AtomicInteger totalTasks = new AtomicInteger(0);
	protected AtomicInteger completedTasks = new AtomicInteger(0);
//	access to progress property should be synchronized
	protected DoubleProperty progress = new SimpleDoubleProperty(0);

	/**
	 * Add muxing data to muxing queue
	 *
	 * @param data containers to mux
	 */
	public abstract void addMuxingData(List<Container> data);

	/**
	 * Gets overall progress, i.e. number of proceeded tasks vs.
	 * all scheduled tasks.
	 *
	 * This method is thread-safe.
	 * @return progress in percents in [0..1]
	 */
	public double getProgress() {
		// progress may be accesed by concurent workers
		synchronized(progress) {
			return progress.get();
		}
	}

	/**
	 * Property indicating completed tasks of this service
	 *
	 * This is value in [0..1] indication number of completed tasks in percent
	 *
	 * @return
	 */
	public ObservableDoubleValue progressProperty() {
		return progress;
	}

	/**
	 * Convenient method for adding muxing data to service.
	 *
	 * Same as calling #addMuxingData() with {@link MuxingTree#getMuxingData()}
	 *
	 * @param tree
	 */
	public void addTree(MuxingTree tree) {
		addMuxingData(tree.getMuxingData());
	}

	/**
	 * Resets progress as if not tasks had been submitted
	 * to MuxingService.
	 *
	 * This method is not thread-save. This should be called only when service
	 * is not running, i.e. is shutdown.
	 */
	public void resetProgress() {
		completedTasks.set(0);
		totalTasks.set(0);
		synchronized (progress) {
			progress.set(0);
		}
	}

	/**
	 * Stops MuxingService from processing further tasks. Service
	 * may or may not complete tasks that has been already started.
	 */
	public abstract void shutdown();

}


text:
package wumpus;

import org.junit.Test;

import static org.junit.Assert.*;

public class RoomTest {

        Room east = new Room();
        Room south = new Room();
        Room north = new Room();
        Room west = new Room();
        Room room = new Room(east, west, north, south);
        Room roomWithALLTHEWALLS = new Room(Room.WALL, Room.WALL, Room.WALL, Room.WALL);

    @Test
    public void navgiation(){

        assertSame(east, room.goEast());
        assertSame(west, room.goWest());
        assertSame(south, room.goSouth());
        assertSame(north, room.goNorth());
    }

    @Test
    public void wumpus_movement_east(){
        Room wumpusStartRoom = room;

        wumpusStartRoom.placeWumpus();
        Room wumpusEndRoom = wumpusStartRoom.goEast();

        assertTrue("we moved east so it shall be in the east room", wumpusEndRoom.hasWumpus());
        assertFalse("Wumpus hsall be moved, not cloned", wumpusStartRoom.hasWumpus());
    }

    @Test
    public void wumpus_movement_west(){
        Room wumpusStartRoom = room;

        wumpusStartRoom.placeWumpus();
        Room wumpusEndRoom = wumpusStartRoom.goWest();

        assertTrue("we moved W west so it shall be in the west room", wumpusEndRoom.hasWumpus());
        assertFalse("Wumpus hsall be moved, not cloned", wumpusStartRoom.hasWumpus());
    }

    @Test
    public void hero_movement_north(){
        Room heroStartRoom = room;

        heroStartRoom.placeHero();
        Room heroEndRoom = heroStartRoom.goNorth();

        assertTrue("we moved H north so it shall be in the north room", heroEndRoom.hasHero());
        assertFalse("Hero hsall be moved, not cloned", heroStartRoom.hasHero());
    }

    @Test
    public void cannot_move_into_wall_north(){
        Room heroStartRoom = roomWithALLTHEWALLS;

         heroStartRoom.placeHero();
         Room heroEndRoom = heroStartRoom.goNorth();

        assertTrue(heroStartRoom.north.isWall());
        assertNull("Cannot move into a wall!", heroEndRoom);
    }
    @Test
    public void cannot_move_into_wall_south(){
        Room heroStartRoom = roomWithALLTHEWALLS;

         heroStartRoom.placeHero();
         Room heroEndRoom = heroStartRoom.goSouth();

        assertTrue(heroStartRoom.south.isWall());
        assertNull("Cannot move into a wall!", heroEndRoom);
    }
    @Test
    public void cannot_move_into_wall_east(){
        Room heroStartRoom = roomWithALLTHEWALLS;

         heroStartRoom.placeHero();
         Room heroEndRoom = heroStartRoom.goEast();

        assertTrue(heroStartRoom.east.isWall());
        assertNull("Cannot move into a wall!", heroEndRoom);
    }
    @Test
    public void cannot_move_into_wall_west(){
        Room heroStartRoom = roomWithALLTHEWALLS;     //haha you are trapped

         heroStartRoom.placeHero();
         Room heroEndRoom = heroStartRoom.goWest();

        assertTrue(heroStartRoom.west.isWall());
        assertNull("Cannot move into a wall!", heroEndRoom);
    }

    @Test
    public void movePlayerIntoPitKillsHimDead() throws Exception {
        Room pitRoom = new Room();
        pitRoom.setPit(true);

        room.north = pitRoom;

        room.placeHero();

        Room destination = room.goNorth();

        assertEquals(Room.DEAD, destination);

    }

    @Test
    public void movePlayerNearPitWindIsBlowing() throws Exception {
        Room pitRoom = new Room();
        pitRoom.setPit(true);

        Room windRoom = new Room();
        windRoom.north = pitRoom;
        room.north = windRoom;

        Room destination = room.goNorth();
        assert(destination.isWindy());
    }
}


text:
package nettools

import (
	"fmt"
	"log"
	"net"
	"os/exec"
	"reflect"
	"testing"

	"github.com/containernetworking/cni/pkg/ns"
	cnitypes "github.com/containernetworking/cni/pkg/types"
	cnicurrent "github.com/containernetworking/cni/pkg/types/current"
	"github.com/davecgh/go-spew/spew"
	"github.com/vishvananda/netlink"
)

const (
	innerHwAddr       = "42:a4:a6:22:80:2e"
	outerHwAddr       = "42:b5:b7:33:91:3f"
	secondInnerHwAddr = "42:a4:a6:22:80:2f"
	secondOuterHwAddr = "42:b5:b7:33:91:3e"
	dummyInnerHwAddr  = "42:a4:a6:22:80:40"
	dummyOuterHwAddr  = "42:b5:b7:33:91:4f"
)

func expectedExtractedLinkInfo(contNsPath string) *cnicurrent.Result {
	return &cnicurrent.Result{
		Interfaces: []*cnicurrent.Interface{
			{
				Name:    "eth0",
				Mac:     innerHwAddr,
				Sandbox: contNsPath,
			},
		},
		IPs: []*cnicurrent.IPConfig{
			{
				Version:   "4",
				Interface: 0,
				Address: net.IPNet{
					IP:   net.IP{10, 1, 90, 5},
					Mask: net.IPMask{255, 255, 255, 0},
				},
				Gateway: net.IP{10, 1, 90, 1},
			},
		},
		Routes: []*cnitypes.Route{
			{
				Dst: net.IPNet{
					IP:   net.IP{0, 0, 0, 0},
					Mask: net.IPMask{0, 0, 0, 0},
				},
				GW: net.IP{10, 1, 90, 1},
			},
		},
	}
}

// withTemporaryNSAvailable creates a new network namespace and
// passes is as an argument to the specified function.
// It does NOT change current network namespace.
func withTempNetNS(t *testing.T, toRun func(ns ns.NetNS)) {
	ns, err := ns.NewNS()
	if err != nil {
		t.Errorf("Error creating network namespace: %v", err)
		return
	}
	defer func() {
		// We use log.Panicf() instead of t.Fatalf() in these tests
		// because ns.Do() uses separate goroutine
		if r := recover(); r != nil {
			t.Fatal(r)
		}
		if err = ns.Close(); err != nil {
			t.Fatalf("Error closing network namespace: %v", err)
		}
	}()
	toRun(ns)
}

func inNS(netNS ns.NetNS, name string, toRun func()) {
	var r interface{}
	if err := netNS.Do(func(ns.NetNS) error {
		defer func() {
			//r = recover()
		}()
		toRun()
		return nil
	}); err != nil {
		log.Fatalf("failed to enter %s: %v", name, err)
	}

	// re-panic in the original goroutine
	if r != nil {
		log.Panic(r)
	}
}

// withHostAndContNS creates two namespaces, one serving as 'host'
// namespace and one serving as 'container' one, and calls
// the specified function in the 'host' namespace, passing both
// namespaces to it.
func withHostAndContNS(t *testing.T, toRun func(hostNS, contNS ns.NetNS)) {
	withTempNetNS(t, func(hostNS ns.NetNS) {
		withTempNetNS(t, func(contNS ns.NetNS) {
			inNS(hostNS, "hostNS", func() { toRun(hostNS, contNS) })
		})
	})
}

func verifyLinkUp(t *testing.T, name, title string) netlink.Link {
	link, err := netlink.LinkByName(name)
	if err != nil {
		log.Panicf("cannot locate link: %s", title)
	}
	if link.Attrs().Flags&net.FlagUp == 0 {
		t.Errorf("link should be up, but it's down: %s", title)
	}
	return link
}

func verifyNoLink(t *testing.T, name, title string) {
	if _, err := netlink.LinkByName(name); err == nil {
		t.Errorf("link should not be present: %s", title)
	}
}

func verifyBridgeMember(t *testing.T, name, title string, bridge netlink.Link) netlink.Link {
	if bridge.Type() != "bridge" {
		log.Panicf("link %q is not a bridge", bridge.Attrs().Name)
	}
	link := verifyLinkUp(t, name, title)
	if link.Attrs().MasterIndex != bridge.Attrs().Index {
		t.Errorf("link %q doesn't belong to bridge %q", name, bridge.Attrs().Name)
	}
	return link
}

func TestEscapePair(t *testing.T) {
	withHostAndContNS(t, func(hostNS, contNS ns.NetNS) {
		hostVeth, contVeth, err := CreateEscapeVethPair(contNS, "esc0", 1500)
		if err != nil {
			log.Panicf("Error creating escape veth pair: %v", err)
		}
		// need to force hostNS here because of side effects of NetNS.Do()
		// See https://github.com/vishvananda/netns/issues/17
		inNS(hostNS, "hostNS", func() {
			verifyLinkUp(t, hostVeth.Attrs().Name, "host veth")
			verifyNoLink(t, contVeth.Attrs().Name, "container veth in host namespace")
		})
		inNS(contNS, "contNS", func() {
			verifyLinkUp(t, contVeth.Attrs().Name, "container veth")
			verifyNoLink(t, hostVeth.Attrs().Name, "host veth in container namespace")
		})
	})
}

func makeTestVeth(t *testing.T, base string, index int) netlink.Link {
	name := fmt.Sprintf("%s%d", base, index)
	veth := &netlink.Veth{
		LinkAttrs: netlink.LinkAttrs{
			Name:  name,
			Flags: net.FlagUp,
			MTU:   1500,
		},
		PeerName: "p" + name,
	}
	if err := netlink.LinkAdd(veth); err != nil {
		log.Panicf("failed to create veth: %v", err)
	}

	return veth
}

func makeTestBridge(t *testing.T, name string, links []netlink.Link) *netlink.Bridge {
	br, err := SetupBridge(name, links)
	if err != nil {
		log.Panicf("failed to create first bridge: %v", err)
	}
	if br.Attrs().Name != name {
		log.Panicf("bad bridge name: %q instead of %q", br.Attrs().Name, name)
	}
	verifyLinkUp(t, name, "bridge")
	return br
}

func TestSetupBridge(t *testing.T) {
	withTempNetNS(t, func(hostNS ns.NetNS) {
		inNS(hostNS, "hostNS", func() {
			var links []netlink.Link
			for i := 0; i < 4; i++ {
				links = append(links, makeTestVeth(t, "veth", i))
			}

			brs := []*netlink.Bridge{
				makeTestBridge(t, "testbr0", links[0:2]),
				makeTestBridge(t, "testbr1", links[2:4]),
			}
			if brs[0].Attrs().Name == brs[1].Attrs().Name {
				t.Errorf("bridges have identical name %q", brs[0].Attrs().Name)
			}
			if brs[0].Attrs().Index == brs[1].Attrs().Index {
				t.Errorf("bridges have the same index %d", brs[0].Attrs().Index)
			}

			for i := 0; i < 4; i++ {
				name := links[i].Attrs().Name
				verifyBridgeMember(t, name, name, brs[i/2])
			}
		})
	})
}

func parseAddr(addr string) *netlink.Addr {
	r, err := netlink.ParseAddr(addr)
	if err != nil {
		log.Panicf("failed to parse addr: %v", err)
	}
	return r
}

func addTestRoute(t *testing.T, route *netlink.Route) {
	if err := netlink.RouteAdd(route); err != nil {
		log.Panicf("Failed to add route %#v: %v", route, err)
	}
}

func setupLink(hwAddrAsText string, link netlink.Link) netlink.Link {
	hwAddr, err := net.ParseMAC(hwAddrAsText)
	if err != nil {
		log.Panicf("Error parsing hwaddr %q: %v", hwAddrAsText, err)
	}
	if err := SetHardwareAddr(link, hwAddr); err != nil {
		log.Panicf("Error setting hardware address: %v", err)
	}

	// re-query attrs (including new mac)
	link, err = netlink.LinkByName(link.Attrs().Name)
	if err != nil {
		log.Panicf("cannot locate link: %s", link.Attrs().Name)
	}

	return link
}

func withFakeCNIVeth(t *testing.T, mtu int, toRun func(hostNS, contNS ns.NetNS, origHostVeth, origContVeth netlink.Link)) {
	withHostAndContNS(t, func(hostNS, contNS ns.NetNS) {
		origHostVeth, origContVeth, err := CreateEscapeVethPair(contNS, "eth0", mtu)
		if err != nil {
			log.Panicf("failed to create veth pair: %v", err)
		}
		// need to force hostNS here because of side effects of NetNS.Do()
		// See https://github.com/vishvananda/netns/issues/17
		inNS(hostNS, "hostNS", func() {
			origHostVeth = setupLink(outerHwAddr, origHostVeth)
		})
		inNS(contNS, "contNS", func() {
			origContVeth = setupLink(innerHwAddr, origContVeth)

			if err = netlink.AddrAdd(origContVeth, parseAddr("10.1.90.5/24")); err != nil {
				log.Panicf("failed to add addr for origContVeth: %v", err)
			}

			toRun(hostNS, contNS, origHostVeth, origContVeth)
		})
	})
}

func withFakeCNIVethAndGateway(t *testing.T, mtu int, toRun func(hostNS, contNS ns.NetNS, origHostVeth, origContVeth netlink.Link)) {
	withFakeCNIVeth(t, mtu, func(hostNS, contNS ns.NetNS, origHostVeth, origContVeth netlink.Link) {
		addTestRoute(t, &netlink.Route{
			Gw:    parseAddr("10.1.90.1/24").IPNet.IP,
			Scope: SCOPE_UNIVERSE,
		})

		toRun(hostNS, contNS, origHostVeth, origContVeth)
	})
}

func verifyNoAddressAndRoutes(t *testing.T, link netlink.Link) {
	if routes, err := netlink.RouteList(link, FAMILY_V4); err != nil {
		t.Errorf("failed to get route list: %v", err)
	} else if len(routes) != 0 {
		t.Errorf("unexpected routes remain on the interface: %s", spew.Sdump(routes))
	}

	if addrs, err := netlink.AddrList(link, FAMILY_V4); err != nil {
		t.Errorf("failed to get addresses for veth: %v", err)
	} else if len(addrs) != 0 {
		t.Errorf("unexpected addresses remain on the interface: %s", spew.Sdump(addrs))
	}
}

func TestFindVeth(t *testing.T) {
	withFakeCNIVethAndGateway(t, defaultMTU, func(hostNS, contNS ns.NetNS, origHostVeth, origContVeth netlink.Link) {
		allLinks, err := netlink.LinkList()
		if err != nil {
			log.Panicf("LinkList() failed: %v", err)
		}
		contVeth, err := FindVeth(allLinks)
		if err != nil {
			log.Panicf("FindVeth() failed: %v", err)
		}

		if contVeth.Attrs().Index != origContVeth.Attrs().Index {
			t.Errorf("GrabInterfaceInfo() didn't return original cont veth. Interface returned: %q", origContVeth.Attrs().Name)
		}
	})
}

func TestStripLink(t *testing.T) {
	withFakeCNIVethAndGateway(t, defaultMTU, func(hostNS, contNS ns.NetNS, origHostVeth, origContVeth netlink.Link) {
		if err := StripLink(origContVeth); err != nil {
			log.Panicf("StripLink() failed: %v", err)
		}
		verifyNoAddressAndRoutes(t, origContVeth)
	})
}

func TestExtractLinkInfo(t *testing.T) {
	withFakeCNIVethAndGateway(t, defaultMTU, func(hostNS, contNS ns.NetNS, origHostVeth, origContVeth netlink.Link) {
		info, err := ExtractLinkInfo(origContVeth, contNS.Path())
		if err != nil {
			log.Panicf("failed to grab interface info: %v", err)
		}
		expectedInfo := expectedExtractedLinkInfo(contNS.Path())
		if !reflect.DeepEqual(info, expectedInfo) {
			t.Errorf("interface info mismatch. Expected:\n%s\nActual:\n%s",
				spew.Sdump(expectedInfo), spew.Sdump(*info))
		}
	})
}

func verifyContainerSideNetwork(t *testing.T, origContVeth netlink.Link, contNsPath string, hostNS ns.NetNS, mtu int) {
	allLinks, err := netlink.LinkList()
	if err != nil {
		log.Panicf("error listing links: %v", err)
	}

	origHwAddr := origContVeth.Attrs().HardwareAddr
	expectedInfo := expectedExtractedLinkInfo(contNsPath)
	csn, err := SetupContainerSideNetwork(expectedInfo, contNsPath, allLinks, false, hostNS)
	if err != nil {
		log.Panicf("failed to set up container side network: %v", err)
	}
	expectedInfo = expectedExtractedLinkInfo(contNsPath)
	if !reflect.DeepEqual(csn.Result, expectedInfo) {
		t.Errorf("interface info mismatch. Expected:\n%s\nActual:\n%s",
			spew.Sdump(expectedInfo), spew.Sdump(*csn.Result))
	}
	if !reflect.DeepEqual(origHwAddr, csn.Interfaces[0].HardwareAddr) {
		t.Errorf("bad hwaddr returned from SetupContainerSideNetwork: %v instead of %v", csn.Interfaces[0].HardwareAddr, origHwAddr)
	}
	// re-query origContVeth attrs
	origContVeth, err = netlink.LinkByName(origContVeth.Attrs().Name)
	if err != nil {
		log.Panicf("the original cni veth is gone")
	}
	if reflect.DeepEqual(origContVeth.Attrs().HardwareAddr, origHwAddr) {
		t.Errorf("cni veth hardware address didn't change")
	}
	if origContVeth.Attrs().MTU != mtu {
		t.Errorf("bad veth MTU: %d instead of %d", origContVeth.Attrs().MTU, mtu)
	}

	verifyNoAddressAndRoutes(t, origContVeth)

	bridge := verifyLinkUp(t, "br0", "in-container bridge")
	verifyBridgeMember(t, origContVeth.Attrs().Name, "origContVeth", bridge)
	tap := verifyBridgeMember(t, "tap0", "tap0", bridge)
	if tap.Type() != "tun" {
		t.Errorf("tap0 interface must have type tun, but has %q instead", tap.Type())
	}
	if tap.Attrs().MTU != mtu {
		t.Errorf("bad tap MTU: %d instead of %d", tap.Attrs().MTU, mtu)
	}

	addrs, err := netlink.AddrList(bridge, FAMILY_V4)
	if err != nil {
		t.Errorf("failed to get addresses for dhcp-side veth: %v", err)
	}
	expectedAddr := "169.254.254.2/24 br0"
	if len(addrs) != 1 {
		t.Errorf("br0 should have exactly one address, but got this instead: %v", spew.Sdump(addrs))
	} else if addrs[0].String() != expectedAddr {
		t.Errorf("bad br0 address %q (expected %q)", addrs[0].String(), expectedAddr)
	}

	if bridge.Attrs().MTU != mtu {
		t.Errorf("bad bridge MTU: %d instead of %d", bridge.Attrs().MTU, mtu)
	}
}

func TestSetUpContainerSideNetworkWithInfo(t *testing.T) {
	withFakeCNIVethAndGateway(t, defaultMTU, func(hostNS, contNS ns.NetNS, origHostVeth, origContVeth netlink.Link) {
		if err := StripLink(origContVeth); err != nil {
			log.Panicf("StripLink() failed: %v", err)
		}
		verifyContainerSideNetwork(t, origContVeth, contNS.Path(), hostNS, defaultMTU)
	})
}

func TestSetUpContainerSideNetworkMTU(t *testing.T) {
	withFakeCNIVethAndGateway(t, 9000, func(hostNS, contNS ns.NetNS, origHostVeth, origContVeth netlink.Link) {
		if err := StripLink(origContVeth); err != nil {
			log.Panicf("StripLink() failed: %v", err)
		}
		verifyContainerSideNetwork(t, origContVeth, contNS.Path(), hostNS, 9000)
	})
}

func TestLoopbackInterface(t *testing.T) {
	withFakeCNIVethAndGateway(t, defaultMTU, func(hostNS, contNS ns.NetNS, origHostVeth, origContVeth netlink.Link) {
		verifyContainerSideNetwork(t, origContVeth, contNS.Path(), hostNS, defaultMTU)
		if out, err := exec.Command("ping", "-c", "1", "127.0.0.1").CombinedOutput(); err != nil {
			log.Panicf("ping 127.0.0.1 failed:\n%s", out)
		}
	})
}

func stringInList(expected string, list []string) bool {
	for _, element := range list {
		if element == expected {
			return true
		}
	}

	return false
}

func verifyNoLinks(t *testing.T, linkNames []string) {
	links, err := netlink.LinkList()
	if err != nil {
		log.Panicf("netlink.LinkList failed: %v", err)
	}

	for _, link := range links {
		linkName := link.Attrs().Name
		if stringInList(linkName, linkNames) {
			t.Errorf("there should not be interface called %s in container namespace", linkName)
		}
	}
}

func verifyVethHaveConfiguration(t *testing.T, info *cnicurrent.Result) {
	allLinks, err := netlink.LinkList()
	if err != nil {
		log.Panicf("LinkList() failed: %v", err)
	}
	contVeth, err := FindVeth(allLinks)
	if err != nil {
		log.Panicf("FindVeth() failed: %v", err)
	}

	addrList, err := netlink.AddrList(contVeth, FAMILY_V4)
	if err != nil {
		log.Panicf("AddrList() failed: %v", err)
	}

	if len(addrList) != 1 {
		t.Errorf("veth should have single address but have: %d", len(addrList))
	}
	if !addrList[0].IP.Equal(info.IPs[0].Address.IP) {
		t.Errorf("veth has ip %s wherever expected is %s", addrList[0].IP.String(), info.IPs[0].Address.IP.String())
	}
	addrMaskSize := addrList[0].Mask.String()
	desiredMaskSize := info.IPs[0].Address.Mask.String()
	if addrMaskSize != desiredMaskSize {
		t.Errorf("veth has ipmask %s wherever expected is %s", addrMaskSize, desiredMaskSize)
	}

	routeList, err := netlink.RouteList(contVeth, FAMILY_V4)
	if err != nil {
		log.Panicf("RouteList() failed: %v", err)
	}

	for _, route := range routeList {
		if route.Gw != nil {
			if route.Gw.String() == info.Routes[0].GW.String() {
				return
			}
		}
	}

	t.Errorf("not found desired route to: %s", info.Routes[0].GW.String())
}

func TestTeardownContainerSideNetwork(t *testing.T) {
	withFakeCNIVethAndGateway(t, defaultMTU, func(hostNS, contNS ns.NetNS, origHostVeth, origContVeth netlink.Link) {
		if err := StripLink(origContVeth); err != nil {
			log.Panicf("StripLink() failed: %v", err)
		}
		allLinks, err := netlink.LinkList()
		if err != nil {
			log.Panicf("error listing links: %v", err)
		}

		csn, err := SetupContainerSideNetwork(expectedExtractedLinkInfo(contNS.Path()), contNS.Path(), allLinks, false, hostNS)
		if err != nil {
			log.Panicf("failed to set up container side network: %v", err)
		}

		if err := Teardown(csn); err != nil {
			log.Panicf("failed to tear down container side network: %v", err)
		}

		verifyNoLinks(t, []string{"br0", "tap0"})
		verifyVethHaveConfiguration(t, expectedExtractedLinkInfo(contNS.Path()))

		// re-quiry origContVeth attrs
		origContVeth, err = netlink.LinkByName(origContVeth.Attrs().Name)
		if err != nil {
			log.Panicf("the original cni veth is gone")
		}
		if !reflect.DeepEqual(origContVeth.Attrs().HardwareAddr, csn.Interfaces[0].HardwareAddr) {
			t.Errorf("cni veth hardware address wasn't restored")
		}
	})
}

func TestFindingLinkByAddress(t *testing.T) {
	withFakeCNIVeth(t, defaultMTU, func(hostNS, contNS ns.NetNS, origHostVeth, origContVeth netlink.Link) {
		expectedInfo := expectedExtractedLinkInfo(contNS.Path())
		allLinks, err := netlink.LinkList()
		if err != nil {
			log.Panicf("LinkList() failed: %v", err)
		}

		link, err := findLinkByAddress(allLinks, expectedInfo.IPs[0].Address)
		if err != nil {
			t.Errorf("didn't found preconfigured link: %v", err)
		}
		if link == nil {
			t.Errorf("<nil> where configured link was expected")
		}

		link, err = findLinkByAddress(allLinks, *parseAddr("1.2.3.4/8").IPNet)
		if link != nil {
			t.Errorf("found link with dummy address")
		}
		if err == nil {
			t.Errorf("expected error but received <nil>")
		}
	})
}

func withMultipleInterfacesConfigured(t *testing.T, toRun func(contNS ns.NetNS, innerLinks []netlink.Link)) {
	withHostAndContNS(t, func(hostNS, contNS ns.NetNS) {
		var origContVeths [2]netlink.Link
		for n, vp := range []struct {
			name        string
			outerHwAddr string
			innerHwAddr string
			ip          string
		}{
			{"eth0", outerHwAddr, innerHwAddr, "10.1.90.5/24"},
			{"eth1", secondOuterHwAddr, secondInnerHwAddr, "192.168.37.8/16"},
		} {
			origHostVeth, origContVeth, err := CreateEscapeVethPair(contNS, vp.name, 1500)
			if err != nil {
				log.Panicf("failed to create veth pair %q: %v", vp.name, err)
			}
			inNS(hostNS, "hostNS", func() { setupLink(vp.outerHwAddr, origHostVeth) })
			inNS(contNS, "contNS", func() {
				origContVeths[n] = setupLink(vp.innerHwAddr, origContVeth)
				if err = netlink.AddrAdd(origContVeths[n], parseAddr(vp.ip)); err != nil {
					log.Panicf("failed to add addr for %q: %v", vp.name, err)
				}
			})
		}
		inNS(contNS, "contNS", func() {
			gwAddr := parseAddr("10.1.90.1/24")
			addTestRoute(t, &netlink.Route{
				Gw:    gwAddr.IPNet.IP,
				Scope: SCOPE_UNIVERSE,
			})

			toRun(contNS, origContVeths[:])
		})
	})
}

func expectedExtractedLinkInfoForMultipleInterfaces(contNsPath string) *cnicurrent.Result {
	expectedInfo := expectedExtractedLinkInfo(contNsPath)
	expectedInfo.IPs = append(expectedInfo.IPs, &cnicurrent.IPConfig{
		Version:   "4",
		Interface: 1,
		Address: net.IPNet{
			IP:   net.IP{192, 168, 37, 8},
			Mask: net.IPMask{255, 255, 0, 0},
		},
	})
	expectedInfo.Interfaces = append(expectedInfo.Interfaces, &cnicurrent.Interface{
		Name:    "eth1",
		Mac:     secondInnerHwAddr,
		Sandbox: contNsPath,
	})
	return expectedInfo
}

func expectedExtractedLinkInfoWithMissingInterface(contNsPath string) *cnicurrent.Result {
	expectedInfo := expectedExtractedLinkInfo(contNsPath)
	expectedInfo.IPs = append(expectedInfo.IPs, &cnicurrent.IPConfig{
		Version:   "4",
		Interface: -1,
		Address: net.IPNet{
			IP:   net.IP{192, 168, 37, 8},
			Mask: net.IPMask{255, 255, 0, 0},
		},
	})
	return expectedInfo
}

func TestMultiInterfaces(t *testing.T) {
	withMultipleInterfacesConfigured(t, func(contNS ns.NetNS, innerLinks []netlink.Link) {
		expectedInfo := expectedExtractedLinkInfoForMultipleInterfaces(contNS.Path())
		result, err := ValidateAndFixCNIResult(expectedInfo, contNS.Path(), innerLinks)
		if err != nil {
			t.Errorf("error during validate/fix cni result: %v", err)
		}
		if !reflect.DeepEqual(result, expectedInfo) {
			t.Errorf("result different than expected:\nActual:\n%s\nExpected:\n%s",
				spew.Sdump(result), spew.Sdump(expectedInfo))
		}
	})
}

func TestMultiInterfacesWithMissingInterface(t *testing.T) {
	withMultipleInterfacesConfigured(t, func(contNS ns.NetNS, innerLinks []netlink.Link) {
		infoToFix := expectedExtractedLinkInfoForMultipleInterfaces(contNS.Path())
		expectedInfo := expectedExtractedLinkInfoForMultipleInterfaces(contNS.Path())
		result, err := ValidateAndFixCNIResult(infoToFix, contNS.Path(), innerLinks)
		if err != nil {
			t.Errorf("error during validate/fix cni result: %v", err)
		}
		if !reflect.DeepEqual(result, expectedInfo) {
			t.Errorf("result different than expected:\nActual:\n%s\nExpected:\n%s",
				spew.Sdump(result), spew.Sdump(expectedInfo))
		}
	})
}


text:
using System.Collections.Generic;

namespace IOC.V2.MovieFinder
{
    public interface IMovieFinder
    {
        List<Movie> FindAll();
    }
}


text:
FOUNDATION_EXPORT double MZFastSortIndexVersionNumber;
FOUNDATION_EXPORT const unsigned char MZFastSortIndexVersionString[];