text:
package org.radargun.stages.cache.test;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.TreeSet;

import org.radargun.Operation;
import org.radargun.config.Init;
import org.radargun.config.Property;
import org.radargun.config.Stage;
import org.radargun.stages.test.OperationLogic;
import org.radargun.stages.test.Stressor;
import org.radargun.traits.BasicOperations;
import org.radargun.traits.InjectTrait;
import org.radargun.utils.SizeConverter;
import org.radargun.utils.TimeConverter;
import org.radargun.utils.TimeService;

/**
 * @author Radim Vansa <rvansa@redhat.com>
 */
@Stage(doc = "During execution, keys expire (entries are removed from the cache) and new keys are used.")
public class KeyExpirationTestStage extends CacheTestStage {

   @Property(doc = "Maximum number of entries stored in the cache by one stressor thread at one moment.")
   protected long numEntriesPerThread = 0;

   @Property(doc = "Maximum number of bytes in entries' values stored in the cache by one stressor thread at one moment.", converter = SizeConverter.class)
   protected long numBytesPerThread = 0;

   @Property(doc = "Due to configuration (eviction, expiration), some keys may spuriously disappear. Do not issue a warning for this situation. Default is false.")
   protected boolean expectLostKeys = false;

   @Property(doc = "With fixedKeys=false, maximum lifespan of an entry. Default is 1 hour.", converter = TimeConverter.class)
   protected long entryLifespan = 3600000;

   @Property(doc = "Ratio of GET requests. Default is 4.")
   protected int getRatio = 4;

   @Property(doc = "Ratio of PUT requests. Default is 1.")
   protected int putRatio = 1;

   @InjectTrait
   BasicOperations basicOperations;

   protected OperationSelector operationSelector;

   @Init
   public void init() {
      operationSelector = new OperationSelector.Builder()
            .add(BasicOperations.PUT, putRatio)
            .add(BasicOperations.GET, getRatio)
            .build();
   }

   @Override
   public OperationLogic getLogic() {
      return new Logic();
   }

   /**
    * @author Radim Vansa <rvansa@redhat.com>
    */
   protected class Logic extends OperationLogic {
      private long minRemoveTimestamp = Long.MAX_VALUE;
      private int minRemoveSize = 0;
      private HashMap<Integer, Load> loadForSize = new HashMap<>();
      private int nextKeyIndex;
      private BasicOperations.Cache nonTxCache;
      private BasicOperations.Cache cache;

      @Override
      public void init(Stressor stressor) {
         super.init(stressor);
         nextKeyIndex = stressor.getGlobalThreadIndex();
         double averageSize = 0;
         Map<Integer, Double> probabilityMap = entrySize.getProbabilityMap();
         long entries;
         if (numBytesPerThread > 0) {
            for (Map.Entry<Integer, Double> entry : probabilityMap.entrySet()) {
               averageSize += entry.getValue() * entry.getKey();
            }
            entries = (long) (numBytesPerThread / averageSize);
         } else {
            entries = numEntriesPerThread;
         }
         long expectedMax = 0;
         for (Map.Entry<Integer, Double> entry : probabilityMap.entrySet()) {
            long valuesForSize = (long) (entries * entry.getValue());
            expectedMax += valuesForSize * entry.getKey();
            loadForSize.put(entry.getKey(), new Load(valuesForSize));
         }
         log.info("Expecting maximal load of " + new SizeConverter().convertToString(expectedMax));

         String cacheName = cacheSelector.getCacheName(stressor.getGlobalThreadIndex());
         nonTxCache = basicOperations.getCache(cacheName);
         if (!useTransactions(cacheName)) {
            cache = nonTxCache;
         }
         stressor.setUseTransactions(useTransactions(cacheName));
      }

      @Override
      public void transactionStarted() {
         cache = stressor.wrap(nonTxCache);
      }

      @Override
      public void transactionEnded() {
         cache = null;
      }

      @Override
      public Object run() throws RequestException {
         Random random = stressor.getRandom();
         KeyWithRemovalTime pair;
         long timestamp = TimeService.currentTimeMillis();
         if (minRemoveTimestamp <= timestamp) {
            Load load = loadForSize.get(minRemoveSize);
            pair = load.scheduledKeys.pollFirst();
            Boolean value;
            try {
               value = (Boolean) stressor.makeRequest(new Invocations.Remove(cache, pair.key));
            } catch (RequestException e) {
               load.scheduledKeys.add(pair);
               return null;
            }
            updateMin();
            if (!value && !expectLostKeys) {
               log.error("REMOVE: Entry for key " + pair.key + " was not found!");
            }
            return value;
         } else {
            Operation operation = operationSelector.next(random);
            if (operation == BasicOperations.GET && minRemoveTimestamp < Long.MAX_VALUE) {
               Load load = null;
               for (int attempt = 0; attempt < 100; ++attempt) {
                  load = loadForSize.get(entrySize.next(random));
                  if (!load.scheduledKeys.isEmpty()) break;
               }
               if (load.scheduledKeys.isEmpty()) {
                  log.error("Current load seems to be null but timestamp is " + minRemoveTimestamp);
                  return null;
               }
               pair = getRandomPair(load.scheduledKeys, timestamp, random);
               Object value = stressor.makeRequest(new Invocations.Get(cache, pair.key));
               if (value == null) {
                  if (expectLostKeys) {
                     load.scheduledKeys.remove(pair);
                     updateMin();
                  } else {
                     log.error("GET: Value for key " + pair.key + " is null!");
                  }
               }
               return value;
            } else {
               int size = 0;
               Load load = null;
               for (int attempt = 0; attempt < 100; ++attempt) {
                  size = entrySize.next(random);
                  load = loadForSize.get(size);
                  if (load.max != 0) break;
               }
               if (load.max == 0) {
                  log.error("Cannot add any entry");
                  return null;
               } else if (load.scheduledKeys.size() < load.max) {
                  long keyIndex = nextKeyIndex;
                  nextKeyIndex += getTotalThreads();
                  pair = new KeyWithRemovalTime(keyGenerator.generateKey(keyIndex), getRandomTimestamp(timestamp, random));
                  load.scheduledKeys.add(pair);
                  updateMin();
               } else {
                  pair = getRandomPair(load.scheduledKeys, timestamp, random);
               }
               Object value = valueGenerator.generateValue(null, size, stressor.getRandom());
               try {
                  return stressor.makeRequest(new Invocations.Put(cache, pair.key, value));
               } catch (RequestException e) {
                  load.scheduledKeys.remove(pair);
                  while (!isTerminated()) {
                     try {
                        return stressor.makeRequest(new Invocations.Remove(cache, pair.key));
                     } catch (RequestException e1) {
                        // exception already logged in Stressor
                     }
                  }
                  return null;
               }
            }
         }
      }

      private void updateMin() {
         minRemoveTimestamp = Long.MAX_VALUE;
         for (Map.Entry<Integer, Load> entry : loadForSize.entrySet()) {
            if (!entry.getValue().scheduledKeys.isEmpty()) {
               long min = entry.getValue().scheduledKeys.first().removeTimestamp;
               if (min < minRemoveTimestamp) {
                  minRemoveTimestamp = min;
                  minRemoveSize = entry.getKey();
               }
            }
         }
      }

      private long getRandomTimestamp(long current, Random random) {
         // ~sqrt probability for 1 - maxRoot^2
         final long maxRoot = (long) Math.sqrt((double) entryLifespan);
         long rand = random.nextLong() % maxRoot;
         return current + rand * rand + random.nextLong() % (2*maxRoot - 2) + 1;
      }

      private KeyWithRemovalTime getRandomPair(TreeSet<KeyWithRemovalTime> scheduledKeys, long timestamp, Random random) {
         // we cannot get random access to PriorityQueue and there is no SortedList or another appropriate structure
         KeyWithRemovalTime pair = scheduledKeys.floor(new KeyWithRemovalTime(null, getRandomTimestamp(timestamp, random)));
         return pair != null ? pair : scheduledKeys.first();
      }
   }

   private static class KeyWithRemovalTime implements Comparable<KeyWithRemovalTime> {
      public final Object key;
      public final long removeTimestamp;

      public KeyWithRemovalTime(Object key, long removeTimestamp) {
         this.key = key;
         this.removeTimestamp = removeTimestamp;
      }

      @Override
      public int compareTo(KeyWithRemovalTime o) {
         if (removeTimestamp < o.removeTimestamp) return -1;
         if (removeTimestamp > o.removeTimestamp) return 1;
         if (key == null || o.key == null) return 0;
         if (key.equals(o.key)) return 0;
         return -1;
      }
   }

   private static class Load {
      public final long max;
      public final TreeSet<KeyWithRemovalTime> scheduledKeys = new TreeSet<>();

      private Load(long max) {
         this.max = max;
      }
   }
}


text:
"use strict";

module.exports = {
  env: { browser: true },
  plugins: ["unicorn"],
  rules: {
    "unicorn/no-document-cookie": "error",
    "unicorn/prefer-add-event-listener": "error",
    "unicorn/prefer-dom-node-append": "error",
    "unicorn/prefer-dom-node-dataset": "error",
    "unicorn/prefer-dom-node-remove": "error",
    "unicorn/prefer-dom-node-text-content": "error",
    "unicorn/prefer-keyboard-event-key": "error",
    "unicorn/prefer-modern-dom-apis": "error",
    "unicorn/prefer-query-selector": "error",
    "unicorn/require-post-message-target-origin": "error",
    "unicorn/no-invalid-remove-event-listener": "error",
  },
};

redpajama_set_name: RedPajamaGithub


text:
module.exports = function(app, options) {
  app.module('associate', require('./associate'))
  app.module('associatable', require('./associatable'))
  app.module('associations', require('./associations'))
  app.module('beads', require('./beads'))
  app.module('board', require('./board'))
  app.module('clippings', require('./clippings'))
  app.module('clippingsToCurate', require('./clippingsToCurate'))
  app.module('connections', require('./connections'))
  app.module('offset', require('./offset'))
  app.module('user', require('./user'));
}


text:
require 'spec_helper'

describe SerpMetrics do
  it "has version" do
    described_class::VERSION.should be_instance_of(String)
    described_class::VERSION.should_not be_empty
  end
end


text:
FOUNDATION_EXPORT double Pods_ScaledCenterCarousel_ExampleVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_ScaledCenterCarousel_ExampleVersionString[];


text:
/**
 * Types used by the update manager to control in which order functions are called.
 */
dbm.registerClass("dbm.constants.generic.UpdaterTypes", null, function(objectFunctions, staticFunctions, ClassReference) {
	//console.log("dbm.constants.generic.UpdaterTypes");
	//"use strict";

	//Self reference
	var UpdaterTypes = dbm.importClass("dbm.constants.generic.UpdaterTypes");

	staticFunctions.UPDATE_INPUT = "updateInput";
	staticFunctions.UPDATE_TIMELINES = "updateTimelines";
	staticFunctions.DEFAULT = "default";
	staticFunctions.UPDATE_FLOW = "updateFlow";
});


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

package com.google.api.ads.adwords.jaxws.v201809.cm;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for ProductPartitionType.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="ProductPartitionType">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="UNKNOWN"/>
 *     <enumeration value="SUBDIVISION"/>
 *     <enumeration value="UNIT"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "ProductPartitionType")
@XmlEnum
public enum ProductPartitionType {

    /**
     *
     *                 Used for return value only. An enumeration could not be processed, typically due to incompatibility with your WSDL version.
     *
     *
     */
    UNKNOWN,

    /**
     *
     *                 Subdivision of products along some product dimension.
     *
     *
     */
    SUBDIVISION,

    /**
     *
     *                 Unit which either defines a bid or delegates bidding to other campaigns.
     *
     *
     */
    UNIT;

    public String value() {
        return name();
    }

    public static ProductPartitionType fromValue(String v) {
        return valueOf(v);
    }

}


text:
<html>
<body>
<span>
  This intention converts tuples and list literals to set literals.
</span>
</body>
</html>


text:
#ifndef AOSOA_TABLE_RANGE
#define AOSOA_TABLE_RANGE

#include "tbb/tbb_stddef.h"

namespace aosoa {

  template<class Iterator>
  class table_range {
  private:
	Iterator lower, upper;

	typedef table_iterator_traits<Iterator> traits;

  public:
	table_range () {}

	table_range (Iterator lower, Iterator upper) : lower(lower), upper(upper) {}

