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

import com.intellij.injected.editor.DocumentWindowImpl;
import com.intellij.injected.editor.VirtualFileWindow;
import com.intellij.lang.Language;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.lang.injection.MultiHostInjector;
import com.intellij.lang.injection.MultiHostRegistrar;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.extensions.ExtensionPoint;
import com.intellij.openapi.extensions.ExtensionPointListener;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.extensions.PluginDescriptor;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.ProperTextRange;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiManagerEx;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ConcurrentHashMap;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;

import java.util.*;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author cdr
 */
public class InjectedLanguageManagerImpl extends InjectedLanguageManager {
  private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.tree.injected.InjectedLanguageManagerImpl");
  private final Project myProject;
  private final DumbService myDumbService;
  private final AtomicReference<MultiHostInjector> myPsiManagerRegisteredInjectorsAdapter = new AtomicReference<MultiHostInjector>();

  public static InjectedLanguageManagerImpl getInstanceImpl(Project project) {
    return (InjectedLanguageManagerImpl)InjectedLanguageManager.getInstance(project);
  }

  public InjectedLanguageManagerImpl(Project project, DumbService dumbService) {
    myProject = project;
    myDumbService = dumbService;

    final ExtensionPoint<MultiHostInjector> multiPoint = Extensions.getArea(project).getExtensionPoint(MultiHostInjector.MULTIHOST_INJECTOR_EP_NAME);
    multiPoint.addExtensionPointListener(new ExtensionPointListener<MultiHostInjector>() {
      public void extensionAdded(@NotNull MultiHostInjector injector, @Nullable PluginDescriptor pluginDescriptor) {
        registerMultiHostInjector(injector);
      }

      public void extensionRemoved(@NotNull MultiHostInjector injector, @Nullable PluginDescriptor pluginDescriptor) {
        unregisterMultiHostInjector(injector);
      }
    });
    final ExtensionPointListener<LanguageInjector> myListener = new ExtensionPointListener<LanguageInjector>() {
      public void extensionAdded(@NotNull LanguageInjector extension, @Nullable PluginDescriptor pluginDescriptor) {
        psiManagerInjectorsChanged();
      }

      public void extensionRemoved(@NotNull LanguageInjector extension, @Nullable PluginDescriptor pluginDescriptor) {
        psiManagerInjectorsChanged();
      }
    };
    final ExtensionPoint<LanguageInjector> psiManagerPoint = Extensions.getRootArea().getExtensionPoint(LanguageInjector.EXTENSION_POINT_NAME);
    psiManagerPoint.addExtensionPointListener(myListener);
    Disposer.register(project, new Disposable() {
      public void dispose() {
        psiManagerPoint.removeExtensionPointListener(myListener);
      }
    });
  }

  public void psiManagerInjectorsChanged() {
    PsiManagerEx psiManager = (PsiManagerEx)PsiManager.getInstance(myProject);
    List<? extends LanguageInjector> injectors = psiManager.getLanguageInjectors();
    LanguageInjector[] extensions = Extensions.getExtensions(LanguageInjector.EXTENSION_POINT_NAME);
    if (injectors.isEmpty() && extensions.length == 0) {
      MultiHostInjector prev = myPsiManagerRegisteredInjectorsAdapter.getAndSet(null);
      if (prev != null) {
        unregisterMultiHostInjector(prev);
      }
    }
    else {
      PsiManagerRegisteredInjectorsAdapter adapter = new PsiManagerRegisteredInjectorsAdapter(psiManager);
      if (myPsiManagerRegisteredInjectorsAdapter.compareAndSet(null, adapter)) {
        registerMultiHostInjector(adapter);
      }
    }
  }

  public PsiLanguageInjectionHost getInjectionHost(@NotNull PsiElement element) {
    final PsiFile file = element.getContainingFile();
    final VirtualFile virtualFile = file == null ? null : file.getVirtualFile();
    if (virtualFile instanceof VirtualFileWindow) {
      PsiElement host = file.getContext();
      if (host != null) {
        return (PsiLanguageInjectionHost)host;
      }
    }
    return null;
  }

  @NotNull
  public TextRange injectedToHost(@NotNull PsiElement injectedContext, @NotNull TextRange injectedTextRange) {
    ProperTextRange.assertProperRange(injectedTextRange);
    PsiFile file = injectedContext.getContainingFile();
    if (file == null) return injectedTextRange;
    Document document = PsiDocumentManager.getInstance(file.getProject()).getCachedDocument(file);
    if (!(document instanceof DocumentWindowImpl)) return injectedTextRange;
    DocumentWindowImpl documentWindow = (DocumentWindowImpl)document;
    return documentWindow.injectedToHost(injectedTextRange);
  }
  public int injectedToHost(@NotNull PsiElement element, int offset) {
    PsiFile file = element.getContainingFile();
    if (file == null) return offset;
    Document document = PsiDocumentManager.getInstance(file.getProject()).getCachedDocument(file);
    if (!(document instanceof DocumentWindowImpl)) return offset;
    DocumentWindowImpl documentWindow = (DocumentWindowImpl)document;
    return documentWindow.injectedToHost(offset);
  }

  private final ConcurrentMap<Class, MultiHostInjector[]> injectors = new ConcurrentHashMap<Class, MultiHostInjector[]>();
  private final ClassMapCachingNulls<MultiHostInjector> cachedInjectors = new ClassMapCachingNulls<MultiHostInjector>(injectors, new MultiHostInjector[0]);

  public void registerMultiHostInjector(@NotNull MultiHostInjector injector) {
    for (Class<? extends PsiElement> place : injector.elementsToInjectIn()) {
      LOG.assertTrue(place != null, injector);
      while (true) {
        MultiHostInjector[] injectors = this.injectors.get(place);
        if (injectors == null) {
          if (this.injectors.putIfAbsent(place, new MultiHostInjector[]{injector}) == null) break;
        }
        else {
          MultiHostInjector[] newInfos = ArrayUtil.append(injectors, injector);
          if (this.injectors.replace(place, injectors, newInfos)) break;
        }
      }
    }
    cachedInjectors.clearCache();
  }

  public boolean unregisterMultiHostInjector(@NotNull MultiHostInjector injector) {
    boolean removed = false;
    Iterator<Map.Entry<Class,MultiHostInjector[]>> iterator = injectors.entrySet().iterator();
    while (iterator.hasNext()) {
      Map.Entry<Class,MultiHostInjector[]> entry = iterator.next();
      MultiHostInjector[] infos = entry.getValue();
      int i = ArrayUtil.find(infos, injector);
      if (i != -1) {
        MultiHostInjector[] newInfos = ArrayUtil.remove(infos, i);
        if (newInfos.length == 0) {
          iterator.remove();
        }
        else {
          injectors.put(entry.getKey(), newInfos);
        }
        removed = true;
      }
    }
    cachedInjectors.clearCache();
    return removed;
  }

  static final Key<String> UNESCAPED_TEXT = Key.create("INJECTED_UNESCAPED_TEXT");
  public String getUnescapedText(@NotNull final PsiElement injectedNode) {
    final StringBuilder text = new StringBuilder(injectedNode.getTextLength());
    // gather text from (patched) leaves
    injectedNode.accept(new PsiRecursiveElementWalkingVisitor() {
      @Override
      public void visitElement(PsiElement element) {
        String unescaped = element.getUserData(UNESCAPED_TEXT);
        if (unescaped != null) {
          text.append(unescaped);
          return;
        }
        if (element.getFirstChild() == null) {
          text.append(element.getText());
          return;
        }
        super.visitElement(element);
      }
    });
    return text.toString();
  }

  /**
   *  intersection may spread over several injected fragments
   *  @param rangeToEdit range in encoded(raw) PSI
   *  @return list of ranges in encoded (raw) PSI
   */
  @SuppressWarnings({"ConstantConditions"})
  @NotNull
  public List<TextRange> intersectWithAllEditableFragments(@NotNull PsiFile injectedPsi, @NotNull TextRange rangeToEdit) {
    Place shreds = InjectedLanguageUtil.getShreds(injectedPsi);
    if (shreds == null) return Collections.emptyList();
    Object result = null; // optimization: TextRange or ArrayList
    int count = 0;
    int offset = 0;
    for (PsiLanguageInjectionHost.Shred shred : shreds) {
      TextRange encodedRange = TextRange.from(offset + shred.prefix.length(), shred.getRangeInsideHost().getLength());
      TextRange intersection = encodedRange.intersection(rangeToEdit);
      if (intersection != null) {
        count++;
        if (count == 1) {
          result = intersection;
        }
        else if (count == 2) {
          TextRange range = (TextRange)result;
          if (range.isEmpty()) {
            result = intersection;
            count = 1;
          }
          else if (intersection.isEmpty()) {
            count = 1;
          }
          else {
            List<TextRange> list = new ArrayList<TextRange>();
            list.add(range);
            list.add(intersection);
            result = list;
          }
        }
        else if (intersection.isEmpty()) {
          count--;
        }
        else {
          ((List<TextRange>)result).add(intersection);
        }
      }
      offset += shred.prefix.length() + shred.getRangeInsideHost().getLength() + shred.suffix.length();
    }
    return count == 0 ? Collections.<TextRange>emptyList() : count == 1 ? Collections.singletonList((TextRange)result) : (List<TextRange>)result;
  }

  public boolean isInjectedFragment(final PsiFile file) {
    return file.getViewProvider() instanceof InjectedFileViewProvider;
  }

  @Override
  public PsiElement findInjectedElementAt(@NotNull PsiFile hostFile, int hostDocumentOffset) {
    return InjectedLanguageUtil.findInjectedElementNoCommitWithOffset(hostFile, hostDocumentOffset);
  }

  private final Map<Class,MultiHostInjector[]> myInjectorsClone = new HashMap<Class, MultiHostInjector[]>();
  @TestOnly
  public void pushInjectors() {
    try {
      assert myInjectorsClone.isEmpty() : myInjectorsClone;
    }
    finally {
      myInjectorsClone.clear();
    }
    myInjectorsClone.putAll(injectors);
  }
  @TestOnly
  public void checkInjectorsAreDisposed() {
    try {
      for (Map.Entry<Class, MultiHostInjector[]> entry : injectors.entrySet()) {
        Class key = entry.getKey();
        MultiHostInjector[] oldInjectors = myInjectorsClone.get(key);
        for (MultiHostInjector injector : entry.getValue()) {
          if (!ArrayUtil.contains(injector, oldInjectors)) {
            throw new AssertionError("Injector was not disposed: " + key + " -> " + injector);
          }
        }
      }
    }
    finally {
      myInjectorsClone.clear();
    }
  }

  public interface InjProcessor {
    boolean process(PsiElement element, MultiHostInjector injector);
  }
  public void processInPlaceInjectorsFor(@NotNull PsiElement element, @NotNull InjProcessor processor) {
    final boolean dumb = myDumbService.isDumb();
    MultiHostInjector[] infos = cachedInjectors.get(element.getClass());
    if (infos != null) {
      for (MultiHostInjector injector : infos) {
        if (dumb && !DumbService.isDumbAware(injector)) {
          continue;
        }

        if (!processor.process(element, injector)) return;
      }
    }
  }

