text:
/* test durability
   runs mongod, kill -9's, recovers
*/

var debugging = false;
var testname = "dur2";
var step = 1;
var conn = null;

var start = new Date();
function howLongSecs() {
    return (new Date() - start) / 1000;
}

function log(str) {
    if (str)
        print("\n" + testname + " step " + step++ + " " + str);
    else
        print(testname + " step " + step++);
}

function verify() {
    log("verify");
    var d = conn.getDB("test");
    var mycount = d.foo.count();
    // print("count:" + mycount);
    assert(mycount > 2, "count wrong");
}

function work() {
    log("work");
    x = 'x';
    while (x.length < 1024)
        x += x;
    var d = conn.getDB("test");
    d.foo.drop();
    d.foo.insert({});

    // go long enough we will have time to kill it later during recovery
    var j = 2;
    var MaxTime = 90;
    while (1) {
        d.foo.insert({_id: j, z: x});
        d.foo.update({_id: j}, {$inc: {a: 1}});
        if (j % 25 == 0)
            d.foo.remove({_id: j});
        j++;
        if (j % 3 == 0)
            d.foo.update({_id: j}, {$inc: {a: 1}}, true);
        if (j % 10000 == 0)
            print(j);
        if (howLongSecs() > MaxTime)
            break;
    }

    verify();
    d.runCommand({getLastError: 1, fsync: 1});
}

if (debugging) {
    // mongod already running in debugger
    print(
        "DOING DEBUG MODE BEHAVIOR AS 'db' IS DEFINED -- RUN mongo --nodb FOR REGULAR TEST BEHAVIOR");
    conn = db.getMongo();
    work();
    sleep(30000);
    quit();
}

// directories
var path = MongoRunner.dataPath + testname + "dur";

log("run mongod with --dur");
conn = MongoRunner.runMongod({
    dbpath: path,
    journal: "",
    smallfiles: "",
    journalOptions: 8 /*DurParanoid*/,
    master: "",
    oplogSize: 64
});
work();

log("kill -9");
MongoRunner.stopMongod(conn, /*signal*/ 9);

// journal file should be present, and non-empty as we killed hard
assert(listFiles(path + "/journal/").length > 0,
       "journal directory is unexpectantly empty after kill");

// restart and recover
log("restart mongod and recover");
conn = MongoRunner.runMongod({
    restart: true,
    cleanData: false,
    dbpath: path,
    journal: "",
    smallfiles: "",
    journalOptions: 8,
    master: "",
    oplogSize: 64
});
verify();

log("stopping mongod " + conn.port);
MongoRunner.stopMongod(conn);

print(testname + " SUCCESS");


text:
package com.google.security.zynamics.binnavi.Gui.GraphWindows.Searchers.Text.Gui;

import com.google.security.zynamics.binnavi.Gui.GraphWindows.Searchers.Text.Model.SearchResult;
import com.google.security.zynamics.binnavi.yfileswrap.Gui.GraphWindows.Searchers.Text.Model.GraphSearcher;
import com.google.security.zynamics.binnavi.yfileswrap.zygraph.NaviEdge;
import com.google.security.zynamics.binnavi.yfileswrap.zygraph.NaviNode;
import com.google.security.zynamics.binnavi.yfileswrap.zygraph.ZyGraph;
import com.google.security.zynamics.binnavi.yfileswrap.zygraph.ZyGraphHelpers;
import com.google.security.zynamics.zylib.gui.CMessageBox;
import com.google.security.zynamics.zylib.gui.zygraph.helpers.GraphHelpers;

import java.awt.Color;
import java.awt.Window;
import java.util.regex.PatternSyntaxException;

import javax.swing.ComboBoxEditor;

/**
 * Contains code for executing a search in a graph window.
 */
public final class CSearchExecuter {
  /**
   * Background color used when a search failed.
   */
  private static final Color BACKGROUND_COLOR_FAIL = new Color(255, 128, 128);

  /**
   * Background color used when a search succeeded.
   */
  private static final Color BACKGROUND_COLOR_SUCCESS = Color.WHITE;

  /**
   * You are not supposed to instantiate this class.
   */
  private CSearchExecuter() {
  }

  /**
   * Cycles through an existing search operation.
   *
   * @param parent Parent window used for dialogs.
   * @param graph Graph to search through.
   * @param searcher Provides search results to cycle through.
   * @param cycleBackwards True, to cycle backwards through the results. False, to cycle in forward
   *        order.
   * @param zoomToResult True, to zoom to a result. False, to move without zooming.
   */
  private static void cycleExistingSearch(final Window parent, final ZyGraph graph,
      final GraphSearcher searcher, final boolean cycleBackwards, final boolean zoomToResult) {
    // If the searcher didn't change since last time, we only skip to
    // the previous (CTRL+ENTER) or next (ENTER) search result. (SHIFT zooms to target)
    if (cycleBackwards) {
      searcher.getCursor().previous();

      if (searcher.getCursor().isBeforeFirst()) {
        CMessageBox.showInformation(
            parent, "All search results were displayed. Going back to the last one");
      }
    } else {
      searcher.getCursor().next();

      if (searcher.getCursor().isAfterLast()) {
        CMessageBox.showInformation(
            parent, "All search results were displayed. Going back to the first one");
      }
    }

    final SearchResult result = searcher.getCursor().current();

    if (result == null) {
      return;
    }

    if (result.getObject() instanceof NaviNode) {
      ZyGraphHelpers.centerNode(graph, (NaviNode) result.getObject(), zoomToResult);
    } else if (result.getObject() instanceof NaviEdge) {
      ZyGraphHelpers.centerEdgeLabel(graph, (NaviEdge) result.getObject(), zoomToResult);
    }
  }

  /**
   * Cycles through an existing search operation.
   *
   * @param parent Parent window used for dialogs.
   * @param editor Combobox editor whose color is changed depending on the search result.
   * @param graph Graph to search through.
   * @param searcher Executes the search over the graph.
   * @param searchString The string to search for.
   * @param zoomToResult True, to zoom to a result. False, to move without zooming.
   */
  private static void startNewSearch(final Window parent,
      final ComboBoxEditor editor,
      final ZyGraph graph,
      final GraphSearcher searcher,
      final String searchString,
      final boolean zoomToResult) {
    try {
      // Search for all occurrences
      searcher.search(GraphHelpers.getNodes(graph), GraphHelpers.getEdges(graph), searchString);

      if (searcher.getResults().isEmpty()) {
        editor.getEditorComponent().setBackground(BACKGROUND_COLOR_FAIL);
      } else {
        editor.getEditorComponent().setBackground(BACKGROUND_COLOR_SUCCESS);
      }

      // Immediately display all search occurrences
      for (final SearchResult result : searcher.getResults()) {
        if (result.getObject() instanceof NaviNode) {
          final NaviNode node = (NaviNode) result.getObject();
          node.setBackgroundColor(
              result.getLine(), result.getPosition(), result.getLength(), Color.YELLOW);
        } else if (result.getObject() instanceof NaviEdge) {
          final NaviEdge edge = (NaviEdge) result.getObject();
          edge.getLabelContent().getLineContent(result.getLine())
              .setBackgroundColor(result.getPosition(), result.getLength(), Color.YELLOW);
        }
      }

      final SearchResult result = searcher.getCursor().current();

      if (result != null) {
        if (result.getObject() instanceof NaviNode) {
          ZyGraphHelpers.centerNode(graph, (NaviNode) result.getObject(), zoomToResult);
        } else if (result.getObject() instanceof NaviEdge) {
          ZyGraphHelpers.centerEdgeLabel(graph, (NaviEdge) result.getObject(), zoomToResult);
        }
      }

      graph.updateGraphViews();
    } catch (final PatternSyntaxException exception) {
      // Do not bother to log this
      CMessageBox.showInformation(
          parent, String.format("Invalid Regular Expression '%s'", searchString));
    }
  }