	bool empty() const {return lower == upper;}

	bool is_divisible() const {return lower.table < upper.table;}

	table_range (table_range& that, tbb::split) {
	  auto mid = (that.upper.table - that.lower.table) / 2;
	  lower.table = that.lower.table + mid + 1;
	  lower.index = 0;
	  upper = that.upper;
	  that.upper.table = that.lower.table + mid;
	  that.upper.index = traits::table_size;
	}

	Iterator begin() {return lower;}
	const Iterator begin() const {return lower;}
	Iterator end() {return upper;}
	const Iterator end() const {return upper;}
  };
}

#endif


text:
namespace google {
namespace protobuf {
namespace compiler {
namespace java {

using internal::WireFormat;
using internal::WireFormatLite;

namespace {

const char* PrimitiveTypeName(JavaType type) {
  switch (type) {
    case JAVATYPE_INT    : return "int";
    case JAVATYPE_LONG   : return "long";
    case JAVATYPE_FLOAT  : return "float";
    case JAVATYPE_DOUBLE : return "double";
    case JAVATYPE_BOOLEAN: return "boolean";
    case JAVATYPE_STRING : return "java.lang.String";
    case JAVATYPE_BYTES  : return "com.google.protobuf.ByteString";
    case JAVATYPE_ENUM   : return NULL;
    case JAVATYPE_MESSAGE: return NULL;

    // No default because we want the compiler to complain if any new
    // JavaTypes are added.
  }

  GOOGLE_LOG(FATAL) << "Can't get here.";
  return NULL;
}

bool IsReferenceType(JavaType type) {
  switch (type) {
    case JAVATYPE_INT    : return false;
    case JAVATYPE_LONG   : return false;
    case JAVATYPE_FLOAT  : return false;
    case JAVATYPE_DOUBLE : return false;
    case JAVATYPE_BOOLEAN: return false;
    case JAVATYPE_STRING : return true;
    case JAVATYPE_BYTES  : return true;
    case JAVATYPE_ENUM   : return true;
    case JAVATYPE_MESSAGE: return true;

    // No default because we want the compiler to complain if any new
    // JavaTypes are added.
  }

  GOOGLE_LOG(FATAL) << "Can't get here.";
  return false;
}

const char* GetCapitalizedType(const FieldDescriptor* field) {
  switch (GetType(field)) {
    case FieldDescriptor::TYPE_INT32   : return "Int32"   ;
    case FieldDescriptor::TYPE_UINT32  : return "UInt32"  ;
    case FieldDescriptor::TYPE_SINT32  : return "SInt32"  ;
    case FieldDescriptor::TYPE_FIXED32 : return "Fixed32" ;
    case FieldDescriptor::TYPE_SFIXED32: return "SFixed32";
    case FieldDescriptor::TYPE_INT64   : return "Int64"   ;
    case FieldDescriptor::TYPE_UINT64  : return "UInt64"  ;
    case FieldDescriptor::TYPE_SINT64  : return "SInt64"  ;
    case FieldDescriptor::TYPE_FIXED64 : return "Fixed64" ;
    case FieldDescriptor::TYPE_SFIXED64: return "SFixed64";
    case FieldDescriptor::TYPE_FLOAT   : return "Float"   ;
    case FieldDescriptor::TYPE_DOUBLE  : return "Double"  ;
    case FieldDescriptor::TYPE_BOOL    : return "Bool"    ;
    case FieldDescriptor::TYPE_STRING  : return "String"  ;
    case FieldDescriptor::TYPE_BYTES   : return "Bytes"   ;
    case FieldDescriptor::TYPE_ENUM    : return "Enum"    ;
    case FieldDescriptor::TYPE_GROUP   : return "Group"   ;
    case FieldDescriptor::TYPE_MESSAGE : return "Message" ;

    // No default because we want the compiler to complain if any new
    // types are added.
  }

  GOOGLE_LOG(FATAL) << "Can't get here.";
  return NULL;
}

// For encodings with fixed sizes, returns that size in bytes.  Otherwise
// returns -1.
int FixedSize(FieldDescriptor::Type type) {
  switch (type) {
    case FieldDescriptor::TYPE_INT32   : return -1;
    case FieldDescriptor::TYPE_INT64   : return -1;
    case FieldDescriptor::TYPE_UINT32  : return -1;
    case FieldDescriptor::TYPE_UINT64  : return -1;
    case FieldDescriptor::TYPE_SINT32  : return -1;
    case FieldDescriptor::TYPE_SINT64  : return -1;
    case FieldDescriptor::TYPE_FIXED32 : return WireFormatLite::kFixed32Size;
    case FieldDescriptor::TYPE_FIXED64 : return WireFormatLite::kFixed64Size;
    case FieldDescriptor::TYPE_SFIXED32: return WireFormatLite::kSFixed32Size;
    case FieldDescriptor::TYPE_SFIXED64: return WireFormatLite::kSFixed64Size;
    case FieldDescriptor::TYPE_FLOAT   : return WireFormatLite::kFloatSize;
    case FieldDescriptor::TYPE_DOUBLE  : return WireFormatLite::kDoubleSize;

    case FieldDescriptor::TYPE_BOOL    : return WireFormatLite::kBoolSize;
    case FieldDescriptor::TYPE_ENUM    : return -1;

    case FieldDescriptor::TYPE_STRING  : return -1;
    case FieldDescriptor::TYPE_BYTES   : return -1;
    case FieldDescriptor::TYPE_GROUP   : return -1;
    case FieldDescriptor::TYPE_MESSAGE : return -1;

    // No default because we want the compiler to complain if any new
    // types are added.
  }
  GOOGLE_LOG(FATAL) << "Can't get here.";
  return -1;
}

void SetPrimitiveVariables(const FieldDescriptor* descriptor,
                           int messageBitIndex,
                           int builderBitIndex,
                           map<string, string>* variables) {
  (*variables)["name"] =
    UnderscoresToCamelCase(descriptor);
  (*variables)["capitalized_name"] =
    UnderscoresToCapitalizedCamelCase(descriptor);
  (*variables)["constant_name"] = FieldConstantName(descriptor);
  (*variables)["number"] = SimpleItoa(descriptor->number());
  (*variables)["type"] = PrimitiveTypeName(GetJavaType(descriptor));
  (*variables)["boxed_type"] = BoxedPrimitiveTypeName(GetJavaType(descriptor));
  (*variables)["field_type"] = (*variables)["type"];
  (*variables)["field_list_type"] = "java.util.List<" +
      (*variables)["boxed_type"] + ">";
  (*variables)["empty_list"] = "java.util.Collections.emptyList();";
  (*variables)["default"] = DefaultValue(descriptor);
  (*variables)["default_init"] = IsDefaultValueJavaDefault(descriptor) ?
      "" : ("= " + DefaultValue(descriptor));
  (*variables)["capitalized_type"] = GetCapitalizedType(descriptor);
  (*variables)["tag"] = SimpleItoa(WireFormat::MakeTag(descriptor));
  (*variables)["tag_size"] = SimpleItoa(
      WireFormat::TagSize(descriptor->number(), GetType(descriptor)));
  if (IsReferenceType(GetJavaType(descriptor))) {
    (*variables)["null_check"] =
        "  if (value == null) {\n"
        "    throw new NullPointerException();\n"
        "  }\n";
  } else {
    (*variables)["null_check"] = "";
  }
  // TODO: Add @deprecated javadoc when generating javadoc is supported
  // by the proto compiler
  (*variables)["deprecation"] = descriptor->options().deprecated()
      ? "@java.lang.Deprecated " : "";
  int fixed_size = FixedSize(GetType(descriptor));
  if (fixed_size != -1) {
    (*variables)["fixed_size"] = SimpleItoa(fixed_size);
  }
  (*variables)["on_changed"] =
      HasDescriptorMethods(descriptor->containing_type()) ? "onChanged();" : "";

  // For singular messages and builders, one bit is used for the hasField bit.
  (*variables)["get_has_field_bit_message"] = GenerateGetBit(messageBitIndex);

  (*variables)["get_has_field_bit_builder"] = GenerateGetBit(builderBitIndex);
  (*variables)["set_has_field_bit_builder"] = GenerateSetBit(builderBitIndex);
  (*variables)["clear_has_field_bit_builder"] =
      GenerateClearBit(builderBitIndex);

  // For repated builders, one bit is used for whether the array is immutable.
  (*variables)["get_mutable_bit_builder"] = GenerateGetBit(builderBitIndex);
  (*variables)["set_mutable_bit_builder"] = GenerateSetBit(builderBitIndex);
  (*variables)["clear_mutable_bit_builder"] = GenerateClearBit(builderBitIndex);

  (*variables)["get_has_field_bit_from_local"] =
      GenerateGetBitFromLocal(builderBitIndex);
  (*variables)["set_has_field_bit_to_local"] =
      GenerateSetBitToLocal(messageBitIndex);
}

}  // namespace

// ===================================================================

PrimitiveFieldGenerator::
PrimitiveFieldGenerator(const FieldDescriptor* descriptor,
                        int messageBitIndex,
                        int builderBitIndex)
  : descriptor_(descriptor), messageBitIndex_(messageBitIndex),
    builderBitIndex_(builderBitIndex) {
  SetPrimitiveVariables(descriptor, messageBitIndex, builderBitIndex,
                        &variables_);
}

PrimitiveFieldGenerator::~PrimitiveFieldGenerator() {}

int PrimitiveFieldGenerator::GetNumBitsForMessage() const {
  return 1;
}

int PrimitiveFieldGenerator::GetNumBitsForBuilder() const {
  return 1;
}

void PrimitiveFieldGenerator::
GenerateInterfaceMembers(io::Printer* printer) const {
  printer->Print(variables_,
    "$deprecation$boolean has$capitalized_name$();\n"
    "$deprecation$$type$ get$capitalized_name$();\n");
}

void PrimitiveFieldGenerator::
GenerateMembers(io::Printer* printer) const {
  printer->Print(variables_,
    "private $field_type$ $name$_;\n"
    "$deprecation$public boolean has$capitalized_name$() {\n"
    "  return $get_has_field_bit_message$;\n"
    "}\n");

  printer->Print(variables_,
    "$deprecation$public $type$ get$capitalized_name$() {\n"
    "  return $name$_;\n"
    "}\n");
}

void PrimitiveFieldGenerator::
GenerateBuilderMembers(io::Printer* printer) const {
  printer->Print(variables_,
    "private $field_type$ $name$_ $default_init$;\n"
    "$deprecation$public boolean has$capitalized_name$() {\n"
    "  return $get_has_field_bit_builder$;\n"
    "}\n");

  printer->Print(variables_,
    "$deprecation$public $type$ get$capitalized_name$() {\n"
    "  return $name$_;\n"
    "}\n");

  printer->Print(variables_,
    "$deprecation$public Builder set$capitalized_name$($type$ value) {\n"
    "$null_check$"
    "  $set_has_field_bit_builder$;\n"
    "  $name$_ = value;\n"
    "  $on_changed$\n"
    "  return this;\n"
    "}\n"
    "$deprecation$public Builder clear$capitalized_name$() {\n"
    "  $clear_has_field_bit_builder$;\n");
  JavaType type = GetJavaType(descriptor_);
  if (type == JAVATYPE_STRING || type == JAVATYPE_BYTES) {
    // The default value is not a simple literal so we want to avoid executing
    // it multiple times.  Instead, get the default out of the default instance.
    printer->Print(variables_,
      "  $name$_ = getDefaultInstance().get$capitalized_name$();\n");
  } else {
    printer->Print(variables_,
      "  $name$_ = $default$;\n");
  }
  printer->Print(variables_,
    "  $on_changed$\n"
    "  return this;\n"
    "}\n");
}

void PrimitiveFieldGenerator::
GenerateFieldBuilderInitializationCode(io::Printer* printer)  const {
  // noop for primitives
}

void PrimitiveFieldGenerator::
GenerateInitializationCode(io::Printer* printer) const {
  printer->Print(variables_, "$name$_ = $default$;\n");
}

void PrimitiveFieldGenerator::
GenerateBuilderClearCode(io::Printer* printer) const {
  printer->Print(variables_,
    "$name$_ = $default$;\n"
    "$clear_has_field_bit_builder$;\n");
}

void PrimitiveFieldGenerator::
GenerateMergingCode(io::Printer* printer) const {
  printer->Print(variables_,
    "if (other.has$capitalized_name$()) {\n"
    "  set$capitalized_name$(other.get$capitalized_name$());\n"
    "}\n");
}

void PrimitiveFieldGenerator::
GenerateBuildingCode(io::Printer* printer) const {
  printer->Print(variables_,
    "if ($get_has_field_bit_from_local$) {\n"
    "  $set_has_field_bit_to_local$;\n"
    "}\n"
    "result.$name$_ = $name$_;\n");
}

void PrimitiveFieldGenerator::
GenerateParsingCode(io::Printer* printer) const {
  printer->Print(variables_,
    "$set_has_field_bit_builder$;\n"
    "$name$_ = input.read$capitalized_type$();\n");
}

void PrimitiveFieldGenerator::
GenerateSerializationCode(io::Printer* printer) const {
  printer->Print(variables_,
    "if ($get_has_field_bit_message$) {\n"
    "  output.write$capitalized_type$($number$, $name$_);\n"
    "}\n");
}

void PrimitiveFieldGenerator::
GenerateSerializedSizeCode(io::Printer* printer) const {
  printer->Print(variables_,
    "if ($get_has_field_bit_message$) {\n"
    "  size += com.google.protobuf.CodedOutputStream\n"
    "    .compute$capitalized_type$Size($number$, $name$_);\n"
    "}\n");
}

void PrimitiveFieldGenerator::
GenerateEqualsCode(io::Printer* printer) const {
  switch (GetJavaType(descriptor_)) {
    case JAVATYPE_INT:
    case JAVATYPE_LONG:
    case JAVATYPE_BOOLEAN:
      printer->Print(variables_,
        "result = result && (get$capitalized_name$()\n"
        "    == other.get$capitalized_name$());\n");
      break;

    case JAVATYPE_FLOAT:
      printer->Print(variables_,
        "result = result && (Float.floatToIntBits(get$capitalized_name$())"
        "    == Float.floatToIntBits(other.get$capitalized_name$()));\n");
      break;

    case JAVATYPE_DOUBLE:
      printer->Print(variables_,
        "result = result && (Double.doubleToLongBits(get$capitalized_name$())"
        "    == Double.doubleToLongBits(other.get$capitalized_name$()));\n");
      break;

    case JAVATYPE_STRING:
    case JAVATYPE_BYTES:
      printer->Print(variables_,
        "result = result && get$capitalized_name$()\n"
        "    .equals(other.get$capitalized_name$());\n");
      break;

    case JAVATYPE_ENUM:
    case JAVATYPE_MESSAGE:
    default:
      GOOGLE_LOG(FATAL) << "Can't get here.";
      break;
  }
}

void PrimitiveFieldGenerator::
GenerateHashCode(io::Printer* printer) const {
  printer->Print(variables_,
    "hash = (37 * hash) + $constant_name$;\n");
  switch (GetJavaType(descriptor_)) {
    case JAVATYPE_INT:
      printer->Print(variables_,
        "hash = (53 * hash) + get$capitalized_name$();\n");
      break;

    case JAVATYPE_LONG:
      printer->Print(variables_,
        "hash = (53 * hash) + hashLong(get$capitalized_name$());\n");
      break;

    case JAVATYPE_BOOLEAN:
      printer->Print(variables_,
        "hash = (53 * hash) + hashBoolean(get$capitalized_name$());\n");
      break;

    case JAVATYPE_FLOAT:
      printer->Print(variables_,
        "hash = (53 * hash) + Float.floatToIntBits(\n"
        "    get$capitalized_name$());\n");
      break;

    case JAVATYPE_DOUBLE:
      printer->Print(variables_,
        "hash = (53 * hash) + hashLong(\n"
        "    Double.doubleToLongBits(get$capitalized_name$()));\n");
      break;

    case JAVATYPE_STRING:
    case JAVATYPE_BYTES:
      printer->Print(variables_,
        "hash = (53 * hash) + get$capitalized_name$().hashCode();\n");
      break;

    case JAVATYPE_ENUM:
    case JAVATYPE_MESSAGE:
    default:
      GOOGLE_LOG(FATAL) << "Can't get here.";
      break;
  }
}

string PrimitiveFieldGenerator::GetBoxedType() const {
  return BoxedPrimitiveTypeName(GetJavaType(descriptor_));
}

// ===================================================================

RepeatedPrimitiveFieldGenerator::
RepeatedPrimitiveFieldGenerator(const FieldDescriptor* descriptor,
                                int messageBitIndex,
                                int builderBitIndex)
  : descriptor_(descriptor), messageBitIndex_(messageBitIndex),
    builderBitIndex_(builderBitIndex) {
  SetPrimitiveVariables(descriptor, messageBitIndex, builderBitIndex,
                        &variables_);
}

RepeatedPrimitiveFieldGenerator::~RepeatedPrimitiveFieldGenerator() {}

int RepeatedPrimitiveFieldGenerator::GetNumBitsForMessage() const {
  return 0;
}

int RepeatedPrimitiveFieldGenerator::GetNumBitsForBuilder() const {
  return 1;
}

void RepeatedPrimitiveFieldGenerator::
GenerateInterfaceMembers(io::Printer* printer) const {
  printer->Print(variables_,
    "$deprecation$java.util.List<$boxed_type$> get$capitalized_name$List();\n"
    "$deprecation$int get$capitalized_name$Count();\n"
    "$deprecation$$type$ get$capitalized_name$(int index);\n");
}

void RepeatedPrimitiveFieldGenerator::
GenerateMembers(io::Printer* printer) const {
  printer->Print(variables_,
    "private $field_list_type$ $name$_;\n"
    "$deprecation$public java.util.List<$boxed_type$>\n"
    "    get$capitalized_name$List() {\n"
    "  return $name$_;\n"   // note:  unmodifiable list
    "}\n"
    "$deprecation$public int get$capitalized_name$Count() {\n"
    "  return $name$_.size();\n"
    "}\n"
    "$deprecation$public $type$ get$capitalized_name$(int index) {\n"
    "  return $name$_.get(index);\n"
    "}\n");

  if (descriptor_->options().packed() &&
      HasGeneratedMethods(descriptor_->containing_type())) {
    printer->Print(variables_,
      "private int $name$MemoizedSerializedSize = -1;\n");
  }
}

void RepeatedPrimitiveFieldGenerator::
GenerateBuilderMembers(io::Printer* printer) const {
  // One field is the list and the bit field keeps track of whether the
  // list is immutable. If it's immutable, the invariant is that it must
  // either an instance of Collections.emptyList() or it's an ArrayList
  // wrapped in a Collections.unmodifiableList() wrapper and nobody else has
  // a refererence to the underlying ArrayList. This invariant allows us to
  // share instances of lists between protocol buffers avoiding expensive
  // memory allocations. Note, immutable is a strong guarantee here -- not
  // just that the list cannot be modified via the reference but that the
  // list can never be modified.
  printer->Print(variables_,
    "private $field_list_type$ $name$_ = $empty_list$;\n");

  printer->Print(variables_,
    "private void ensure$capitalized_name$IsMutable() {\n"
    "  if (!$get_mutable_bit_builder$) {\n"
    "    $name$_ = new java.util.ArrayList<$boxed_type$>($name$_);\n"
    "    $set_mutable_bit_builder$;\n"
    "   }\n"
    "}\n");

    // Note:  We return an unmodifiable list because otherwise the caller
    //   could hold on to the returned list and modify it after the message
    //   has been built, thus mutating the message which is supposed to be
    //   immutable.
  printer->Print(variables_,
    "$deprecation$public java.util.List<$boxed_type$>\n"
    "    get$capitalized_name$List() {\n"
    "  return java.util.Collections.unmodifiableList($name$_);\n"
    "}\n"
    "$deprecation$public int get$capitalized_name$Count() {\n"
    "  return $name$_.size();\n"
    "}\n"
    "$deprecation$public $type$ get$capitalized_name$(int index) {\n"
    "  return $name$_.get(index);\n"
    "}\n"
    "$deprecation$public Builder set$capitalized_name$(\n"
    "    int index, $type$ value) {\n"
    "$null_check$"
    "  ensure$capitalized_name$IsMutable();\n"
    "  $name$_.set(index, value);\n"
    "  $on_changed$\n"
    "  return this;\n"
    "}\n"
    "$deprecation$public Builder add$capitalized_name$($type$ value) {\n"
    "$null_check$"
    "  ensure$capitalized_name$IsMutable();\n"
    "  $name$_.add(value);\n"
    "  $on_changed$\n"
    "  return this;\n"
    "}\n"
    "$deprecation$public Builder addAll$capitalized_name$(\n"
    "    java.lang.Iterable<? extends $boxed_type$> values) {\n"
    "  ensure$capitalized_name$IsMutable();\n"
    "  super.addAll(values, $name$_);\n"
    "  $on_changed$\n"
    "  return this;\n"
    "}\n"
    "$deprecation$public Builder clear$capitalized_name$() {\n"
    "  $name$_ = $empty_list$;\n"
    "  $clear_mutable_bit_builder$;\n"
    "  $on_changed$\n"
    "  return this;\n"
    "}\n");
}

void RepeatedPrimitiveFieldGenerator::
GenerateFieldBuilderInitializationCode(io::Printer* printer)  const {
  // noop for primitives
}

void RepeatedPrimitiveFieldGenerator::
GenerateInitializationCode(io::Printer* printer) const {
  printer->Print(variables_, "$name$_ = $empty_list$;\n");
}

void RepeatedPrimitiveFieldGenerator::
GenerateBuilderClearCode(io::Printer* printer) const {
  printer->Print(variables_,
    "$name$_ = $empty_list$;\n"
    "$clear_mutable_bit_builder$;\n");
}

void RepeatedPrimitiveFieldGenerator::
GenerateMergingCode(io::Printer* printer) const {
  // The code below does two optimizations:
  //   1. If the other list is empty, there's nothing to do. This ensures we
  //      don't allocate a new array if we already have an immutable one.
  //   2. If the other list is non-empty and our current list is empty, we can
  //      reuse the other list which is guaranteed to be immutable.
  printer->Print(variables_,
    "if (!other.$name$_.isEmpty()) {\n"
    "  if ($name$_.isEmpty()) {\n"
    "    $name$_ = other.$name$_;\n"
    "    $clear_mutable_bit_builder$;\n"
    "  } else {\n"
    "    ensure$capitalized_name$IsMutable();\n"
    "    $name$_.addAll(other.$name$_);\n"
    "  }\n"
    "  $on_changed$\n"
    "}\n");
}

void RepeatedPrimitiveFieldGenerator::
GenerateBuildingCode(io::Printer* printer) const {
  // The code below ensures that the result has an immutable list. If our
  // list is immutable, we can just reuse it. If not, we make it immutable.
  printer->Print(variables_,
    "if ($get_mutable_bit_builder$) {\n"
    "  $name$_ = java.util.Collections.unmodifiableList($name$_);\n"
    "  $clear_mutable_bit_builder$;\n"
    "}\n"
    "result.$name$_ = $name$_;\n");
}

void RepeatedPrimitiveFieldGenerator::
GenerateParsingCode(io::Printer* printer) const {
  printer->Print(variables_,
    "ensure$capitalized_name$IsMutable();\n"
    "$name$_.add(input.read$capitalized_type$());\n");
}

void RepeatedPrimitiveFieldGenerator::
GenerateParsingCodeFromPacked(io::Printer* printer) const {
  printer->Print(variables_,
    "int length = input.readRawVarint32();\n"
    "int limit = input.pushLimit(length);\n"
    "while (input.getBytesUntilLimit() > 0) {\n"
    "  add$capitalized_name$(input.read$capitalized_type$());\n"
    "}\n"
    "input.popLimit(limit);\n");
}

void RepeatedPrimitiveFieldGenerator::
GenerateSerializationCode(io::Printer* printer) const {
  if (descriptor_->options().packed()) {
    printer->Print(variables_,
      "if (get$capitalized_name$List().size() > 0) {\n"
      "  output.writeRawVarint32($tag$);\n"
      "  output.writeRawVarint32($name$MemoizedSerializedSize);\n"
      "}\n"
      "for (int i = 0; i < $name$_.size(); i++) {\n"
      "  output.write$capitalized_type$NoTag($name$_.get(i));\n"
      "}\n");
  } else {
    printer->Print(variables_,
      "for (int i = 0; i < $name$_.size(); i++) {\n"
      "  output.write$capitalized_type$($number$, $name$_.get(i));\n"
      "}\n");
  }
}

void RepeatedPrimitiveFieldGenerator::
GenerateSerializedSizeCode(io::Printer* printer) const {
  printer->Print(variables_,
    "{\n"
    "  int dataSize = 0;\n");
  printer->Indent();

  if (FixedSize(GetType(descriptor_)) == -1) {
    printer->Print(variables_,
      "for (int i = 0; i < $name$_.size(); i++) {\n"
      "  dataSize += com.google.protobuf.CodedOutputStream\n"
      "    .compute$capitalized_type$SizeNoTag($name$_.get(i));\n"
      "}\n");
  } else {
    printer->Print(variables_,
      "dataSize = $fixed_size$ * get$capitalized_name$List().size();\n");
  }

  printer->Print(
      "size += dataSize;\n");

  if (descriptor_->options().packed()) {
    printer->Print(variables_,
      "if (!get$capitalized_name$List().isEmpty()) {\n"
      "  size += $tag_size$;\n"
      "  size += com.google.protobuf.CodedOutputStream\n"
      "      .computeInt32SizeNoTag(dataSize);\n"
      "}\n");
  } else {
    printer->Print(variables_,
      "size += $tag_size$ * get$capitalized_name$List().size();\n");
  }

  // cache the data size for packed fields.
  if (descriptor_->options().packed()) {
    printer->Print(variables_,
      "$name$MemoizedSerializedSize = dataSize;\n");
  }

  printer->Outdent();
  printer->Print("}\n");
}

void RepeatedPrimitiveFieldGenerator::
GenerateEqualsCode(io::Printer* printer) const {
  printer->Print(variables_,
    "result = result && get$capitalized_name$List()\n"
    "    .equals(other.get$capitalized_name$List());\n");
}

void RepeatedPrimitiveFieldGenerator::
GenerateHashCode(io::Printer* printer) const {
  printer->Print(variables_,
    "if (get$capitalized_name$Count() > 0) {\n"
    "  hash = (37 * hash) + $constant_name$;\n"
    "  hash = (53 * hash) + get$capitalized_name$List().hashCode();\n"
    "}\n");
}

string RepeatedPrimitiveFieldGenerator::GetBoxedType() const {
  return BoxedPrimitiveTypeName(GetJavaType(descriptor_));
}

}  // namespace java
}  // namespace compiler
}  // namespace protobuf
}  // namespace google