  private static class PsiManagerRegisteredInjectorsAdapter implements MultiHostInjector {
    private final PsiManagerEx myPsiManager;

    private PsiManagerRegisteredInjectorsAdapter(PsiManagerEx psiManager) {
      myPsiManager = psiManager;
    }

    public void getLanguagesToInject(@NotNull final MultiHostRegistrar injectionPlacesRegistrar, @NotNull PsiElement context) {
      final PsiLanguageInjectionHost host = (PsiLanguageInjectionHost)context;
      InjectedLanguagePlaces placesRegistrar = new InjectedLanguagePlaces() {
        public void addPlace(@NotNull Language language, @NotNull TextRange rangeInsideHost, @NonNls @Nullable String prefix, @NonNls @Nullable String suffix) {
          ProperTextRange.assertProperRange(rangeInsideHost);
          injectionPlacesRegistrar
            .startInjecting(language)
            .addPlace(prefix, suffix, host, rangeInsideHost)
            .doneInjecting();
        }
      };
      for (LanguageInjector injector : myPsiManager.getLanguageInjectors()) {
        injector.getLanguagesToInject(host, placesRegistrar);
      }
      for (LanguageInjector injector : Extensions.getExtensions(LanguageInjector.EXTENSION_POINT_NAME)) {
        injector.getLanguagesToInject(host, placesRegistrar);
      }
    }

    @NotNull
    public List<? extends Class<? extends PsiElement>> elementsToInjectIn() {
      return Arrays.asList(PsiLanguageInjectionHost.class);
    }
  }
}


text:
namespace WinUsbRx.Ninject
{
    using System;
    using global::Ninject.Modules;

    /// <summary>
    /// The guid module.
    /// </summary>
    internal class GuidModule : NinjectModule
    {
        /// <summary>
        /// The _guid.
        /// </summary>
        private readonly Guid _guid;

        /// <summary>
        /// Initializes a new instance of the <see cref="GuidModule"/> class.
        /// </summary>
        /// <param name="guid">
        /// The guid.
        /// </param>
        public GuidModule(Guid guid)
        {
            _guid = guid;
        }