  /**
   * Executes a search operation.
   *
   * @param parent Parent window used for dialogs.
   * @param editor Combobox editor whose color is changed depending on the search result.
   * @param graph Graph to search through.
   * @param searcher Executes the search over the graph.
   * @param searchString The string to search for.
   * @param cycleBackwards True, to cycle backwards through the results. False, to cycle in forward
   *        order.
   * @param zoomToResult True, to zoom to a result. False, to move without zooming.
   */
  public static void search(final Window parent,
      final ComboBoxEditor editor,
      final ZyGraph graph,
      final GraphSearcher searcher,
      final String searchString,
      final boolean cycleBackwards,
      final boolean zoomToResult) {
    // If something in the searcher changed, we have to recalculate
    // the search results.
    if (searcher.hasChanged() || !searchString.equals(searcher.getLastSearchString())) {
      CSearchExecuter.startNewSearch(parent, editor, graph, searcher, searchString, zoomToResult);
    } else if (!searcher.getResults().isEmpty()) // Don't bother cycling through an empty results
                                                 // list
    {
      CSearchExecuter.cycleExistingSearch(parent, graph, searcher, cycleBackwards, zoomToResult);
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
.parent {
  display: flex;
  flex-direction: column;
  justify-content: center;
}


text:
/* IOStream.h */
/* Copyright (C) 2012 mbed.org, MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
 * and associated documentation files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge, publish, distribute,
 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or
 * substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#ifndef IOSTREAM_H_
#define IOSTREAM_H_

#include "rtos.h"

class IStream
{
public:
  //IStream();
  //virtual ~IStream();

    //0 for non-blocking (returns immediately), osWaitForever for infinite blocking
    virtual int read(uint8_t* buf, size_t* pLength, size_t maxLength, uint32_t timeout=osWaitForever) = 0;
    virtual size_t available() = 0;
    virtual int waitAvailable(uint32_t timeout=osWaitForever) = 0; //Wait for data to be available
    virtual int abortRead() = 0; //Abort current reading (or waiting) operation
};

class OStream
{
public:
  //OStream();
  //virtual ~OStream();

    //0 for non-blocking (returns immediately), osWaitForever for infinite blocking
    virtual int write(uint8_t* buf, size_t length, uint32_t timeout=osWaitForever) = 0;
    virtual size_t space() = 0;
    virtual int waitSpace(uint32_t timeout=osWaitForever) = 0; //Wait for space to be available
    virtual int abortWrite() = 0; //Abort current writing (or waiting) operation
};

class IOStream : public IStream, public OStream
{
public:
  //IOStream();
  //virtual ~IOStream();
};

#endif /* IOSTREAM_H_ */


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Diagnostics.Contracts;
using System.Xml.Linq;
using System.Diagnostics;

namespace PumpingLemma
{
    // These should probably be case classes
    // C# does not have case classes
    public class SymbolicString
    {
        public enum SymbolicStringType { Symbol, Concat, Repeat };

        public SymbolicStringType expression_type;

        // Used if it is a symbol
        public String atomic_symbol;

        // Used if it is concat
        public List<SymbolicString> sub_strings;

        // Used if it is a repeat
        public SymbolicString root;
        public LinearIntegerExpression repeat;

        public bool isEpsilon()
        {
            return this.expression_type == SymbolicStringType.Concat && this.sub_strings.Count == 0;
        }

        public bool isFlat()
        {
            switch(this.expression_type)
            {
                case SymbolicStringType.Symbol:
                    return true;
                case SymbolicStringType.Repeat:
                    return this.root.isWord();
                case SymbolicStringType.Concat:
                    return this.sub_strings.All(x =>
                        x.expression_type == SymbolicStringType.Symbol ||
                        x.expression_type == SymbolicStringType.Repeat && x.root.isWord());
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

        public bool isWord()
        {
            switch (this.expression_type)
            {
                case SymbolicStringType.Symbol:
                    return true;
                case SymbolicStringType.Repeat:
                    return false;
                case SymbolicStringType.Concat:
                    return this.sub_strings.All(x => x.expression_type == SymbolicStringType.Symbol);
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

        public IEnumerable<String> word()
        {
            Debug.Assert(this.isWord());
            Debug.Assert(this.isFlat());
            if (this.expression_type == SymbolicStringType.Symbol)
                return new List<String> { this.atomic_symbol };
            else if (this.expression_type == SymbolicStringType.Concat)
                return this.sub_strings.Select(x => x.atomic_symbol);
            else
                throw new ArgumentException();
        }

        public IEnumerable<SymbolicString> wordSymbols()
        {
            Debug.Assert(this.isWord());
            Debug.Assert(this.isFlat());
            if (this.expression_type == SymbolicStringType.Symbol)
                return new List<SymbolicString> { this };
            else if (this.expression_type == SymbolicStringType.Concat)
                return this.sub_strings;
            else
                throw new ArgumentException();
        }

        public int wordLength()
        {
            Debug.Assert(this.isWord());
            Debug.Assert(this.isFlat());
            if (this.expression_type == SymbolicStringType.Symbol)
                return 1;
            else if (this.expression_type == SymbolicStringType.Concat)
                return this.sub_strings.Count();
            else
                throw new ArgumentException();
        }

        public int StarHeight()
        {
            switch (this.expression_type)
            {
                case SymbolicStringType.Symbol:
                    return 0;
                case SymbolicStringType.Repeat:
                    return 1 + this.root.StarHeight();
                case SymbolicStringType.Concat:
                    return this.sub_strings.Max(x => x.StarHeight());
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

        public LinearIntegerExpression length()
        {
            switch (this.expression_type)
            {
                case SymbolicStringType.Symbol:
                    return LinearIntegerExpression.Constant(1);
                case SymbolicStringType.Concat:
                    return LinearIntegerExpression.Plus(this.sub_strings.Select(x => x.length()));
                case SymbolicStringType.Repeat:
                    var sub = this.root.length();
                    Contract.Assert(sub.isConstant());
                    return LinearIntegerExpression.Times(sub.constant, this.repeat);
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

        public void flatten()
        {
            // Contract.Requires(this.StarHeight() <= 1);
            // Contract.Ensures(this.isFlat());
            switch (this.expression_type)
            {
                case SymbolicStringType.Symbol:
                    break;
                case SymbolicStringType.Repeat:
                    this.root.flatten();
                    break;
                case SymbolicStringType.Concat:
                    this.sub_strings.ForEach(x => x.flatten());
                    var new_substrings = new List<SymbolicString>();
                    foreach (var sub in sub_strings)
                    {
                        switch (sub.expression_type)
                        {
                            case SymbolicStringType.Symbol:
                                new_substrings.Add(sub);
                                break;
                            case SymbolicStringType.Repeat:
                                new_substrings.Add(sub);
                                break;
                            case SymbolicStringType.Concat:
                                foreach (var subsub in sub.sub_strings)
                                    new_substrings.Add(subsub);
                                break;
                            default:
                                throw new ArgumentOutOfRangeException();
                        }
                    }
                    this.sub_strings = new_substrings;
                    if (this.sub_strings.Count == 1)
                        this.Copy(this.sub_strings.First());
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

        #region Splitting
        /// All the methods in this region work only only flat symbolic strings, i.e.,
        /// use flatten before calling

        public List<LinearIntegerExpression> repeats()
        {
            var repeatLengths = new List<LinearIntegerExpression>();
            if (this.expression_type == SymbolicStringType.Concat)
            {
                foreach (var sub in this.sub_strings)
                    if (sub.expression_type == SymbolicStringType.Repeat)
                        repeatLengths.Add(sub.repeat);
            }
            if (this.expression_type == SymbolicStringType.Repeat)
                repeatLengths.Add(this.repeat);
            return repeatLengths;
        }

        private Tuple<int, int, SymbolicString> makeSegment(Dictionary<VariableType, int> model, ref int start)
        {
            int len = this.length().Eval(model);
            int oldStart = start;
            start += len;
            return new Tuple<int, int, SymbolicString>(oldStart, start, this);
        }

        private List<Tuple<int, int, SymbolicString>> getSegments(Dictionary<VariableType, int> model, ref int start)
        {
            var ret = new List<Tuple<int, int, SymbolicString>>();
            switch (this.expression_type)
            {
                case SymbolicStringType.Symbol:
                case SymbolicStringType.Repeat:
                    ret.Add(this.makeSegment(model, ref start));
                    break;
                case SymbolicStringType.Concat:
                    foreach (var sub in this.sub_strings)
                        ret.Add(sub.makeSegment(model, ref start));
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
            return ret;
        }

        // Generates XML for the
        public XElement SplitDisplayXML(
            VariableType pumpingLength,
            BooleanExpression additionalConstraints)
        {
            Contract.Assert(additionalConstraints.GetVariables().Count() <= 1);
            if (additionalConstraints.GetVariables().Count == 1)
                Contract.Assert(additionalConstraints.GetVariables().First().Equals(pumpingLength));
            var pumpingLengthVariable = LinearIntegerExpression.SingleTerm(1, pumpingLength);

            var repeatLengths = repeats();

            // For great and inexplicable reasons. Trust me, it looks better this way.
            var displayConstraints = LogicalExpression.And(repeatLengths.Select(x =>
                ComparisonExpression.GreaterThanOrEqual(x, LinearIntegerExpression.Constant(5))
            ));

            XElement symbstrings = new XElement("symbstrings");

            foreach (var split in this.ValidSplits(pumpingLengthVariable, additionalConstraints))
            {
                var splitRepeatLengths = split.start.repeats();
                splitRepeatLengths.AddRange(split.mid.repeats());
                splitRepeatLengths.AddRange(split.end.repeats());

                // Get models that don't look terrible
                var splitDisplayConstraints = LogicalExpression.And(splitRepeatLengths.Select(x =>
                    ComparisonExpression.GreaterThanOrEqual(x, LinearIntegerExpression.Constant(1))
                    ));
                var constraint = LogicalExpression.And(displayConstraints, split.constraints, splitDisplayConstraints);

                if (!constraint.isSatisfiable())
                    continue;
                var splitModel = constraint.getModel();

                var symbstr = new XElement("symbstr");
                var strings = new XElement("strings");
                var splits = new XElement("splits");
                var constrs = new XElement("constraints");

                Func<string, Tuple<int, int, SymbolicString>, XElement> handleSegment = (parentTagName, segment) => {
                    var parent = new XElement(parentTagName);
                    var from = new XElement("from"); from.Value = segment.Item1.ToString();
                    var to = new XElement("to"); to.Value = segment.Item2.ToString();
                    var label = new XElement("label"); label.Add(segment.Item3.ToDisplayXML());
                    parent.Add(from);
                    parent.Add(to);
                    parent.Add(label);
                    return parent;
                };

                int strIndex = 0;
                foreach (var segment in getSegments(splitModel, ref strIndex))
                    strings.Add(handleSegment("string", segment));

                int splitIndex = 0;
                foreach (var segment in new[] { split.start, split.mid, split.end })
                    splits.Add(handleSegment("split", segment.makeSegment(splitModel, ref splitIndex)));

                var constr = new XElement("constraint");
                constr.Add(split.constraints.ToDisplayXML());
                constrs.Add(constr);

                symbstr.Add(strings);
                symbstr.Add(splits);
                symbstr.Add(constrs);
                symbstrings.Add(symbstr);
            }

            return symbstrings;
        }

        private XElement ToDisplayXML()
        {
            var root = new XElement("text");
            switch (this.expression_type)
            {
                case SymbolicStringType.Symbol:
                    root.Add(new XElement("tspan", this.ToString()));
                    break;
                case SymbolicStringType.Repeat:
                    if (this.root.wordLength() > 1)
                        root.Add(new XElement("tspan", "("));
                    root.Add(new XElement("tspan", this.root.ToString()));
                    if (this.root.wordLength() > 1)
                        root.Add(new XElement("tspan", ")"));

                    var tspan2 = new XElement("tspan");
                    tspan2.SetAttributeValue("dominant-baseline", "hanging");
                    tspan2.SetAttributeValue("font-size", "50%");
                    XElement exp = this.repeat.ToDisplayXML();
                    foreach (var child in exp.Elements())
                    {
                        tspan2.Add(child);
                    }
                    root.Add(tspan2);
                    break;
                case SymbolicStringType.Concat:
                    foreach (var sub in this.sub_strings.Select(x => x.ToDisplayXML()))
                    {
                        foreach (var child in sub.Elements())
                            root.Add(child);
                    }
                    break;
                default:
                    throw new ArgumentException();
            }
            return root;
        }

        // Generates splits (x, y, z) such that |y| > 0 and |xy| < p
        public IEnumerable<Split> ValidSplits(
            LinearIntegerExpression pumpingLengthVariable,
            BooleanExpression additionalConstraints)
        {
            foreach (var split in this.Splits())
            {
                if (split.mid.isEpsilon())
                    continue;

                var cond1 = ComparisonExpression.GreaterThan(split.mid.length(), LinearIntegerExpression.Constant(0));
                var cond2 = ComparisonExpression.LessThan(split.start.length() + split.mid.length(), pumpingLengthVariable);
                var condition = LogicalExpression.And(additionalConstraints, cond1, cond2);

                if (condition.isMaybeSatisfiable())
                {
                    split.AddConstraint(condition);
                    yield return split;
                }
            }
        }

        // Generates splits where all three parts may be empty
        public IEnumerable<Split> Splits()
        {
            // Contract.Requires<ArgumentException>(this.isFlat());
            switch (this.expression_type)
            {
                case SymbolicStringType.Symbol:
                    yield return Split.MakeSplit(this, SymbolicString.Epsilon(), SymbolicString.Epsilon(), LogicalExpression.True());
                    yield return Split.MakeSplit(SymbolicString.Epsilon(), this, SymbolicString.Epsilon(), LogicalExpression.True());
                    yield return Split.MakeSplit(SymbolicString.Epsilon(), SymbolicString.Epsilon(), this, LogicalExpression.True());
                    break;
                case SymbolicStringType.Repeat:
                    var v1 = LinearIntegerExpression.FreshVariable();
                    var v2 = LinearIntegerExpression.FreshVariable();
                    var v3 = LinearIntegerExpression.FreshVariable();
                    var sanityConstraint = LogicalExpression.And(
                        ComparisonExpression.GreaterThanOrEqual(v1, 0),
                        ComparisonExpression.GreaterThanOrEqual(v2, 0),
                        ComparisonExpression.GreaterThanOrEqual(v3, 0)
                        );
                    // Suppose the word w = a_0 a_1 \ldots a_{n-1}
                    // All splits are of the form
                    //    BEG: (a_0 \ldots a_{n-1})^i (a_0 \ldots a_p)                              = w^i . w_1
                    //    MID: (a_{p+1} \ldots a_{n-1} a_0 \ldots a_p)^j (a_{p+1} \ldots a_q)       = (w_2 w_1)^j  w_3
                    //    END: (a_{q+1} \ldots a_{n-1}) (a_0 \ldots a_{n-1})^k                          = w_4 w^k
                    var w = this.root.wordSymbols();
                    var ww = w.Concat(w);
                    int n = w.Count();
                    for (int w1len = 0; w1len < n; w1len++)
                    {
                        var w_1 = w.Take(w1len);
                        var w_2 = w.Skip(w1len);
                        var beg = SymbolicString.Concat(
                                        SymbolicString.Repeat(this.root, v1),
                                        SymbolicString.Concat(w_1));
                        var mid_root = SymbolicString.Concat(
                                        SymbolicString.Concat(w_2),
                                        SymbolicString.Concat(w_1));
                        var mid_beg = SymbolicString.Repeat(mid_root, v2);
                        for (int w3len = 0; w3len < n; w3len++)
                        {
                            var w_3 = ww.Skip(w1len).Take(w3len);
                            var mid = SymbolicString.Concat(mid_beg, SymbolicString.Concat(w_3.ToList()));

                            IEnumerable<SymbolicString> w_4;
                            if (w1len + w3len == 0)
                                w_4 = new List<SymbolicString>();
                            else if (w1len + w3len <= n)
                                w_4 = w.Skip(w1len).Skip(w3len);
                            else
                                w_4 = ww.Skip(w1len).Skip(w3len);
                            var end = SymbolicString.Concat(
                                SymbolicString.Concat(w_4.ToList()),
                                SymbolicString.Repeat(this.root, v3)
                                );

                            var consumed = (w_1.Count() + w_3.Count() + w_4.Count()) / w.Count();
                            yield return Split.MakeSplit(
                                beg,
                                mid,
                                end,
                                LogicalExpression.And(
                                    ComparisonExpression.Equal(v1 + v2 + v3 + consumed, this.repeat),
                                    sanityConstraint
                                )
                            );
                        }
                    }
                    break;
                case SymbolicStringType.Concat:
                    foreach (var beg_midend in this.TwoSplits())
                    {
                        foreach (var mid_end in beg_midend.end.TwoSplits())
                        {
                            yield return Split.MakeSplit(
                                beg_midend.start,
                                mid_end.start,
                                mid_end.end,
                                LogicalExpression.And(beg_midend.constraints, mid_end.constraints));
                        }
                    }
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

        // Generate TwoSplit's where either one may be empty
        // Generates the splits in order, i.e., by length of the prefix
        // So, for s being symbol and concat, first one will always be (\epsilon, s) and last one always (s, \epsilon)
        // So, for s being repeat (abc)^n, first will be ((abc)^i,(abc)^j) and last one always ((abc)^i ab, c(abc)^j)
        // Requires a flat symbolic string
        public IEnumerable<TwoSplit> TwoSplits()
        {
            SymbolicString prefix, suffix;
            // Contract.Requires(this.isFlat());

            switch (this.expression_type)
            {
                case SymbolicStringType.Symbol:
                    yield return TwoSplit.MakeSplit(SymbolicString.Epsilon(), this, LogicalExpression.True());
                    yield return TwoSplit.MakeSplit(this, SymbolicString.Epsilon(), LogicalExpression.True());
                    break;
                case SymbolicStringType.Concat:
                    yield return TwoSplit.MakeSplit(SymbolicString.Epsilon(), this, LogicalExpression.True());
                    for (int i = 0; i < this.sub_strings.Count; i++)
                    {
                        prefix = SymbolicString.Concat(this.sub_strings.Take(i).ToList());
                        suffix = SymbolicString.Concat(this.sub_strings.Skip(i + 1).ToList());
                        foreach (var split in this.sub_strings[i].TwoSplits())
                        {
                            if (!split.start.isEpsilon())
                                yield return split.extend(prefix, suffix);
                        }
                    }
                    break;

                case SymbolicStringType.Repeat:
                    var v1 = LinearIntegerExpression.FreshVariable();
                    var v2 = LinearIntegerExpression.FreshVariable();
                    var sanityConstraint = LogicalExpression.And(
                        ComparisonExpression.GreaterThanOrEqual(v1, 0),
                        ComparisonExpression.GreaterThanOrEqual(v2, 0)
                        );
                    prefix = SymbolicString.Repeat(this.root, v1);
                    suffix = SymbolicString.Repeat(this.root, v2);
                    yield return TwoSplit.MakeSplit(
                        prefix,
                        suffix,
                        LogicalExpression.And(sanityConstraint, ComparisonExpression.Equal(v1 + v2, this.repeat))
                        );
                    if (this.root.expression_type != SymbolicStringType.Concat)
                        break;
                    for (int i = 1; i < this.root.sub_strings.Count; i++)
                    {
                        var split = TwoSplit.MakeSplit(
                            SymbolicString.Concat(this.root.sub_strings.Take(i)),
                            SymbolicString.Concat(this.root.sub_strings.Skip(i)),
                            LogicalExpression.And(
                                ComparisonExpression.Equal(v1 + v2 + 1, this.repeat),
                                sanityConstraint
                            )
                        );
                        yield return split.extend(prefix, suffix);
                    }
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

        }

        #endregion

        public override String ToString()
        {
            switch (expression_type)
            {
                case SymbolicStringType.Concat:
                    return String.Join(" ", sub_strings.Select(x => x.ToString()));
                case SymbolicStringType.Repeat:
                    if (root.expression_type == SymbolicStringType.Symbol)
                        return root.ToString()+ "^(" + repeat.ToString() + ")";
                    else
                        return "(" + root.ToString() + ")^(" + repeat.ToString() + ")";
                case SymbolicStringType.Symbol:
                    return atomic_symbol;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

        public HashSet<VariableType> GetIntegerVariables()
        {
            HashSet<VariableType> ret;
            switch (expression_type)
            {
                case SymbolicStringType.Repeat:
                    ret = root.GetIntegerVariables();
                    foreach (VariableType v in repeat.GetVariables())
                        ret.Add(v);
                    break;
                case SymbolicStringType.Concat:
                    ret = new HashSet<VariableType>();
                    foreach (var sub in sub_strings)
                        foreach (VariableType v in sub.GetIntegerVariables())
                            ret.Add(v);
                    break;
                case SymbolicStringType.Symbol:
                    ret = new HashSet<VariableType>();
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
            return ret;
        }

        #region Constructors
        // Constructors
        private SymbolicString(String atomic_symbol)
        {
            this.expression_type = SymbolicStringType.Symbol;
            this.atomic_symbol = atomic_symbol;
        }
        private SymbolicString(List<SymbolicString> sub_strings)
        {
            if (sub_strings.Count == 1)
            {
                this.Copy(sub_strings.First());
            }
            else
            {
                this.expression_type = SymbolicStringType.Concat;
                this.sub_strings = sub_strings;
            }
        }
        private SymbolicString(SymbolicString root, LinearIntegerExpression repeat)
        {
            this.expression_type = SymbolicStringType.Repeat;
            this.root = root;
            this.repeat = repeat;
        }
        private void Copy(SymbolicString that)
        {
            this.expression_type = that.expression_type;
            this.atomic_symbol = that.atomic_symbol;
            this.root = that.root;
            this.repeat = that.repeat;
            this.sub_strings = that.sub_strings;
        }
        #endregion

        #region Factory Methods
        // Factory methods
        public static SymbolicString Symbol(String atomic_symbol)
        {
            return new SymbolicString(atomic_symbol);
        }
        public static SymbolicString Concat(params SymbolicString[] sub_strings)
        {
            return Concat(sub_strings.ToList());
        }
        public static SymbolicString Concat(IEnumerable<SymbolicString> sub_strings)
        {
            var ans = new SymbolicString(sub_strings.ToList());
            ans.flatten();
            return ans;
        }
        public static SymbolicString Epsilon()
        {
            return new SymbolicString(new List<SymbolicString>());
        }
        public static SymbolicString Repeat(SymbolicString root, LinearIntegerExpression repeat)
        {
            return new SymbolicString(root, repeat);
        }

        public static SymbolicString FromTextDescription(List<String> alphabet, string symbolicStringText)
        {
            var symbolPattern = new Regex(@"^[a-zA-Z0-9]$");
            var illegalSymbols = alphabet.FindAll(s => !symbolPattern.IsMatch(s));
            if (illegalSymbols.Count > 0)
            {
                var message = string.Format(
                    "Found illegal symbols {0} in alphabet. Symbols should match [a-zA-Z0-9]",
                    string.Join(", ", illegalSymbols)
                );
                throw new PumpingLemmaException(message);
            }

            // Parse the language
            var ss = PumpingLemma.Parser.parseSymbolicString(symbolicStringText, alphabet);
            if (ss == null)
                throw new PumpingLemmaException("Unable to parse string");
            return ss;
        }

        #endregion

        public SymbolicString reverse()
        {
            switch (this.expression_type)
            {
                case SymbolicStringType.Symbol: return this;
                case SymbolicStringType.Repeat: return Repeat(this.root.reverse(), this.repeat);
                case SymbolicStringType.Concat:
                    var reversed = new List<SymbolicString>();
                    foreach (var sub in this.sub_strings)
                        reversed.Add(sub.reverse());
                    reversed.Reverse();
                    return Concat(reversed);
                default:
                    throw new ArgumentException();
            }
        }
    }
}


text:
require File.expand_path('../../../../spec_helper', __FILE__)
require 'net/ftp'
require File.expand_path('../fixtures/server', __FILE__)

describe "Net::FTP#voidcmd" do
  before(:each) do
    @server = NetFTPSpecs::DummyFTP.new
    @server.serve_once

    @ftp = Net::FTP.new
    @ftp.connect("127.0.0.1", 9876)
  end

  after(:each) do
    @ftp.quit rescue nil
    @ftp.close
    @server.stop
  end

  it "sends the passed command to the server" do
    @server.should_receive(:help).and_respond("2xx Does not raise.")
    lambda { @ftp.voidcmd("HELP") }.should_not raise_error
  end

  it "returns nil" do
    @server.should_receive(:help).and_respond("2xx Does not raise.")
    @ftp.voidcmd("HELP").should be_nil
  end

  it "raises a Net::FTPReplyError when the response code is 1xx" do
    @server.should_receive(:help).and_respond("1xx Does raise a Net::FTPReplyError.")
    lambda { @ftp.voidcmd("HELP")  }.should raise_error(Net::FTPReplyError)
  end

  it "raises a Net::FTPReplyError when the response code is 3xx" do
    @server.should_receive(:help).and_respond("3xx Does raise a Net::FTPReplyError.")
    lambda { @ftp.voidcmd("HELP") }.should raise_error(Net::FTPReplyError)
  end

  it "raises a Net::FTPTempError when the response code is 4xx" do
    @server.should_receive(:help).and_respond("4xx Does raise a Net::FTPTempError.")
    lambda { @ftp.voidcmd("HELP") }.should raise_error(Net::FTPTempError)
  end

  it "raises a Net::FTPPermError when the response code is 5xx" do
    @server.should_receive(:help).and_respond("5xx Does raise a Net::FTPPermError.")
    lambda { @ftp.voidcmd("HELP") }.should raise_error(Net::FTPPermError)
  end

  it "raises a Net::FTPProtoError when the response code is not valid" do
    @server.should_receive(:help).and_respond("999 Does raise a Net::FTPProtoError.")
    lambda { @ftp.voidcmd("HELP") }.should raise_error(Net::FTPProtoError)
  end
end


text:
from typing import Any

from azure.core.configuration import Configuration
from azure.core.pipeline import policies

from .._version import VERSION

class AzureTableConfiguration(Configuration):
    """Configuration for AzureTable.

    Note that all parameters used to create this instance are saved as instance
    attributes.

    :param url: The URL of the service account or table that is the targe of the desired operation.
    :type url: str
    """

    def __init__(
        self,
        url: str,
        **kwargs: Any
    ) -> None:
        if url is None:
            raise ValueError("Parameter 'url' must not be None.")
        super(AzureTableConfiguration, self).__init__(**kwargs)

        self.url = url
        self.version = "2019-02-02"
        kwargs.setdefault('sdk_moniker', 'data-tables/{}'.format(VERSION))
        self._configure(**kwargs)

    def _configure(
        self,
        **kwargs: Any
    ) -> None:
        self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs)
        self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs)
        self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs)
        self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs)
        self.http_logging_policy = kwargs.get('http_logging_policy') or policies.HttpLoggingPolicy(**kwargs)
        self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs)
        self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs)
        self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs)
        self.authentication_policy = kwargs.get('authentication_policy')


text:
#ifndef __CompositorScriptScompiler2_H__
#define __CompositorScriptScompiler2_H__

#include "OgreScriptCompiler.h"
#include "OgreCompositionTechnique.h"
#include "OgreCompositionTargetPass.h"
#include "OgreCompositionPass.h"

namespace Ogre
{
	class CompositorScriptCompiler2;

	/** This is the listener specific to the compositor compiler. It allows for
		notifications and overriding of compiler functions.
	*/
	class _OgreExport CompositorScriptCompilerListener : public ScriptCompilerListener
	{
	public:
		CompositorScriptCompilerListener();

		/// Override this to customly allocate compositors
		Compositor *getCompositor(const String &name, const String &group);
		/// Override this to do custom processing
		virtual bool processNode(ScriptNodeList::iterator &iter, ScriptNodeList::iterator &end, CompositorScriptCompiler2*);
	};

	/** This class uses the new ScriptCompiler to compile compositor scripts.
		It uses a word id map, and allows a listener to override resource acquisitions
		and allocations.
	*/
	class _OgreExport CompositorScriptCompiler2 : public ScriptCompiler
	{
	public:
		enum
		{
			ID_COMPOSITOR,
			ID_TECHNIQUE,
			ID_TARGET,
			ID_TARGET_OUTPUT,
			ID_PASS,

			ID_TEXTURE,
			ID_INPUT,
				ID_NONE,
				ID_PREVIOUS,
				ID_TARGET_WIDTH,
				ID_TARGET_HEIGHT,
			ID_ONLY_INITIAL,
			ID_VISIBILITY_MASK,
			ID_LOD_BIAS,
			ID_MATERIAL_SCHEME,

			ID_CLEAR,
			ID_STENCIL,
			ID_RENDER_SCENE,
			ID_RENDER_QUAD,
			ID_MATERIAL,
			ID_IDENTIFIER,
			ID_FIRST_RENDER_QUEUE,
			ID_LAST_RENDER_QUEUE,

			ID_BUFFERS,
				ID_COLOUR,
				ID_DEPTH,
			ID_COLOUR_VALUE,
			ID_DEPTH_VALUE,
			ID_STENCIL_VALUE,

			ID_CHECK,
			ID_COMP_FUNC,
				ID_ALWAYS_FAIL,
				ID_ALWAYS_PASS,
				ID_LESS_EQUAL,
				ID_LESS,
				ID_EQUAL,
				ID_NOT_EQUAL,
				ID_GREATER_EQUAL,
				ID_GREATER,
			ID_REF_VALUE,
			ID_MASK,
			ID_FAIL_OP,
				ID_KEEP,
				ID_ZERO,
				ID_REPLACE,
				ID_INCREMENT,
				ID_DECREMENT,
				ID_INCREMENT_WRAP,
				ID_DECREMENT_WRAP,
				ID_INVERT,
			ID_DEPTH_FAIL_OP,
			ID_PASS_OP,
			ID_TWO_SIDED
		};
	public:
		CompositorScriptCompiler2();

		/// Sets the listener used for overriding compiler functions
		void setListener(CompositorScriptCompilerListener *listener);
	protected:
		/// This is the implementation for compiling the compositor scripts
		bool compileImpl(ScriptNodeListPtr nodes);
		/// This allows for overriding processing of script nodes
		bool processNode(ScriptNodeList::iterator &i, ScriptNodeList::iterator &end);
		/// This is the override for loading imports
		ScriptNodeListPtr loadImportPath(const String &name);
		/// Allows a listener to override the word id map before parsing
		void preParse();
		/// Allows a listener to override error handling in the compiler
		bool errorRaised(const ScriptCompilerErrorPtr &error);
	private: // Custom node handling
		void compileCompositor(const ScriptNodePtr &node);
		void compileTechnique(const ScriptNodePtr &node);
		void compileTarget(const ScriptNodePtr &node, CompositionTechnique *technique);
		void compileTargetOutput(const ScriptNodePtr &node, CompositionTechnique *technique);
		void compilePass(const ScriptNodePtr &node, CompositionTargetPass *target);
		void compileTargetOptions(ScriptNodeList::iterator &i, ScriptNodeList::iterator &end, CompositionTargetPass *target);
		bool getCompareFunction(const ScriptNodePtr &node, CompareFunction &func);
		bool getStencilOp(const ScriptNodePtr &node, StencilOperation &op);
		bool getColourValue(ScriptNodeList::iterator &i, ScriptNodeList::iterator &end, ColourValue &c);
	private:
		// The listener
		CompositorScriptCompilerListener *mListener;
		// This is the compositor being compiled
		Compositor *mCompositor;
	};

}

#endif


text:
@interface ReportDetailsViewController : UIViewController
@property PFObject *report;
@end


text:
use std::ffi::OsString;
use std::ptr::null_mut;
use winapi::Interface;
use winapi::BSTR;
use winapi::LPCOLESTR;
use winapi::LPSAFEARRAY;
use winapi::S_FALSE;
use winapi::{CoCreateInstance, CLSCTX_ALL};
use winapi::{IUnknown, IUnknownVtbl};
use winapi::{HRESULT, LCID, LPCWSTR, PULONGLONG};
use winapi::{LPFILETIME, ULONG};

use com::{BStr, ComPtr};

// Bindings to the Setup.Configuration stuff
pub type InstanceState = u32;

pub const eNone: InstanceState = 0;
pub const eLocal: InstanceState = 1;
pub const eRegistered: InstanceState = 2;
pub const eNoRebootRequired: InstanceState = 4;
pub const eComplete: InstanceState = -1i32 as u32;

RIDL! {#[uuid(0xb41463c3, 0x8866, 0x43b5, 0xbc, 0x33, 0x2b, 0x06, 0x76, 0xf7, 0xf4, 0x2e)]
interface ISetupInstance(ISetupInstanceVtbl): IUnknown(IUnknownVtbl) {
    fn GetInstanceId(
        pbstrInstanceId: *mut BSTR,
    ) -> HRESULT,
    fn GetInstallDate(
        pInstallDate: LPFILETIME,
    ) -> HRESULT,
    fn GetInstallationName(
        pbstrInstallationName: *mut BSTR,
    ) -> HRESULT,
    fn GetInstallationPath(
        pbstrInstallationPath: *mut BSTR,
    ) -> HRESULT,
    fn GetInstallationVersion(
        pbstrInstallationVersion: *mut BSTR,
    ) -> HRESULT,
    fn GetDisplayName(
        lcid: LCID,
        pbstrDisplayName: *mut BSTR,
    ) -> HRESULT,
    fn GetDescription(
        lcid: LCID,
        pbstrDescription: *mut BSTR,
    ) -> HRESULT,
    fn ResolvePath(
        pwszRelativePath: LPCOLESTR,
        pbstrAbsolutePath: *mut BSTR,
    ) -> HRESULT,
}}

RIDL! {#[uuid(0x89143c9a, 0x05af, 0x49b0, 0xb7, 0x17, 0x72, 0xe2, 0x18, 0xa2, 0x18, 0x5c)]
interface ISetupInstance2(ISetupInstance2Vtbl): ISetupInstance(ISetupInstanceVtbl) {
    fn GetState(
        pState: *mut InstanceState,
    ) -> HRESULT,
    fn GetPackages(
        ppsaPackages: *mut LPSAFEARRAY,
    ) -> HRESULT,
    fn GetProduct(
        ppPackage: *mut *mut ISetupPackageReference,
    ) -> HRESULT,
    fn GetProductPath(
        pbstrProductPath: *mut BSTR,
    ) -> HRESULT,
}}

RIDL! {#[uuid(0x6380bcff, 0x41d3, 0x4b2e, 0x8b, 0x2e, 0xbf, 0x8a, 0x68, 0x10, 0xc8, 0x48)]
interface IEnumSetupInstances(IEnumSetupInstancesVtbl): IUnknown(IUnknownVtbl) {
    fn Next(
        celt: ULONG,
        rgelt: *mut *mut ISetupInstance,
        pceltFetched: *mut ULONG,
    ) -> HRESULT,
    fn Skip(
        celt: ULONG,
    ) -> HRESULT,
    fn Reset() -> HRESULT,
    fn Clone(
        ppenum: *mut *mut IEnumSetupInstances,
    ) -> HRESULT,
}}

RIDL! {#[uuid(0x42843719, 0xdb4c, 0x46c2, 0x8e, 0x7c, 0x64, 0xf1, 0x81, 0x6e, 0xfd, 0x5b)]
interface ISetupConfiguration(ISetupConfigurationVtbl): IUnknown(IUnknownVtbl) {
    fn EnumInstances(
        ppEnumInstances: *mut *mut IEnumSetupInstances,
    ) -> HRESULT,
    fn GetInstanceForCurrentProcess(
        ppInstance: *mut *mut ISetupInstance,
    ) -> HRESULT,
    fn GetInstanceForPath(
        wzPath: LPCWSTR,
        ppInstance: *mut *mut ISetupInstance,
    ) -> HRESULT,
}}

RIDL! {#[uuid(0x26aab78c, 0x4a60, 0x49d6, 0xaf, 0x3b, 0x3c, 0x35, 0xbc, 0x93, 0x36, 0x5d)]
interface ISetupConfiguration2(ISetupConfiguration2Vtbl):
    ISetupConfiguration(ISetupConfigurationVtbl) {
    fn EnumAllInstances(
        ppEnumInstances: *mut *mut IEnumSetupInstances,
    ) -> HRESULT,
}}

RIDL! {#[uuid(0xda8d8a16, 0xb2b6, 0x4487, 0xa2, 0xf1, 0x59, 0x4c, 0xcc, 0xcd, 0x6b, 0xf5)]
interface ISetupPackageReference(ISetupPackageReferenceVtbl): IUnknown(IUnknownVtbl) {
    fn GetId(
        pbstrId: *mut BSTR,
    ) -> HRESULT,
    fn GetVersion(
        pbstrVersion: *mut BSTR,
    ) -> HRESULT,
    fn GetChip(
        pbstrChip: *mut BSTR,
    ) -> HRESULT,
    fn GetLanguage(
        pbstrLanguage: *mut BSTR,
    ) -> HRESULT,
    fn GetBranch(
        pbstrBranch: *mut BSTR,
    ) -> HRESULT,
    fn GetType(
        pbstrType: *mut BSTR,
    ) -> HRESULT,
    fn GetUniqueId(
        pbstrUniqueId: *mut BSTR,
    ) -> HRESULT,
}}

RIDL! {#[uuid(0x42b21b78, 0x6192, 0x463e, 0x87, 0xbf, 0xd5, 0x77, 0x83, 0x8f, 0x1d, 0x5c)]
interface ISetupHelper(ISetupHelperVtbl): IUnknown(IUnknownVtbl) {
    fn ParseVersion(
        pwszVersion: LPCOLESTR,
        pullVersion: PULONGLONG,
    ) -> HRESULT,
    fn ParseVersionRange(
        pwszVersionRange: LPCOLESTR,
        pullMinVersion: PULONGLONG,
        pullMaxVersion: PULONGLONG,
    ) -> HRESULT,
}}

DEFINE_GUID! {CLSID_SetupConfiguration,
0x177f0c4a, 0x1cd3, 0x4de7, 0xa3, 0x2c, 0x71, 0xdb, 0xbb, 0x9f, 0xa3, 0x6d}

// Safe wrapper around the COM interfaces
pub struct SetupConfiguration(ComPtr<ISetupConfiguration>);

impl SetupConfiguration {
    pub fn new() -> Result<SetupConfiguration, i32> {
        let mut obj = null_mut();
        let err = unsafe {
            CoCreateInstance(
                &CLSID_SetupConfiguration,
                null_mut(),
                CLSCTX_ALL,
                &ISetupConfiguration::uuidof(),
                &mut obj,
            )
        };
        if err < 0 {
            return Err(err);
        }
        let obj = unsafe { ComPtr::from_raw(obj as *mut ISetupConfiguration) };
        Ok(SetupConfiguration(obj))
    }
    pub fn get_instance_for_current_process(&self) -> Result<SetupInstance, i32> {
        let mut obj = null_mut();
        let err = unsafe { self.0.GetInstanceForCurrentProcess(&mut obj) };
        if err < 0 {
            return Err(err);
        }
        Ok(unsafe { SetupInstance::from_raw(obj) })
    }
    pub fn enum_instances(&self) -> Result<EnumSetupInstances, i32> {
        let mut obj = null_mut();
        let err = unsafe { self.0.EnumInstances(&mut obj) };
        if err < 0 {
            return Err(err);
        }
        Ok(unsafe { EnumSetupInstances::from_raw(obj) })
    }
    pub fn enum_all_instances(&self) -> Result<EnumSetupInstances, i32> {
        let mut obj = null_mut();
        let this = try!(self.0.cast::<ISetupConfiguration2>());
        let err = unsafe { this.EnumAllInstances(&mut obj) };
        if err < 0 {
            return Err(err);
        }
        Ok(unsafe { EnumSetupInstances::from_raw(obj) })
    }
}

pub struct SetupInstance(ComPtr<ISetupInstance>);

impl SetupInstance {
    pub unsafe fn from_raw(obj: *mut ISetupInstance) -> SetupInstance {
        SetupInstance(ComPtr::from_raw(obj))
    }
    pub fn instance_id(&self) -> Result<OsString, i32> {
        let mut s = null_mut();
        let err = unsafe { self.0.GetInstanceId(&mut s) };
        let bstr = unsafe { BStr::from_raw(s) };
        if err < 0 {
            return Err(err);
        }
        Ok(bstr.to_osstring())
    }
    pub fn installation_name(&self) -> Result<OsString, i32> {
        let mut s = null_mut();
        let err = unsafe { self.0.GetInstallationName(&mut s) };
        let bstr = unsafe { BStr::from_raw(s) };
        if err < 0 {
            return Err(err);
        }
        Ok(bstr.to_osstring())
    }
    pub fn installation_path(&self) -> Result<OsString, i32> {
        let mut s = null_mut();
        let err = unsafe { self.0.GetInstallationPath(&mut s) };
        let bstr = unsafe { BStr::from_raw(s) };
        if err < 0 {
            return Err(err);
        }
        Ok(bstr.to_osstring())
    }
    pub fn installation_version(&self) -> Result<OsString, i32> {
        let mut s = null_mut();
        let err = unsafe { self.0.GetInstallationVersion(&mut s) };
        let bstr = unsafe { BStr::from_raw(s) };
        if err < 0 {
            return Err(err);
        }
        Ok(bstr.to_osstring())
    }
    pub fn product_path(&self) -> Result<OsString, i32> {
        let mut s = null_mut();
        let this = try!(self.0.cast::<ISetupInstance2>());
        let err = unsafe { this.GetProductPath(&mut s) };
        let bstr = unsafe { BStr::from_raw(s) };
        if err < 0 {
            return Err(err);
        }
        Ok(bstr.to_osstring())
    }
}

pub struct EnumSetupInstances(ComPtr<IEnumSetupInstances>);

impl EnumSetupInstances {
    pub unsafe fn from_raw(obj: *mut IEnumSetupInstances) -> EnumSetupInstances {
        EnumSetupInstances(ComPtr::from_raw(obj))
    }
}

impl Iterator for EnumSetupInstances {
    type Item = Result<SetupInstance, i32>;
    fn next(&mut self) -> Option<Result<SetupInstance, i32>> {
        let mut obj = null_mut();
        let err = unsafe { self.0.Next(1, &mut obj, null_mut()) };
        if err < 0 {
            return Some(Err(err));
        }
        if err == S_FALSE {
            return None;
        }
        Some(Ok(unsafe { SetupInstance::from_raw(obj) }))
    }
}


text:
package sg.yikjiun.scf4j.map;

import java.util.Map;
/**
 * @author Lee Yik Jiun
 */
public class JDKByteIntMapAdapter implements ByteIntMap {
    private final Map<Byte, Integer> map;

    public JDKByteIntMapAdapter(Map<Byte, Integer> map) {
        this.map = map;
    }

    public void clear() {
        map.clear();
    }

    public boolean containsKey(byte key) {
        return map.containsKey(key);
    }

    public boolean containsValue(int value) {
        return map.containsValue(value);
    }

    public int get(byte key) {
        return map.get(key);
    }

    public boolean isEmpty() {
        return map.isEmpty();
    }

    public int put(byte key, int value) {
        return map.put(key, value);
    }

    public int remove(byte key) {
        return map.remove(key);
    }

    public int size() {
        return map.size();
    }
}


text:
import logging

__version__ = '0.1.1'

try:
    from graphicsmagick_engine.engine import Engine  # NOQA
except ImportError:
    logging.exception('Could not import graphicsmagick_engine. Probably due to setup.py installing it.')


text:
import {KernelConfig, Less} from '@tensorflow/tfjs-core';

import {BinaryOpType} from '../binary_op_util';
import {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';
import {lessImplCPU as cpuLess} from '../kernel_utils/shared';

export const less = binaryKernelFunc(
    {opType: BinaryOpType.LESS, dtype: 'bool', cpuKernelImpl: cpuLess});

export const lessConfig: KernelConfig = {
  kernelName: Less,
  backendName: 'webgpu',
  kernelFunc: less
};


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

<TITLE>
example.chord Class Hierarchy
</TITLE>

<META NAME="date" CONTENT="2009-07-31">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For Package example.chord

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object

java.rmi.server.RemoteObject (implements java.rmi.Remote, java.io.Serializable)

java.rmi.server.RemoteServer

java.rmi.server.UnicastRemoteObject

example.chord.LaunchImpl (implements example.chord.Launch)

example.chord.NodeImpl (implements example.chord.Node)

Interface Hierarchy

java.rmi.Remote

example.chord.Launch
example.chord.Node (also extends synapse.Synapse)

synapse.Synapse

example.chord.Node (also extends java.rmi.Remote)

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
from mparts.manager import Task
from mparts.host import HostInfo, CHECKED, UNCHECKED
from mparts.util import Progress
from support import ResultsProvider, SetCPUs, PrefetchList, FileSystem, \
    SystemMonitor

import os

__all__ = []

__all__.append("PsearchyLoad")
class PsearchyLoad(Task, ResultsProvider):
    MODE_THREAD = intern("thread")
    MODE_PROCESS = intern("process")

    ORDER_SEQ = intern("seq")
    ORDER_RR = intern("rr")

    __info__ = ["host", "psearchyPath", "filesPath", "dbPath",
                "mode", "order", "mem", "dblim", "trial", "*sysmonOut"]

    def __init__(self, host, trial, psearchyPath, filesPath, dbPath, cores,
                 mode, order, mem, dblim, setcpus, sysmon):
        assert mode in [PsearchyLoad.MODE_THREAD, PsearchyLoad.MODE_PROCESS], \
            "Invalid mode %s" % mode
        assert order in [PsearchyLoad.ORDER_SEQ, PsearchyLoad.ORDER_RR], \
            "Invalid order %s" % order

        Task.__init__(self, host = host, trial = trial)
        ResultsProvider.__init__(self, cores)
        self.host = host
        self.trial = trial
        self.psearchyPath = psearchyPath
        self.filesPath = filesPath
        self.dbPath = dbPath
        self.mode = mode
        self.order = order
        self.mem = mem
        self.dblim = dblim
        self.setcpus = setcpus
        self.sysmon = sysmon

    def wait(self, m):
        # Construct command
        cmd = [os.path.join(self.psearchyPath, "mkdb", "pedsort"),
               "-t", self.dbPath,
               "-c", str(self.cores),
               "-m", str(self.mem)]
        if self.mode == PsearchyLoad.MODE_PROCESS:
            cmd.append("-p")
        if self.dblim:
            cmd.extend(["-l", str(self.dblim)])
        # For the submission, we measured the entire time, including
        # file list loading.  This is probably a more natural
        # definition of "job", even though that part is sequential.
        cmd = self.sysmon.wrap(cmd)
        # We could instead only start measuring once we start
        # indexing.
        #cmd = self.sysmon.wrap(cmd, "Building index")

        # Run
        logPath = self.host.getLogPath(self)
        self.host.r.run(cmd, stdin = self.filesPath, stdout = logPath,
                        addEnv = {"CPUSEQ" : self.setcpus.getSeqStr()},
                        wait = CHECKED)

        # Get result
        log = self.host.r.readFile(logPath)
        self.sysmonOut = self.sysmon.parseLog(log)
        self.setResults(1, "job", "jobs", self.sysmonOut["time.real"])

__all__.append("Mkfiles")
class Mkfiles(Task):
    __info__ = ["host", "psearchyPath", "baseDir"]

    def __init__(self, host, psearchyPath, baseDir):
        Task.__init__(self, host = host)
        self.host = host
        self.psearchyPath = psearchyPath
        self.baseDir = baseDir

        self.filesPath = \
            os.path.join(self.psearchyPath, "files-%08x" % abs(hash(baseDir)))

    def start(self):
        # Do I need to construct the files list?
        test = self.host.r.run(["test", "-f", self.filesPath],
                               wait = UNCHECKED)
        if test.getCode() != 0:
            # Yes
            with Progress("Generating files list"):
                self.host.r.run([os.path.join(self.psearchyPath, "mkfiles"),
                                 self.baseDir],
                                stdout = self.filesPath + ".tmp",
                                noCheck = True)
                self.host.r.run(["mv", self.filesPath + ".tmp",
                                 self.filesPath])

class PsearchyRunner(object):
    def __str__(self):
        return "psearchy"

    @staticmethod
    def run(m, cfg):
        host = cfg.primaryHost
        m += host
        m += HostInfo(host)
        fs = FileSystem(host, cfg.fs, clean = True)
        m += fs
        psearchyPath = os.path.join(cfg.benchRoot, "psearchy")
        files = Mkfiles(host, psearchyPath, cfg.textRoot)
        m += files
        m += PrefetchList(host, files.filesPath, reuse = True)
        setcpus = SetCPUs(host = host, num = cfg.cores, hotplug = cfg.hotplug,
                          seq = cfg.order)
        m += setcpus
        sysmon = SystemMonitor(host)
        m += sysmon
        for trial in range(cfg.trials):
            m += PsearchyLoad(host, trial, psearchyPath, files.filesPath,
                              fs.path, cfg.cores, cfg.mode, cfg.order, cfg.mem,
                              cfg.dblim, setcpus, sysmon)
        # XXX
        # m += cfg.monitors
        m.run()

__all__.append("runner")
runner = PsearchyRunner()


text:
class AddPipelineInactiveToPeople < ActiveRecord::Migration
  def self.up
    add_column :people, :pipeline_inactive, :boolean
  end

  def self.down
    remove_column :people, :pipeline_inactive
  end
end


text: a web app to create polls and vote


text:
========
Usage
========

To use vmware_nsx_tempest in a project::

    import vmware_nsx_tempest


text:
const char *in_file_name = "text.in";
const char *out_file_name = "text.out";

using namespace std;

ifstream in_file;

void die(bool assertion, const char *message)
{
	if (assertion) {
		fprintf(stderr, "(%s, %d): ",__FILE__, __LINE__);
		perror(message);
		exit(EXIT_FAILURE);
	}
}

int get_medium_length()
{
	int numLetters = 0, numWords = 0;
	char ch;
	bool flag = true;

	while (in_file >> noskipws >> ch) {
		if (isalpha(ch)) {

		 	numLetters++;

		 	if (flag)
		 		numWords++;

		 	flag = false;
		 }
		else
		 	flag = true;
	}

	return numLetters/numWords;
}

int main()
{

	ofstream out_file;

	in_file.open(in_file_name, ios::in);
	die(!in_file, "Error opening file for reading");

	out_file.open(out_file_name, ios::out);
	die(!out_file, "Error opening file for writing");

	out_file << get_medium_length();

	in_file.close();
	out_file.close();

	return 0;
}


text:
#ifndef NKVG_H
#define NKVG_H

#pragma once

#include <nanovg.h>

#include "nuklear.h"

#ifdef __cplusplus
extern "C" {
#endif

struct font_registry;

struct nk_vg_context {
    struct nk_buffer commands_buffer;
    NVGcontext *nvg_context;
    struct font_registry *font_registry;
};

struct nk_vg {
    struct nk_vg_context *nkvg_ctx;
    struct nk_context *nk_ctx;
};

int nk_vg_create(struct nk_context *nk_ctx, struct nk_vg **out);
void nk_vg_destroy(struct nk_vg **nkvg);

NVGcontext *nk_vg_context(struct nk_vg *nkvg);

int nk_vg_add_font(struct nk_vg *nkvg, const char *id, const char *filename,
                   int default_height);

int nk_vg_font(struct nk_vg *nkvg, const char *id,
               struct nk_user_font *user_font);

void nk_vg_render(struct nk_vg *nkvg, struct nk_color bg, int w, int h);

#ifdef __cplusplus
}
#endif

#endif /* NKVG_H */


text:
Localight

    Localight is a mobile giftcard and loyalty program for small businesses. It used user's phones to request giftcards through text message, which would then bring them to a mobile web-app to send and receive giftcards from their friends. Localight was developed
    by Localism in downtown Long Beach, CA. However, the app was taken down as Localism went through some restructuring after I had left.

At Localism, I worked on a two-person team to create a web-app that provided a local ecommerce/gift-card platform on top of the MEAN stack. I was responsible for the
    application's styling, controller logic, user validation, deployment, and debit card charge requests.

Localism was built using
    NodeJs,
    Express,
    AngularJS, and
    Sass. As well as several third-party libraries, such as
    Stripe,
    Twilio,
    Animate.css, and
    Moment.JS.


text:
var _ = require('lodash');
var path = require('path');

function deepMerge(object, source) {
  return _.mergeWith(object, source, function(objValue, srcValue) {
    if (_.isObject(objValue) && srcValue) {
      return deepMerge(objValue, srcValue);
    }
    return objValue;
  });
}
_.deepMerge = deepMerge;

module.exports = function(app) {
  if (process.env.SERVICES_ENV) {
    app.set('env', process.env.SERVICES_ENV);
  }

  var env = app.web.services.get('env');

  console.log('Running on env:', env);

  function data(file) {
    var result = null;
    try {
      result = require(file);
    } catch (e) {
      if (e.code == 'MODULE_NOT_FOUND') {
        if (e.message.indexOf(file) < 0) {
          throw e;
        }
      } else {
        throw e;
      }
    }

    if (_.isFunction(result)) {
      result = result(app);
    }

    return result || {};
  }

  var dirs = app.get('services_include');

  function load(name) {
    var result = {};

    for (var dir of dirs) {
      _.merge(result, data(path.join(dir, name)));
      _.merge(result, data(path.join(dir, name + '.' + env)));
    }

    return result;
  }

  app.configurator = {
    load: load
  };

  return app.configurator;
};


text:
package empleados.domain;

public class Diseñador extends Empleado {

	public Diseñador() {
	}

	public Diseñador(String nombre, String puesto, int nivel) {
		this.nombre = nombre;
		this.puesto = puesto;
		this.nivel = nivel;
	}

	public void desplegarInformacion() {
		System.out.println("Nombre del Empleado: " + this.nombre);
		System.out.println("Puesto: " + this.puesto);
		System.out.println("Nivel: " + this.nivel);

	}

}


text:
from mcpi.minecraft import *
from mcpi.block import *

if __name__ == "__main__":

    # Create a connection to the Minecraft game
    mc = Minecraft.create()

    # Get the player position
    playerPosition = mc.player.getTilePos()

    # Set coordinates (position) for the block that is slightly away from the player
    # Note y is the vertical coordinate, x and z the horizontal
    blockYposn = playerPosition.y+1
    blockZposn = playerPosition.z+1

    for column in range(16):
        #increase the distance along and up that the block is placed at
        blockXposn = playerPosition.x + 1 + column
        print("Creating block with data %d at (%d, %d, %d)" % (column, blockXposn, blockYposn, blockZposn))
        # Create a block
        mc.setBlock(blockXposn, blockYposn, blockZposn, WOOL.withData(column))


text:
layout: default
---

Portfolio

You should see your shots here but...

Did you enter your Dribbble Username and Client Access Token to the _config.yml file?

  Go back to the repository page to see the instructions again.


text:
//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//// PARTICULAR PURPOSE.
////
//// Copyright (c) Microsoft Corporation. All rights reserved

(function () {
    "use strict";

    var page = WinJS.UI.Pages.define("/html/scenario1.html", {
        ready: function (element, options) {
            document.getElementById("picture-thumb-start").addEventListener("click", pickPhoto, false);
        }
    });

    function pickPhoto() {
        // Map thumbnail modes to HTML <select> options
        var modes = {
            "picturesGrid": Windows.Storage.FileProperties.ThumbnailMode.picturesView,
            "picturesList": Windows.Storage.FileProperties.ThumbnailMode.listView,
            "singlePicture": Windows.Storage.FileProperties.ThumbnailMode.singleItem,
        };
        var modeNames = {
            "picturesGrid": "ThumbnailMode.picturesView",
            "picturesList": "ThumbnailMode.listView",
            "singlePicture": "ThumbnailMode.singleItem",
        };

        // Get scenario options from HTML
        var modeSelector = document.getElementById("picture-thumb-mode");
        var modeSelected = modeSelector.options[modeSelector.selectedIndex].value,
            isFastSelected = document.getElementById("picture-thumb-fastThumbnail").checked;

        // Set API parameters
        var requestedSize = 200,
            thumbnailMode = modes[modeSelected],
            thumbnailOptions = Windows.Storage.FileProperties.ThumbnailOptions.useCurrentScale;

        if (isFastSelected) {
            thumbnailOptions |= Windows.Storage.FileProperties.ThumbnailOptions.returnOnlyIfCached;
        }

        // Clean output in case of repeat usage
        cleanOutput();

        var openpicker = new Windows.Storage.Pickers.FileOpenPicker();
        openpicker.fileTypeFilter.replaceAll([".jpg", ".png", ".bmp", ".gif", ".tif"]);
        openpicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.picturesLibrary;
        openpicker.pickSingleFileAsync().done(function (file) {
            if (file) {
                file.getThumbnailAsync(thumbnailMode, requestedSize, thumbnailOptions).done(function (thumbnail) {
                    if (thumbnail) {
                        outputResult(file, thumbnail, modeNames[modeSelected], requestedSize);
                    } else if (isFastSelected) {
                        WinJS.log && WinJS.log(SdkSample.errors.noExif, "sample", "status");
                    } else {
                        WinJS.log && WinJS.log(SdkSample.errors.noThumbnail, "sample", "status");
                    }
                }, function (error) {
                    WinJS.log && WinJS.log(SdkSample.errors.fail, "sample", "status");
                });
            } else {
                WinJS.log && WinJS.log(SdkSample.errors.cancel, "sample", "status");
            }
        });
    }

    function outputResult(item, thumbnailImage, thumbnailMode, requestedSize) {
        document.getElementById("picture-thumb-imageHolder").src = URL.createObjectURL(thumbnailImage, { oneTimeOnly: true });
        // Close the thumbnail stream once the image is loaded
        document.getElementById("picture-thumb-imageHolder").onload = function () {
            thumbnailImage.close();
        };
        document.getElementById("picture-thumb-modeName").innerText = thumbnailMode;
        document.getElementById("picture-thumb-fileName").innerText = "File used: " + item.name;
        document.getElementById("picture-thumb-requestedSize").innerText = "Requested size: " + requestedSize;
        document.getElementById("picture-thumb-returnedSize").innerText = "Returned size: " + thumbnailImage.originalWidth + "x" + thumbnailImage.originalHeight;
    }

    function cleanOutput() {
        WinJS.log && WinJS.log("", "sample", "status");
        document.getElementById("picture-thumb-imageHolder").src = "";
        document.getElementById("picture-thumb-modeName").innerText = "";
        document.getElementById("picture-thumb-fileName").innerText = "";
        document.getElementById("picture-thumb-requestedSize").innerText = "";
        document.getElementById("picture-thumb-returnedSize").innerText = "";
    }
})();


text:
package com.tresorit.zerokit.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TenantIdResolver {
    private static Pattern HostedTenantUrlPattern = Pattern.compile("\\Ahttps?://[^/,^?,^#]*/tenant-([a-z][a-z0-9]{7,9})/?\\z");
    private static Pattern ProductionTenantUrlPattern = Pattern.compile("\\Ahttps?://([a-z][a-z0-9]{7,9})\\.[^/,^?,^#]*/?\\z");
    private static Pattern TenantIdRegex = Pattern.compile("\\A[a-z][a-z0-9]{7,9}\\z");

    public static String getTenantId(String baseUrl){
        Matcher matcher = ProductionTenantUrlPattern.matcher(baseUrl);
        String tenantId = null;
        if (matcher.matches()){
            tenantId = matcher.group(1);
        }
        else{
            matcher = HostedTenantUrlPattern.matcher(baseUrl);
            if (matcher.matches()){
                tenantId = matcher.group(1);
            }
        }
        if (tenantId == null || !TenantIdRegex.matcher(tenantId).matches())
            throw new IllegalArgumentException("The given or parsed tenant ID is invalid.");
        return tenantId;
    }
}


text:
class CreateMailRecipients < ActiveRecord::Migration
  def self.up
    create_table :mail_recipients do |t|
      t.integer     :organization_id
      t.integer     :mail_summary_id
      t.integer     :recipient_id
      t.timestamps
    end
  end

  def self.down
    drop_table :mail_recipients
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SF.Sys
{
	public static class DateTimeUtils
	{
		public static DateTime JSDateOffset { get; } = new DateTime(1970, 1, 1,0,0,0,DateTimeKind.Local).AddHours(8);
		/// <summary>
		/// 转换成JS格式时间,当前时间必须是UTC格式
		/// </summary>
		/// <param name="time"></param>
		/// <returns></returns>
		public static long ToJsTime(this DateTime time)
		{
			return (long)time.Subtract(JSDateOffset).TotalMilliseconds;
		}
        public static uint ToUnixTime(this DateTime time)
        {
            return (uint)(time.ToJsTime() / 1000);
        }
		public static DateTime FromJsTime(long time)
		{
			return JSDateOffset.AddMilliseconds(time);
		}
		public static DateTime FromUnixTime(long time)
		{
			return JSDateOffset.AddMilliseconds(time*1000);
		}
		public static DateTime FloorToSecond(this DateTime Time)
		{
			return new DateTime((Time.Ticks / 10000000) * 10000000);
		}
		public static DateTime ToUtcTime(this DateTime Time)
		{
			switch (Time.Kind)
			{
				case DateTimeKind.Local:
					return Time.ToUniversalTime();
				case DateTimeKind.Unspecified:
					return new DateTime(Time.Ticks, DateTimeKind.Local).ToUniversalTime();
				case DateTimeKind.Utc:
					return Time;
				default:
					throw new NotSupportedException();
			}
		}
	}
}


text:
ActiveRecord::Schema.define do
  create_table :books do |t|
    t.string :title
    t.integer :edition
    t.integer :year
    t.float :price
    t.integer :rank
    t.timestamps
  end

  create_table :book_snapshots do |t|
    t.integer :snapped_id
    t.datetime :snapped_at

    t.string :title
    t.integer :edition
    t.float :price
    t.integer :rank
  end
end

class Book < ActiveRecord::Base
  include ActiveRecordSnapshot::Snapped

  snapshot :title # default: :dirty
  snapshot :price, when: :always
  snapshot :edition, when: :dirty
  snapshot :rank, when: :always
end

class BookSnapshot < ActiveRecord::Base
  include ActiveRecordSnapshot::Snapshot
end

ActiveRecord::Schema.define do
  create_table :movies do |t|
    t.string :title
    t.integer :release
    t.integer :year
    t.float :gross
    t.integer :rank
    t.timestamps
  end

  create_table :movie_snapshots do |t|
    t.integer :snapped_id
    t.datetime :snapped_at

    t.string :title
    t.integer :release
    t.integer :year
    t.float :gross
    t.integer :rank
  end
end

class Movie < ActiveRecord::Base
  include ActiveRecordSnapshot::Snapped
  dirty_snapshot [:title, :release]
  always_snapshot [:gross, :rank]
end

class MovieSnapshot < ActiveRecord::Base
  include ActiveRecordSnapshot::Snapshot
end


text:
<?php

namespace Laravist;

class Person {
    protected $name;

    /**
     * Person constructor.
     * @param $name
     */
    public function __construct($name)
    {
        $this->name = $name;
    }
}


text:
<?php
namespace SON\CatalogoBundle\DataFixtures\ORM;

//use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use SON\CatalogoBundle\Entity\Catalogo;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\DataFixtures\AbstractFixture;

class LoadCatalogo extends AbstractFixture implements OrderedFixtureInterface{

    public function load(ObjectManager $manager) {
        $user = $this->getReference('user-user');

        $catalogo = new Catalogo;
        $catalogo->setName('Quadros Futuristas')
                ->setDescricao('Acervo de quadros futuristas')
                ->setLancamento(new \DateTime("now"))
                ->setImageName('futuristas.png')
                ->setAutor($user);

        $catalogo2 = new Catalogo;
        $catalogo2->setName('Quadros Antigos')
                ->setDescricao('Acervo de quadros antigos')
                ->setLancamento(new \DateTime("yesterday noon"))
                ->setImageName('antigos.png');

        $manager->persist($catalogo);

        $manager->persist($catalogo2);
        $manager->flush();
    }

    public function getOrder(){
        return 20;
    }

}


text:
package m11.mib.paf.quiz.result;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import m11.mib.paf.quiz.Application;
import m11.mib.paf.quiz.category.Category;
import m11.mib.paf.quiz.category.CategoryRepository;
import m11.mib.paf.quiz.user.User;
import m11.mib.paf.quiz.user.UserRepository;

/**
 * ResultInitializer
 * Startup databse filler for results
 *
 * @author M11
 * @version 1.0
 */
public class ResultInitializer {

    private static final Logger log = LoggerFactory.getLogger(Application.class);

    private final CategoryRepository categoryRepository; // ~~~ CrudRepository of the categories, injected by Spring
    private final ResultRepository resultRepository; // ~~~ CrudRepository of the results, injected by Spring
    private final UserRepository userRepository; // ~~~ CrudRepository of the users, injected by Spring

    public ResultInitializer(
	    CategoryRepository categoryRepository,
	    ResultRepository resultrepository,
	    UserRepository userRepository
	   ) {
	this.categoryRepository = categoryRepository;
	this.resultRepository = resultrepository;
	this.userRepository = userRepository;
    }

    /**
     * @param user to create results for
     * @param category of the created results
     */
    private void createResultsFor(User user, Category category) {
	List<Category> categoryList = new ArrayList<Category>();
	categoryList.add(category);

	int random = ThreadLocalRandom.current().nextInt(0, 10);
	for (int i = 0; i < 10; i++) {
	    if ( i < random ) {
		this.resultRepository.save(new Result(user, categoryList, true));
	    } else {
		this.resultRepository.save(new Result(user, categoryList, false));
	    }
	}
	log.info(this.resultRepository.countByCategoriesOfResult(category) + " total results for " + category.getJsonName());
	log.info(this.resultRepository.countByCategoriesOfResultAndCorrectTrue(category) + " correct results for " + category.getJsonName());
	log.info(this.resultRepository.countByUserOfResultAndCategoriesOfResult(user, category) + " total results of " + user.getJsonId() + " for " + category.getJsonName());
	log.info(this.resultRepository.countByUserOfResultAndCategoriesOfResultAndCorrectTrue(user, category) + " correct results of " + user.getJsonId() + " for " + category.getJsonName());
    }

    /**
     * Initialize various results for different users in the database
     * Each of these users gets 10 results per Category to support a simple statistical output.
     */
    public void initialize() {
	Iterable<Category> categories = this.categoryRepository.findAll();

	User rookie = this.userRepository.findOne("Rookie");
	User pro    = this.userRepository.findOne("Pro");

	for (Category category : categories) {
	    this.createResultsFor(rookie, category);
	    this.createResultsFor(pro, category);
	    this.createResultsFor(pro, category);
	    this.createResultsFor(pro, category);
	}
    }

}


text:
#ifndef EXPANDEDDATUM_H
#define EXPANDEDDATUM_H

/* Size of an EXTERNAL datum that contains a pointer to an expanded object */
#define EXPANDED_POINTER_SIZE (VARHDRSZ_EXTERNAL + sizeof(varatt_expanded))

/*
 * "Methods" that must be provided for any expanded object.
 *
 * get_flat_size: compute space needed for flattened representation (total,
 * including header).
 *
 * flatten_into: construct flattened representation in the caller-allocated
 * space at *result, of size allocated_size (which will always be the result
 * of a preceding get_flat_size call; it's passed for cross-checking).
 *
 * The flattened representation must be a valid in-line, non-compressed,
 * 4-byte-header varlena object.
 *
 * Note: construction of a heap tuple from an expanded datum calls
 * get_flat_size twice, so it's worthwhile to make sure that that doesn't
 * incur too much overhead.
 */
typedef Size (*EOM_get_flat_size_method) (ExpandedObjectHeader *eohptr);
typedef void (*EOM_flatten_into_method) (ExpandedObjectHeader *eohptr,
										 void *result, Size allocated_size);

/* Struct of function pointers for an expanded object's methods */
typedef struct ExpandedObjectMethods
{
	EOM_get_flat_size_method get_flat_size;
	EOM_flatten_into_method flatten_into;
} ExpandedObjectMethods;

/*
 * Every expanded object must contain this header; typically the header
 * is embedded in some larger struct that adds type-specific fields.
 *
 * It is presumed that the header object and all subsidiary data are stored
 * in eoh_context, so that the object can be freed by deleting that context,
 * or its storage lifespan can be altered by reparenting the context.
 * (In principle the object could own additional resources, such as malloc'd
 * storage, and use a memory context reset callback to free them upon reset or
 * deletion of eoh_context.)
 *
 * We set up two TOAST pointers within the standard header, one read-write
 * and one read-only.  This allows functions to return either kind of pointer
 * without making an additional allocation, and in particular without worrying
 * whether a separately palloc'd object would have sufficient lifespan.
 * But note that these pointers are just a convenience; a pointer object
 * appearing somewhere else would still be legal.
 *
 * The typedef declaration for this appears in postgres.h.
 */
struct ExpandedObjectHeader
{
	/* Phony varlena header */
	int32		vl_len_;		/* always EOH_HEADER_MAGIC, see below */

	/* Pointer to methods required for object type */
	const ExpandedObjectMethods *eoh_methods;

	/* Memory context containing this header and subsidiary data */
	MemoryContext eoh_context;

	/* Standard R/W TOAST pointer for this object is kept here */
	char		eoh_rw_ptr[EXPANDED_POINTER_SIZE];

	/* Standard R/O TOAST pointer for this object is kept here */
	char		eoh_ro_ptr[EXPANDED_POINTER_SIZE];
};

/*
 * Particularly for read-only functions, it is handy to be able to work with
 * either regular "flat" varlena inputs or expanded inputs of the same data
 * type.  To allow determining which case an argument-fetching function has
 * returned, the first int32 of an ExpandedObjectHeader always contains -1
 * (EOH_HEADER_MAGIC to the code).  This works since no 4-byte-header varlena
 * could have that as its first 4 bytes.  Caution: we could not reliably tell
 * the difference between an ExpandedObjectHeader and a short-header object
 * with this trick.  However, it works fine if the argument fetching code
 * always returns either a 4-byte-header flat object or an expanded object.
 */
#define EOH_HEADER_MAGIC (-1)
#define VARATT_IS_EXPANDED_HEADER(PTR) \
	(((varattrib_4b *) (PTR))->va_4byte.va_header == EOH_HEADER_MAGIC)

/*
 * Generic support functions for expanded objects.
 * (More of these might be worth inlining later.)
 */

#define EOHPGetRWDatum(eohptr)	PointerGetDatum((eohptr)->eoh_rw_ptr)
#define EOHPGetRODatum(eohptr)	PointerGetDatum((eohptr)->eoh_ro_ptr)

/* Does the Datum represent a writable expanded object? */
#define DatumIsReadWriteExpandedObject(d, isnull, typlen) \
	(((isnull) || (typlen) != -1) ? false : \
	 VARATT_IS_EXTERNAL_EXPANDED_RW(DatumGetPointer(d)))

#define MakeExpandedObjectReadOnly(d, isnull, typlen) \
	(((isnull) || (typlen) != -1) ? (d) : \
	 MakeExpandedObjectReadOnlyInternal(d))

extern ExpandedObjectHeader *DatumGetEOHP(Datum d);
extern void EOH_init_header(ExpandedObjectHeader *eohptr,
				const ExpandedObjectMethods *methods,
				MemoryContext obj_context);
extern Size EOH_get_flat_size(ExpandedObjectHeader *eohptr);
extern void EOH_flatten_into(ExpandedObjectHeader *eohptr,
				 void *result, Size allocated_size);
extern Datum MakeExpandedObjectReadOnlyInternal(Datum d);
extern Datum TransferExpandedObject(Datum d, MemoryContext new_parent);
extern void DeleteExpandedObject(Datum d);

#endif							/* EXPANDEDDATUM_H */


text:
<?php

namespace WebinoData\Select;

use Zend\Db\Sql\Select;

/**
 * Class GroupTrait
 */
trait GroupTrait
{
    use ExpressionTrait;
    use PredicateTrait;

    /**
     * @return Select
     */
    abstract public function getSqlSelect();

    /**
     * @param string $group
     * @return $this
     */
    public function group($group)
    {
        $this->getSqlSelect()->group($this->handleExpression($this->handleVars($group)));
        return $this;
    }
}


text:
public class LecteurFichierPalindrome extends LecteurFichier {

	public LecteurFichierPalindrome(String file_name){
		super(file_name);
	}

	public void show() {
		for(int i = 0; i < this.content.size(); i++){
			System.out.print(this.content.get(i));
		}
		for(int i = this.content.size()-1; i >=0 ; i--){
			System.out.print(this.content.get(i));
		}
	}
}


text:
package org.apache.sis.internal.jaxb.metadata;

import javax.xml.bind.annotation.XmlElementRef;
import org.opengis.metadata.quality.PositionalAccuracy;
import org.apache.sis.metadata.iso.quality.AbstractPositionalAccuracy;
import org.apache.sis.internal.jaxb.gco.PropertyType;

/**
 * JAXB adapter mapping implementing class to the GeoAPI interface. See
 * package documentation for more information about JAXB and interface.
 *
 * @author  Martin Desruisseaux (Geomatys)
 * @since   0.6
 * @version 0.6
 * @module
 */
public final class DQ_PositionalAccuracy extends PropertyType<DQ_PositionalAccuracy, PositionalAccuracy> {
    /**
     * Empty constructor for JAXB only.
     */
    public DQ_PositionalAccuracy() {
    }

    /**
     * Returns the GeoAPI interface which is bound by this adapter.
     * This method is indirectly invoked by the private constructor
     * below, so it shall not depend on the state of this object.
     *
     * @return {@code PositionalAccuracy.class}
     */
    @Override
    protected Class<PositionalAccuracy> getBoundType() {
        return PositionalAccuracy.class;
    }

    /**
     * Constructor for the {@link #wrap} method only.
     */
    private DQ_PositionalAccuracy(final PositionalAccuracy metadata) {
        super(metadata);
    }

    /**
     * Invoked by {@link PropertyType} at marshalling time for wrapping the given metadata value
     * in a {@code <gmd:DQ_PositionalAccuracy>} XML element.
     *
     * @param  metadata The metadata element to marshall.
     * @return A {@code PropertyType} wrapping the given the metadata element.
     */
    @Override
    protected DQ_PositionalAccuracy wrap(final PositionalAccuracy metadata) {
        return new DQ_PositionalAccuracy(metadata);
    }

    /**
     * Invoked by JAXB at marshalling time for getting the actual metadata to write
     * inside the {@code <gmd:DQ_PositionalAccuracy>} XML element.
     * This is the value or a copy of the value given in argument to the {@code wrap} method.
     *
     * @return The metadata to be marshalled.
     */
    @XmlElementRef
    public AbstractPositionalAccuracy getElement() {
        return AbstractPositionalAccuracy.castOrCopy(metadata);
    }

    /**
     * Invoked by JAXB at unmarshalling time for storing the result temporarily.
     *
     * @param metadata The unmarshalled metadata.
     */
    public void setElement(final AbstractPositionalAccuracy metadata) {
        this.metadata = metadata;
    }
}


text:
var Backbone = require('backbone'),
    Marionette = require('backbone.marionette'),
    $ = require('jquery'),
    _ = require('underscore'),

    // Config
    layout = require('./js/layout.js'),

    // Controller
    PrimaryDisplayController = require('./js/controller/PrimaryDisplayController'),

    // View
    MainLayout = require('./js/view/MainLayout'),
    WelcomeScreen = require('./js/view/WelcomeScreen'),
    RegionModal = require('./js/common/modal/RegionModal.js'),
    ToolbarItem = require('./js/view/ToolbarItem'),

    // Util
    FileIO = require('./js/common/storage/FileIO.js');

require('./js/common/library/CurrencyInputStyler');

var Banknote = new Marionette.Application();

Banknote.addRegions({
   central: '#app',
   modal: RegionModal
});

Banknote.addInitializer(function(options) {
   var mainLayout = new MainLayout(),
       welcomeScreen = new WelcomeScreen(),
       downloadSheetItem = new ToolbarItem({
          model: new Backbone.Model({
             'icon': 'fa-download'
          })
       }),
       controller = new PrimaryDisplayController(),
       openFile;

   Banknote.central.show(mainLayout);
   mainLayout.toolbar.show(downloadSheetItem);

   downloadSheetItem.on('element:click', function() {
      if (!openFile) {
         return;
      }

      var fileIO = new FileIO();
      fileIO.save(JSON.stringify(controller.exportToData()), openFile.name);
   });

   welcomeScreen.on('click:newsheet', function() {
      $.getJSON('demo.json', function(data) {
         var layoutView = controller.render(data);

         mainLayout.elements.show(layoutView);
      });

   });

   welcomeScreen.on('select:file', function(file) {
      var fileIO = new FileIO();
      fileIO.on('read:file', function(contents) {
         var layoutView = controller.render($.parseJSON(contents));

         mainLayout.elements.show(layoutView);
      });
      fileIO.read(file);

      openFile = file;
   });

   // Present welcome screen
   mainLayout.elements.show(welcomeScreen);
});

Banknote.start();

// Make Banknote available globally
global.Banknote = Banknote;


text:
namespace Tethys.Forms
{
  partial class ProgressBarNeverEnd
  {
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    #region Component Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
      components = new System.ComponentModel.Container();
      this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
    }

    #endregion
  }
}


text:
package info.rolandkrueger.userservice.api.enums;

/**
 * Enum that defines the available projections for the User resource.
 *
 * @author Roland Krüger
 * @see info.rolandkrueger.userservice.api.resources.UserResource#useProjection(UserProjections)
 */
public enum UserProjections {

    /**
     * Projection that sends the complete data set for a user, including the user's list of authorities and the
     * hashed and salted password.
     */
    FULL_DATA(Values.USER_FULL_DATA),

    /**
     * Projection that sends an excerpt of a user's data set: user name, registration date, last login time, and
     * email address. Can be used to save bandwidth.
     */
    EXCERPT(Values.USER_EXCERPT_DATA);

    private String name;

    UserProjections(String name) {
        this.name = name;
    }

    /**
     * Returns the projection's name as defined by {@link info.rolandkrueger.userservice.api.enums.UserProjections.Values}
     */
    public String getName() {
        return name;
    }

    /**
     * Projection names as used by the service.
     */
    public static class Values {
        public static final String USER_FULL_DATA = "full-data";
        public static final String USER_EXCERPT_DATA = "excerpt";
    }

}


text:
可以返回自定义的 `Option` label

## en-US

You could set custom `Option` label


text:
package com.intellij.plugins.haxe.config.sdk.ui;

import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VirtualFile;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author: Fedor.Korotkov
 */
public class HaxeAdditionalConfigurablePanel {
  private TextFieldWithBrowseButton myNekoTextField;
  private JPanel myPanel;
  private JLabel myNekoLabel;
  private TextFieldWithBrowseButton myHaxelibTextField;
  private JLabel myHaxelibLabel;

  public HaxeAdditionalConfigurablePanel() {
    myNekoTextField.getButton().addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        final FileChooserDescriptor descriptor = new FileChooserDescriptor(true, false, false, false, false, false);
        final VirtualFile file = FileChooser.chooseFile(descriptor, myPanel, null, null);
        if (file != null) {
          setNekoBinPath(FileUtil.toSystemIndependentName(file.getPath()));
        }
      }
    });
    myNekoLabel.setLabelFor(myNekoTextField.getTextField());
    myHaxelibTextField.getButton().addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        final FileChooserDescriptor descriptor = new FileChooserDescriptor(true, false, false, false, false, false);
        final VirtualFile file = FileChooser.chooseFile(descriptor, myPanel, null, null);
        if (file != null) {
          setHaxelibPath(FileUtil.toSystemIndependentName(file.getPath()));
        }
      }
    });
    myHaxelibLabel.setLabelFor(myHaxelibTextField.getTextField());
  }

  public JComponent getPanel() {
    return myPanel;
  }

  public void setNekoBinPath(String path) {
    myNekoTextField.setText(FileUtil.toSystemDependentName(path));
  }

  public String getNekoBinPath() {
    return FileUtil.toSystemIndependentName(myNekoTextField.getText());
  }

  public void setHaxelibPath(String path) {
    myHaxelibTextField.setText(FileUtil.toSystemDependentName(path));
  }

  public String getHaxelibPath() {
    return FileUtil.toSystemIndependentName(myHaxelibTextField.getText());
  }
}


text:
@interface MainWindowController ()

@property (unsafe_unretained) IBOutlet NSTextView *tfNoteTextView;

- (IBAction)closeButtonClicked:(id)sender;
- (IBAction)postButtonClicked:(id)sender;

@end

@implementation MainWindowController

- (instancetype)init
{
    if (self = [super initWithWindowNibName:@"MainWindowController" owner:self]) {
    }

    return self;
}

- (void)windowDidLoad
{
    [super windowDidLoad];

    _tfNoteTextView.font = [NSFont systemFontOfSize:15];

    NSString *strDefaultGitRepoPath = GetDailyNoteGitRepoPath();

    if (!strDefaultGitRepoPath) {
        RunAlertPanel(@"No valid git repository path configuration found!", @"Please go to Preferences window to choose one.");
        _tfNoteTextView.editable = NO;
    } else {
        _tfNoteTextView.editable = YES;
    }
}

#pragma mark - Actions

- (IBAction)closeButtonClicked:(id)sender
{
    [self close];
}

- (IBAction)postButtonClicked:(id)sender
{
    NSString *text = _tfNoteTextView.string;

    if ([text isEmpty]) {
        RunAlertPanel(@"Content shouldn't be empty", @"");
        return;
    }

    NoteRecord *record = [NoteRecord createNoteRecordWithCurrentDate:text];

    if (![[DBHelper sharedInstance] isExist:record]) {
        [[DBHelper sharedInstance] saveRecord:record];
        DDLogInfo(@"Saved note record '%@' to database.", record);

        [self showHUDState:@"Saved!"];
    }
}

#pragma mark -

- (void)showHUDState:(NSString *)hudText
{
    NSView *superView = self.tfNoteTextView;

    NSTextField *hudView = [[NSTextField alloc] init];

    [hudView setStringValue:hudText];
    hudView.editable = NO;
    hudView.bordered = NO;
    hudView.wantsLayer = YES;
    hudView.font = [NSFont systemFontOfSize:16];
    [hudView setTextColor:[NSColor redColor]];
    [hudView setBackgroundColor:[NSColor clearColor]];
    [superView addSubview:hudView];
    [hudView sizeToFit];

    CGSize size = hudView.frame.size, contentSize = superView.frame.size;
    hudView.frame = CGRectMake((contentSize.width - size.width) / 2, (contentSize.height - size.height) / 2, size.width, size.height);

    [NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {
        context.duration = 2;
        hudView.animator.alphaValue = 0;
    }
                        completionHandler:^{
        [hudView removeFromSuperview];
    }];
}

@end