text:
"""
This file contains API calls and data
"""

import six
from sys import version_info
from termcolor import colored
from .data import *
from os import geteuid
import netifaces

__version__ = "1.0.4"
__all__ = ["run_console", "run", "GlobalParameters"]

# --------------------------------------------------------------------------
#
# Command line options
#
# --------------------------------------------------------------------------
def run_console(config):
    """
    :param config: GlobalParameters option instance
    :type config: `GlobalParameters`

    :raises: TypeError
    """
    if not isinstance(config, GlobalParameters):
        raise TypeError("Expected GlobalParameters, got '%s' instead" % type(config))

    six.print_(colored("[*]", "blue"), "Starting Pyersinia execution -->")
    run(config)
    six.print_(colored("\n[*]", "yellow"), "Attack stopped. ")

# ----------------------------------------------------------------------
#
# API call
#
# ----------------------------------------------------------------------
def run(config):
    """
    :param config: GlobalParameters option instance
    :type config: `GlobalParameters`

    :raises: TypeError
    """
    if not isinstance(config, GlobalParameters):
        raise TypeError("Expected GlobalParameters, got '%s' instead" % type(config))

    # --------------------------------------------------------------------------
    # Evaluate the type of attack and the interface to be launched
    # --------------------------------------------------------------------------
    if geteuid():
        six.print_(colored("[!]", "red"), "DENIED! Please run as root.")
        exit()

    # --------------------------------------------------------------------------
    # Evaluate the type of attack and the interface to be launched
    # --------------------------------------------------------------------------
    ifaceList = netifaces.interfaces()      # List of interfaces
    if config.interface[0] in ifaceList:

        # ARP attack import
        if config.attack == ['arp_poison']:

            from .libs.plugins.arp_poison import run_attack
            six.print_(colored("[*]", "blue"), "Running ARP SPOOF ATTACK...")

        # Dhcp_discover_dos attack import
        elif config.attack == ['dhcp_discover_dos']:
            from .libs.plugins.dhcp_discover_dos import run_attack
            six.print_(colored("[*]", "blue"), "Running DHCP DISCOVER DoS ATTACK...")

        # Stp_tcn attack import
        elif config.attack == ['stp_tcn']:
            from .libs.plugins.stp_tcn import run_attack
            six.print_(colored("[*]", "blue"), "Running STP TCN ATTACK...")

        # Stp_conf attack import
        elif config.attack == ['stp_conf']:
            from .libs.plugins.stp_bdpu_conf import run_attack
            six.print_(colored("[*]", "blue"), "Running STP CONF ATTACK...")

        # Stp_root attack import
        elif config.attack == ['stp_root_role']:
            from .libs.plugins.stp_root_role import run_attack
            six.print_(colored("[*]", "blue"), "Running STP ROOT ROLE ATTACK...")
        elif config.attack == ['dhcp_rogue']:
            from .libs.plugins.dhcp_rogue import run_attack
            six.print_(colored("[*]", "blue"), "Running DHCP ROGUE ATTACK...")
        elif config.attack == ['xss']:
            from .libs.plugins.xss import run_attack
            six.print_(colored("[*]", "blue"), "Running PoC DHCP XSS ...")

        # New attack import
        # ...
        # ...

        else:
            six.print_(colored("[!]", "red"), "ERROR! Attack does not exist.")
            exit()

    else:
        six.print_(colored("[!]", "red"), "ERROR! You are not connected to require interface.")
        exit()

    # Run attack chosen
    run_attack(config)


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;