        /// <summary>
        /// The load.
        /// </summary>
        public override void Load()
        {
            Bind<Guid>().ToConstant(_guid).InSingletonScope();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.project.project2;

/**
 * Created by Zac on 10/19/2014.
 */
public class Node<T> {

    public T iData;              // data item (key)
    public Node<T> next;              // next node in the list

    // -------------------------------------------------------------
    public Node(T id) {           // constructor
        iData = id;
        next = null;		// (next automatically null)
    }

    // -------------------------------------------------------------
    public void displayNode() {     // display yourself
        System.out.print(iData + " ");
    }

    public T getValue()    {

        return this.iData;
    }
}  // end class Node

class Stack<T>{
    private Node<T> current;          // ref to current node
    private int count;                 // # of nodes on list
    private Node<T> bottom;

    public Stack() {             // constructor
        count = 0;                         // no nodes in the list yet
        current = null;
        bottom = null;
    }

    public void push(T id) {   // insert  node before current

        // COMPLETE THIS METHOD
        Node<T> aNode = new Node (id);
        if(current == null) {
            aNode.next = aNode;
            bottom = aNode;
        }
        else if(current.next == null && current != null){
            aNode.next = current;
            current.next = aNode;
        }
        else if(current != null){
            aNode.next = current.next;
            current.next = aNode;
        }

        current = aNode;

        count++;
        System.out.println("The Node: " + current.getValue() + " was pushed onto stack");
        //current = current.next;
    }

    public void pop() {         // delete current node

        // COMPLETE THIS METHOD
        if (count == 0) {
            System.out.println("No Nodes");

        }
        else {

            //current = bottom;
            Node temp = current;
            //current.next = temp.next;
            this.current = null;
            count--;
            current = temp;

            System.out.println("The Node: " + temp.getValue() + " was deleted");
            //return temp;
        }

        //return null;
    }

    public void display(){
        if (count == 0) {
            System.out.println("No Nodes");
        }
        else {

            current = current.next;
            for (int i = 1; i <= count; i++) {
                current.displayNode();
                current = current.next;
            }
            for (int i = 1; i <= count-1; i++) {
                current = current.next;
            }
            System.out.println("Count: " + count);
            //System.out.println("Current: " + current);

        }
    }
}                          // end class CircList

class StackApp {

    public static void main(String[] args) {
        Stack arr1;
        arr1 = new Stack();

        arr1.push("a");
        arr1.push(1);
        arr1.push("c");
        arr1.push(2);
        arr1.push(5);
        arr1.pop();
        //arr1.push(6);
        //arr1.push(7);

        arr1.display();

        //System.out.print(arr1);
    }
}


text:
package com.jme3.effect;

import com.jme3.material.RenderState;
import com.jme3.math.Matrix3f;
import com.jme3.renderer.Camera;
import com.jme3.scene.Mesh;

/**
 * The ParticleMesh is the underlying visual implementation of a
 * {@link ParticleEmitter particle emitter}.
 *
 * @author Kirill Vainer
 */
public abstract class ParticleMesh extends Mesh {

    /**
     * Type of particle mesh
     */
    public enum Type {
        /**
         * The particle mesh is composed of points. Each particle is a point.
         * This can be used in conjuction with {@link RenderState#setPointSprite(boolean) point sprites}
         * to render particles the usual way.
         */
        Point,

        /**
         * The particle mesh is composed of triangles. Each particle is
         * two triangles making a single quad.
         */
        Triangle;
    }

    /**
     * Initialize mesh data.
     *
     * @param emitter The emitter which will use this ParticleMesh.
     * @param numParticles The maxmimum number of particles to simulate
     */
    public abstract void initParticleData(ParticleEmitter emitter, int numParticles);

    /**
     * Set the images on the X and Y coordinates
     * @param imagesX Images on the X coordinate
     * @param imagesY Images on the Y coordinate
     */
    public abstract void setImagesXY(int imagesX, int imagesY);

    /**
     * Update the particle visual data. Typically called every frame.
     */
    public abstract void updateParticleData(Particle[] particles, Camera cam, Matrix3f inverseRotation);

}


text:
<rss version="2.0">
    <channel>
        <title>Hacker News</title>
        <link>https://news.ycombinator.com/</link>
        <description>Links for the intellectually curious, ranked by readers.</description>
        <item>
            <title>VNC Roulette</title>
            <link>http://vncroulette.com</link>
            <pubDate>Sat, 26 Mar 2016 22:04:20 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11367666</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>Tools for thought: graphical algebra and Fourier analysis</title>
            <link>https://acko.net/files/gltalks/toolsforthought/#0</link>
            <pubDate>Thu, 24 Mar 2016 17:38:47 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11354730</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>What do you call this in Ruby?</title>
            <link>https://github.com/JuanitoFatas/what-do-you-call-this-in-ruby</link>
            <pubDate>Sun, 27 Mar 2016 01:47:55 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11368448</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>Andy Grove's Warning to Silicon Valley</title>
            <link>http://www.nytimes.com/2016/03/26/opinion/andy-groves-warning-to-silicon-valley.html?action=click&pgtype=Homepage&clickSource=story-heading&module=opinion-c-col-left-region&region=opinion-c-col-left-region&WT.nav=opinion-c-col-left-region&_r=0</link>
            <pubDate>Sat, 26 Mar 2016 16:35:53 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11366265</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>How to Get Out of Bed</title>
            <link>http://www.theparisreview.org/blog/2016/03/24/how-to-get-out-of-bed/</link>
            <pubDate>Sat, 26 Mar 2016 20:34:00 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11367331</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>My dad hid his depression. I won't hide mine</title>
            <link>
                https://www.washingtonpost.com/news/inspired-life/wp/2016/02/09/my-dad-killed-himself-when-i-was-13-he-hid-his-depression-i-wont-hide-mine/?tid=a_inl
            </link>
            <pubDate>Sat, 26 Mar 2016 20:32:13 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11367325</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>CakeML: A verified implementation of ML</title>
            <link>https://github.com/CakeML/cakeml</link>
            <pubDate>Sat, 26 Mar 2016 21:03:35 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11367438</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>Why Are Educators Learning How to Interrogate Their Students?</title>
            <link>http://www.newyorker.com/news/news-desk/why-are-educators-learning-how-to-interrogate-their-students
            </link>
            <pubDate>Sun, 27 Mar 2016 01:00:29 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11368316</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>The Mystery of the Phantom Page Turner</title>
            <link>http://www.collectorsweekly.com/articles/the-mystery-of-the-phantom-page-turner/</link>
            <pubDate>Sat, 26 Mar 2016 01:45:31 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11364048</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>The fight against food fraud</title>
            <link>https://next.ft.com/content/42985f40-f148-11e5-aff5-19b4e253664a</link>
            <pubDate>Sat, 26 Mar 2016 19:15:55 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11367000</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>The Impious Delights of Hieronymus Bosch</title>
            <link>https://newrepublic.com/article/132024/impious-delights-hieronymus-bosch</link>
            <pubDate>Sat, 26 Mar 2016 13:48:58 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11365634</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>Generating Factoid Questions with RNNs: The 30M Factoid Question-Answer Corpus</title>
            <link>http://arxiv.org/abs/1603.06807</link>
            <pubDate>Sat, 26 Mar 2016 21:36:37 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11367571</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>Patent that cost Microsoft millions gets invalidated</title>
            <link>
                http://arstechnica.com/tech-policy/2016/03/game-companies-knock-out-patent-that-slammed-microsoft-with-388m-verdict/
            </link>
            <pubDate>Sat, 26 Mar 2016 13:00:16 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11365499</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>Project West Ford</title>
            <link>https://en.wikipedia.org/wiki/Project_West_Ford</link>
            <pubDate>Sat, 26 Mar 2016 14:48:21 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11365795</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>A 120-Year Lease on Life Outlasts Apartment Heir (1995)</title>
            <link>http://www.nytimes.com/1995/12/29/world/a-120-year-lease-on-life-outlasts-apartment-heir.html</link>
            <pubDate>Sat, 26 Mar 2016 20:57:52 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11367422</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>With No Inkling of the Contents: Viewing Narnia Through a Hindu Lens</title>
            <link>http://www.mantlethought.org/world-literature/no-inkling-contents-viewing-narnia-through-hindu-lens
            </link>
            <pubDate>Sat, 26 Mar 2016 22:51:15 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11367831</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>Computational thinking, 10 years later</title>
            <link>https://blogs.msdn.microsoft.com/msr_er/2016/03/23/computational-thinking-10-years-later/</link>
            <pubDate>Sat, 26 Mar 2016 23:53:45 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11368089</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>Caradoc – a PDF parser and validator written in OCaml</title>
            <link>https://github.com/ANSSI-FR/caradoc</link>
            <pubDate>Sat, 26 Mar 2016 17:39:50 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11366569</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>Direct Manipulation: A Step Beyond Programming Languages (1983) [pdf]</title>
            <link>http://www.csc.kth.se/utbildning/kth/kurser/DH3050/hcihist11/DM.pdf</link>
            <pubDate>Sat, 26 Mar 2016 12:15:12 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11365359</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>Minecraftly: Inspire kids to learn computing via Minecraft</title>
            <link>https://m.ly</link>
            <pubDate>Sat, 26 Mar 2016 09:04:50 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11364975</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>The Way of the Gopher: Making the Switch from Node.js to Golang</title>
            <link>https://medium.com/@theflapjack103/the-way-of-the-gopher-6693db15ae1f</link>
            <pubDate>Sat, 26 Mar 2016 05:21:28 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11364550</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>Scientists push a record 57Gbps through fiber optic lines</title>
            <link>http://www.engadget.com/2016/03/24/scientists-set-fiber-optic-data-record/</link>
            <pubDate>Fri, 25 Mar 2016 10:25:31 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11359322</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>US contractor fined $3.1M for outsourcing work to India</title>
            <link>
                http://sakshipost.com/index.php/news/international/77667-us-contractor-fined-$3-1mn-for-outsourcing-work-to-india.html
            </link>
            <pubDate>Sat, 26 Mar 2016 16:01:22 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11366108</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>Fun with solving puzzles (and dragons): Thoughts after 500 days of PAD</title>
            <link>http://cory.li/puzzle-and-dragons/</link>
            <pubDate>Sat, 26 Mar 2016 22:16:03 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11367703</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>FlagStories</title>
            <link>http://flagstories.co/</link>
            <pubDate>Sat, 26 Mar 2016 10:46:54 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11365195</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>A history of the Amiga, part 9: The Video Toaster</title>
            <link>http://arstechnica.co.uk/gadgets/2016/03/history-of-the-amiga-video-toaster/</link>
            <pubDate>Sat, 26 Mar 2016 11:16:34 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11365252</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>The cost of a system call [pdf]</title>
            <link>http://www.cs.cmu.edu/~chensm/Big_Data_reading_group/papers/flexsc-osdi10.pdf</link>
            <pubDate>Sat, 26 Mar 2016 17:43:16 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11366585</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>What Is a Robot?</title>
            <link>http://www.theatlantic.com/technology/print/2016/03/what-is-a-human/473166/?single_page=true</link>
            <pubDate>Wed, 23 Mar 2016 03:03:37 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11341823</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>The Enduring Mystery of 'Jawn', Philadelphia's All-Purpose Noun</title>
            <link>
                http://www.atlasobscura.com/articles/the-enduring-mystery-of-jawn-philadelphias-allpurpose-noun?utm_source=facebook.com&utm_medium=slate
            </link>
            <pubDate>Sat, 26 Mar 2016 20:54:05 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11367406</comments>
            <description><![CDATA[Comments]]></description>
        </item>
        <item>
            <title>The Hidden Histories of Maps Made by Women: Early North America</title>
            <link>http://www.citylab.com/design/2016/03/women-in-cartography-early-north-america/471609/</link>
            <pubDate>Wed, 23 Mar 2016 04:04:56 +0000</pubDate>
            <comments>https://news.ycombinator.com/item?id=11342082</comments>
            <description><![CDATA[Comments]]></description>
        </item>
    </channel>
</rss>


text:
ACCEPTED

#### According to
GRIN Taxonomy for Plants

#### Published in
Bot. Jahrb. Syst. 9:93. 1888

#### Original name
null

### Remarks
null


text:
package org.apache.hadoop.hdfs.server.namenode.mapdb;

import java.util.Iterator;
import java.util.Map;
import java.util.NavigableSet;
import java.util.concurrent.ConcurrentMap;

/**
 * Binding is simple yet powerful way to keep secondary collection synchronized with primary collection.
 * Primary collection provides notification on updates and secondary collection is modified accordingly.
 * This way MapDB provides secondary indexes, values and keys. It also supports less usual scenarious such
 * as histograms, inverse lookup index (on maps), group counters and so on.
 *
 * There are two things to keep on mind when using binding:
 *
 *  * Binding is not persistent, so it needs to be restored every time store is reopened.
 *    If you modify primary collection before binding is restored, secondary collection does not get updated and becomes
 *    inconsistent.
 *
 *  * If secondary collection is empty, binding will recreate its content based on primary collection.
 *    If there is even single item on secondary collection, binding assumes it is consistent and leaves it as its.
 *
 *  Any thread-safe collection can be used as secondary (not just collections provided by MapDB).
 *  This gives great flexibility for modeling
 *  and scaling your data. For example primary data can be stored in durable DB with transactions and large secondary
 *  indexes may be stored in other faster non-durable DB. Or primary collection may be stored on disk and smaller
 *  secondary index (such as category counters) can be stored in memory for faster lookups. Also you may use
 *  ordinary `java.util.*` collections (if they are thread safe) to get additional speed.
 *
 *  There are many [code examples](https://github.com/jankotek/MapDB/tree/master/src/test/java/examples)
 *  how Collection Binding can be used.
 *
 * @author Jan Kotek
 */
public final class Bind {

    private Bind(){}

    /**
     * Listener called when `Map` is modified.
     * @param <K> key type  in map
     * @param <V> value type in map
     */
    public interface MapListener<K,V>{
        /**
         * Callback method called after `Map` was modified.
         * It is called on insert, update or delete.
         *
         * MapDB collections do not support null keys or values.
         * Null parameter may be than used to indicate operation:
         *
         *
         *
         * @param key key in map
         * @param oldVal old value in map (if any, null on inserts)
         * @param newVal new value in map (if any, null on deletes)
         */
        void update(K key, V oldVal, V newVal);
    }

    /**
     * Primary Maps must provide notifications when it is modified.
     * So Primary Maps must implement this interface to allow registering callback listeners.
     *
     * @param <K> key type  in map
     * @param <V> value type in map
     */
    public interface MapWithModificationListener<K,V> extends Map<K,V> {
        /**
         * Add new modification listener notified when Map has been updated
         * @param listener callback interface notified when map changes
         */
        public void addModificationListener(MapListener<K,V> listener);

        /**
         * Remove registered notification listener
         *
         * @param listener  callback interface notified when map changes
         */
        public void removeModificationListener(MapListener<K,V> listener);
    }

    /**
     * Binds {@link Atomic.Long} to Primary Map so the Atomic.Long contains size of Map.
     * `Atomic.Long` is incremented on each insert and decremented on each entry removal.
     * MapDB collections usually do not keep their size, but require complete traversal to count items.
     *
     * If `Atomic.Long` has zero value, it will be updated with value from `map.size()` and than
     * bind to map.
     *
     * This binding is not persistent. You need to restore it every time store is reopened.
     *
     * NOTE: {@link BTreeMap} and {@link HTreeMap} already supports this directly as optional parameter named `keepCounter`.
     * In that case all calls to `Map.size()` are forwarded to underlying counter. Check parameters at
     * {@link DB#createHashMap(String, boolean, Serializer, Serializer)} and
     * {@link DB#createTreeMap(String, int, boolean, boolean, BTreeKeySerializer, Serializer, java.util.Comparator)}
     *
     *
     * @param map primary map whose size needs to be tracked
     * @param sizeCounter number updated when Map Entry is added or removed.
     */
    public static void size(MapWithModificationListener map, final Atomic.Long sizeCounter){
        //set initial value first if necessary
        if(sizeCounter.get() == 0)
            sizeCounter.set(map.size()); //TODO long overflow?

        map.addModificationListener(new MapListener() {
            @Override
            public void update(Object key, Object oldVal, Object newVal) {
                if(oldVal == null && newVal!=null){
                    sizeCounter.incrementAndGet();
                }else if(oldVal!=null && newVal == null){
                    sizeCounter.decrementAndGet();
                }

                //update does not change collection size
            }
        });
    }

    /**
     * Binds Secondary Map so that it contains Key from Primary Map and custom Value.
     * Secondary Value is updated every time Primary Map is modified.
     *
     * If Secondary Map is empty its content will be recreated from Primary Map.
     * This binding is not persistent. You need to restore it every time store is reopened.
     *
     * @param map Primary Map
     * @param secondary Secondary Map with custom
     * @param fun function which calculates secondary value from primary key and value
     * @param <K> key type in primary and Secondary Map
     * @param <V> value type in Primary Map
     * @param <V2> value type in Secondary Map.
     */
    public static <K,V, V2> void secondaryValue(MapWithModificationListener<K, V> map,
                                              final Map<K, V2> secondary,
                                              final Fun.Function2<V2, K, V> fun){
        //fill if empty
        if(secondary.isEmpty()){
            for(Map.Entry<K,V> e:map.entrySet())
                secondary.put(e.getKey(), fun.run(e.getKey(),e.getValue()));
        }
        //hook listener
        map.addModificationListener(new MapListener<K, V>() {
            @Override
            public void update(K key, V oldVal, V newVal) {
                if(newVal == null){
                    //removal
                    secondary.remove(key);
                }else{
                    secondary.put(key, fun.run(key,newVal));
                }
            }
        });
    }

    /**
     * Binds Secondary Set so it contains Secondary Key (Index). Usefull if you need
     * to lookup Keys from Primary Map by custom criteria. Other use is for reverse lookup
     *
     * To lookup keys in Secondary Set use {@link Bind#findSecondaryKeys(java.util.NavigableSet, Object)}
     *
     *
     * If Secondary Set is empty its content will be recreated from Primary Map.
     * This binding is not persistent. You need to restore it every time store is reopened.
     *
     * @param map primary map
     * @param secondary secondary set
     * @param fun function which calculates Secondary Key from Primary Key and Value
     * @param <K> Key in Primary Map
     * @param <V> Value in Primary Map
     * @param <K2> Secondary
     */
    public static <K,V, K2> void secondaryKey(MapWithModificationListener<K, V> map,
                                                final NavigableSet<Fun.Tuple2<K2, K>> secondary,
                                                final Fun.Function2<K2, K, V> fun){
        //fill if empty
        if(secondary.isEmpty()){
            for(Map.Entry<K,V> e:map.entrySet()){
                secondary.add(Fun.t2(fun.run(e.getKey(),e.getValue()), e.getKey()));
            }
        }
        //hook listener
        map.addModificationListener(new MapListener<K, V>() {
            @Override
            public void update(K key, V oldVal, V newVal) {
                if(newVal == null){
                    //removal
                    secondary.remove(Fun.t2(fun.run(key, oldVal), key));
                }else if(oldVal==null){
                    //insert
                    secondary.add(Fun.t2(fun.run(key,newVal), key));
                }else{
                    //update, must remove old key and insert new
                    K2 oldKey = fun.run(key, oldVal);
                    K2 newKey = fun.run(key, newVal);
                    if(oldKey == newKey || oldKey.equals(newKey)) return;
                    secondary.remove(Fun.t2(oldKey, key));
                    secondary.add(Fun.t2(newKey,key));
                }
            }
        });
    }

    /**
     * Binds Secondary Set so it contains inverse mapping to Primary Map: Primary Value will become Secondary Key.
     * This is useful for creating bi-directional Maps.
     *
     * To lookup keys in Secondary Set use {@link Bind#findSecondaryKeys(java.util.NavigableSet, Object)}
     *
     * If Secondary Set is empty its content will be recreated from Primary Map.
     * This binding is not persistent. You need to restore it every time store is reopened.
     *
     * @param primary Primary Map for which inverse mapping will be created
     * @param inverse Secondary Set which will contain inverse mapping
     * @param <K> Key in Primary Map and Second Value in Secondary Set
     * @param <V> Value in Primary Map and Primary Value in Secondary Set
     */
    public static <K,V> void mapInverse(MapWithModificationListener<K,V> primary,
                                        NavigableSet<Fun.Tuple2<V, K>> inverse) {
        Bind.secondaryKey(primary,inverse, new Fun.Function2<V, K,V>(){
            @Override public V run(K key, V value) {
                return value;
            }
        });
    }

    /**
     * Find all Primary Keys associated with Secondary Key.
     * This is useful companion to {@link Bind#mapInverse(org.mapdb.Bind.MapWithModificationListener, java.util.NavigableSet)}
     * and {@link Bind#secondaryKey(org.mapdb.Bind.MapWithModificationListener, java.util.NavigableSet, org.mapdb.Fun.Function2)}
     * It can by also used to find values from 'MultiMap'.
     *
     * @param secondaryKeys Secondary Set or 'MultiMap' to find values in
     * @param secondaryKey key to look from
     * @param <K2> Secondary Key type
     * @param <K1> Primary Key type
     * @return all keys where primary value equals to `secondaryKey`
     */
    public static <K2,K1> Iterable<K1> findSecondaryKeys(final NavigableSet<Fun.Tuple2<K2,K1>> secondaryKeys, final K2 secondaryKey) {
        return new Iterable<K1>(){
            @Override
            public Iterator<K1> iterator() {
                //use range query to get all values
                final Iterator<Fun.Tuple2<K2,K1>> iter =
                        ((NavigableSet)secondaryKeys) //cast is workaround for generics
                                .subSet(
                                        Fun.t2(secondaryKey,null), //NULL represents lower bound, everything is larger than null
                                        Fun.t2(secondaryKey,Fun.HI) // HI is upper bound everything is smaller then HI
                                ).iterator();

                return new Iterator<K1>() {
                    @Override
                    public boolean hasNext() {
                        return iter.hasNext();
                    }

                    @Override
                    public K1 next() {
                        return iter.next().b;
                    }

                    @Override
                    public void remove() {
                        iter.remove();
                    }
                };
            }
        };

    }

    /**
     * Binds Secondary Map so it it creates [histogram](http://en.wikipedia.org/wiki/Histogram) from
     * data in Primary Map. Histogram keeps count how many items are in each category.
     * This method takes function which defines in what category each Primary Map entry is in.
     *
     *
     * If Secondary Map is empty its content will be recreated from Primary Map.
     * This binding is not persistent. You need to restore it every time store is reopened.
     *
     * @param primary Primary Map to create histrogram for
     * @param histogram Secondary Map to create histogram for, key is Category, value is number of items in category
     * @param entryToCategory returns Category in which entry from Primary Map belongs to.
     * @param <K> Key type in primary map
     * @param <V> Value type in primary map
     * @param <C> Category type
     */
    public static <K,V,C> void histogram(MapWithModificationListener<K,V> primary, final ConcurrentMap<C,Long> histogram,
                                  final Fun.Function2<C, K, V> entryToCategory){

        MapListener<K,V> listener = new MapListener<K, V>() {
            @Override public void update(K key, V oldVal, V newVal) {
                if(newVal == null){
                    //removal
                    C category = entryToCategory.run(key,oldVal);
                    incrementHistogram(category, -1);
                }else if(oldVal==null){
                    //insert
                    C category = entryToCategory.run(key,newVal);
                    incrementHistogram(category, 1);
                }else{
                    //update, must remove old key and insert new
                    C oldCat = entryToCategory.run(key, oldVal);
                    C newCat = entryToCategory.run(key, newVal);
                    if(oldCat == newCat || oldCat.equals(newCat)) return;
                    incrementHistogram(oldCat,-1);
                    incrementHistogram(oldCat,1);
                }

            }

            /** atomically update counter in histogram*/
            private void incrementHistogram(C category, long i) {
                for(;;){
                    Long oldCount = histogram.get(category);
                    if(oldCount == null){
                        //insert new count
                        if(histogram.putIfAbsent(category,i) == null)
                            return;
                    }else{
                        //increase existing count
                        Long newCount = oldCount+i;
                        if(histogram.replace(category,oldCount, newCount))
                            return;
                    }
                }
            }
        };

        primary.addModificationListener(listener);
    }

}


text:
package com.jroossien.boxx.options.single;

import com.jroossien.boxx.messages.Msg;
import com.jroossien.boxx.messages.Param;
import com.jroossien.boxx.options.SingleOption;
import com.jroossien.boxx.util.Numbers;
import org.bukkit.command.CommandSender;

public class DoubleO extends SingleOption<Double, DoubleO> {

    private Double min = null;
    private Double max = null;

    public DoubleO min(Double min) {
        this.min = min;
        return this;
    }

    public DoubleO max(Double max) {
        this.max = max;
        return this;
    }

    @Override
    public boolean parse(CommandSender sender, String input) {
        try {
            value = Double.parseDouble(input);
        } catch (Exception e) {
            error = Msg.getString("double.invalid", Param.P("input", input));
            return false;
        }

        if (min != null && (Double)value < min) {
            error = Msg.getString("number-too-low", Param.P("input", input), Param.P("min", min));
            return false;
        }

        if (max != null && (Double)value > max) {
            error = Msg.getString("number-too-high", Param.P("input", input), Param.P("max", max));
            return false;
        }

        return true;
    }

    public String serialize(int roundDecimals) {
        return serialize(getValue(), roundDecimals);
    }

    public static String serialize(Double val, int roundDecimals) {
        return val == null ? null : Double.toString(Numbers.round(val, roundDecimals));
    }

    @Override
    public String getDisplayValue() {
        return display(getValue());
    }

    public static String display(Double val) {
        return val == null ? null : Msg.getString("double.display", Param.P("val", val));
    }

    public static String display(Double val, int roundDecimals) {
        return val == null ? null : Msg.getString("double.display", Param.P("val", Numbers.round(val, roundDecimals)));
    }

    @Override
    public String getTypeName() {
        return "Double";
    }

    @Override
    public DoubleO clone() {
        return super.cloneData(new DoubleO().min(min).max(max));
    }
}


text:
var phantomify = require("../phantomify")
phantomify(process.argv[2])


text:
@implementation SettingsViewController

@synthesize speedAuto;
@synthesize tableView, Nav;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.tableView.delegate = self;
        self.tableView.dataSource = self;

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    self.tableView.frame = self.view.bounds;
    //self.navigationItem.title = [NSString stringWithFormat:@"%@", NSLocalizedString(@"sTitolo", @"")];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	speedAuto.on = [defaults boolForKey:kSpeedAuto];

}

- (void)vieWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	speedAuto.on = [defaults boolForKey:kSpeedAuto];
}

- (void)viewDidAppear :(BOOL)animated {
    NSLog(@"Accedo a viewDidAppear");
    [super viewDidAppear:animated];
    //self.navigationController.navigationBarHidden = FALSE;

    //self.navigationItem.title=[NSString stringWithFormat:@"%@", NSLocalizedString(@"sTitolo", @"")];
    self.navigationItem.hidesBackButton = FALSE;

	//acceto al plist dei settaggi e lo leggo
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	speedAuto.on = [defaults boolForKey:kSpeedAuto];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = TRUE;

}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults setBool:speedAuto.on forKey:kSpeedAuto];
	[defaults synchronize];
    if (speedAuto.on) {
        NSLog(@"Autospeed Attivato");
    } else {
        NSLog(@"Autospeed' Disattivato");
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *head = [NSString stringWithFormat:@"%@", NSLocalizedString(@"aCosa", @"")];
    return head;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    cell.textLabel.text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"aVolume", @"")];
    //cell.textLabel.text =@"Volume Automatico";
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    speedAuto = [[UISwitch alloc] initWithFrame:CGRectZero];
    cell.accessoryView = speedAuto;
    //[caca setOn:NO animated:NO];
    [speedAuto setOn:NO animated:NO];
    [speedAuto addTarget:self action:@selector(speedAutoChange:) forControlEvents:UIControlEventValueChanged];
    [speedAuto release];

    return cell;
}