/* @var $this yii\web\View */
/* @var $model app\models\UsersLevelSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>
    <?= $form->field($model, 'user_id')->dropDownList(ArrayHelper::merge(['' => '请选择学员'],ArrayHelper::map(\app\models\Users::getAll(),'id', 'username')),['style'=>'width:200px']) ?>

    <?= $form->field($model, 'level_id')->dropDownList(ArrayHelper::map(\app\models\Level::getAllByEnd(),'id', 'name'),['style'=>'width:100px']) ?>

    <?= $form->field($model, 'certificate_number')->textInput(['style'=>'width:200px']) ?>

    <?php // echo $form->field($model, 'receive_address') ?>

    <?php // echo $form->field($model, 'postcode') ?>

    <?php // echo $form->field($model, 'is_pay') ?>

    <?php // echo $form->field($model, 'create_time') ?>

    <?php // echo $form->field($model, 'update_time') ?>

    <?php // echo $form->field($model, 'update_user') ?>

        <?= Html::submitButton('搜索', ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton('重置', ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
/*
 *   This file is part of the computer assignment for the
 *   Information Retrieval course at KTH.
 *
 *   First version:  Johan Boye, 2010
 *   Second version: Johan Boye, 2012
 *   Additions: Hedvig Kjellström, 2012-14
 */

package ir;

import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeMap;
import java.util.LinkedList;

public interface Index {

    /* Index types */
    public static final int HASHED_INDEX = 0;

    /* Query types */
    public static final int INTERSECTION_QUERY = 0;
    public static final int PHRASE_QUERY = 1;
    public static final int RANKED_QUERY = 2;

    /* Ranking types */
    public static final int TF_IDF = 0;
    public static final int PAGERANK = 1;
    public static final int COMBINATION = 2;

    /* Structure types */
    public static final int UNIGRAM = 0;
    public static final int BIGRAM = 1;
    public static final int SUBPHRASE = 2;

    /* Searching types */
    public static final int ALLFRAMES = 0;
    public static final int CLOSEFRAMES = 1;

    public HashMap<String, String> docIDs = new HashMap<String,String>();
    public HashMap<String,Integer> docLengths = new HashMap<String,Integer>();
    public HashMap<String,Integer> docLengthsExtended = new HashMap<String,Integer>();
    public HashMap<String,Double> docTimeFrame = new HashMap<String,Double>();
    public LinkedList<Double> pageRank = new LinkedList<Double>();

    public void insert( String token, int docID, int frame);
    public void insert(String token, PostingsList postings);
    public Iterator<String> getDictionary();
    public TreeMap<String,PostingsList> order();
    public PostingsList getPostings( String token );
    public boolean containsToken (String token);
    public int getSize();
    public PostingsList search( Query query, int queryType, int rankingType, int frameType, double weightPopularity, double[] popularityScores, int distanceFrames, boolean optimization, double idf_threshold, boolean addition, double sweight_addition);
    public void cleanup();

}


text:
package test.org.blueskiron.goldilocks.membership;

import static org.junit.Assert.assertTrue;

import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.LongAdder;

import org.blueskiron.goldilocks.api.statemachine.Command;
import org.blueskiron.goldilocks.api.statemachine.StateMachine;
import org.junit.Before;
import org.junit.Test;

public class TestKVStore {

    static final String STATE_MACHINE_NAME = "TestKVStore";
    private final StateMachine<KVStore, Command<KVStore>> sm = new KVStore();
    private final LongAdder la = new LongAdder();
    private final List<Command<KVStore>> commands = new LinkedList<Command<KVStore>>();

    @Before
    public void setup() {
        commands.add(new KVStore.InitialCommand(STATE_MACHINE_NAME));
        int size = 10;
        while (size > 0) {
            commands.add(generateCommand(STATE_MACHINE_NAME));
            size--;
        }
    }

    @Test
    public void test() {
        Command<KVStore> initial = commands.remove(0);
        sm.applyFunction().apply(0L, initial);
        commands.forEach(c -> {
            final long index = la.longValue();
            sm.applyFunction().apply(index, c);
            la.increment();
        });
        KVStore kvsm = (KVStore) sm;
        kvsm.getKvMap().forEach((k, v) -> System.out.println(k + " --> " + v));
        assertTrue(kvsm.getKvMap().size() == 10);
    }

    private static Command<KVStore> generateCommand(String smName) {
        return new Command<KVStore>() {

            private static final long serialVersionUID = 1L;

            @Override
            public String getStateMachineId() {
                return smName;
            }

            @Override
            public Class<KVStore> getStateMachineType() {
                return KVStore.class;
            }

            @Override
            public Object[] getFunctionParameters() {
                return new Object[]{UUID.randomUUID().toString()};
            }
        };
    }

    /**
     * @return the sm
     */
    public StateMachine<KVStore, Command<KVStore>> getStateMachine() {
      return sm;
    }

    /**
     * @return the commands
     */
    public List<Command<KVStore>> getCommands() {
      return commands;
    }
}


text:
'use strict';

//
// An Ampersand.js Collection of Img models
//

var Img = require('./image.js');
var Collection = require('ampersand-collection');

module.exports = Collection.extend({
    model: Img
});


text:
cask "atemosc" do
  version "3.1.6"
  sha256 "d4487e5d81da790a05ad3c0f3198792c8cfc88092352dc3bef0120c5078e69c5"

  url "https://github.com/SteffeyDev/atemOSC/releases/download/v#{version}/atemOSC_#{version}.dmg",
      verified: "github.com/SteffeyDev/atemOSC/"
  appcast "https://github.com/SteffeyDev/atemOSC/releases.atom"
  name "atemOSC"
  desc "Control BMD ATEM video switchers with OSC"
  homepage "http://www.atemosc.com/"

  app "atemOSC.app"

  zap trash: "~/Library/Caches/cc.buechele.atemOSC"
end


text:
describe TodoBot::Task, type: :model do
  describe 'relations' do
    it { is_expected.to belong_to(:list) }
    it { is_expected.to belong_to(:user) }
  end
end


text:
package com.google.javascript.jscomp;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.jscomp.NodeTraversal.Callback;
import com.google.javascript.rhino.Node;

import java.util.HashSet;
import java.util.Set;

/**
 * An optimization pass to prune J2CL clinits.
 */
public class J2clClinitPrunerPass implements CompilerPass {

  private final AbstractCompiler compiler;

  J2clClinitPrunerPass(AbstractCompiler compiler) {
    this.compiler = compiler;
  }

  @Override
  public void process(Node externs, Node root) {
    NodeTraversal.traverseEs6(compiler, root, new RedundantClinitPruner());
    NodeTraversal.traverseEs6(compiler, root, new LookAheadRedundantClinitPruner());
    NodeTraversal.traverseEs6(compiler, root, new EmptyClinitPruner());
  }

  /**
   * Removes redundant clinit calls inside method body if it is guaranteed to be called earlier.
   */
  private static final class RedundantClinitPruner implements Callback {
    private HierarchicalSet<String> clinitsCalledAtBranch = new HierarchicalSet<>(null);

    @Override
    public boolean shouldTraverse(NodeTraversal t, Node node, Node parent) {
      if (parent != null && NodeUtil.isFunctionDeclaration(node)) {
        // Unlike function expressions, we don't know when the function in a function declaration
        // will be executed so lets start a new traversal to avoid inheriting anything from the
        // current branch.
        NodeTraversal.traverseEs6(t.getCompiler(), node, new RedundantClinitPruner());
        return false;
      }

      if (isNewControlBranch(parent)) {
        clinitsCalledAtBranch = new HierarchicalSet(clinitsCalledAtBranch);
        if (isClinitMethod(parent)) {
          // Adds itself as any of your children can assume clinit is already called.
          clinitsCalledAtBranch.add(NodeUtil.getName(parent));
        }
      }

      return true;
    }

    @Override
    public void visit(NodeTraversal t, Node node, Node parent) {
      tryRemovingClinit(t, node, parent);

      if (isNewControlBranch(parent)) {
        clinitsCalledAtBranch = clinitsCalledAtBranch.parent;
      }
    }

    private void tryRemovingClinit(NodeTraversal t, Node node, Node parent) {
      String clinitName = node.isCall() ? getClinitMethodName(node.getFirstChild()) : null;
      if (clinitName == null) {
        return;
      }

      if (clinitsCalledAtBranch.add(clinitName)) {
        // This is the first time we are seeing this clinit so cannot remove it.
        return;
      }

      // Replacing with '0' is a simple way of removing without introducing invalid AST.
      parent.replaceChild(node, Node.newNumber(0).useSourceInfoIfMissingFrom(node));
      t.getCompiler().reportCodeChange();
    }

    private static boolean isNewControlBranch(Node n) {
      return n != null
          && (NodeUtil.isControlStructure(n)
              || n.isHook()
              || n.isAnd()
              || n.isOr()
              || n.isFunction());
    }
  }

  // TODO(michaelthomas): Prune clinit calls in functions, if previous functions or the immediate
  // next function guarantees clinit call. With that we won't need this pass.
  /**
   * Prunes clinit calls which immediately precede calls to a static function which calls the same
   * clinit. e.g. "Foo.clinit(); return new Foo()" -> "return new Foo()"
   */
  private static final class LookAheadRedundantClinitPruner extends AbstractPostOrderCallback {

    @Override
    public void visit(NodeTraversal t, Node node, Node parent) {
      if (!node.isExprResult()) {
        return;
      }

      // Find clinit calls.
      String clinitName =
          node.getFirstChild().isCall() ? getClinitMethodName(node.getFirstFirstChild()) : null;
      if (clinitName == null) {
        return;
      }

      // Check for calls to a static method immediately following the clinit call.
      Node callOrNewNode = getCallOrNewNode(node.getNext());
      if (callOrNewNode == null || !callOrNewNode.getFirstChild().isName()) {
        return;
      }

      // Check that the call isn't a recursive call to the same function.
      Node enclosingFunction = NodeUtil.getEnclosingFunction(node);
      if (enclosingFunction == null || callOrNewNode.getFirstChild().getString()
          .equals(NodeUtil.getNearestFunctionName(enclosingFunction))) {
        return;
      }

      // Find the definition of the function being called.
      Var var = t.getScope().getVar(callOrNewNode.getFirstChild().getString());
      if (var == null || var.getInitialValue() == null || !var.getInitialValue().isFunction()) {
        return;
      }

      // Check that the clinit is safe to prune.
      Node staticFnNode = var.getInitialValue();
      if (callsClinit(staticFnNode, clinitName) && hasSafeArguments(t, callOrNewNode)) {
        parent.removeChild(node);
        t.getCompiler().reportCodeChange();
      }
    }

    /**
     * Returns whether the arguments to the specified call/new node are "safe". i.e. they are only
     * parameters to the enclosing function or literal values (and not e.g. a static field reference
     * which might need the clinit we are trying to remove).
     */
    private boolean hasSafeArguments(NodeTraversal t, Node callOrNewNode) {
      Node child = callOrNewNode.getSecondChild();
      while (child != null) {
        if (!NodeUtil.isLiteralValue(child, false /* includeFunctions */)
            && !isParameter(t, child)) {
          return false;
        }
        child = child.getNext();
      }
      return true;
    }

    /** Returns whether the specified node is defined as a parameter to its enclosing function. */
    private boolean isParameter(NodeTraversal t, Node n) {
      if (!n.isName()) {
        return false;
      }
      Var var = t.getScope().getVar(n.getString());
      return var.getParentNode().isParamList();
    }

    /**
     * Returns the call node associated with the specified node if one exists, otherwise returns
     * null.
     */
    private Node getCallOrNewNode(Node n) {
      if (n == null) {
        return null;
      }
      switch (n.getToken()) {
        case EXPR_RESULT:
        case RETURN:
          return getCallOrNewNode(n.getFirstChild());
        case CALL:
        case NEW:
          return n;
        case CONST:
        case LET:
        case VAR:
          return n.getChildCount() == 1 ? getCallOrNewNode(n.getFirstFirstChild()) : null;
        default:
          return null;
      }
    }

    /** Returns whether the specified function contains a call to the specified clinit. */
    private boolean callsClinit(Node fnNode, String clinitName) {
      Preconditions.checkNotNull(clinitName);
      // TODO(michaelthomas): Consider checking all children, but watch out for return statements
      // that could short-circuit the clinit.
      Node child = fnNode.getLastChild().getFirstChild();
      return child != null
          && child.isExprResult()
          && child.getFirstChild().isCall()
          && clinitName.equals(getClinitMethodName(child.getFirstFirstChild()));
    }
  }

  /**
   * A traversal callback that removes the body of empty clinits.
   */
  private static final class EmptyClinitPruner extends AbstractPostOrderCallback {

    @Override
    public void visit(NodeTraversal t, Node node, Node parent) {
      if (!isClinitMethod(node)) {
        return;
      }

      trySubstituteEmptyFunction(node, t.getCompiler());
    }

    /**
     * Clears the body of any functions are are equivalent to empty functions.
     */
    private void trySubstituteEmptyFunction(Node fnNode, AbstractCompiler compiler) {
      String fnQualifiedName = NodeUtil.getName(fnNode);

      // Ignore anonymous/constructor functions.
      if (Strings.isNullOrEmpty(fnQualifiedName)) {
        return;
      }

      Node body = fnNode.getLastChild();
      if (!body.hasChildren()) {
        return;
      }

      // Ensure that the first expression in the body is setting itself to the empty function and
      // there are no other expressions.
      Node firstExpr = body.getFirstChild();
      if (!isAssignToEmptyFn(firstExpr, fnQualifiedName) || firstExpr.getNext() != null) {
        return;
      }

      body.removeChild(firstExpr);
      compiler.reportCodeChange();
    }

    private static boolean isAssignToEmptyFn(Node node, String enclosingFnName) {
      if (!NodeUtil.isExprAssign(node)) {
        return false;
      }

      Node lhs = node.getFirstChild().getFirstChild();
      Node rhs = node.getFirstChild().getLastChild();
      return NodeUtil.isEmptyFunctionExpression(rhs) && lhs.matchesQualifiedName(enclosingFnName);
    }
  }

  private static boolean isClinitMethod(Node node) {
    return node.isFunction() && isClinitMethodName(NodeUtil.getName(node));
  }

  private static String getClinitMethodName(Node fnNode) {
    String fnName = fnNode.getQualifiedName();
    return isClinitMethodName(fnName) ? fnName : null;
  }

  private static boolean isClinitMethodName(String fnName) {
    // The '.$clinit' case) only happens when collapseProperties is off.
    return fnName != null && (fnName.endsWith("$$0clinit") || fnName.endsWith(".$clinit"));
  }

  /**
   * A minimalist implelementation of a hierarchical Set where an item might exist in current set or
   * any of its parents.
   */
  private static class HierarchicalSet<T> {
    private Set<T> currentSet = new HashSet<>();
    private HierarchicalSet<T> parent;

    public HierarchicalSet(HierarchicalSet parent) {
      this.parent = parent;
    }

    public boolean add(T o) {
      return !parentsContains(o) && currentSet.add(o);
    }

    /** Returns true either my parent or any of its parents contains the item. */
    private boolean parentsContains(Object o) {
      return parent != null && (parent.currentSet.contains(o) || parent.parentsContains(o));
    }
  }
}


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Oobe update screen implementation.
 */

cr.define('oobe', function() {
  /**
   * Creates a new oobe screen div.
   * @constructor
   * @extends {HTMLDivElement}
   */
  var UpdateScreen = cr.ui.define('div');

  /** @const */ var ELLIPSIS = ['', '.', '..', '...'];
  /** @const */ var ELLIPSIS_ANIMATION_TIMEOUT_MS = 1000;

  /**
   * Registers with Oobe.
   */
  UpdateScreen.register = function() {
    var screen = $('update');
    UpdateScreen.decorate(screen);
    Oobe.getInstance().registerScreen(screen);
  };

  UpdateScreen.prototype = {
    __proto__: HTMLDivElement.prototype,

    /** @inheritDoc */
    decorate: function() {
    },

    onBeforeShow: function(data) {
      UpdateScreen.startEllipsisAnimation();
    },

    onBeforeHide: function() {
      UpdateScreen.stopEllipsisAnimation();
    },

    /**
     * Header text of the screen.
     * @type {string}
     */
    get header() {
      return localStrings.getString('updateScreenTitle');
    },

    /**
     * Buttons in oobe wizard's button strip.
     * @type {array} Array of Buttons.
     */
    get buttons() {
      return null;
    },

    /**
     * Cancels the screen.
     */
    cancel: function() {
      // It's safe to act on the accelerator even if it's disabled on official
      // builds, since Chrome will just ignore the message in that case.
      var updateCancelHint = $('update-cancel-hint').firstElementChild;
      updateCancelHint.textContent =
          localStrings.getString('cancelledUpdateMessage');
      chrome.send('cancelUpdate');
    },
  };

  var ellipsis_animation_active = false;

  /**
   * Updates number of dots in the ellipsis.
   *
   * @private
   * @param {number} count Number of dots that should be shown.
   */
  function updateEllipsisAnimation_(count) {
    $('update-checking-ellipsis').textContent = ELLIPSIS[count];
    if (ellipsis_animation_active) {
      window.setTimeout(function() {
          updateEllipsisAnimation_((count + 1) % ELLIPSIS.length);
        }, ELLIPSIS_ANIMATION_TIMEOUT_MS);
    }
  };

  /**
   * Makes 'press Escape to cancel update' hint visible.
   */
  UpdateScreen.enableUpdateCancel = function() {
    $('update-cancel-hint').hidden = false;
  };

  /**
   * Starts animation for tail ellipses in "Checking for update..." label.
   */
  UpdateScreen.startEllipsisAnimation = function() {
    ellipsis_animation_active = true;
    updateEllipsisAnimation_(0);
  };

  /**
   * Stops animation for tail ellipses in "Checking for update..." label.
   */
  UpdateScreen.stopEllipsisAnimation = function() {
    ellipsis_animation_active = false;
  };

  return {
    UpdateScreen: UpdateScreen
  };
});


text:
package org.nikosoft.oanda.bot.streaming

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

import akka.NotUsed
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpRequest
import akka.http.scaladsl.model.headers.RawHeader
import akka.stream.{ActorMaterializer, ClosedShape}
import akka.stream.scaladsl.{Broadcast, Flow, Framing, GraphDSL, RunnableGraph, Sink, Source, ZipWith}
import akka.util.ByteString
import org.json4s.jackson.Serialization.read
import org.nikosoft.oanda.GlobalProperties
import org.nikosoft.oanda.api.ApiModel.PrimitivesModel.InstrumentName
import org.nikosoft.oanda.api.JsonSerializers
import org.nikosoft.oanda.api.`def`.InstrumentApi.CandlesResponse
import org.nikosoft.oanda.bot.streaming.InvestingComStreamer.{Advices, SummaryAverages, SummaryTechnical, advisorSource}
import org.nikosoft.oanda.instruments.Model.CandleStick