- (void) speedAutoChange:(id)sender {
    UISwitch* switchControl = sender;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSLog( @"SpeedAuto %@", switchControl.on ? @"ON" : @"OFF" );
    [defaults setBool:speedAuto.on forKey:kSpeedAuto];
    [defaults synchronize];
}

-(void)dealloc {
    [speedAuto release];
    [tableView release];
    [super dealloc];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    speedAuto = nil;
    self.tableView = nil;

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end


text:
@implementation WhatsInAppLib

@end


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
//
// Copyright (c) 2006 Georgia Tech Research Corporation
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation;
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// Author: Rajib Bhattacharjea<raj.b@gatech.edu>
//

// Georgia Tech Network Simulator - Round Trip Time Estimation Class
// George F. Riley.  Georgia Tech, Spring 2002

#ifndef RTT_ESTIMATOR_H
#define RTT_ESTIMATOR_H

#include <deque>
#include "ns3/sequence-number.h"
#include "ns3/nstime.h"
#include "ns3/object.h"

namespace ns3 {

/**
 * \ingroup tcp
 *
 * \brief Helper class to store RTT measurements
 */
class RttHistory {
public:
  /**
   * \brief Constructor - builds an RttHistory with the given parameters
   * \param s First sequence number in packet sent
   * \param c Number of bytes sent
   * \param t Time this one was sent
   */
  RttHistory (SequenceNumber32 s, uint32_t c, Time t);
  /**
   * \brief Copy constructor
   * \param h the object to copy
   */
  RttHistory (const RttHistory& h); // Copy constructor
public:
  SequenceNumber32  seq;  //!< First sequence number in packet sent
  uint32_t        count;  //!< Number of bytes sent
  Time            time;   //!< Time this one was sent
  bool            retx;   //!< True if this has been retransmitted
};

/// Container for RttHistory objects
typedef std::deque<RttHistory> RttHistory_t;

/**
 * \ingroup tcp
 *
 * \brief Base class for all RTT Estimators
 */
class RttEstimator : public Object {
public:
  /**
   * \brief Get the type ID.
   * \return the object TypeId
   */
  static TypeId GetTypeId (void);

  RttEstimator();
  /**
   * \brief Copy constructor
   * \param r the object to copy
   */
  RttEstimator (const RttEstimator& r);

  virtual ~RttEstimator();

  virtual TypeId GetInstanceTypeId (void) const;

  /**
   * \brief Note that a particular sequence has been sent
   * \param seq the packet sequence number.
   * \param size the packet size.
   */
  virtual void SentSeq (SequenceNumber32 seq, uint32_t size);

  /**
   * \brief Note that a particular ack sequence has been received
   * \param ackSeq the ack sequence number.
   * \return The measured RTT for this ack.
   */
  virtual Time AckSeq (SequenceNumber32 ackSeq);

  /**
   * \brief Clear all history entries
   */
  virtual void ClearSent ();

  /**
   * \brief Add a new measurement to the estimator. Pure virtual function.
   * \param t the new RTT measure.
   */
  virtual void  Measurement (Time t) = 0;

  /**
   * \brief Returns the estimated RTO. Pure virtual function.
   * \return the estimated RTO.
   */
  virtual Time RetransmitTimeout () = 0;

  /**
   * \brief Copy object
   * \returns a copy of itself
   */
  virtual Ptr<RttEstimator> Copy () const = 0;

  /**
   * \brief Increase the estimation multiplier up to MaxMultiplier.
   */
  virtual void IncreaseMultiplier ();

  /**
   * \brief Resets the estimation multiplier to 1.
   */
  virtual void ResetMultiplier ();

  /**
   * \brief Resets the estimation to its initial state.
   */
  virtual void Reset ();

  /**
   * \brief Sets the Minimum RTO.
   * \param minRto The minimum RTO returned by the estimator.
   */
  void SetMinRto (Time minRto);

  /**
   * \brief Get the Minimum RTO.
   * \return The minimum RTO returned by the estimator.
   */
  Time GetMinRto (void) const;

  /**
   * \brief Sets the current RTT estimate (forcefully).
   * \param estimate The current RTT estimate.
   */
  void SetCurrentEstimate (Time estimate);

  /**
   * \brief gets the current RTT estimate.
   * \return The current RTT estimate.
   */
  Time GetCurrentEstimate (void) const;

private:
  SequenceNumber32 m_next;    //!< Next expected sequence to be sent
  RttHistory_t m_history;     //!< List of sent packet
  uint16_t m_maxMultiplier;   //!< Maximum RTO Multiplier
  Time m_initialEstimatedRtt; //!< Initial RTT estimation

protected:
  Time         m_currentEstimatedRtt;     //!< Current estimate
  Time         m_minRto;                  //!< minimum value of the timeout
  uint32_t     m_nSamples;                //!< Number of samples
  uint16_t     m_multiplier;              //!< RTO Multiplier
};

/**
 * \ingroup tcp
 *
 * \brief The "Mean--Deviation" RTT estimator, as discussed by Van Jacobson
 *
 * This class implements the "Mean--Deviation" RTT estimator, as discussed
 * by Van Jacobson and Michael J. Karels, in
 * "Congestion Avoidance and Control", SIGCOMM 88, Appendix A
 *
 */
class RttMeanDeviation : public RttEstimator {
public:
  /**
   * \brief Get the type ID.
   * \return the object TypeId
   */
  static TypeId GetTypeId (void);

  RttMeanDeviation ();

  /**
   * \brief Copy constructor
   * \param r the object to copy
   */
  RttMeanDeviation (const RttMeanDeviation& r);

  virtual TypeId GetInstanceTypeId (void) const;

  /**
   * \brief Add a new measurement to the estimator.
   * \param measure the new RTT measure.
   */
  void Measurement (Time measure);

  /**
   * \brief Returns the estimated RTO.
   * \return the estimated RTO.
   */
  Time RetransmitTimeout ();

  Ptr<RttEstimator> Copy () const;

  /**
   * \brief Resets the estimator.
   */
  void Reset ();

  /**
   * \brief Sets the estimator Gain.
   * \param g the gain, where 0 < g < 1.
   */
  void Gain (double g);

private:
  double       m_gain;       //!< Filter gain
  Time         m_variance;   //!< Current variance
};
} // namespace ns3

#endif /* RTT_ESTIMATOR_H */


text:
.. Copyright 2013 splinter authors. All rights reserved.
   Use of this source code is governed by a BSD-style
   license that can be found in the LICENSE file.

.. meta::
    :description: New splinter features on version 0.5.5.
    :keywords: splinter 0.5.5, python, news, documentation, tutorial, web application

whats's new in splinter 0.5.5?
==============================

Improvements
------------

* Handle "internet explorer" as remote driver.
* implemented `get_screenshot_as_file`.
* `fill_form` now supports custom field types.
* More robust `find_link_by_partial_text`.
* support for selenium 2.39.0.
* support for zope.testbrowser 4.0.4.


text:
<!DOCTYPE html>

  <meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Execute the callable of a stageRunnerNode. — stageRunnerNode_run • stagerunner</title>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-T8Gy5hrqNKT+hzMclPo118YTQO6cYprQmhrYwIiQ/3axmI1hQomh7Ud2hPOy8SP1" crossorigin="anonymous">

<link href="../pkgdown.css" rel="stylesheet">

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar">

      </button>
      stagerunner

  Reference

  News

Execute the callable of a stageRunnerNode.

Execute the callable of a stageRunnerNode.

stageRunnerNode_run(..., .cached_env = NULL, .callable = self$callable)

 Arguments

    <colgroup><col class="name" /><col class="desc" /></colgroup>

      ...

additional arguments to the callable. This allows,
stagerunner stages to be uniformly parametrized (for example,
if all stages should have a verbose parameter.

      .cached_env

An internal helper that passes the cached environment
to be used for storing the results of this execution.

      .callable

Another internal helper used for some recursive
metaprogramming.

Value

TRUE if the execution was successful, or an error otherwise.

Contents

Arguments

Value

Developed by Robert Krzyzanowski.

Site built with pkgdown.


text:
//------------------------------------------------------------
// Game Framework
// Copyright © 2013-2021 Jiang Yin. All rights reserved.
// Homepage: https://gameframework.cn/
// Feedback: mailto:ellan@gameframework.cn
//------------------------------------------------------------

using System;
using System.Collections.Generic;

namespace GameFramework.ObjectPool
{
    /// <summary>
    /// 释放对象筛选函数。
    /// </summary>
    /// <typeparam name="T">对象类型。</typeparam>
    /// <param name="candidateObjects">要筛选的对象集合。</param>
    /// <param name="toReleaseCount">需要释放的对象数量。</param>
    /// <param name="expireTime">对象过期参考时间。</param>
    /// <returns>经筛选需要释放的对象集合。</returns>
    public delegate List<T> ReleaseObjectFilterCallback<T>(List<T> candidateObjects, int toReleaseCount, DateTime expireTime) where T : ObjectBase;
}


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

namespace CTC.CvsntGitImporter
{
	class ManualBranchResolver : ITagResolver
	{
		private readonly ILogger m_log;
		private readonly ITagResolver m_fallback;
		private readonly ITagResolver m_tagResolver;
		private readonly RenameRule m_branchpointRule;
		private Dictionary<string, Commit> m_resolvedCommits;
		private IList<Commit> m_commits;

		public ManualBranchResolver(ILogger log, ITagResolver fallbackResolver, ITagResolver tagResolver, RenameRule branchpointRule)
		{
			m_log = log;
			m_fallback = fallbackResolver;
			m_tagResolver = tagResolver;
			m_branchpointRule = branchpointRule;
		}

		public IDictionary<string, Commit> ResolvedTags
		{
			get { return m_resolvedCommits; }
		}

		public IEnumerable<string> UnresolvedTags
		{
			get { return m_fallback.UnresolvedTags; }
		}

		public IEnumerable<Commit> Commits
		{
			get { return m_commits; }
		}

		public bool Resolve(IEnumerable<string> branches, IEnumerable<Commit> commits)
		{
			var rule = m_branchpointRule;
			m_resolvedCommits = new Dictionary<string, Commit>();
			m_commits = commits.ToListIfNeeded();

			m_log.DoubleRuleOff();
			m_log.WriteLine("Matching branches to branchpoints");
			using (m_log.Indent())
			{
				foreach (var branch in branches.Where(b => rule.IsMatch(b)))
				{
					var tag = rule.Apply(branch);

					var commit = ResolveBranchpoint(branch, tag);
					if (commit != null)
					{
						m_resolvedCommits[branch] = commit;
						m_log.WriteLine("Branch {0} -> Tag {1}", branch, tag);
					}
					else
					{
						m_log.WriteLine("Branch {0}: tag {1} is unresolved", branch, tag);
					}
				}
			}

			var otherBranches = branches.Except(m_resolvedCommits.Keys).ToList();
			if (otherBranches.Any())
			{
				var result = m_fallback.Resolve(otherBranches, m_commits);

				foreach (var kvp in m_fallback.ResolvedTags)
					m_resolvedCommits[kvp.Key] = kvp.Value;

				m_commits = m_fallback.Commits.ToListIfNeeded();
				return result;
			}
			else
			{
				return true;
			}
		}

		private Commit ResolveBranchpoint(string branch, string tag)
		{
			Commit branchCommit;
			if (!m_tagResolver.ResolvedTags.TryGetValue(tag, out branchCommit))
				return null;

			// check for commits to the branch that occur before the tag
			CommitMoveRecord moveRecord = null;
			foreach (var c in m_commits)
			{
				if (c == branchCommit)
					break;

				if (c.Branch == branch)
				{
					if (moveRecord == null)
						moveRecord = new CommitMoveRecord(branch, m_log) { FinalCommit = branchCommit };
					moveRecord.AddCommit(c, c.Select(r => r.File));
				}
			}

			if (moveRecord != null)
			{
				m_log.WriteLine("Some commits on {0} need moving after branchpoint {1}", branch, tag);
				using (m_log.Indent())
				{
					moveRecord.Apply(m_commits);
				}
			}

			return branchCommit;
		}
	}
}


text:
Package.describe({
  name: 'telescope-bootstrap-wysiwyg',
  version: '0.0.1',
  // Brief, one-line summary of the package.
  summary: 'Change the post editor to bootstrap-wysiwyg',
  // URL to the Git repository containing the source code for this package.
  git: '',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.versionsFrom('1.0.5');
  api.use(['less', 'templating'], 'client');

  api.use(['telescope-base', 'telescope-lib', 'fourseven:scss', 'aldeed:autoform', 'djedi:sanitize-html'], 'client');

  api.addFiles('bootstrap/bootstrap.min.js', 'client', {bare: true});
  api.addFiles('bootstrap/bootstrap.less', 'client');

  api.addFiles('wysiwyg/bootstrap-wysiwyg.js', 'client', {bare: true});
  api.addFiles('wysiwyg/style.less', 'client');

  api.addFiles([
    'client/views/forms/bootstrap-wysiwyg.html',
    'client/views/forms/bootstrap-wysiwyg.js',
    'client/views/posts/post_form.html',
    'client/views/posts/post_edit.html',
    'client/views/posts/post_submit.html',
  ], 'client');

  api.addFiles('index.js', ['client', 'server']);
});

Package.onTest(function(api) {
  api.use('tinytest');
  api.use('telescope-bootstrap-wysiwyg');
});


text:
package com.spotify.helios.common.descriptors;

import static java.nio.charset.StandardCharsets.UTF_8;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.spotify.helios.common.Json;
import java.io.IOException;

public abstract class Descriptor {

  public String toJsonString() {
    return Json.asStringUnchecked(this);
  }

  public byte[] toJsonBytes() {
    try {
      return Json.asBytes(this);
    } catch (JsonProcessingException e) {
      throw new RuntimeException(e);
    }
  }

  public static <T extends Descriptor> T parse(final byte[] bytes, Class<T> clazz)
      throws IOException {
    return Json.read(bytes, clazz);
  }

  public static <T extends Descriptor> T parse(final String value, Class<T> clazz)
      throws IOException {
    return parse(value.getBytes(UTF_8), clazz);
  }
}


text:
using System;
using WTM.Domain;

namespace WTM.Mobile.Core
{
    public class UserEvent : EventArgs
    {
        public UserEvent(User user)
        {
            User = user;
        }

        public User User { get; private set; }
    }
}


text:
require 'json'
require 'openc/json_schema'


text:
Plugin.define "phpGreetCards" do
author "Brendan Coles <bcoles@gmail.com>" # 2010-08-01
version "0.1"
description "PHP greeting card mailer"
website "http://www.w2b.ru/webapplications/index.php"

# Dorks #
dorks [
'"Powered by phpGreetCards"'
]

# Matches #
matches [

# Powered by text
{ :text=>'Powered by phpGreetCards, ' },
{ :text=>'Powered by phpGreetCards, ' },

]

end


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>BlahCade Podcast</title>

    <meta name="HandheldFriendly" content="True">
    <meta name="MobileOptimized" content="320">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <meta name="description" content="Digital Pinball, Real Pinball, Movies, Snacks (but mostly Digital Pinball)">

    <meta name="twitter:card" content="summary">
    <meta name="twitter:title" content="BlahCade Podcast">
    <meta name="twitter:description" content="Digital Pinball, Real Pinball, Movies, Snacks (but mostly Digital Pinball)">

    <meta property="og:type" content="article">
    <meta property="og:title" content="BlahCade Podcast">
    <meta property="og:description" content="Digital Pinball, Real Pinball, Movies, Snacks (but mostly Digital Pinball)">

    <link href="/favicon.ico" rel="shortcut icon" type="image/x-icon">
    <link href="/apple-touch-icon-precomposed.png" rel="apple-touch-icon">

    <link rel="stylesheet" type="text/css" href="//blahcadepinball.com/themes/uno/assets/css/uno.css?v=1.0.0" />

    <link rel="canonical" href="http://blahcadepinball.com" />
    <meta name="generator" content="Ghost ?" />
    <link rel="alternate" type="application/rss+xml" title="BlahCade Podcast" href="http://blahcadepinball.com/rss" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css">

BlahCade Podcast

Digital Pinball, Real Pinball, Movies, Snacks (but mostly Digital Pinball)

Blog

                      Twitter

                      Google-plus

                      Github

                      Email

Tag: U-I

Episode 62: Console Yourself With Cheap Steam

It’s a bit light on this week with pinball news. In light of this, we look into how folks on other platforms could capitalise on Steam Sales for PC. You might be surprised about how easy it is for a TPA Console player (PS3/PS4 or XBox) to…

            <time datetime="29 Jun 2016" class="post-list__meta--date date">29 Jun 2016</time> •
            steam,  console,  UI,  BackRoom

Episode 36: Metadata Mike from Farsight

With No Fear going out the door, we wanted to get FarSight back on to talk with us about all things Digital Pinball. As you can see from the show notes, nary a thing is left untouched. What was most interesting was to hear about what Mike actually does as…

            <time datetime="07 Dec 2015" class="post-list__meta--date date">07 Dec 2015</time> •
            Mike,  Reitmeyer,  FarSight,  Interview,  UI

Episode 8: Super-sized Lost in the Zone

As promised last time, Lost In The Zone takes up most of the podcast this go around. Some listener topics are discussed, Twilight Zone gets the in depth treatment, and the joys/perils of owning a table get tossed around. Also in this pod: summer movies that we may or…

            <time datetime="12 Jun 2014" class="post-list__meta--date date">12 Jun 2014</time> •
            LitZ,  Movies,  UI

    Page 1 of 1

                © 2016. All rights reserved.
                Uno theme by Dale-Anthony
                Proudly published with Hubpress


text:
"""Sanity tests for tf.flags."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import unittest

from absl import flags as absl_flags

from tensorflow.python.platform import flags

flags.DEFINE_string(
    flag_name='old_string', default_value='default', docstring='docstring')
flags.DEFINE_string(
    name='new_string', default='default', help='docstring')
flags.DEFINE_integer(
    flag_name='old_integer', default_value=1, docstring='docstring')
flags.DEFINE_integer(
    name='new_integer', default=1, help='docstring')
flags.DEFINE_float(
    flag_name='old_float', default_value=1.5, docstring='docstring')
flags.DEFINE_float(
    name='new_float', default=1.5, help='docstring')
flags.DEFINE_bool(
    flag_name='old_bool', default_value=True, docstring='docstring')
flags.DEFINE_bool(
    name='new_bool', default=True, help='docstring')
flags.DEFINE_boolean(
    flag_name='old_boolean', default_value=False, docstring='docstring')
flags.DEFINE_boolean(
    name='new_boolean', default=False, help='docstring')

class FlagsTest(unittest.TestCase):

  def test_global_flags_object(self):
    self.assertIs(flags.FLAGS, absl_flags.FLAGS)

  def test_keyword_arguments(self):
    test_cases = (
        ('old_string', 'default'),
        ('new_string', 'default'),
        ('old_integer', 1),
        ('new_integer', 1),
        ('old_float', 1.5),
        ('new_float', 1.5),
        ('old_bool', True),
        ('new_bool', True),
        ('old_boolean', False),
        ('new_boolean', False),
    )
    for flag_name, default_value in test_cases:
      self.assertEqual(default_value, absl_flags.FLAGS[flag_name].default)
      self.assertEqual('docstring', absl_flags.FLAGS[flag_name].help)

if __name__ == '__main__':
  unittest.main()


text:
namespace cc {
namespace benchmark_instrumentation {

// Please do not change the trace events in this file without updating
// tools/perf/measurements/rendering_stats.py accordingly.
// The benchmarks search for events and their arguments by name.

void IssueImplThreadRenderingStatsEvent(const RenderingStats& stats) {
  TRACE_EVENT_INSTANT1(
      "benchmark,rail", "BenchmarkInstrumentation::ImplThreadRenderingStats",
      TRACE_EVENT_SCOPE_THREAD, "data", stats.AsTraceableData());
}

void IssueDisplayRenderingStatsEvent() {
  std::unique_ptr<base::trace_event::TracedValue> record_data(
      new base::trace_event::TracedValue());
  record_data->SetInteger("frame_count", 1);
  TRACE_EVENT_INSTANT1(
      "benchmark", "BenchmarkInstrumentation::DisplayRenderingStats",
      TRACE_EVENT_SCOPE_THREAD, "data", std::move(record_data));
}

}  // namespace benchmark_instrumentation
}  // namespace cc


text:
Installation
============

First of all, you'll need Python_.
Any version where CFFI_ is supported should work.
If you don't have Python installed yet, you should get one of the
distributions which already include CFFI and NumPy_ (and many other useful
things), e.g. Anaconda_ or WinPython_.

.. only:: html

   .. image:: https://anaconda.org/conda-forge/python-sounddevice/badges/version.svg
      :target: https://anaconda.org/conda-forge/python-sounddevice

If you are using the ``conda`` package manager (e.g. with Anaconda_ for
Linux/macOS/Windows), you can install the ``sounddevice`` module from the
``conda-forge`` channel::

   conda install -c conda-forge python-sounddevice

There are also packages for several other package managers:

.. only:: html

   .. image:: https://repology.org/badge/vertical-allrepos/python:sounddevice.svg
      :target: https://repology.org/metapackage/python:sounddevice

.. only:: latex

   https://repology.org/metapackage/python:sounddevice

If you are using Windows, you can alternatively install one of the packages
provided at https://www.lfd.uci.edu/~gohlke/pythonlibs/#sounddevice.
The PortAudio_ library is included in the package and you can get the rest
of the dependencies on the same page.

Note that some of the aforementioned packages may be out-of-date.
You can always get the newest ``sounddevice`` release from PyPI_
(using ``pip``).
If you want to try the latest development version, have a look at the section
about :doc:`CONTRIBUTING`.

.. only:: html

   .. image:: https://badge.fury.io/py/sounddevice.svg
      :target: https://pypi.org/project/sounddevice/

To install the latest release from PyPI, use::

   python3 -m pip install sounddevice --user

If you want to install it system-wide for all users (assuming you have the
necessary rights), you can just drop the ``--user`` option.
If you have installed the module already, you can use the ``--upgrade`` flag to
get the newest release.

To un-install, use::

   python3 -m pip uninstall sounddevice

If you install the ``sounddevice`` module with ``pip`` on macOS or Windows, the
PortAudio_ library will be installed automagically.
On other platforms, you might have to install PortAudio with your package
manager (the package might be called ``libportaudio2`` or similar).

You might also have to install CFFI_ (from a package called ``python3-cffi`` or
similar).

NumPy_ is only needed if you want to play back and record NumPy arrays.
The classes `sounddevice.RawStream`, `sounddevice.RawInputStream` and
`sounddevice.RawOutputStream` use plain Python buffer objects and don't need
NumPy at all.
If you need NumPy, you should install it with your package manager (from a
package named ``python3-numpy`` or similar) or use a Python distribution that
already includes NumPy (see above).
You can also install NumPy with ``pip``, but depending on your platform, this
might require a compiler and several additional libraries.

.. _PortAudio: http://www.portaudio.com/
.. _NumPy: http://www.numpy.org/
.. _Python: https://www.python.org/
.. _Anaconda: https://www.anaconda.com/download/
.. _WinPython: http://winpython.github.io/
.. _CFFI: http://cffi.readthedocs.io/
.. _PyPI: https://pypi.org/project/sounddevice/


text:
! { dg do-run }
! Tests passing of character array initialiser as actual argument.
! Fixes PR18109.
! Contributed by Paul Thomas pault@gcc.gnu.org
program char_initialiser
  character*5, dimension(3) :: x
  character*5, dimension(:), pointer :: y
  x=(/"is Ja","ne Fo","nda"/)
  call sfoo ("is Ja", x(1))
  call afoo ((/"is Ja","ne Fo","nda"/), x)
  y => pfoo ((/"is Ja","ne Fo","nda"/))
  call afoo (y, x)
contains
  subroutine sfoo(ch1, ch2)
     character*(*)               :: ch1, ch2
     if (ch1 /= ch2) call abort ()
  end subroutine sfoo
  subroutine afoo(ch1, ch2)
     character*(*), dimension(:) :: ch1, ch2
     if (any(ch1 /= ch2)) call abort ()
  end subroutine afoo
  function pfoo(ch2)
     character*5, dimension(:), target  :: ch2
     character*5, dimension(:), pointer :: pfoo
     pfoo => ch2
  end function pfoo
end program


text:
using Silphid.Extensions;
using Silphid.Showzup.Virtual;
using Silphid.Showzup.Virtual.Layout;
using UnityEngine;

namespace Silphid.Showzup.Test.Controls.Virtual.Layout
{
    public class LayoutIntegrationTest : MonoBehaviour
    {
        private class LayoutCollection : ILayoutCollection
        {
            private readonly RectTransform[] _transforms;

            public LayoutCollection(RectTransform[] transforms)
            {
                _transforms = transforms;
            }

            public int Count => _transforms.Length;
            public bool IsLoaded(int index) => true;
            public bool IsLayouted(int index) => false;

            public Vector2 GetPreferredSize(int index) =>
                _transforms[index]
                   .GetPreferredSize();

            public Rect GetRect(int index) =>
                _transforms[index]
                   .rect;

            public void SetRect(int index, Rect rect) =>
                _transforms[index]
                   .SetLayoutRect(rect);
        }

        public RectTransform Container;
        public RectTransform Bottom;
        public RectTransform[] Transforms;
        public LayoutInfo LayoutInfo = new LayoutInfo();

        private void Update()
        {
            var rect = Container.rect;
            var collection = new LayoutCollection(Transforms);
            var ranges = new RangeCache(collection);
            var layout = new DelegatingLayout(LayoutInfo, ranges);

            var (requiredSizeAlong, _) = layout.Perform(
                LayoutDirection.Forward,
                collection,
                new Rect(Vector2.zero, rect.size),
                rect.size);

            Bottom.SetLayoutRect(new Rect(0, requiredSizeAlong, Container.rect.width, 2));
        }
    }
}


text:
"""Admin section, including Role and Permission authorized."""
from flask import Blueprint, flash, redirect, render_template, request, url_for, abort
from flask_login import current_user, login_required, login_user, logout_user
from flask_menu import register_menu

from goldeneye.extensions import db
from goldeneye.user.models import User, Role, Permission

blueprint = Blueprint('admin', __name__, url_prefix='/admin', static_folder='../static')

@blueprint.route('/admin_settings/')
@register_menu(blueprint, '.admin_settings', '系统设置', type='N', cls='fa-gears')
def admin_settings():
    return None

@blueprint.route('/authorized/', methods=['GET'])
@register_menu(blueprint, 'admin_settings.authorized', '授权查看', type='M')
def authorized():
    roles = db.session.query(Role).all()
    active_rid = request.args.get('active_rid', type=int)
    perms = []
    if active_rid:
        perms =[perm.slug for perm in db.session.query(Permission).join(Role, Permission.roles).filter(Role.id==active_rid).all()]
    return render_template('admin/authorized.html',
                           active_rid = active_rid,
                           roles=roles,
                           perms=perms)

@blueprint.route('/save_authorized/', methods=['GET', 'POST'])
@register_menu(blueprint, 'admin_settings.authorized.save_authorized', '权限设置', type='B')
def save_authorized():
    active_rid = request.values.get('active_rid')
    perms = request.values.getlist('perms')

    if active_rid:
        acti_role = Role.get_by_id(active_rid)
        acti_perms = db.session.query(Permission).filter(Permission.slug.in_(perms)).all()
        acti_role.permissions=acti_perms
        acti_role.save()

    return redirect(url_for('admin.authorized', active_rid=active_rid))

@blueprint.route('/save_role/', methods=['POST'])
def save_role():
    role_id = request.values.get('role_id', default=None)
    role_name = request.values.get('role_name')
    if role_id:
        role = Role.get_by_id(role_id)
        role.name = role_name
        role.save()
    else:
        Role.create(name=role_name)
    return redirect(url_for('admin.authorized', active_rid=role_id))

@blueprint.route('/del_role/', methods=['POST'])
def del_role():
    role_id = request.values.get('role_id', default=None)
    if role_id:
        Role.get_by_id(role_id).delete()
    return redirect(url_for('admin.authorized'))


text:
//////////////////////////////////////////////////////////////////////////////
// INCLUDES
//////////////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stddef.h>
#include <string.h>
#include "apx/event_listener.h"
#include "apx/node_data.h"
#include "apx/client.h"
#include "application.h"
#include "pack.h"

//////////////////////////////////////////////////////////////////////////////
// PRIVATE CONSTANTS AND DATA TYPES
//////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////
// PRIVATE FUNCTION PROTOTYPES
//////////////////////////////////////////////////////////////////////////////
static void onClientConnected(void* arg, apx_clientConnection_t* client_connection);
static void onClientDisconnected(void* arg, apx_clientConnection_t* client_connection);
static void onRequirePortWrite(void *arg, apx_portInstance_t *port_instance, uint8_t const* data, apx_size_t size);
static double calculate_average_events_per_second(void);

//////////////////////////////////////////////////////////////////////////////
// PRIVATE VARIABLES
//////////////////////////////////////////////////////////////////////////////
static apx_client_t *m_client = NULL;
static apx_nodeInstance_t *m_node_instance = NULL;
static uint32_t m_event_count;
static bool m_is_connected;
static bool m_has_pending_start_cmd;
static bool m_is_test_ongoing;
static bool m_is_requester;
static apx_portInstance_t *m_rqst_handle;
static apx_portInstance_t *m_rsp_handle;
static dtl_sv_t *m_sv;
static uint32_t m_timer = 0u;
static application_cfg_t m_cfg;

//////////////////////////////////////////////////////////////////////////////
// PUBLIC FUNCTIONS
//////////////////////////////////////////////////////////////////////////////
/*
* Returns true on success, false otherwise
*/
bool application_init(const application_cfg_t *cfg)
{
   apx_clientEventListener_t handlerTable;
   apx_error_t result;
   memset(&handlerTable, 0, sizeof(handlerTable));
   handlerTable.client_connect1 = onClientConnected;
   handlerTable.client_disconnect1 = onClientDisconnected;
   handlerTable.require_port_write1 = onRequirePortWrite;
   if (cfg == NULL)
   {
      printf("cfg is NULL, aborting\n");
      return false;
   }
   memcpy(&m_cfg, cfg, sizeof(m_cfg));

   m_is_requester = false;
   m_event_count = 0u;
   m_is_connected = false;
   m_has_pending_start_cmd = true;
   m_is_test_ongoing = false;
   m_sv = dtl_sv_new();
   if (m_cfg.timer_init == 0)
   {
      m_cfg.timer_init = 1u; //Default to 1 second
   }
   m_client = apx_client_new();
   if (m_client != 0)
   {
      apx_client_register_event_listener(m_client, &handlerTable);
      result = apx_client_build_node(m_client, m_cfg.apx_definition);
      if (result != APX_NO_ERROR)
      {
         printf("apx_client_build_node failed with error %d\n", (int) result);
         return false;
      }
      m_node_instance = apx_client_get_last_attached_node(m_client);
      if ( (strcmp(apx_nodeInstance_get_name(m_node_instance), "RequestNode")==0) )
      {
         printf("Running in requester mode\n");
         m_is_requester = true;
         m_rqst_handle = apx_nodeInstance_get_provide_port(m_node_instance, (apx_portId_t) 0u);
         m_rsp_handle = apx_nodeInstance_get_require_port(m_node_instance, (apx_portId_t)0u);
      }
      else
      {
         printf("Running in responder mode\n");
         m_rqst_handle = apx_nodeInstance_get_require_port(m_node_instance, (apx_portId_t)0u);
         m_rsp_handle = apx_nodeInstance_get_provide_port(m_node_instance, (apx_portId_t)0u);
      }
      assert(m_rqst_handle != NULL);
      assert(m_rsp_handle != NULL);
      printf("Connecting to %s\n", m_cfg.server_address);
      switch(m_cfg.resource_type)
      {
      case APX_RESOURCE_TYPE_IPV4: //fall-trough
      case APX_RESOURCE_TYPE_IPV6:
         result = apx_client_connect_tcp(m_client, m_cfg.server_address, m_cfg.tcp_port);
         if (result != APX_NO_ERROR)
         {
            printf("apx_client_connect_tcp failed with error %d\n", (int) result);
            return false;
         }
         break;
      case APX_RESOURCE_TYPE_FILE:
#ifdef _WIN32
         printf("UNIX domain socket path not supported in Windows\n");
         return false;
#else
         result = apx_client_connect_unix(m_client, m_cfg.server_address);
         if (result != APX_NO_ERROR)
         {
            printf("apx_client_connect_unix failed with error %d\n", (int) result);
            return false;
         }
#endif
         break;
      case APX_RESOURCE_TYPE_NAME:
         if ( strcmp(m_cfg.server_address, "localhost") == 0 )
         {
            result = apx_client_connect_tcp(m_client, "127.0.0.1", m_cfg.tcp_port);
            if (result != APX_NO_ERROR)
            {
               printf("apx_client_connect_unix failed with error %d\n", (int) result);
               return false;
            }
         }
         else
         {
            fprintf(stderr, "Error: Unsupported connection name \"%s\"\n", m_cfg.server_address);
            return false;
         }
      break;
      }
      return true;
   }
   printf("apx_client_new failed\n");
   return false;
}

/*
* Returns true if the application want to continue to run, false otherwise
*/
bool application_run(void)
{
   if (m_is_connected)
   {
      if (m_is_requester)
      {
         if (m_has_pending_start_cmd)
         {
            apx_error_t result;
            m_event_count = 1u;
            m_has_pending_start_cmd = false;
            m_is_test_ongoing = true;
            m_timer = m_cfg.timer_init;
            dtl_sv_set_u32(m_sv, m_event_count);
            result = apx_client_write_port_data(m_client, m_rqst_handle, (dtl_dv_t*) m_sv);
            assert(result == APX_NO_ERROR);
            printf("Test started\n");
         }
         else
         {
            if (m_is_test_ongoing)
            {
               m_timer--;
            }
            if (m_timer == 0u)
            {
               m_is_test_ongoing = false;
               double result = calculate_average_events_per_second();
               printf("Test completed.\nTotal Events: %u. Events/s: %.2f.\n", m_event_count, result);
               return false;
            }
         }
      }
   }
   return true;
}

//////////////////////////////////////////////////////////////////////////////
// PRIVATE FUNCTIONS
//////////////////////////////////////////////////////////////////////////////

static void onClientConnected(void* arg, apx_clientConnection_t* client_connection)
{
   (void)arg;
   (void)client_connection;
   m_is_connected = true;
   printf("Connected to server\n");
}

static void onClientDisconnected(void* arg, apx_clientConnection_t* client_connection)
{
   (void)arg;
   (void)client_connection;

   m_is_connected = false;
   m_has_pending_start_cmd = true;
   m_is_test_ongoing = false;
   printf("Disconnected from server\n");
}

static void onRequirePortWrite(void* arg, apx_portInstance_t* port_instance, uint8_t const* data, apx_size_t size)
{
   (void)arg;
   (void)data;
   (void)size;
   if (m_is_requester)
   {
      if ((m_is_test_ongoing) && (port_instance == m_rsp_handle))
      {
         apx_error_t result;
         uint32_t value;
         bool ok;
         dtl_sv_t* sv = NULL;
         result = apx_client_read_port_data(m_client, m_rsp_handle, (dtl_dv_t**)&sv);
         assert(result == APX_NO_ERROR);
         assert(sv != NULL);
         value = dtl_sv_to_u32(sv, &ok);
         if (ok)
         {
            m_event_count = value;
            dtl_sv_set_u32(sv, value + 1);
            result = apx_client_write_port_data(m_client, m_rqst_handle, (dtl_dv_t*)sv);
            assert(result == APX_NO_ERROR);
         }
         dtl_dv_dec_ref((dtl_dv_t*)sv);
      }
   }
   else
   {
      if ((m_rqst_handle != NULL) && (m_rsp_handle != NULL))
      {
         apx_error_t result;
         dtl_sv_t* sv = NULL;
         uint32_t value;
         bool ok;
         result = apx_client_read_port_data(m_client, m_rqst_handle, (dtl_dv_t**)&sv);
         assert(result == APX_NO_ERROR);
         assert(sv != NULL);
         value = dtl_sv_to_u32(sv, &ok);
         if (ok)
         {
            dtl_sv_set_u32(sv, value + 1);
            result = apx_client_write_port_data(m_client, m_rsp_handle, (dtl_dv_t*)sv);
            assert(result == APX_NO_ERROR);
         }
         dtl_dv_dec_ref((dtl_dv_t*)sv);
      }
   }
}

static double calculate_average_events_per_second(void)
{
   double events = (double)m_event_count;
   double time = (double)m_cfg.timer_init;
   return events / time;
}


text:
"""tf.data.Dataset interface to the MNIST dataset."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import gzip
import os
import shutil
import tempfile

import numpy as np
from six.moves import urllib
import tensorflow as tf

def read32(bytestream):
    """Read 4 bytes from bytestream as an unsigned 32-bit integer."""
    dtype = np.dtype(np.uint32).newbyteorder(">")
    return np.frombuffer(bytestream.read(4), dtype=dtype)[0]

def check_image_file_header(filename):
    """Validate that filename corresponds to images for the MNIST dataset."""
    with tf.gfile.Open(filename, "rb") as fptr:
        magic = read32(fptr)
        read32(fptr)  # num_images, unused
        rows = read32(fptr)
        cols = read32(fptr)
        if magic != 2051:
            raise ValueError(
                "Invalid magic number %d in MNIST file %s" % (magic, fptr.name)
            )
        if rows != 28 or cols != 28:
            raise ValueError(
                "Invalid MNIST file %s: Expected 28x28 images, found %dx%d"
                % (fptr.name, rows, cols)
            )

def check_labels_file_header(filename):
    """Validate that filename corresponds to labels for the MNIST dataset."""
    with tf.gfile.Open(filename, "rb") as fptr:
        magic = read32(fptr)
        read32(fptr)  # num_items, unused
        if magic != 2049:
            raise ValueError(
                "Invalid magic number %d in MNIST file %s" % (magic, fptr.name)
            )

def download(directory, filename):
    """Download (and unzip) a file from the MNIST dataset if not already done."""
    filepath = os.path.join(directory, filename)
    if tf.gfile.Exists(filepath):
        return filepath
    if not tf.gfile.Exists(directory):
        tf.gfile.MakeDirs(directory)
    # CVDF mirror of http://yann.lecun.com/exdb/mnist/
    url = (
        "https://storage.googleapis.com/cvdf-datasets/mnist/"
        + filename
        + ".gz"
    )
    _, zipped_filepath = tempfile.mkstemp(suffix=".gz")
    print("Downloading %s to %s" % (url, zipped_filepath))
    urllib.request.urlretrieve(url, zipped_filepath)
    with gzip.open(zipped_filepath, "rb") as f_in, tf.gfile.Open(
        filepath, "wb"
    ) as f_out:
        shutil.copyfileobj(f_in, f_out)
    os.remove(zipped_filepath)
    return filepath

def dataset(directory, images_file, labels_file):
    """Download and parse MNIST dataset."""

    images_file = download(directory, images_file)
    labels_file = download(directory, labels_file)

    check_image_file_header(images_file)
    check_labels_file_header(labels_file)

    def decode_image(image):
        """Decodes and normalizes the image."""
        # Normalize from [0, 255] to [0.0, 1.0]
        image = tf.decode_raw(image, tf.uint8)
        image = tf.cast(image, tf.float32)
        image = tf.reshape(image, [784])
        image = image / 255.0  # [0.0, 1.0]
        image = image * 2.0  # [0.0, 2.0]
        image = image - 1.0  # [-1.0, 1.0]
        return image

    def decode_label(label):
        """Decodes and reshapes the label."""
        label = tf.decode_raw(label, tf.uint8)  # tf.string -> [tf.uint8]
        label = tf.reshape(label, [])  # label is a scalar
        return tf.to_int32(label)

    images = tf.data.FixedLengthRecordDataset(
        images_file, 28 * 28, header_bytes=16
    ).map(decode_image)
    labels = tf.data.FixedLengthRecordDataset(
        labels_file, 1, header_bytes=8
    ).map(decode_label)
    return tf.data.Dataset.zip((images, labels))

def train(directory):
    """tf.data.Dataset object for MNIST training data."""
    return dataset(
        directory, "train-images-idx3-ubyte", "train-labels-idx1-ubyte"
    )

def test(directory):
    """tf.data.Dataset object for MNIST test data."""
    return dataset(
        directory, "t10k-images-idx3-ubyte", "t10k-labels-idx1-ubyte"
    )


text:
package oci

import (
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path"
	"strings"
	"testing"

	v1 "github.com/google/go-containerregistry/pkg/v1"
	"github.com/google/go-containerregistry/pkg/v1/layout"
	"github.com/google/go-containerregistry/pkg/v1/tarball"
	"github.com/google/go-containerregistry/pkg/v1/validate"
	"github.com/pkg/errors"
)

var (
	blob     = "blobs/"
	testPath = "testdata/test_write1"
)

var testCases = []struct {
	// name is the name of the test case.
	name string
	// dataPath is where the test data is found.
	dataPath string
	// path to the image manifest relative to the dataPath.
	manifestPath string
	// expectedContent is a mapping from a file expected to exist in the image
	// relative to the "dataPath" to the expected sha256 digest of that file.
	expectedContent map[string]v1.Hash
}{
	{
		"alpine_linux",
		"testdata/test_write1/small_linux.tar",
		"sha256/9a96f3888ebad00d46bca04ccb591e70d091624835998668af551f48512d9b5c",
		// Note: the following keys correspond to the OCI image format.
		map[string]v1.Hash{
			"blobs/sha256/9a96f3888ebad00d46bca04ccb591e70d091624835998668af551f48512d9b5c": v1.Hash{Algorithm: "sha256", Hex: "9a96f3888ebad00d46bca04ccb591e70d091624835998668af551f48512d9b5c"},
			"index.json": v1.Hash{Algorithm: "sha256", Hex: "ce6ed2e6817add8a5a0e94f4c2ac00360c7ca2cc98c4972b86530f14de622508"},
			"oci-layout": v1.Hash{Algorithm: "sha256", Hex: "b66dbb27a73334db6ac9c030475837bd7f4472d835c72b2360534b203edce6cb"},
		},
	},
}

// TestWrite checks to ensure that the v1.Image written is in OCI format by validating image output format and content.
func TestWrite(t *testing.T) {
	for _, wt := range testCases {
		t.Run(wt.name, func(t *testing.T) {
			tmp, err := ioutil.TempDir("", "write-oci-index-test")
			if err != nil {
				t.Errorf("Unable to create a TempDir %s: %v", os.TempDir(), err)
			}

			defer os.RemoveAll(tmp)

			img, err := tarball.ImageFromPath(wt.dataPath, nil)
			if err != nil {
				t.Errorf("Error loading image from testdata: %v", err)
			}

			if err := Write(img, tmp); err != nil {
				t.Errorf("Write(%s): %v", tmp, err)
			}

			if err := assertValidImageOCILayout(tmp, img, wt.expectedContent, wt.manifestPath); err != nil {
				t.Errorf("Image index written is not a valid OCI format: %v", err)
			}
		})
	}
}

// assertValidImageOCILayout checks that the index written is not corrupt
// and that the contents of the OCI layout are all present and non-corrupt.
func assertValidImageOCILayout(ociDir string, img v1.Image, wantContent map[string]v1.Hash, shaPth string) error {
	written, err := layout.ImageIndexFromPath(ociDir)
	if err != nil {
		return errors.Wrapf(err, "failed to write image to temp path %s", ociDir)
	}

	if err := validate.Index(written); err != nil {
		return errors.Wrapf(err, "failed to validate the image written to %s using validate.Index()", ociDir)
	}

	// validate that the contents of blobs/ were written in the following format:
	// Top level:
	//     oci-layout, index.json, blobs/.
	// Under blobs/, for each image:
	// 	   one file for each layer, config blob, and manifest blob.
	for wantFile, wantDigest := range wantContent {
		// validate the files (i.e. index.json, oci-layout).
		if err := validateFile(path.Join(ociDir, wantFile), wantFile, wantDigest.Hex, ociDir); err != nil {
			return errors.Wrapf(err, "failed to validate %s file", wantFile)
		}
	}

	return nil
}

// compares the SHA256 value of src file to example.
func compareSHA(src, want string) error {
	f, err := os.Open(src)
	if err != nil {
		return errors.Wrapf(err, "failed to open file")
	}
	defer f.Close()

	h := sha256.New()
	if _, err := io.Copy(h, f); err != nil {
		return errors.Wrapf(err, "sha256 hashing of file %s failed", src)
	}
	if got := hex.EncodeToString(h.Sum(nil)); strings.Compare(got, want) != 0 {
		return fmt.Errorf("sha256 hex code of file %s did not match, got: %s want: %s", src, got, want)
	}

	return nil
}

// validates a file being tested for by checking file is not empty or corrupt.
func validateFile(src, file, want, dir string) error {
	f, err := os.Stat(src)
	if err != nil {
		return errors.Wrapf(err, "unable to stat %s", src)
	}

	if os.IsNotExist(err) {
		return errors.Wrapf(err, "wrong OCI output format; got: %v, want: %s", err, file)
	}
	if f.Size() == 0 {
		return fmt.Errorf("error occured: empty %s, size: %d", file, f.Size())
	}
	if err = compareSHA(path.Join(dir, file), want); err != nil {
		return errors.Wrapf(err, "sha256 hex code for %s did not match", src)
	}

	return nil
}


text:
/**
* Require cultivo.notify.js
*/

Cultivo.prototype.httpPost = function(resource, data, callBack) {
  var self = this;
  $.ajax({
    type: 'POST',
    url: resource,
    data: data,
    contentType: 'application/json; utf-8',
    dataType: 'json',
    success: callBack,
    error: function(xhr, textStatus, errorThrown) {
      self.notifyDanger({
        title: xhr.status,
        message: errorThrown
      });
    }
  });

}


text: require('scrollbar').setup()