import scala.concurrent.duration.DurationDouble
import scala.util.{Failure, Success}
import org.json4s.jackson.Serialization._

object CandleWithInvestingComStreamer extends App {

  implicit val formats = JsonSerializers.formats

  implicit val actorSystem = ActorSystem("streamer")
  implicit val materializer = ActorMaterializer()

  def url = s"/v3/instruments/${InstrumentName("EUR_USD").value}/candles?" +
//    s"from=${LocalDateTime.now.format(DateTimeFormatter.ISO_DATE_TIME) + "Z"}&" +
//    s"to=${LocalDateTime.now.plusDays(1).format(DateTimeFormatter.ISO_DATE_TIME) + "Z"}&" +
    s"count=1&granularity=M1"

  val flow: Flow[String, CandleStick, NotUsed] = Flow[String].map(_ => HttpRequest(uri = url, headers = List(RawHeader("Authorization", GlobalProperties.OandaToken))) -> 1)
    .via(Http().cachedHostConnectionPoolHttps("api-fxtrade.oanda.com"))
    .collect { case (Success(response), _) => response }
    .flatMapConcat(_.entity.dataBytes.via(
      Framing.delimiter(ByteString("\n"), maximumFrameLength = 999999, allowTruncation = true)
        .map(_.utf8String)
        .map(read[CandlesResponse])
        .mapConcat(_.candles.toList)))
    .mapConcat(candle => candle.mid.map(CandleStick.toCandleStick(candle, _)).toList)

  RunnableGraph.fromGraph(GraphDSL.create() { implicit builder =>
    import GraphDSL.Implicits._

    val zip = builder.add(ZipWith[CandleStick, Advices, Advices, Advices, Advices, Advices, (CandleStick, Advices, Advices, Advices, Advices, Advices)]((a, b, c, d, e, f) => (a, b, c, d, e, f)))
    val tick = Source.tick(0.minutes, 1.minute, "_")
    val broadcast = builder.add(Broadcast[String](6))

    val printlnSink = Sink.foreach[(CandleStick, Advices, Advices, Advices, Advices, Advices)](a => {
      println(s"${a._1}")
      println(s"${a._2.find(_._1 == SummaryAverages).get} - ${a._2.find(_._1 == SummaryTechnical).get}")
      println(s"${a._3.find(_._1 == SummaryAverages).get} - ${a._3.find(_._1 == SummaryTechnical).get}")
      println(s"${a._4.find(_._1 == SummaryAverages).get} - ${a._4.find(_._1 == SummaryTechnical).get}")
      println(s"${a._5.find(_._1 == SummaryAverages).get} - ${a._5.find(_._1 == SummaryTechnical).get}")
      println(s"${a._6.find(_._1 == SummaryAverages).get} - ${a._6.find(_._1 == SummaryTechnical).get}")
      println("-----")
    })

    // @formatter:off
    tick ~> broadcast
            broadcast ~> flow                ~> zip.in0
            broadcast ~> advisorSource(60)   ~> zip.in1
            broadcast ~> advisorSource(300)  ~> zip.in2
            broadcast ~> advisorSource(900)  ~> zip.in3
            broadcast ~> advisorSource(1800) ~> zip.in4
            broadcast ~> advisorSource(3600) ~> zip.in5
                                                zip.out ~> printlnSink
    // @formatter:on

    ClosedShape
  }).run()

}


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

namespace Arch.CFX.AppInternals.Configuration
{

    public class PropertyChangeEventArgs : EventArgs
    {
        public string PropertyName
        { get; set; }
        public object NewValue
        { get; set; }
        public object OldValue
        { get; set; }
    }
}


text:
namespace Azure.Analytics.Synapse.Artifacts.Models
{
    /// <summary> The exposure control response. </summary>
    internal partial class ExposureControlResponse
    {
        /// <summary> Initializes a new instance of ExposureControlResponse. </summary>
        internal ExposureControlResponse()
        {
        }

        /// <summary> The feature name. </summary>
        public string FeatureName { get; }
        /// <summary> The feature value. </summary>
        public string Value { get; }
    }
}


text:
"""
Collects data from squid servers

#### Dependencies

"""

import re
import socket
import diamond.collector

class SquidCollector(diamond.collector.Collector):

    def __init__(self, *args, **kwargs):
        super(SquidCollector, self).__init__(*args, **kwargs)
        self.squid_hosts = {}

        host_pattern = re.compile("(([^@]+)@)?([^:]+)(:([0-9]+))?")
        self.stat_pattern = re.compile("^([^ ]+) = ([0-9\.]+)$")

        for host in self.config['hosts']:
            matches = host_pattern.match(host)

            if matches.group(5):
                port = matches.group(5)
            else:
                port = 3128

            if matches.group(2):
                nick = matches.group(2)
            else:
                nick = port

            self.squid_hosts[nick] = {
                'host': matches.group(3),
                'port': int(port)
            }

    def get_default_config_help(self):
        config_help = super(SquidCollector, self).get_default_config_help()
        config_help.update({
            'hosts': 'List of hosts to collect from. Format is '
            + '[nickname@]host[:port], [nickname@]host[:port], etc',
        })
        return config_help

    def get_default_config(self):
        """
        Returns the default collector settings
        """
        config = super(SquidCollector, self).get_default_config()
        config.update({
            'hosts': ['localhost:3128'],
            'path': 'squid',
        })
        return config

    def _getData(self, host, port):
        try:
            squid_sock = socket.socket()
            squid_sock.connect((host, int(port)))
            squid_sock.settimeout(0.25)
            squid_sock.sendall("GET cache_object://localhost/counters HTTP/1.0"
                               + "\r\nHost: localhost\r\nAccept: */*\r\nConnec"
                               + "tion: close\r\n\r\n")

            fulldata = ''

            while True:
                data = squid_sock.recv(1024)
                if not data:
                    break
                fulldata = fulldata + data
        except Exception, e:
            self.log.error('Couldnt connect to squid: %s', e)
            return None
        squid_sock.close()

        return fulldata

    def collect(self):
        for nickname in self.squid_hosts.keys():
            squid_host = self.squid_hosts[nickname]

            fulldata = self._getData(squid_host['host'],
                                     squid_host['port']).splitlines()

            for data in fulldata:
                matches = self.stat_pattern.match(data)
                if matches:
                    self.publish_counter("%s.%s" % (nickname,
                                                    matches.group(1)),
                                         float(matches.group(2)))


text:
<?php

/**
 * iThemes file handler.
 *
 * Writes to core files including wp-config.php, htaccess and nginx.conf.
 *
 * @package iThemes_Security
 *
 * @since   4.0.0
 */
final class ITSEC_Files {
	static $instance = false;

	private function __construct() {

		add_action( 'itsec-new-blacklisted-ip', array( $this, 'quick_ban' ) );

	}

	public static function get_instance() {
		if ( ! self::$instance ) {
			self::$instance = new self;
		}

		return self::$instance;
	}

	/**
	 * Check the setting that allows writing files.
	 *
	 * @since 1.15.0
	 *
	 * @return bool True if files can be written to, false otherwise.
	 */
	public static function can_write_to_files() {
		$can_write = (bool) ITSEC_Modules::get_setting( 'global', 'write_files' );
		$can_write = apply_filters( 'itsec_filter_can_write_to_files', $can_write );

		return $can_write;
	}

	public static function regenerate_wp_config( $add_responses = true ) {
		require_once( ITSEC_Core::get_core_dir() . '/lib/class-itsec-lib-config-file.php' );

		$result = ITSEC_Lib_Config_File::update_wp_config();
		$success = ! is_wp_error( $result );

		if ( $add_responses && is_wp_error( $result ) ) {
			ITSEC_Response::add_error( $result );
		}

		return $success;
	}

	public static function regenerate_server_config( $add_responses = true ) {
		require_once( ITSEC_Core::get_core_dir() . '/lib/class-itsec-lib-config-file.php' );

		$result = ITSEC_Lib_Config_File::update_server_config();
		$success = ! is_wp_error( $result );
		$server = ITSEC_Lib_Utility::get_web_server();

		if ( $add_responses ) {
			if ( is_wp_error( $result ) ) {
				ITSEC_Response::add_error( $result );

				$file = ITSEC_Lib_Config_File::get_server_config_file_path();
			} else if ( 'nginx' === $server ) {
				ITSEC_Response::add_message( __( 'You must restart your NGINX server for the changes to take effect.', 'better-wp-security' ) );
			}
		}

		return $success;
	}

	/**
	 * Execute activation functions.
	 *
	 * Writes necessary information to wp-config and .htaccess upon plugin activation.
	 *
	 * @since  4.0.0
	 *
	 * @return void
	 */
	public function do_activate() {
		self::regenerate_wp_config( false );
		self::regenerate_server_config( false );
	}

	/**
	 * Execute deactivation functions.
	 *
	 * Writes necessary information to wp-config and .htaccess upon plugin deactivation.
	 *
	 * @since  4.0.0
	 *
	 * @return void
	 */
	public function do_deactivate() {
		require_once( ITSEC_Core::get_core_dir() . '/lib/class-itsec-lib-config-file.php' );

		ITSEC_Lib_Config_File::reset_wp_config();
		ITSEC_Lib_Config_File::reset_server_config();
	}

	/**
	 * Process quick ban of host.
	 *
	 * Immediately adds the supplied host to the .htaccess file for banning.
	 *
	 * @since 4.0.0
	 *
	 * @param string $host the host to ban
	 *
	 * @return bool true on success or false on failure
	 */
	public function quick_ban( $host ) {
		$host = trim( $host );

		require_once( ITSEC_Core::get_core_dir() . '/lib/class-itsec-lib-ip-tools.php' );

		if ( ! ITSEC_Lib_IP_Tools::validate( $host ) ) {
			return false;
		}

		$host_rule = '# ' . __( 'Quick ban IP. Will be updated on next formal rules save.', 'better-wp-security' ) . "\n";

		if ( 'nginx' === ITSEC_Lib::get_server() ) {
			$host_rule .= "\tdeny $host;\n";
		} else if ( 'apache' === ITSEC_Lib::get_server() ) {
			$dhost = str_replace( '.', '\\.', $host ); //re-define $dhost to match required output for SetEnvIf-RegEX

			$host_rule .= "SetEnvIF REMOTE_ADDR \"^$dhost$\" DenyAccess\n"; //Ban IP
			$host_rule .= "SetEnvIF X-FORWARDED-FOR \"^$dhost$\" DenyAccess\n"; //Ban IP from Proxy-User
			$host_rule .= "SetEnvIF X-CLUSTER-CLIENT-IP \"^$dhost$\" DenyAccess\n"; //Ban IP for Cluster/Cloud-hosted WP-Installs
			$host_rule .= "<IfModule mod_authz_core.c>\n";
			$host_rule .= "\t<RequireAll>\n";
			$host_rule .= "\t\tRequire all granted\n";
			$host_rule .= "\t\tRequire not env DenyAccess\n";
			$host_rule .= "\t\tRequire not ip $host\n";
			$host_rule .= "\t</RequireAll>\n";
			$host_rule .= "</IfModule>\n";
			$host_rule .= "<IfModule !mod_authz_core.c>\n";
			$host_rule .= "\tOrder allow,deny\n";
			$host_rule .= "\tDeny from env=DenyAccess\n";
			$host_rule .= "\tDeny from $host\n";
			$host_rule .= "\tAllow from all\n";
			$host_rule .= "</IfModule>\n";
		}

		require_once( ITSEC_Core::get_core_dir() . '/lib/class-itsec-lib-config-file.php' );
		$result = ITSEC_Lib_Config_File::append_server_config( $host_rule );

		if ( is_wp_error( $result ) ) {
			return false;
		}

		return true;
	}

	/**
	 * Attempt to get a lock for atomic operations.
	 *
	 * Tries to get a more robust lock on the file in question. Useful in situations where automatic
	 * file locking doesn't work.
	 *
	 * @since  4.0.0
	 *
	 * @param string $lock_file file name of lock
	 * @param int    $exp       seconds until lock expires
	 *
	 * @return bool true if lock was achieved, else false
	 */
	public function get_file_lock( $lock_file, $exp = 180 ) {

		if ( ITSEC_Modules::get_setting( 'global', 'lock_file' ) ) {
			return true;
		}

		clearstatcache();

		$lock_file = ITSEC_Core::get_storage_dir() . '/' . sanitize_text_field( $lock_file ) . '.lock';
		$dir_age   = @filectime( $lock_file );

		if ( false === @mkdir( $lock_file ) ) {

			if ( false !== $dir_age ) {

				if ( ( time() - $dir_age ) > intval( $exp ) ) { //see if the lock has expired

					@rmdir( $lock_file );
					@mkdir( $lock_file );

				} else { //couldn't get the lock

					return false;

				}

			} else {

				return false;

			}

		}

		return true; //file lock was achieved

	}

	/**
	 * Release the lock.
	 *
	 * Releases a file lock to allow others to use it.
	 *
	 * @since  4.0.0
	 *
	 * @param string $lock_file file name of lock
	 *
	 * @return bool true if released, false otherwise
	 */
	public function release_file_lock( $lock_file ) {
		if ( ITSEC_Modules::get_setting( 'global', 'lock_file' ) ) {
			return true;
		}

		require_once( ITSEC_Core::get_core_dir() . '/lib/class-itsec-lib-directory.php' );

		$lock_file = ITSEC_Core::get_storage_dir() . '/' . sanitize_text_field( $lock_file ) . '.lock';

		$result = ITSEC_Lib_Directory::remove( $lock_file );

		if ( is_wp_error( $result ) ) {
			return false;
		}

		return true;
	}
}


text:
package io.grpc.xds;

import static com.google.common.base.Preconditions.checkNotNull;
import static io.grpc.xds.InternalXdsAttributes.ATTR_DRAIN_GRACE_NANOS;
import static io.grpc.xds.InternalXdsAttributes.ATTR_FILTER_CHAIN_SELECTOR_MANAGER;
import static io.grpc.xds.XdsServerWrapper.ATTR_SERVER_ROUTING_CONFIG;
import static io.grpc.xds.internal.security.SecurityProtocolNegotiators.ATTR_SERVER_SSL_CONTEXT_PROVIDER_SUPPLIER;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;
import com.google.common.collect.Iterables;
import com.google.protobuf.UInt32Value;
import io.grpc.Attributes;
import io.grpc.internal.ObjectPool;
import io.grpc.netty.GrpcHttp2ConnectionHandler;
import io.grpc.netty.InternalGracefulServerCloseCommand;
import io.grpc.netty.InternalProtocolNegotiationEvent;
import io.grpc.netty.InternalProtocolNegotiator;
import io.grpc.netty.InternalProtocolNegotiator.ProtocolNegotiator;
import io.grpc.netty.ProtocolNegotiationEvent;
import io.grpc.xds.EnvoyServerProtoData.CidrRange;
import io.grpc.xds.EnvoyServerProtoData.ConnectionSourceType;
import io.grpc.xds.EnvoyServerProtoData.FilterChain;
import io.grpc.xds.EnvoyServerProtoData.FilterChainMatch;
import io.grpc.xds.XdsServerWrapper.ServerRoutingConfig;
import io.grpc.xds.internal.Matchers.CidrMatcher;
import io.grpc.xds.internal.security.SslContextProviderSupplier;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AsciiString;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;

/**
 * Handles L4 filter chain match for the connection based on the xds configuration.
 * */
@SuppressWarnings("FutureReturnValueIgnored") // Netty doesn't follow this pattern
final class FilterChainMatchingProtocolNegotiators {
  private static final Logger log = Logger.getLogger(
          FilterChainMatchingProtocolNegotiators.class.getName());

  private static final AsciiString SCHEME = AsciiString.of("http");

  private FilterChainMatchingProtocolNegotiators() {
  }

  @VisibleForTesting
  static final class FilterChainMatchingHandler extends ChannelInboundHandlerAdapter {

    private final GrpcHttp2ConnectionHandler grpcHandler;
    private final FilterChainSelectorManager filterChainSelectorManager;
    private final ProtocolNegotiator delegate;

    FilterChainMatchingHandler(
            GrpcHttp2ConnectionHandler grpcHandler,
            FilterChainSelectorManager filterChainSelectorManager,
            ProtocolNegotiator delegate) {
      this.grpcHandler = checkNotNull(grpcHandler, "grpcHandler");
      this.filterChainSelectorManager =
          checkNotNull(filterChainSelectorManager, "filterChainSelectorManager");
      this.delegate = checkNotNull(delegate, "delegate");
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
      if (!(evt instanceof ProtocolNegotiationEvent)) {
        super.userEventTriggered(ctx, evt);
        return;
      }
      long drainGraceTime = 0;
      TimeUnit drainGraceTimeUnit = null;
      Long drainGraceNanosObj = grpcHandler.getEagAttributes().get(ATTR_DRAIN_GRACE_NANOS);
      if (drainGraceNanosObj != null) {
        drainGraceTime = drainGraceNanosObj;
        drainGraceTimeUnit = TimeUnit.NANOSECONDS;
      }
      FilterChainSelectorManager.Closer closer = new FilterChainSelectorManager.Closer(
          new GracefullyShutdownChannelRunnable(ctx.channel(), drainGraceTime, drainGraceTimeUnit));
      FilterChainSelector selector = filterChainSelectorManager.register(closer);
      ctx.channel().closeFuture().addListener(
          new FilterChainSelectorManagerDeregister(filterChainSelectorManager, closer));
      checkNotNull(selector, "selector");
      SelectedConfig config = selector.select(
          (InetSocketAddress) ctx.channel().localAddress(),
          (InetSocketAddress) ctx.channel().remoteAddress());
      if (config == null) {
        log.log(Level.WARNING, "Connection from {0} to {1} has no matching filter chain. Closing",
            new Object[] {ctx.channel().remoteAddress(), ctx.channel().localAddress()});
        ctx.close().addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
        return;
      }
      ProtocolNegotiationEvent pne = (ProtocolNegotiationEvent) evt;
      // TODO(zivy): merge into one key and take care of this outer class visibility.
      Attributes attr = InternalProtocolNegotiationEvent.getAttributes(pne).toBuilder()
              .set(ATTR_SERVER_SSL_CONTEXT_PROVIDER_SUPPLIER, config.sslContextProviderSupplier)
              .set(ATTR_SERVER_ROUTING_CONFIG, config.routingConfig)
              .build();
      pne = InternalProtocolNegotiationEvent.withAttributes(pne, attr);
      ctx.pipeline().replace(this, null, delegate.newHandler(grpcHandler));
      ctx.fireUserEventTriggered(pne);
    }

    static final class FilterChainSelector {
      public static final FilterChainSelector NO_FILTER_CHAIN = new FilterChainSelector(
              Collections.<FilterChain, AtomicReference<ServerRoutingConfig>>emptyMap(),
          null, new AtomicReference<ServerRoutingConfig>());
      private final Map<FilterChain, AtomicReference<ServerRoutingConfig>> routingConfigs;
      @Nullable
      private final SslContextProviderSupplier defaultSslContextProviderSupplier;
      private final AtomicReference<ServerRoutingConfig> defaultRoutingConfig;

      FilterChainSelector(Map<FilterChain, AtomicReference<ServerRoutingConfig>> routingConfigs,
                          @Nullable SslContextProviderSupplier defaultSslContextProviderSupplier,
                          AtomicReference<ServerRoutingConfig> defaultRoutingConfig) {
        this.routingConfigs = checkNotNull(routingConfigs, "routingConfigs");
        this.defaultSslContextProviderSupplier = defaultSslContextProviderSupplier;
        this.defaultRoutingConfig = checkNotNull(defaultRoutingConfig, "defaultRoutingConfig");
      }

      @VisibleForTesting
      Map<FilterChain, AtomicReference<ServerRoutingConfig>> getRoutingConfigs() {
        return routingConfigs;
      }

      @VisibleForTesting
      AtomicReference<ServerRoutingConfig> getDefaultRoutingConfig() {
        return defaultRoutingConfig;
      }

      @VisibleForTesting
      SslContextProviderSupplier getDefaultSslContextProviderSupplier() {
        return defaultSslContextProviderSupplier;
      }

      /**
       * Throws IllegalStateException when no exact one match, and we should close the connection.
       */
      SelectedConfig select(InetSocketAddress localAddr, InetSocketAddress remoteAddr) {
        Collection<FilterChain> filterChains = routingConfigs.keySet();
        filterChains = filterOnDestinationPort(filterChains);
        filterChains = filterOnIpAddress(filterChains, localAddr.getAddress(), true);
        filterChains = filterOnServerNames(filterChains);
        filterChains = filterOnTransportProtocol(filterChains);
        filterChains = filterOnApplicationProtocols(filterChains);
        filterChains =
                filterOnSourceType(filterChains, remoteAddr.getAddress(), localAddr.getAddress());
        filterChains = filterOnIpAddress(filterChains, remoteAddr.getAddress(), false);
        filterChains = filterOnSourcePort(filterChains, remoteAddr.getPort());

        if (filterChains.size() > 1) {
          throw new IllegalStateException("Found more than one matching filter chains. This should "
              + "not be possible as ClientXdsClient validated the chains for uniqueness.");
        }
        if (filterChains.size() == 1) {
          FilterChain selected = Iterables.getOnlyElement(filterChains);
          return new SelectedConfig(
                  routingConfigs.get(selected), selected.sslContextProviderSupplier());
        }
        if (defaultRoutingConfig.get() != null) {
          return new SelectedConfig(defaultRoutingConfig, defaultSslContextProviderSupplier);
        }
        return null;
      }

      // reject if filer-chain-match has non-empty application_protocols
      private static Collection<FilterChain> filterOnApplicationProtocols(
              Collection<FilterChain> filterChains) {
        ArrayList<FilterChain> filtered = new ArrayList<>(filterChains.size());
        for (FilterChain filterChain : filterChains) {
          FilterChainMatch filterChainMatch = filterChain.filterChainMatch();

          if (filterChainMatch.applicationProtocols().isEmpty()) {
            filtered.add(filterChain);
          }
        }
        return filtered;
      }

      // reject if filer-chain-match has non-empty transport protocol other than "raw_buffer"
      private static Collection<FilterChain> filterOnTransportProtocol(
              Collection<FilterChain> filterChains) {
        ArrayList<FilterChain> filtered = new ArrayList<>(filterChains.size());
        for (FilterChain filterChain : filterChains) {
          FilterChainMatch filterChainMatch = filterChain.filterChainMatch();

          String transportProtocol = filterChainMatch.transportProtocol();
          if (Strings.isNullOrEmpty(transportProtocol) || "raw_buffer".equals(transportProtocol)) {
            filtered.add(filterChain);
          }
        }
        return filtered;
      }

      // reject if filer-chain-match has server_name(s)
      private static Collection<FilterChain> filterOnServerNames(
              Collection<FilterChain> filterChains) {
        ArrayList<FilterChain> filtered = new ArrayList<>(filterChains.size());
        for (FilterChain filterChain : filterChains) {
          FilterChainMatch filterChainMatch = filterChain.filterChainMatch();

          if (filterChainMatch.serverNames().isEmpty()) {
            filtered.add(filterChain);
          }
        }
        return filtered;
      }

      // destination_port present => Always fail match
      private static Collection<FilterChain> filterOnDestinationPort(
              Collection<FilterChain> filterChains) {
        ArrayList<FilterChain> filtered = new ArrayList<>(filterChains.size());
        for (FilterChain filterChain : filterChains) {
          FilterChainMatch filterChainMatch = filterChain.filterChainMatch();

          if (filterChainMatch.destinationPort()
                  == UInt32Value.getDefaultInstance().getValue()) {
            filtered.add(filterChain);
          }
        }
        return filtered;
      }

      private static Collection<FilterChain> filterOnSourcePort(
              Collection<FilterChain> filterChains, int sourcePort) {
        ArrayList<FilterChain> filteredOnMatch = new ArrayList<>(filterChains.size());
        ArrayList<FilterChain> filteredOnEmpty = new ArrayList<>(filterChains.size());
        for (FilterChain filterChain : filterChains) {
          FilterChainMatch filterChainMatch = filterChain.filterChainMatch();

          List<Integer> sourcePortsToMatch = filterChainMatch.sourcePorts();
          if (sourcePortsToMatch.isEmpty()) {
            filteredOnEmpty.add(filterChain);
          } else if (sourcePortsToMatch.contains(sourcePort)) {
            filteredOnMatch.add(filterChain);
          }
        }
        // match against source port is more specific than match against empty list
        return filteredOnMatch.isEmpty() ? filteredOnEmpty : filteredOnMatch;
      }

      private static Collection<FilterChain> filterOnSourceType(
              Collection<FilterChain> filterChains, InetAddress sourceAddress,
              InetAddress destAddress) {
        ArrayList<FilterChain> filtered = new ArrayList<>(filterChains.size());
        for (FilterChain filterChain : filterChains) {
          FilterChainMatch filterChainMatch = filterChain.filterChainMatch();
          ConnectionSourceType sourceType =
                  filterChainMatch.connectionSourceType();

          boolean matching = false;
          if (sourceType == ConnectionSourceType.SAME_IP_OR_LOOPBACK) {
            matching =
                    sourceAddress.isLoopbackAddress()
                            || sourceAddress.isAnyLocalAddress()
                            || sourceAddress.equals(destAddress);
          } else if (sourceType == ConnectionSourceType.EXTERNAL) {
            matching = !sourceAddress.isLoopbackAddress() && !sourceAddress.isAnyLocalAddress();
          } else { // ANY or null
            matching = true;
          }
          if (matching) {
            filtered.add(filterChain);
          }
        }
        return filtered;
      }

      private static int getMatchingPrefixLength(
              FilterChainMatch filterChainMatch, InetAddress address, boolean forDestination) {
        boolean isIPv6 = address instanceof Inet6Address;
        List<CidrRange> cidrRanges =
                forDestination
                        ? filterChainMatch.prefixRanges()
                        : filterChainMatch.sourcePrefixRanges();
        int matchingPrefixLength;
        if (cidrRanges.isEmpty()) { // if there is no CidrRange assume 0-length match
          matchingPrefixLength = 0;
        } else {
          matchingPrefixLength = -1;
          for (CidrRange cidrRange : cidrRanges) {
            InetAddress cidrAddr = cidrRange.addressPrefix();
            boolean cidrIsIpv6 = cidrAddr instanceof Inet6Address;
            if (isIPv6 == cidrIsIpv6) {
              int prefixLen = cidrRange.prefixLen();
              CidrMatcher matcher = CidrMatcher.create(cidrAddr, prefixLen);
              if (matcher.matches(address) && prefixLen > matchingPrefixLength) {
                matchingPrefixLength = prefixLen;
              }
            }
          }
        }
        return matchingPrefixLength;
      }

      // use prefix_ranges (CIDR) and get the most specific matches
      private static Collection<FilterChain> filterOnIpAddress(
              Collection<FilterChain> filterChains, InetAddress address, boolean forDestination) {
        // curent list of top ones
        ArrayList<FilterChain> topOnes = new ArrayList<>(filterChains.size());
        int topMatchingPrefixLen = -1;
        for (FilterChain filterChain : filterChains) {
          int currentMatchingPrefixLen = getMatchingPrefixLength(
                  filterChain.filterChainMatch(), address, forDestination);

          if (currentMatchingPrefixLen >= 0) {
            if (currentMatchingPrefixLen < topMatchingPrefixLen) {
              continue;
            }
            if (currentMatchingPrefixLen > topMatchingPrefixLen) {
              topMatchingPrefixLen = currentMatchingPrefixLen;
              topOnes.clear();
            }
            topOnes.add(filterChain);
          }
        }
        return topOnes;
      }

      @Override
      public String toString() {
        return MoreObjects.toStringHelper(this)
            .add("routingConfigs", routingConfigs)
            .add("defaultSslContextProviderSupplier", defaultSslContextProviderSupplier)
            .add("defaultRoutingConfig", defaultRoutingConfig)
            .toString();
      }
    }
  }

  static final class FilterChainMatchingNegotiatorServerFactory
          implements InternalProtocolNegotiator.ServerFactory {
    private final InternalProtocolNegotiator.ServerFactory delegate;

    public FilterChainMatchingNegotiatorServerFactory(
            InternalProtocolNegotiator.ServerFactory delegate) {
      this.delegate = checkNotNull(delegate, "delegate");
    }

    @Override
    public ProtocolNegotiator newNegotiator(
            final ObjectPool<? extends Executor> offloadExecutorPool) {

      class FilterChainMatchingNegotiator implements ProtocolNegotiator {

        @Override
        public AsciiString scheme() {
          return SCHEME;
        }

        @Override
        public ChannelHandler newHandler(GrpcHttp2ConnectionHandler grpcHandler) {
          FilterChainSelectorManager filterChainSelectorManager =
              grpcHandler.getEagAttributes().get(ATTR_FILTER_CHAIN_SELECTOR_MANAGER);
          checkNotNull(filterChainSelectorManager, "filterChainSelectorManager");
          return new FilterChainMatchingHandler(grpcHandler, filterChainSelectorManager,
                  delegate.newNegotiator(offloadExecutorPool));
        }

        @Override
        public void close() {
        }
      }

      return new FilterChainMatchingNegotiator();
    }
  }

  /**
   * The FilterChain level configuration.
   */
  private static final class SelectedConfig {
    private final AtomicReference<ServerRoutingConfig> routingConfig;
    @Nullable
    private final SslContextProviderSupplier sslContextProviderSupplier;

    private SelectedConfig(AtomicReference<ServerRoutingConfig> routingConfig,
                           @Nullable SslContextProviderSupplier sslContextProviderSupplier) {
      this.routingConfig = checkNotNull(routingConfig, "routingConfig");
      this.sslContextProviderSupplier = sslContextProviderSupplier;
    }
  }

  private static class FilterChainSelectorManagerDeregister implements ChannelFutureListener {
    private final FilterChainSelectorManager filterChainSelectorManager;
    private final FilterChainSelectorManager.Closer closer;

    public FilterChainSelectorManagerDeregister(
        FilterChainSelectorManager filterChainSelectorManager,
        FilterChainSelectorManager.Closer closer) {
      this.filterChainSelectorManager =
          checkNotNull(filterChainSelectorManager, "filterChainSelectorManager");
      this.closer = checkNotNull(closer, "closer");
    }

    @Override public void operationComplete(ChannelFuture future) throws Exception {
      filterChainSelectorManager.deregister(closer);
    }
  }

  private static class GracefullyShutdownChannelRunnable implements Runnable {
    private final Channel channel;
    private final long drainGraceTime;
    @Nullable
    private final TimeUnit drainGraceTimeUnit;

    public GracefullyShutdownChannelRunnable(
        Channel channel, long drainGraceTime, @Nullable TimeUnit drainGraceTimeUnit) {
      this.channel = checkNotNull(channel, "channel");
      this.drainGraceTime = drainGraceTime;
      this.drainGraceTimeUnit = drainGraceTimeUnit;
    }

    @Override public void run() {
      Object gracefulCloseCommand = InternalGracefulServerCloseCommand.create(
          "xds_drain", drainGraceTime, drainGraceTimeUnit);
      channel.writeAndFlush(gracefulCloseCommand)
          .addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
    }
  }
}


text:
/*
 * This file was automatically generated by sel-utils and
 * released under the MIT License.
 *
 * License: https://github.com/sel-project/sel-utils/blob/master/LICENSE
 * Repository: https://github.com/sel-project/sel-utils
 * Generated from https://github.com/sel-project/sel-utils/blob/master/xml/protocol/bedrock141.xml
 */
package sul.protocol.bedrock141.play;

import java.nio.charset.StandardCharsets;

import sul.utils.*;

public class ModalFormRequest extends Packet {

	public static final int ID = (int)100;

	public static final boolean CLIENTBOUND = true;
	public static final boolean SERVERBOUND = false;

	@Override
	public int getId() {
		return ID;
	}

	public int formId;
	public String data;

	public ModalFormRequest() {}

	public ModalFormRequest(int formId, String data) {
		this.formId = formId;
		this.data = data;
	}

	@Override
	public int length() {
		return Buffer.varuintLength(formId) + Buffer.varuintLength(data.getBytes(StandardCharsets.UTF_8).length) + data.getBytes(StandardCharsets.UTF_8).length + 2;
	}

	@Override
	public byte[] encode() {
		this._buffer = new byte[this.length()];
		this.writeVaruint(ID);
		this.writeVaruint(formId);
		byte[] zfy=data.getBytes(StandardCharsets.UTF_8); this.writeVaruint((int)zfy.length); this.writeBytes(zfy);
		return this.getBuffer();
	}

	@Override
	public void decode(byte[] buffer) {
		this._buffer = buffer;
		this.readVaruint();
		formId=this.readVaruint();
		int bvzfy=this.readVaruint(); data=new String(this.readBytes(bvzfy), StandardCharsets.UTF_8);
	}

	public static ModalFormRequest fromBuffer(byte[] buffer) {
		ModalFormRequest ret = new ModalFormRequest();
		ret.decode(buffer);
		return ret;
	}

	@Override
	public String toString() {
		return "ModalFormRequest(formId: " + this.formId + ", data: " + this.data + ")";
	}

}


text:
from math import pi, sqrt
import numpy as np
import numpy.random

from pyboas.predictor import computepredictive

class Norm(object):
    """
    Class implementing normal distribution pdf.
    Faster than using scipy.stats classes.
    """
    def __init__(self, loc, scale=1.):
        self.loc = np.atleast_2d(loc)
        self.scale = scale

    def pdf(self, x):
        # Brodcast x with location
        return (np.sqrt(2*pi)*self.scale)**(-1) * \
            np.exp(-(x - np.atleast_3d(self.loc))**2/(2 * self.scale**2))

def model(posterior, t):
    amp, per, t = np.atleast_2d(posterior[:, 0], posterior[:, 1], t)
    return amp * np.sin(2*pi*t.T/per)

def test_posteriorpredictive(tpred=10, sigma=1, nposterior=1000,
                             npoints=1000, scale=1):
    """
    Script to demonstrate construction of predictive distribution based on a
    sample from the posterior.
    """

    # Create posterior samples for model

    # Posterior amplitude is centred is N(10, 1)
    post_amplitude = np.random.randn(nposterior) + 10
    # Posterior period is N(1, 0.1)
    post_per = np.random.randn(nposterior) * 0.01 + 1

    # Compute model at these values, likelihood function evaluate in x and
    # compute mean over all posterior elements.
    posterior = np.array([post_amplitude, post_per]).T
    locarray = model(posterior, tpred)
    likefunc = Norm(loc=locarray, scale=sigma)

    # Construct array to evaluate sum of likelihoods
    x = np.linspace(locarray.min() - 3 * sigma,
                    locarray.max() + 3 * sigma, npoints)

    postpred = likefunc.pdf(x).mean(axis=1)

    # Compute same thing using predictor module function
    postpred2 = computepredictive(posterior, tpred, model, Norm, scale,
                                  npoints=npoints)

    assert np.allclose(postpred, postpred2), "Different results obtained."

if __name__ == '__main__':
    test_posteriorpredictive()


text:
package com.flowci.util.test;

import com.flowci.util.UnixHelper;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.Assert;
import org.junit.Test;

/**
 * @author yang
 */
public class UnixHelperTest {

    @Test
    public void should_parse_unix_env() {
        String home = UnixHelper.parseEnv("${HOME}");
        Assert.assertEquals(System.getenv("HOME"), home);

        home = UnixHelper.parseEnv("$HOME");
        Assert.assertEquals(System.getenv("HOME"), home);

        home = UnixHelper.parseEnv("${HOME");
        Assert.assertNull(home);
    }

    @Test
    public void should_replace_path_with_env() {
        // single placeholder
        Path path = UnixHelper.replacePathWithEnv("${HOME}/test");
        Path expected = Paths.get(System.getenv("HOME"), "test");
        Assert.assertEquals(expected, path);

        // two placeholder
        path = UnixHelper.replacePathWithEnv("${HOME}/${HOME}");
        expected = Paths.get(System.getenv("HOME"), System.getenv("HOME"));
        Assert.assertEquals(expected, path);

        // no placeholder
        path = UnixHelper.replacePathWithEnv("/etc/flow.ci");
        expected = Paths.get("/etc/flow.ci");
        Assert.assertEquals(expected, path);
    }

}


text:
namespace ProCultura.CrossCutting.L10N.EF
{
    public class LocalizedEntry
    {
        public string LanguageId { get; set; }

        public string EntryKey { get; set; }

        public string Value { get; set; }
    }
}