text:
package com.komanov.serialization.domain.protos.events

@SerialVersionUID(0L)
final case class PageComponentPositionSetPb(
    id: com.google.protobuf.ByteString = com.google.protobuf.ByteString.EMPTY,
    x: Int = 0,
    y: Int = 0
    ) extends com.trueaccord.scalapb.GeneratedMessage with com.trueaccord.scalapb.Message[PageComponentPositionSetPb] with com.trueaccord.lenses.Updatable[PageComponentPositionSetPb] {
    @transient
    private[this] var __serializedSizeCachedValue: Int = 0
    private[this] def __computeSerializedValue(): Int = {
      var __size = 0
      if (id != com.google.protobuf.ByteString.EMPTY) { __size += com.google.protobuf.CodedOutputStream.computeBytesSize(1, id) }
      if (x != 0) { __size += com.google.protobuf.CodedOutputStream.computeUInt32Size(2, x) }
      if (y != 0) { __size += com.google.protobuf.CodedOutputStream.computeUInt32Size(3, y) }
      __size
    }
    final override def serializedSize: Int = {
      var read = __serializedSizeCachedValue
      if (read == 0) {
        read = __computeSerializedValue()
        __serializedSizeCachedValue = read
      }
      read
    }
    def writeTo(output: com.google.protobuf.CodedOutputStream): Unit = {
      {
        val __v = id
        if (__v != com.google.protobuf.ByteString.EMPTY) {
          output.writeBytes(1, __v)
        }
      };
      {
        val __v = x
        if (__v != 0) {
          output.writeUInt32(2, __v)
        }
      };
      {
        val __v = y
        if (__v != 0) {
          output.writeUInt32(3, __v)
        }
      };
    }
    def mergeFrom(__input: com.google.protobuf.CodedInputStream): com.komanov.serialization.domain.protos.events.PageComponentPositionSetPb = {
      var __id = this.id
      var __x = this.x
      var __y = this.y
      var _done__ = false
      while (!_done__) {
        val _tag__ = __input.readTag()
        _tag__ match {
          case 0 => _done__ = true
          case 10 =>
            __id = __input.readBytes()
          case 16 =>
            __x = __input.readUInt32()
          case 24 =>
            __y = __input.readUInt32()
          case tag => __input.skipField(tag)
        }
      }
      com.komanov.serialization.domain.protos.events.PageComponentPositionSetPb(
          id = __id,
          x = __x,
          y = __y
      )
    }
    def withId(__v: com.google.protobuf.ByteString): PageComponentPositionSetPb = copy(id = __v)
    def withX(__v: Int): PageComponentPositionSetPb = copy(x = __v)
    def withY(__v: Int): PageComponentPositionSetPb = copy(y = __v)
    def getField(__field: com.google.protobuf.Descriptors.FieldDescriptor): scala.Any = {
      __field.getNumber match {
        case 1 => {
          val __t = id
          if (__t != com.google.protobuf.ByteString.EMPTY) __t else null
        }
        case 2 => {
          val __t = x
          if (__t != 0) __t else null
        }
        case 3 => {
          val __t = y
          if (__t != 0) __t else null
        }
      }
    }
    override def toString: String = com.trueaccord.scalapb.TextFormat.printToUnicodeString(this)
    def companion = com.komanov.serialization.domain.protos.events.PageComponentPositionSetPb
}

object PageComponentPositionSetPb extends com.trueaccord.scalapb.GeneratedMessageCompanion[PageComponentPositionSetPb] {
  implicit def messageCompanion: com.trueaccord.scalapb.GeneratedMessageCompanion[PageComponentPositionSetPb] = this
  def fromFieldsMap(__fieldsMap: Map[com.google.protobuf.Descriptors.FieldDescriptor, scala.Any]): com.komanov.serialization.domain.protos.events.PageComponentPositionSetPb = {
    require(__fieldsMap.keys.forall(_.getContainingType() == descriptor), "FieldDescriptor does not match message type.")
    val __fields = descriptor.getFields
    com.komanov.serialization.domain.protos.events.PageComponentPositionSetPb(
      __fieldsMap.getOrElse(__fields.get(0), com.google.protobuf.ByteString.EMPTY).asInstanceOf[com.google.protobuf.ByteString],
      __fieldsMap.getOrElse(__fields.get(1), 0).asInstanceOf[Int],
      __fieldsMap.getOrElse(__fields.get(2), 0).asInstanceOf[Int]
    )
  }
  def descriptor: com.google.protobuf.Descriptors.Descriptor = EventsProto.descriptor.getMessageTypes.get(20)
  def messageCompanionForField(__field: com.google.protobuf.Descriptors.FieldDescriptor): com.trueaccord.scalapb.GeneratedMessageCompanion[_] = throw new MatchError(__field)
  def enumCompanionForField(__field: com.google.protobuf.Descriptors.FieldDescriptor): com.trueaccord.scalapb.GeneratedEnumCompanion[_] = throw new MatchError(__field)
  lazy val defaultInstance = com.komanov.serialization.domain.protos.events.PageComponentPositionSetPb(
  )
  implicit class PageComponentPositionSetPbLens[UpperPB](_l: com.trueaccord.lenses.Lens[UpperPB, PageComponentPositionSetPb]) extends com.trueaccord.lenses.ObjectLens[UpperPB, PageComponentPositionSetPb](_l) {
    def id: com.trueaccord.lenses.Lens[UpperPB, com.google.protobuf.ByteString] = field(_.id)((c_, f_) => c_.copy(id = f_))
    def x: com.trueaccord.lenses.Lens[UpperPB, Int] = field(_.x)((c_, f_) => c_.copy(x = f_))
    def y: com.trueaccord.lenses.Lens[UpperPB, Int] = field(_.y)((c_, f_) => c_.copy(y = f_))
  }
  final val ID_FIELD_NUMBER = 1
  final val X_FIELD_NUMBER = 2
  final val Y_FIELD_NUMBER = 3
}


text:
from azure.identity import DefaultAzureCredential
from azure.mgmt.hanaonazure import HanaManagementClient

"""
# PREREQUISITES
    pip install azure-identity
    pip install azure-mgmt-hanaonazure
# USAGE
    python list_all_sap_monitors_in_a_subscription.py

    Before run the sample, please set the values of the client ID, tenant ID and client secret
    of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
    AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
    https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""

def main():
    client = HanaManagementClient(
        credential=DefaultAzureCredential(),
        subscription_id="00000000-0000-0000-0000-000000000000",
    )

    response = client.sap_monitors.list()
    for item in response:
        print(item)

# x-ms-original-file: specification/hanaonazure/resource-manager/Microsoft.HanaOnAzure/preview/2020-02-07-preview/examples/SapMonitors_List.json
if __name__ == "__main__":
    main()

redpajama_set_name: RedPajamaGithub


text:
.settings_panel li
{
    margin-top: 30px;

    list-style: none;
}

.settings_panel td
{
    padding-right: 30px;
}

h1 {
  color: #505050;
}

.error {
  color: #FF0000;
}

div.settings-section-title
{
    font-size: large;
    font-weight: bold;
    color: #505050;
}

div.settings-section-body
{
    margin-left: 20px;
}

div.buttons
{

}

.settings_panel button {
  margin: 30px 40px 0 40px;
  font-size: 1em;
  border-radius: 5px;
  outline: none;
  /*
  The transparent border ensures that the button does not change size if we need to set the
  border e.g. when the button is disabled
  */
  border: 1px solid transparent;
  color: #fff;
  cursor: pointer;
  padding: 4px 7px;
  transition-duration: 0.3s;
}

button.save {
  background-color: #1e88e5;
}

button.save:hover,
button.save:focus {
  background-color: #1879cd;
}

button.cancel {
  background-color: #999;
}

button.cancel:hover,
button.cancel:focus {
  background-color: #777;
}

button[disabled=disabled],
button[disabled=disabled]:hover,
button[disabled=disabled]:focus {
    background-color: #eee;
    color: #ff0;
    border: 1px solid #aaa;
    color: #777;
    cursor: not-allowed;
}


text:
{% extends "base.html" %}

{% block content %}

Control Phone Call

                        <form style="display:inline;" class="in-call form-inline" action="/next-question">
                            <input type="hidden" name="call_sid" value={{call_sid}}>
                            <select id="next-call-select" name="topic_id" class="btn btn-default form-control">
                                <option value="" disabled selected>Next Question Topic</option>
                                <option value=0>Any</option>
                                {% for topic in topics %}
                                    <option value={{topic.id}}>{{ topic.name }}</option>
                                {% endfor %}
                            </select>
                            <input id="next-call-btn" class="btn in-call-btn btn-primary form-control" type="submit" value="Go To Next Question">
                        </form>

                        <select onchange="set_lang();" class="form-control" id="language" style="width: 40%; margin: 0 0 5% 30%;">
                            {% if not language %}
                                <option value="" disabled selected>Choose language</option>
                            {% endif %}
                            {% for l in languages %}
                                {% if l != language %}
                                    <option>
                                        {{ l }}
                                    </option>
                                {% else %}
                                    <option id="{{language}}" value="{{language}}" selected>{{language}}</option>
                                {% endif %}
                            {% endfor %}
                        </select>

                        <form style="display:inline;"class="in-call form-inline" action="/repeat">
                            <input type="hidden" name="call_sid" value={{call_sid}}>
                            <input type="hidden" name="question_id" value={{question_id}}>
                            <input type="hidden" name="voted" value={{voted}}>
                            <input id="repeat-input" type="hidden" name="user_input" value="">
                            <input id="repeat-language" type="hidden" name="language" value="">
                            <input onclick="set_input_and_language('repeat');" id="in-call-btn" class="btn btn-default form-control" type="submit" value="Repeat">
                        </form>

                        <form style="display:inline;" class="in-call form-inline" action="/hint">
                            <input type="hidden" name="call_sid" value={{call_sid}}>
                            <input type="hidden" name="question_id" value={{question_id}}>
                            <input type="hidden" name="voted" value={{voted}}>
                            <input id="hint-input" type="hidden" name="user_input" value="">
                            <input id="hint-language" type="hidden" name="language" value="">
                            <input onclick="set_input_and_language('hint');" id="in-call-btn" class="btn in-call-btn btn-default form-control" type="submit" value="Hint">
                        </form>

                            <input id="show-answer" onclick='show_answer( "{{answer_language}}" );' class="btn in-call-btn btn-default form-control" type="submit" value="Show Answer" style="width: 200px;height: 60px;margin: 0 2% 2% 2%;font-size: 140%;">
                            <button id="hide-answer" style="display:none; width: 200px;height: 60px;margin: 0 2% 2% 2%;font-size: 140%;" onclick='hide_answer( "{{language}}" );' class="btn form-control answer-btn btn-default">Hide Answer</button>

                        {% if not voted %}
                            <form style="display:inline;" class="in-call-btn form-inline" action="/upvote">
                                <input type="hidden" name="call_sid" value={{call_sid}}>
                                <input type="hidden" name="question_id" value={{question_id}}>
                                <input id="upvote-input" type="hidden" name="user_input" value="">
                                <input id="upvote-language" type="hidden" name="language" value="">
                                <input onclick="set_input_and_language('upvote');" id="in-call-btn" class="btn in-call-btn btn-default form-control" type="submit" value="Upvote">
                            </form>
                        {% else %}
                            <form style="display:inline;" id="in-call-btn form-inline" class="in-call form-inline" action="/upvote">
                                <input id="in-call-btn" class="btn in-call-btn btn-default form-control" type="submit" value="Upvote" disabled>
                            </form>
                        {% endif %}

                        <form class="in-call-btn form-inline" action="\hangup">
                            <input type="hidden" name="call_sid" value={{call_sid}}>
                            <input type="submit" id="in-call-btn" class="btn in-call-btn btn-default form-control" value="Hangup">
                        </form>

{{user_input}}

{{answer}}

{% endblock %}


text:
<?php
declare(strict_types=1);

namespace TestApp\Validation;

class CustomProvider
{
    /**
     * @param mixed $value
     * @param mixed $context
     */
    public function validate($value, $context): bool
    {
        return is_bool($value);
    }
}


text:
var express = require('express');
var router = express.Router();
var User = require('../models/User.js');
var Project = require('../models/Project.js');
var Exception = require('../models/Exception.js');
var Instance = require('../models/Instance.js');

router.api = {

	handleError: function(err){
		res.send(err);
	},

	buildInstance: function(req){
		var ua = require('ua-parser-js');
		var useragent = ua(req.body.useragent);
		return new Instance({
			message: req.body.message,
			browser: useragent.browser,
			engine: useragent.engine,
			os: useragent.os,
			device: useragent.device,
			cpu: useragent.cpu,
			method: req.body.method,
	  		url: req.body.url,
			ip: req.body.ip,
			location: req.body.location,
			source: req.body.source,
			trace: req.body.trace,
			env: req.body.env,
			cookies: req.body.cookies,
			data: req.body.data,
			useragent: req.body.useragent,
			project: req.body.project
		})
	},

	setUser: function(req, instance){
		if(req.body.user){
			return {
				user_id: req.body.user.id,
				name: req.body.user.name
			};
		}
	},

	makeHash: function(req){
		var md5 = require('md5');
		console.log(md5(req.body.class+""+req.body.file+""+req.body.line));
		return md5(req.body.class+""+req.body.file+""+req.body.line);
	},

	checkIfExceptionExists: function(hash, callback){
		Exception.findOne({hash: hash}, function(err, exception){
			if(err) router.api.handleError(err);
			return callback(exception);
		});
	},

	buildException: function(req, instance, hash){
		return new Exception({
			class: req.body.class,
			file: req.body.file,
			line: req.body.line,
			hash: hash,
			project: req.body.project,
			resolved: {
				state: false
			},
			last_occurred: new Date,
			last_message: instance.message
		});
	},

	processError: function(req, res, callback){
		var instance, hash, prevResolved, promise;

		instance = router.api.buildInstance(req);

		instance.user = router.api.setUser(req, instance);

		hash = router.api.makeHash(req);

		router.api.checkIfExceptionExists(hash, function(exception){
			if(!exception){
				// It's a new exception
				console.log('its new');
				exception = router.api.buildException(req, instance, hash);
				exception.save(function(err, exception){
				instance.exception = {
					exception_id: exception._id,
					resolved: false
				};
				instance.save(function(err, instance){
					// Now add the instance to the exception (messy i kno)
					exception.addInstance(instance._id, instance.created_at, function(){
						console.log('New exception saved');
						global.bridge.emit('exception.new', {
							exception: exception,
							instance: instance
						});
						callback(instance._id);
					});
				});
			});

			}else{
				console.log('its existing');
				// It's another occurence
				prevResolved = exception.resolved;
				instance.exception = {
					exception_id: exception._id,
					resolved: false
				};
				exception.resolved.state = false;
				exception.last_occurred = new Date();
				exception.last_message = instance.message;
				promise = [];
				promise.push(exception.save());
				promise.push(instance.save());
				Promise.all(promise).then(function(values){
					values[0].addInstance(values[1]._id, exception.last_occurred, function(exception){
						values[0] = exception;
						console.log('New instance of exception saved');
						global.bridge.emit('exception.existing', {
							prevResolved: prevResolved,
							exception: values[0],
							instance: values[1]
						});
						callback(values[1]._id);
					});
				});
			}

		});

	}
};

/**
 * @api {post} /api/exception Store a new instance of an exception
 * @apiName StoreException
 * @apiGroup Exceptions
 *
 * @apiParam {Mixed}  [user] 	The user that this error occurred for. This could be an ID, email, name etc.
 * @apiParam {String} method 	The HTTP method used when this error occurred.
 * @apiParam {String} [url] 		The referrer URL from when this error occurred.
 * @apiParam {String} [ip] 		The IP address from where this error occurred.
 * @apiParam {String} [location] 	The IP based location from where this error occured.
 * @apiParam {String} [useragent]	The user agent string from where this error occured.
 * @apiParam {String} project 	The Zappem Project ID which this error relates to.
 * @apiParam {String} message 	The error message
 * @apiParam {String} [class] 	The class in which the error occurred in.
 * @apiParam {String} file		The file in which the error occurred in.
 * @apiParam {Integer} line		The line number where the error occurred.
 * @apiParam {Object[]} [trace]	The trace stack
 * @apiParam {String} trace.class The class name
 * @apiParam {String} trace.file  The file name
 * @apiParam {Integer} trace.line The line number
 *
 * @api
 */
router.post('/exception', function(req, res){
	// An exception happened.
	// Does it already exist?

	Project.findById(req.body.project, function(err, project){
		if(!project){
			res.send('Project not found');
		}else{
			project.set_up = true;
			project.save();
			router.api.processError(req, res, function(code){
				res.send(code);
			});
		}
	});
});

module.exports = router;


text:
account_helper = AccountHelper.new(node)
redis_user = account_helper.redis_user
redis_exporter_log_dir = node['monitoring']['redis-exporter']['log_directory']
redis_exporter_static_etc_dir = node['monitoring']['redis-exporter']['env_directory']

directory redis_exporter_log_dir do
  owner redis_user
  mode '0700'
  recursive true
end

directory redis_exporter_static_etc_dir do
  owner redis_user
  mode '0700'
  recursive true
end

env_dir redis_exporter_static_etc_dir do
  variables node['monitoring']['redis-exporter']['env']
  notifies :restart, "runit_service[redis-exporter]"
end

runtime_flags = PrometheusHelper.new(node).flags('redis-exporter')
runit_service 'redis-exporter' do
  options({
    log_directory: redis_exporter_log_dir,
    flags: runtime_flags,
    env_dir: redis_exporter_static_etc_dir
  }.merge(params))
  log_options node['gitlab']['logging'].to_hash.merge(node['registry'].to_hash)
end

if node['gitlab']['bootstrap']['enable']
  execute "/opt/gitlab/bin/gitlab-ctl start redis-exporter" do
    retries 20
  end
end

consul_service node['monitoring']['redis-exporter']['consul_service_name'] do
  id 'redis-exporter'
  meta node['monitoring']['redis-exporter']['consul_service_meta']
  action Prometheus.service_discovery_action
  socket_address node['monitoring']['redis-exporter']['listen_address']
  reload_service false unless Services.enabled?('consul')
end


text:
namespace net {

namespace {

// Constants used to build histogram names
const char kLeafCert[] = "Leaf";
const char kIntermediateCert[] = "Intermediate";
const char kRootCert[] = "Root";
// Matches the order of X509Certificate::PublicKeyType
const char* const kCertTypeStrings[] = {
    "Unknown",
    "RSA",
    "DSA",
    "ECDSA",
    "DH",
    "ECDH"
};
// Histogram buckets for RSA/DSA/DH key sizes.
const int kRsaDsaKeySizes[] = {512, 768, 1024, 1536, 2048, 3072, 4096, 8192,
                               16384};
// Histogram buckets for ECDSA/ECDH key sizes. The list is based upon the FIPS
// 186-4 approved curves.
const int kEccKeySizes[] = {163, 192, 224, 233, 256, 283, 384, 409, 521, 571};

const char* CertTypeToString(int cert_type) {
  if (cert_type < 0 ||
      static_cast<size_t>(cert_type) >= arraysize(kCertTypeStrings)) {
    return "Unsupported";
  }
  return kCertTypeStrings[cert_type];
}

void RecordPublicKeyHistogram(const char* chain_position,
                              bool baseline_keysize_applies,
                              size_t size_bits,
                              X509Certificate::PublicKeyType cert_type) {
  std::string histogram_name =
      base::StringPrintf("CertificateType2.%s.%s.%s",
                         baseline_keysize_applies ? "BR" : "NonBR",
                         chain_position,
                         CertTypeToString(cert_type));
  // Do not use UMA_HISTOGRAM_... macros here, as it caches the Histogram
  // instance and thus only works if |histogram_name| is constant.
  base::HistogramBase* counter = NULL;

  // Histogram buckets are contingent upon the underlying algorithm being used.
  if (cert_type == X509Certificate::kPublicKeyTypeECDH ||
      cert_type == X509Certificate::kPublicKeyTypeECDSA) {
    // Typical key sizes match SECP/FIPS 186-3 recommendations for prime and
    // binary curves - which range from 163 bits to 571 bits.
    counter = base::CustomHistogram::FactoryGet(
        histogram_name,
        base::CustomHistogram::ArrayToCustomRanges(kEccKeySizes,
                                                   arraysize(kEccKeySizes)),
        base::HistogramBase::kUmaTargetedHistogramFlag);
  } else {
    // Key sizes < 1024 bits should cause errors, while key sizes > 16K are not
    // uniformly supported by the underlying cryptographic libraries.
    counter = base::CustomHistogram::FactoryGet(
        histogram_name,
        base::CustomHistogram::ArrayToCustomRanges(kRsaDsaKeySizes,
                                                   arraysize(kRsaDsaKeySizes)),
        base::HistogramBase::kUmaTargetedHistogramFlag);
  }
  counter->Add(size_bits);
}

// Returns true if |type| is |kPublicKeyTypeRSA| or |kPublicKeyTypeDSA|, and
// if |size_bits| is < 1024. Note that this means there may be false
// negatives: keys for other algorithms and which are weak will pass this
// test.
bool IsWeakKey(X509Certificate::PublicKeyType type, size_t size_bits) {
  switch (type) {
    case X509Certificate::kPublicKeyTypeRSA:
    case X509Certificate::kPublicKeyTypeDSA:
      return size_bits < 1024;
    default:
      return false;
  }
}

// Returns true if |cert| contains a known-weak key. Additionally, histograms
// the observed keys for future tightening of the definition of what
// constitutes a weak key.
bool ExaminePublicKeys(const scoped_refptr<X509Certificate>& cert,
                       bool should_histogram) {
  // The effective date of the CA/Browser Forum's Baseline Requirements -
  // 2012-07-01 00:00:00 UTC.
  const base::Time kBaselineEffectiveDate =
      base::Time::FromInternalValue(GG_INT64_C(12985574400000000));
  // The effective date of the key size requirements from Appendix A, v1.1.5
  // 2014-01-01 00:00:00 UTC.
  const base::Time kBaselineKeysizeEffectiveDate =
      base::Time::FromInternalValue(GG_INT64_C(13033008000000000));

  size_t size_bits = 0;
  X509Certificate::PublicKeyType type = X509Certificate::kPublicKeyTypeUnknown;
  bool weak_key = false;
  bool baseline_keysize_applies =
      cert->valid_start() >= kBaselineEffectiveDate &&
      cert->valid_expiry() >= kBaselineKeysizeEffectiveDate;

  X509Certificate::GetPublicKeyInfo(cert->os_cert_handle(), &size_bits, &type);
  if (should_histogram) {
    RecordPublicKeyHistogram(kLeafCert, baseline_keysize_applies, size_bits,
                             type);
  }
  if (IsWeakKey(type, size_bits))
    weak_key = true;

  const X509Certificate::OSCertHandles& intermediates =
      cert->GetIntermediateCertificates();
  for (size_t i = 0; i < intermediates.size(); ++i) {
    X509Certificate::GetPublicKeyInfo(intermediates[i], &size_bits, &type);
    if (should_histogram) {
      RecordPublicKeyHistogram(
          (i < intermediates.size() - 1) ? kIntermediateCert : kRootCert,
          baseline_keysize_applies,
          size_bits,
          type);
    }
    if (!weak_key && IsWeakKey(type, size_bits))
      weak_key = true;
  }

  return weak_key;
}

}  // namespace

// static
CertVerifyProc* CertVerifyProc::CreateDefault() {
#if defined(USE_NSS) || defined(OS_IOS)
  return new CertVerifyProcNSS();
#elif defined(USE_OPENSSL) && !defined(OS_ANDROID)
  return new CertVerifyProcOpenSSL();
#elif defined(OS_ANDROID)
  return new CertVerifyProcAndroid();
#elif defined(OS_MACOSX)
  return new CertVerifyProcMac();
#elif defined(OS_WIN)
  return new CertVerifyProcWin();
#else
  return NULL;
#endif
}

CertVerifyProc::CertVerifyProc() {}

CertVerifyProc::~CertVerifyProc() {}

int CertVerifyProc::Verify(X509Certificate* cert,
                           const std::string& hostname,
                           int flags,
                           CRLSet* crl_set,
                           const CertificateList& additional_trust_anchors,
                           CertVerifyResult* verify_result) {
  verify_result->Reset();
  verify_result->verified_cert = cert;

  if (IsBlacklisted(cert)) {
    verify_result->cert_status |= CERT_STATUS_REVOKED;
    return ERR_CERT_REVOKED;
  }

  // We do online revocation checking for EV certificates that aren't covered
  // by a fresh CRLSet.
  // TODO(rsleevi): http://crbug.com/142974 - Allow preferences to fully
  // disable revocation checking.
  if (flags & CertVerifier::VERIFY_EV_CERT)
    flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED_EV_ONLY;

  int rv = VerifyInternal(cert, hostname, flags, crl_set,
                          additional_trust_anchors, verify_result);

  // This check is done after VerifyInternal so that VerifyInternal can fill
  // in the list of public key hashes.
  if (IsPublicKeyBlacklisted(verify_result->public_key_hashes)) {
    verify_result->cert_status |= CERT_STATUS_REVOKED;
    rv = MapCertStatusToNetError(verify_result->cert_status);
  }

  // Check for weak keys in the entire verified chain.
  bool weak_key = ExaminePublicKeys(verify_result->verified_cert,
                                    verify_result->is_issued_by_known_root);

  if (weak_key) {
    verify_result->cert_status |= CERT_STATUS_WEAK_KEY;
    // Avoid replacing a more serious error, such as an OS/library failure,
    // by ensuring that if verification failed, it failed with a certificate
    // error.
    if (rv == OK || IsCertificateError(rv))
      rv = MapCertStatusToNetError(verify_result->cert_status);
  }

  // Treat certificates signed using broken signature algorithms as invalid.
  if (verify_result->has_md2 || verify_result->has_md4) {
    verify_result->cert_status |= CERT_STATUS_INVALID;
    rv = MapCertStatusToNetError(verify_result->cert_status);
  }

  // Flag certificates using weak signature algorithms.
  if (verify_result->has_md5) {
    verify_result->cert_status |= CERT_STATUS_WEAK_SIGNATURE_ALGORITHM;
    // Avoid replacing a more serious error, such as an OS/library failure,
    // by ensuring that if verification failed, it failed with a certificate
    // error.
    if (rv == OK || IsCertificateError(rv))
      rv = MapCertStatusToNetError(verify_result->cert_status);
  }

  // Flag certificates from publicly-trusted CAs that are issued to intranet
  // hosts. While the CA/Browser Forum Baseline Requirements (v1.1) permit
  // these to be issued until 1 November 2015, they represent a real risk for
  // the deployment of gTLDs and are being phased out ahead of the hard
  // deadline.
  // TODO(rsleevi): http://crbug.com/119212 - Also match internal IP address
  // ranges.
  if (verify_result->is_issued_by_known_root && IsHostnameNonUnique(hostname)) {
    verify_result->cert_status |= CERT_STATUS_NON_UNIQUE_NAME;
  }

  return rv;
}

// static
bool CertVerifyProc::IsBlacklisted(X509Certificate* cert) {
  static const unsigned kComodoSerialBytes = 16;
  static const uint8 kComodoSerials[][kComodoSerialBytes] = {
    // Not a real certificate. For testing only.
    {0x07,0x7a,0x59,0xbc,0xd5,0x34,0x59,0x60,0x1c,0xa6,0x90,0x72,0x67,0xa6,0xdd,0x1c},

    // The next nine certificates all expire on Fri Mar 14 23:59:59 2014.
    // Some serial numbers actually have a leading 0x00 byte required to
    // encode a positive integer in DER if the most significant bit is 0.
    // We omit the leading 0x00 bytes to make all serial numbers 16 bytes.

    // Subject: CN=mail.google.com
    // subjectAltName dNSName: mail.google.com, www.mail.google.com
    {0x04,0x7e,0xcb,0xe9,0xfc,0xa5,0x5f,0x7b,0xd0,0x9e,0xae,0x36,0xe1,0x0c,0xae,0x1e},
    // Subject: CN=global trustee
    // subjectAltName dNSName: global trustee
    // Note: not a CA certificate.
    {0xd8,0xf3,0x5f,0x4e,0xb7,0x87,0x2b,0x2d,0xab,0x06,0x92,0xe3,0x15,0x38,0x2f,0xb0},
    // Subject: CN=login.live.com
    // subjectAltName dNSName: login.live.com, www.login.live.com
    {0xb0,0xb7,0x13,0x3e,0xd0,0x96,0xf9,0xb5,0x6f,0xae,0x91,0xc8,0x74,0xbd,0x3a,0xc0},
    // Subject: CN=addons.mozilla.org
    // subjectAltName dNSName: addons.mozilla.org, www.addons.mozilla.org
    {0x92,0x39,0xd5,0x34,0x8f,0x40,0xd1,0x69,0x5a,0x74,0x54,0x70,0xe1,0xf2,0x3f,0x43},
    // Subject: CN=login.skype.com
    // subjectAltName dNSName: login.skype.com, www.login.skype.com
    {0xe9,0x02,0x8b,0x95,0x78,0xe4,0x15,0xdc,0x1a,0x71,0x0a,0x2b,0x88,0x15,0x44,0x47},
    // Subject: CN=login.yahoo.com
    // subjectAltName dNSName: login.yahoo.com, www.login.yahoo.com
    {0xd7,0x55,0x8f,0xda,0xf5,0xf1,0x10,0x5b,0xb2,0x13,0x28,0x2b,0x70,0x77,0x29,0xa3},
    // Subject: CN=www.google.com
    // subjectAltName dNSName: www.google.com, google.com
    {0xf5,0xc8,0x6a,0xf3,0x61,0x62,0xf1,0x3a,0x64,0xf5,0x4f,0x6d,0xc9,0x58,0x7c,0x06},
    // Subject: CN=login.yahoo.com
    // subjectAltName dNSName: login.yahoo.com
    {0x39,0x2a,0x43,0x4f,0x0e,0x07,0xdf,0x1f,0x8a,0xa3,0x05,0xde,0x34,0xe0,0xc2,0x29},
    // Subject: CN=login.yahoo.com
    // subjectAltName dNSName: login.yahoo.com
    {0x3e,0x75,0xce,0xd4,0x6b,0x69,0x30,0x21,0x21,0x88,0x30,0xae,0x86,0xa8,0x2a,0x71},
  };

  const std::string& serial_number = cert->serial_number();
  if (!serial_number.empty() && (serial_number[0] & 0x80) != 0) {
    // This is a negative serial number, which isn't technically allowed but
    // which probably happens. In order to avoid confusing a negative serial
    // number with a positive one once the leading zeros have been removed, we
    // disregard it.
    return false;
  }

  base::StringPiece serial(serial_number);
  // Remove leading zeros.
  while (serial.size() > 1 && serial[0] == 0)
    serial.remove_prefix(1);

  if (serial.size() == kComodoSerialBytes) {
    for (unsigned i = 0; i < arraysize(kComodoSerials); i++) {
      if (memcmp(kComodoSerials[i], serial.data(), kComodoSerialBytes) == 0) {
        UMA_HISTOGRAM_ENUMERATION("Net.SSLCertBlacklisted", i,
                                  arraysize(kComodoSerials) + 1);
        return true;
      }
    }
  }

  return false;
}

// static
// NOTE: This implementation assumes and enforces that the hashes are SHA1.
bool CertVerifyProc::IsPublicKeyBlacklisted(
    const HashValueVector& public_key_hashes) {
  static const unsigned kNumHashes = 10;
  static const uint8 kHashes[kNumHashes][base::kSHA1Length] = {
    // Subject: CN=DigiNotar Root CA
    // Issuer: CN=Entrust.net x2 and self-signed
    {0x41, 0x0f, 0x36, 0x36, 0x32, 0x58, 0xf3, 0x0b, 0x34, 0x7d,
     0x12, 0xce, 0x48, 0x63, 0xe4, 0x33, 0x43, 0x78, 0x06, 0xa8},
    // Subject: CN=DigiNotar Cyber CA
    // Issuer: CN=GTE CyberTrust Global Root
    {0xc4, 0xf9, 0x66, 0x37, 0x16, 0xcd, 0x5e, 0x71, 0xd6, 0x95,
     0x0b, 0x5f, 0x33, 0xce, 0x04, 0x1c, 0x95, 0xb4, 0x35, 0xd1},
    // Subject: CN=DigiNotar Services 1024 CA
    // Issuer: CN=Entrust.net
    {0xe2, 0x3b, 0x8d, 0x10, 0x5f, 0x87, 0x71, 0x0a, 0x68, 0xd9,
     0x24, 0x80, 0x50, 0xeb, 0xef, 0xc6, 0x27, 0xbe, 0x4c, 0xa6},
    // Subject: CN=DigiNotar PKIoverheid CA Organisatie - G2
    // Issuer: CN=Staat der Nederlanden Organisatie CA - G2
    {0x7b, 0x2e, 0x16, 0xbc, 0x39, 0xbc, 0xd7, 0x2b, 0x45, 0x6e,
     0x9f, 0x05, 0x5d, 0x1d, 0xe6, 0x15, 0xb7, 0x49, 0x45, 0xdb},
    // Subject: CN=DigiNotar PKIoverheid CA Overheid en Bedrijven
    // Issuer: CN=Staat der Nederlanden Overheid CA
    {0xe8, 0xf9, 0x12, 0x00, 0xc6, 0x5c, 0xee, 0x16, 0xe0, 0x39,
     0xb9, 0xf8, 0x83, 0x84, 0x16, 0x61, 0x63, 0x5f, 0x81, 0xc5},
    // Subject: O=Digicert Sdn. Bhd.
    // Issuer: CN=GTE CyberTrust Global Root
    // Expires: Jul 17 15:16:54 2012 GMT
    {0x01, 0x29, 0xbc, 0xd5, 0xb4, 0x48, 0xae, 0x8d, 0x24, 0x96,
     0xd1, 0xc3, 0xe1, 0x97, 0x23, 0x91, 0x90, 0x88, 0xe1, 0x52},
    // Subject: O=Digicert Sdn. Bhd.
    // Issuer: CN=Entrust.net Certification Authority (2048)
    // Expires: Jul 16 17:53:37 2015 GMT
    {0xd3, 0x3c, 0x5b, 0x41, 0xe4, 0x5c, 0xc4, 0xb3, 0xbe, 0x9a,
     0xd6, 0x95, 0x2c, 0x4e, 0xcc, 0x25, 0x28, 0x03, 0x29, 0x81},
    // Issuer: CN=Trustwave Organization Issuing CA, Level 2
    // Covers two certificates, the latter of which expires Apr 15 21:09:30
    // 2021 GMT.
    {0xe1, 0x2d, 0x89, 0xf5, 0x6d, 0x22, 0x76, 0xf8, 0x30, 0xe6,
     0xce, 0xaf, 0xa6, 0x6c, 0x72, 0x5c, 0x0b, 0x41, 0xa9, 0x32},
    // Cyberoam CA certificate. Private key leaked, but this certificate would
    // only have been installed by Cyberoam customers. The certificate expires
    // in 2036, but we can probably remove in a couple of years (2014).
    {0xd9, 0xf5, 0xc6, 0xce, 0x57, 0xff, 0xaa, 0x39, 0xcc, 0x7e,
     0xd1, 0x72, 0xbd, 0x53, 0xe0, 0xd3, 0x07, 0x83, 0x4b, 0xd1},
    // Win32/Sirefef.gen!C generates fake certifciates with this public key.
    {0xa4, 0xf5, 0x6e, 0x9e, 0x1d, 0x9a, 0x3b, 0x7b, 0x1a, 0xc3,
     0x31, 0xcf, 0x64, 0xfc, 0x76, 0x2c, 0xd0, 0x51, 0xfb, 0xa4},
  };

  for (unsigned i = 0; i < kNumHashes; i++) {
    for (HashValueVector::const_iterator j = public_key_hashes.begin();
         j != public_key_hashes.end(); ++j) {
      if (j->tag == HASH_VALUE_SHA1 &&
          memcmp(j->data(), kHashes[i], base::kSHA1Length) == 0) {
        return true;
      }
    }
  }

  return false;
}

}  // namespace net


text:
typedef enum {
    LPGoogleDistanceMatrixAvoidNone,
    LPGoogleDistanceMatrixAvoidTolls,
    LPGoogleDistanceMatrixAvoidHighways,
    LPGoogleDistanceMatrixAvoidFerries,
    LPGoogleDistanceMatrixAvoidIndoor
} LPGoogleDistanceMatrixAvoid;

typedef enum {
    LPGoogleDistanceMatrixUnitMetric,
    LPGoogleDistanceMatrixUnitImperial
} LPGoogleDistanceMatrixUnit;

typedef enum {
    LPGoogleDistanceMatrixModeDriving,
    LPGoogleDistanceMatrixModeWalking,
    LPGoogleDistanceMatrixModeBicycling,
    LPGoogleDistanceMatrixModeTransit
} LPGoogleDistanceMatrixTravelMode;

@interface LPDistanceMatrix : NSObject <NSCoding>

@property (nonatomic, strong) NSString *statusCode;
@property (nonatomic, assign) LPGoogleDistanceMatrixTravelMode requestTravelMode;
@property (nonatomic, strong) NSArray *destinationAddresses;
@property (nonatomic, strong) NSArray *originAddresses;
@property (nonatomic, strong) NSArray *rows;

+ (id)distanceMatrixWithObjects:(NSDictionary *)dictionary;

- (NSDictionary *)dictionary;

- (id)copyWithZone:(NSZone *)zone;

+ (LPGoogleDistanceMatrixTravelMode)getDistanceMatrixTravelModeFromString:(NSString *)string;
+ (NSString *)getDistanceMatrixTravelMode:(LPGoogleDistanceMatrixTravelMode)travelMode;

+ (NSString *)getDistanceMatrixAvoid:(LPGoogleDistanceMatrixAvoid)avoid;
+ (NSString *)getDistanceMatrixUnit:(LPGoogleDistanceMatrixUnit)unit;

@end


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------

namespace Microsoft.Azure.Commands.StorageSync.Test.UnitTests
{
    using System.Collections.Generic;
    using Microsoft.Azure.Commands.StorageSync.Evaluation;
    using Microsoft.Azure.Commands.StorageSync.Evaluation.Interfaces;
    using Xunit;
    using Moq;
    using System;
    using Microsoft.WindowsAzure.Commands.ScenarioTest;

    public class NamespaceEnumeratorTests
    {
        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void EnumerationTotals()
        {
            var nsEnumerator = new NamespaceEnumerator();
            int depth = 3;
            int numberOfSubdirs = 5;
            int numberOfFilesPerDirectory = 3;
            int totalBytes = 1024 * 1024;
            NamespaceInfo nsInfo = nsEnumerator.Run(MockFactory.DirectoryWithGivenParameters(
                root: "c:",
                depth: depth,
                numberOfDirectories: numberOfSubdirs,
                numberOfFilesPerDirectory: numberOfFilesPerDirectory,
                totalSize: totalBytes));

            Assert.True(nsInfo != null, "namespace information was returned");
            Assert.True(nsInfo.IsComplete, "namespace scan is complete");

            int totalDirs = ((int)Math.Pow(numberOfSubdirs, depth + 1) - 1) / (numberOfSubdirs - 1);
            int totalFiles = totalDirs * numberOfFilesPerDirectory;
            Assert.True(nsInfo.NumberOfDirectories == totalDirs, "number of directories is as expected");
            Assert.True(nsInfo.NumberOfFiles == totalFiles, "number of files is as expected");
            Assert.True(nsInfo.TotalFileSizeInBytes == totalBytes, "size is as expected");
        }
    }
}


text:
#include <aws/ssm/model/Activation.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace SSM
{
namespace Model
{

Activation::Activation() :
    m_activationIdHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_defaultInstanceNameHasBeenSet(false),
    m_iamRoleHasBeenSet(false),
    m_registrationLimit(0),
    m_registrationLimitHasBeenSet(false),
    m_registrationsCount(0),
    m_registrationsCountHasBeenSet(false),
    m_expirationDateHasBeenSet(false),
    m_expired(false),
    m_expiredHasBeenSet(false),
    m_createdDateHasBeenSet(false)
{
}

Activation::Activation(JsonView jsonValue) :
    m_activationIdHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_defaultInstanceNameHasBeenSet(false),
    m_iamRoleHasBeenSet(false),
    m_registrationLimit(0),
    m_registrationLimitHasBeenSet(false),
    m_registrationsCount(0),
    m_registrationsCountHasBeenSet(false),
    m_expirationDateHasBeenSet(false),
    m_expired(false),
    m_expiredHasBeenSet(false),
    m_createdDateHasBeenSet(false)
{
  *this = jsonValue;
}

Activation& Activation::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("ActivationId"))
  {
    m_activationId = jsonValue.GetString("ActivationId");

    m_activationIdHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Description"))
  {
    m_description = jsonValue.GetString("Description");

    m_descriptionHasBeenSet = true;
  }

  if(jsonValue.ValueExists("DefaultInstanceName"))
  {
    m_defaultInstanceName = jsonValue.GetString("DefaultInstanceName");

    m_defaultInstanceNameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("IamRole"))
  {
    m_iamRole = jsonValue.GetString("IamRole");

    m_iamRoleHasBeenSet = true;
  }

  if(jsonValue.ValueExists("RegistrationLimit"))
  {
    m_registrationLimit = jsonValue.GetInteger("RegistrationLimit");

    m_registrationLimitHasBeenSet = true;
  }

  if(jsonValue.ValueExists("RegistrationsCount"))
  {
    m_registrationsCount = jsonValue.GetInteger("RegistrationsCount");

    m_registrationsCountHasBeenSet = true;
  }

  if(jsonValue.ValueExists("ExpirationDate"))
  {
    m_expirationDate = jsonValue.GetDouble("ExpirationDate");

    m_expirationDateHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Expired"))
  {
    m_expired = jsonValue.GetBool("Expired");

    m_expiredHasBeenSet = true;
  }

  if(jsonValue.ValueExists("CreatedDate"))
  {
    m_createdDate = jsonValue.GetDouble("CreatedDate");

    m_createdDateHasBeenSet = true;
  }

  return *this;
}

JsonValue Activation::Jsonize() const
{
  JsonValue payload;

  if(m_activationIdHasBeenSet)
  {
   payload.WithString("ActivationId", m_activationId);

  }

  if(m_descriptionHasBeenSet)
  {
   payload.WithString("Description", m_description);

  }

  if(m_defaultInstanceNameHasBeenSet)
  {
   payload.WithString("DefaultInstanceName", m_defaultInstanceName);

  }

  if(m_iamRoleHasBeenSet)
  {
   payload.WithString("IamRole", m_iamRole);

  }

  if(m_registrationLimitHasBeenSet)
  {
   payload.WithInteger("RegistrationLimit", m_registrationLimit);

  }

  if(m_registrationsCountHasBeenSet)
  {
   payload.WithInteger("RegistrationsCount", m_registrationsCount);

  }

  if(m_expirationDateHasBeenSet)
  {
   payload.WithDouble("ExpirationDate", m_expirationDate.SecondsWithMSPrecision());
  }

  if(m_expiredHasBeenSet)
  {
   payload.WithBool("Expired", m_expired);

  }

  if(m_createdDateHasBeenSet)
  {
   payload.WithDouble("CreatedDate", m_createdDate.SecondsWithMSPrecision());
  }

  return payload;
}

} // namespace Model
} // namespace SSM
} // namespace Aws


text:
<?php

namespace Account\Action\Claim;

use Account\Controller\ClaimController;
use Account\Service\ClaimAccountService;
use Account\ViewModel\ReviewViewModel;
use Core\Action\RedirectToRoute;
use Core\Action\ViewActionResult;
use DvsaCommon\Auth\MotIdentityProviderInterface;
use DvsaCommon\HttpRestJson\Exception\ValidationException;

class ReviewAction
{

    const TEMPLATE = 'account/claim/review';

    /** @var ClaimAccountService $claimAccountService */
    private $claimAccountService;

    /** @var MotIdentityProviderInterface $motIdentityProvider */
    private $motIdentityProvider;

    /**
     * ReviewAction constructor.
     * @param ClaimAccountService $claimAccountService
     * @param MotIdentityProviderInterface $motIdentityProvider
     */
    public function __construct(
        ClaimAccountService $claimAccountService,
        MotIdentityProviderInterface $motIdentityProvider
    )
    {
        $this->claimAccountService = $claimAccountService;
        $this->motIdentityProvider = $motIdentityProvider;
    }

    /**
     * @param $isPost
     * @param null $formData
     * @return ViewActionResult | RedirectToRoute
     */
    public function execute($isPost, $formData = null)
    {
        if ($isPost && $formData===null) {
            throw new \InvalidArgumentException('$formData cannot be null when $isPost is true');
        }

        if (!$this->claimAccountService->isStepRecorded(ClaimController::STEP_1_NAME)) {
            return new RedirectToRoute(ClaimController::ROUTE_CLAIM_ACCOUNT_CONFIRM_PASSWORD);
        }

        if (!$this->claimAccountService->isStepRecorded(ClaimController::STEP_2_NAME)) {
            return new RedirectToRoute(ClaimController::ROUTE_CLAIM_ACCOUNT_SET_SECURITY_QUESTION);
        }

        $actionResult = new ViewActionResult();

        $actionResult->layout()->setTemplate('layout/layout-govuk.phtml');

        $sessionData = $this->claimAccountService->getSession()->getArrayCopy();

        if ($isPost) {
            try {
                $this->claimAccountService->sendToApi($sessionData);
            } catch (ValidationException $e) {
                $inlineMessages = $e->getInlineMessages();
                $redirectAction = new RedirectToRoute(ClaimController::ROUTE_CLAIM_ACCOUNT_CONFIRM_PASSWORD);

                $redirectAction->addErrorMessage(ClaimController::NEW_PASSWORD_ERROR_MESSAGE_FIELD_NAME . $inlineMessages['password']);

                return $redirectAction;
            }

            $this->claimAccountService->markClaimedSuccessfully();

            $formData['submitted_step'] = ClaimController::STEP_3_NAME;

            $this->claimAccountService->captureStep($formData);
            return new RedirectToRoute(ClaimController::ROUTE_CLAIM_ACCOUNT_SUCCESS);
        }

        $sessionAsArray = $this->claimAccountService->sessionToArray() ?: [];
        $stepData = $this->getStepData() + $sessionAsArray;

        $reviewViewModel = new ReviewViewModel($stepData);
        $reviewViewModel->setData($stepData);
        $reviewViewModel->setSecurityQuestions($this->claimAccountService->getSecurityQuestions());

        $actionResult->setViewModel($reviewViewModel)
            ->setTemplate(self::TEMPLATE);

        return $actionResult;
    }

    /**
     * To assemble required parameters mainly to be passed to the view model.
     *
     * @return array
     */
    protected function getStepData()
    {
        $stepDataInSession = $this->claimAccountService->getFromSession(ClaimController::STEP_3_NAME);
        $stepData = is_null($stepDataInSession) ? [] : $stepDataInSession;
        $stepData['stepName'] = ClaimController::STEP_3_NAME;
        $stepData['serviceName'] = ClaimController::SERVICE_NAME;
        $stepData['username'] = $this->motIdentityProvider->getIdentity()->getUsername();
        $stepData['fullReview'] = $this->claimAccountService->sessionToArray() ?: [];

        return $stepData;
    }

    private function addErrors($messages, $field = '')
    {
        foreach ($messages as $message) {
            $this->addError($message, $field);
        }
    }

    private function addError($message, $field = '')
    {
        if (!array_key_exists($field, $this->errors)) {
            $this->errors[$field] = [];
        }

        $this->errors[$field][] = $message;
    }

}


text:
import os
import numpy as np
import math
import SimpleITK as sitk
from scipy import ndimage
import nibabel as nib
from PIL import Image
import scipy.misc
from scipy import signal
import warnings

warnings.filterwarnings("ignore")

def doggen(sigma):
    """
    Helper function to generate derivatives of Gaussian kernels, in either 1D, 2D, or 3D.
    Source code in MATLAB obtained from Qiyuan Tian, Stanford University, September 2015
    :param sigma: Sigma for use (see defaults in generate_FSL_structure_tensor)
    :return: Derivative of Gaussian kernel with dimensions of sigma.
    """
    halfsize = np.ceil(3 * np.max(sigma))
    x = range(np.single(-halfsize), np.single(halfsize + 1));  # Python colon is not inclusive at end, while MATLAB is.
    dim = len(sigma);

    if dim == 1:
        X = np.array(x);  # Remember that, by default, numpy arrays are elementwise multiplicative
        X = X.astype(float);
        k = -X * np.exp(-X ** 2 / (2 * sigma ** 2));

    elif dim == 2:
        [X, Y] = np.meshgrid(x, x);
        X = X.astype(float);
        Y = Y.astype(float);
        k = -X * np.exp(-X ** 2 / (2 * sigma[0] ^ 2) * np.exp(-Y ** 2))

    elif dim == 3:
        [X, Y, Z] = np.meshgrid(x, x, x);
        X = X.transpose(0, 2, 1);  # Obtained through vigorous testing (see below...)
        Y = Y.transpose(2, 0, 1);
        Z = Z.transpose(2, 1, 0);

        X = X.astype(float);
        Y = Y.astype(float);
        Z = Z.astype(float);
        k = -X * np.exp(np.divide(-np.power(X, 2), 2 * np.power(sigma[0], 2))) * np.exp(
            np.divide(-np.power(Y, 2), 2 * np.power(sigma[1], 2))) * np.exp(
            np.divide(-np.power(Z, 2), 2 * np.power(sigma[2], 2)))

    else:
        print
        'Only supports up to 3 dimensions'

    return np.divide(k, np.sum(np.abs(k[:])));

def gaussgen(sigma):
    """
    Function to generate Gaussian kernels, in 1D, 2D and 3D.
    Source code in MATLAB obtained from Qiyuan Tian, Stanford University, September 2015
    :param sigma: Sigma for use in generating Gaussian kernel (see defaults in generate_FSL_structure_tensor)
    :return: Gaussian kernel with dimensions of sigma.
    """
    halfsize = np.ceil(3 * max(sigma));
    x = range(np.single(-halfsize), np.single(halfsize + 1));

    dim = len(sigma);

    if dim == 1:
        x = x.astype(float);
        k = np.exp(-x ** 2 / (2 * sigma ^ 2));

    elif dim == 2:
        [X, Y] = np.meshgrid(x, x);
        X = X.astype(float);
        Y = Y.astype(float);

        k = np.exp(-X ** 2 / (2 * sigma[0] ** 2)) * np.exp(-Y ** 2 / (2 * sigma[1] ** 2));

    elif dim == 3:
        [X, Y, Z] = np.meshgrid(x, x, x);
        X = X.transpose(0, 2, 1);  # Obtained through vigorous testing (see below...)
        Y = Y.transpose(2, 0, 1);
        Z = Z.transpose(2, 1, 0);

        X = X.astype(float);
        Y = Y.astype(float);
        Z = Z.astype(float);
        k = np.exp(-X ** 2 / (2 * sigma[0] ** 2)) * np.exp(-Y ** 2 / (2 * sigma[1] ** 2)) * np.exp(
            -Z ** 2 / (2 * sigma[2] ** 2));

    else:
        print
        'Only supports up to dimension 3'

    return np.divide(k, np.sum(np.abs(k)));

def tiff_to_array(folder_path, input_path):
    """
    Function takes a single image (TIFF, or other also works), and returns
    the single image as a numpy array.  Called by tiff_stack_to_array.
    :param input_path: Single image file to open.
    :return: Numpy representation of image.
    """
    im = Image.open(folder_path + input_path)
    # im.show()

    imarray = np.array(im)
    # print(imarray)

    return imarray

def tiff_stack_to_array(input_path):
    """
    Function takes input_path, which should should lead to a directory.
    Loads all TIFFs in input_path, then generates numpy arrays from the
    TIFF stack by calling tiff_to_array helper function.  Make sure TIFF
    images are ordered in numerical order.
    :param input_path: Folder or directory containing .tiff stack.
    :return: Numpy array of tiff stack.
    """
    im_list = [];
    for filename in os.listdir(input_path):
        if filename.endswith(".tiff"):
            # print(os.path.join(directory, filename))
            im_arr = tiff_to_array(input_path, filename)
            im_list.append(im_arr)

    s = np.stack(im_list, axis=2)
    print
    s.shape
    return s

def nii_to_tiff_stack(input_path, token):
    """
    Function loads an nii using SITK, then converts the nii into a folder containing a TIFF stack.
    This function is useful later on for generating the structure tensor.
    :param input_path: Path to .nii file.
    :param token: Name of token.
    """

    image = sitk.ReadImage(input_path);

    planes_number = image.GetSize();
    data = sitk.GetArrayFromImage(image)
    z_dimension = planes_number[2];

    ## if we have (i, j, k), we want (k, j, i)  (converts nibabel format to sitk format)
    ##new_im = aut_1367.swapaxes(0,2) # just swap i and k

    if not os.path.exists(token + "_TIFFs"):
        os.makedirs(token + "_TIFFs");

    plane = 0;

    for plane in range(0, z_dimension):
        output = data[plane, :, :]
        scipy.misc.toimage(output).save(token + "_TIFFs/" + token + "_" + str(plane) + '.tiff')

def generate_FSL_structure_tensor(img_data, filename, dogsigmaArr=[1], gausigmaArr=[2.3], angleArr=[25]):
    """
    Function takes a numpy array (from TIFF_stack_to_array) and saves output
    FSL structure tensor as filename string. Allows inputting alternate dogsigmaArr,
    gausigmaArr, angleArr, although defaults to currently to parameters from MATLAB script.
    Also returns tensorfsl (the tensor fsl structure) image numpy array.
    ## Parameters (the script loops through all parameters and saves each result automatically)
    # dogsigmaArr = [1]; Sigma values for derivative of gaussian filter, recommended value: 0.6 - 1.3 (based on actual data)
    # gausigmaArr = [2.3]; Sigma values for gaussian filter, recommended value: 1.3 - 2.3 (based on actual data)
    # angleArr = [25]; Angle thresholds for fiber tracking, recommended value: 20 - 30.
    Follows code from MATLAB CAPTURE scripts.
    :param img_data: Numpy array of image, typically from tiff_stack_to_array called on a directory of TIFFs.
    :param filename: Name to save the FSL structure tensor as.
    :param dogsigmaArr: Sigma values for derivative of Gaussian filter, with recommended values between 0.6 - 1.3.
    :param gausigmaArr: Sigma values for Gaussian filter, with recommended values between 1.3 - 2.3.
    :param angleArr: Angle threshold for fiber tracking, with recommended values between 20 - 30.
    :return tensorfsl: TensorFSL format of structure tensor (upper triangular matrix)
    """
    for jj in range(len(dogsigmaArr)):
        dogsigma = dogsigmaArr[jj];
        print
        "Start DoG Sigma on " + str(dogsigma);

        # Generate dog kernels
        dogkercc = doggen([dogsigma, dogsigma, dogsigma]);
        dogkercc = np.transpose(dogkercc, (0, 2, 1));  # annoying

        # print dogkercc.shape;
        # print dogkercc[:, :, 0];

        dogkerrr = np.transpose(dogkercc, (1, 0, 2));

        # print dogkerrr[:, :, 0];
        dogkerzz = np.transpose(dogkercc, (0, 2, 1));

        # print dogkerzz[:, :, 0];

        # Compute gradients
        grr = signal.convolve(img_data, dogkerrr, 'same');

        # print grr[:, :, 0];

        gcc = signal.convolve(img_data, dogkercc, 'same');

        # print gcc[:, :, 0];

        gzz = signal.convolve(img_data, dogkerzz, 'same');

        # print gzz[:, :, 0];

        # Compute gradient products
        gprrrr = np.multiply(grr, grr);

        # print gprrrr[:, :, 0];

        gprrcc = np.multiply(grr, gcc);

        # print gprrcc[:, :, 0];

        gprrzz = np.multiply(grr, gzz);

        # print gprrzz[:, :, 0]

        gpcccc = np.multiply(gcc, gcc);
        gpcczz = np.multiply(gcc, gzz);
        gpzzzz = np.multiply(gzz, gzz);

        # Compute gradient amplitudes
        # print ga.dtype;
        ga = np.sqrt(gprrrr + gpcccc + gpzzzz);

        # print ga[:, :, 0];

        # print "GA SHAPE:"
        # print ga.shape;

        # Convert numpy ndarray object to Nifti data type
        gradient_amplitudes_data = nib.Nifti1Image(ga, affine=np.eye(4));

        # Save gradient amplitudes image
        nib.save(gradient_amplitudes_data, 'gradient_amplitudes.nii');

        # Compute gradient vectors
        gv = np.concatenate((grr[..., np.newaxis], gcc[..., np.newaxis], gzz[..., np.newaxis]), axis=3);

        # print gv[:, :, 0, 0];

        gv = np.divide(gv, np.tile(ga[..., None], [1, 1, 1, 3]));
        # print gv[:, :, 0, 1];

        # print "GV SHAPE:"
        # print gv.shape;

        # Convert numpy ndarray object to Nifti data type
        gradient_vectors_data = nib.Nifti1Image(gv, affine=np.eye(4));

        # Save gradient vectors
        nib.save(gradient_vectors_data, 'gradient_vectors.nii');

        # Compute structure tensor
        for kk in range(len(gausigmaArr)):
            gausigma = gausigmaArr[kk];
            print
            "Start Gauss Sigma with gausigma = " + str(gausigma);

            print
            "Generating Gaussian kernel..."
            gaussker = np.single(gaussgen([gausigma, gausigma, gausigma]));

            # print gaussker[:, :, 0];

            print
            "Blurring gradient products..."
            gprrrrgauss = signal.convolve(gprrrr, gaussker, "same");

            # print gprrrrgauss[:, :, 0];

            gprrccgauss = signal.convolve(gprrcc, gaussker, "same");

            # print gprrccgauss[:, :, 0];

            gprrzzgauss = signal.convolve(gprrzz, gaussker, "same");
            gpccccgauss = signal.convolve(gpcccc, gaussker, "same");
            gpcczzgauss = signal.convolve(gpcczz, gaussker, "same");
            gpzzzzgauss = signal.convolve(gpzzzz, gaussker, "same");

            print
            "Saving a copy for this Gaussian sigma..."
            tensorfsl = np.concatenate((gprrrrgauss[..., np.newaxis], gprrccgauss[..., np.newaxis],
                                        gprrzzgauss[..., np.newaxis], gpccccgauss[..., np.newaxis],
                                        gpcczzgauss[..., np.newaxis], gpzzzzgauss[..., np.newaxis]), axis=3);

            # Convert numpy ndarray object to Nifti data type
            tensor_fsl_data = nib.Nifti1Image(tensorfsl, affine=np.eye(4));

            nib.save(tensor_fsl_data, str(filename) + "dogsigma_" + str(jj) + "gausigma_" + str(kk) + 'tensorfsl.nii');

    print
    'Completed computing structure tensor on ' + str(filename) + '!'
    return tensorfsl


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

<TITLE>
com.google.gxp.compiler (GXP Compiler 0.2.4-beta (BETA))
</TITLE>

<META NAME="date" CONTENT="2008-12-12">

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

      Overview
    Package
      Class
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package com.google.gxp.compiler

Interface Summary

CompilationManager
Strategy for helping CompilationSet determine when it should execute
 compilation tasks.

Configuration
Configuration for the GXP Compiler.

Class Summary

CompilationSet
A set of CompilationUnits, and the logic for compiling (subsets of)
 them.

CompilationSet.Builder
Builds a CompilationSet.

CompilationTask
Represents a fine-grained unit of work when compiling.

CompilationUnit
A compilation unit.

Compiler
The core GXP Compiler class.

SimpleCompilationManager
A simple, ultra-conservative, CompilationManager that always assumes
 that everything needs rebuilding.

Enum Summary

Phase
The compilation phases, in order.

Exception Summary

InvalidConfigException
Exception indicating that the Configuration is invalid in some way.

      Overview
    Package
      Class
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes


text:
import authActions from './auth-actions';
module.exports = {
  authActions
};


text:
<component name="ProjectRunConfigurationManager">
  <configuration default="false" name="Test Performance" type="JUnit" factoryName="JUnit">
    <module name="intellij-rust.test" />
    <option name="PACKAGE_NAME" value="org.rustPerformanceTests" />
    <option name="MAIN_CLASS_NAME" value="" />
    <option name="METHOD_NAME" value="" />
    <option name="TEST_OBJECT" value="package" />
    <option name="VM_PARAMETERS" value="-ea -Didea.system.path=$PROJECT_DIR$/build/idea-sandbox/system-test -Didea.config.path=$PROJECT_DIR$/build/idea-sandbox/config-test" />
    <option name="PARAMETERS" value="" />
    <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
    <method v="2">
      <option name="Make" enabled="true" />
    </method>
  </configuration>
</component>


text:
class AddReviewToPermissions < ActiveRecord::Migration
  def change
    add_column :permissions, :review, :boolean, :default => false
  end
end


text:
<?PHP

?>
<?PHP require_once"include/init.php"; ?>
<?PHP include"web.parts/header.php"; ?>

Donations

    <form name="filterfrm" id="filterfrm" action='donations.php' method="get">
        <fieldset>
            <legend onclick="$('#search_form_options').toggle()" class="cursor">Search Options</legend>

Donation ID<input type="text" name="donation_id" class="text" value="<?PHP  if(isset($_GET['donation_id'])) echo $_GET['donation_id']?>" />

First Name<input type="text" name="first_name" class="text" value="<?PHP  if(isset($_GET['first_name'])) echo $_GET['first_name']?>" />

Last Name<input type="text" name="last_name" class="text" value="<?PHP  if(isset($_GET['last_name'])) echo $_GET['last_name']?>" />

Email<input type="text" name="email" class="text" value="<?PHP  if(isset($_GET['email'])) echo $_GET['email']?>" />

From Date (YYYY-MM-DD)<input type="text" id="date_from" name="date_from" class="text date_input" value="<?PHP  if(isset($_GET['date_from'])) echo $_GET['date_from']?>" />

To Date (YYYY-MM-DD)<input type="text" id="date_to" name="date_to" class="text date_input" value="<?PHP  if(isset($_GET['date_to'])) echo $_GET['date_to']?>" />

Payment Status
                   <select id="country" name="status_id">
                        <option value=""> -- View All -- </option>
                        <?PHP
                        echo clsDonationStatus::Instance()->Combo($_GET['status_id']);
                    ?>
                    </select>

Order By
                    <select name='order_by' id='order_by' class="select">
                        <?PHP
                        echo clsArray::arrayToComboOptions(modDonations::OrderFields(),$_GET['order_by']);
                        ?>

                    </select>

Order Direction

                     <select name='order_direction' id='order_direction' class="select">
                        <?PHP
                        $options = array();
                        $options['desc'] = "DESC";
                        $options['asc'] = "ASC";

                        echo clsArray::arrayToComboOptions($options,$_GET['order_direction']);
                        ?>

                    </select>

Per Page

                     <select name='per_page' id='per_page' class="select">
                        <?PHP
                        $options = array();
                        $options['50'] = "50";
                        $options['100'] = "100";
                        $options['150'] = "150";
                        $options['200'] = "200";
                        $options['250'] = "250";
                        $options['300'] = "300";
                        $options['400'] = "400";
                        $options['500'] = "500";
                        $options['1000'] = "1000";

                        echo clsArray::arrayToComboOptions($options,$_GET['per_page']);
                        ?>

                    </select>

<input name="btn" type="submit" value="Search" class="btn" />

        </fieldset>
    </form>

    <?PHP CommonFunc::RenderFlashMessage(); ?>

    <?PHP
    $oDonations = new modDonations(MySql::Instance());

    $paging = $oDonations->PagedDataSet($_GET);
    if($paging->hasRows()):
    ?>
    <form method="post" action="csv_export.php">
        <input type="hidden" name="qstr" value="<?PHP echo http_build_query($_GET); ?>" />

            <input type='checkbox' name='checkall' onclick='checkUncheckAll(this);' class="check_radio" />
            First Name
            Last Name
            Email
            Date
            Amount
            Status
            Action

        <?PHP
        $i=0;
        while($donation = MySql::Instance()->myArray($paging->result)):
            $class = CommonFunc::tr_class($i);

        ?>
        <tr class="<?PHP echo $class; ?>">

                <input type='hidden' name='visible_donation_ids[]' value='<?=$donation['donation_id']?>' />
                <input type='checkbox' name='donation_ids[]' value='<?=$donation['donation_id']?>' class="check_radio" />
            <?PHP echo $donation['first_name']; ?>
            <?PHP echo $donation['last_name']; ?>
            <?PHP echo $donation['email']; ?>
            <?PHP echo CommonFunc::getFormatedDateTime( $donation['donation_date']); ?>
            <?PHP echo $donation['amount']; ?>
            <?PHP echo ucWords($donation['status_id']); ?>

                <a title="View" onclick="return GB_showFullScreen('Request#<?PHP echo $donation['donation_id']; ?>', '../../../php/view.php?id=<?PHP echo $donation['donation_id']; ?>')" class="btn">
                <a Title="Delete" onclick="return confirm('Are you sure you wish to delete this entry?');" href="delete_donation.php?id=<?PHP echo $donation['donation_id']; ?>" class="btn">

        <?PHP $i++; endwhile; ?>

            <input type="submit" name="export_selected" value="Export Selected Records" class="btn" />
            <input type="submit" name="export_all_visible" value="Export Visible Records" class="btn" />
            <input type="submit" name="export_all_csv" value="Export ALL Records" class="btn" />

    </form>

        <?PHP echo $paging->render(); ?>

    <?PHP else: ?>

No donations found

    <?PHP endif; ?>
<?PHP include"web.parts/footer.php"; ?>


text:
#pragma once

#include <memory>
#include <string>
#include <vector>

#include "modules/drivers/lidar/proto/velodyne.pb.h"

#include "cyber/cyber.h"
#include "modules/drivers/lidar/velodyne/parser/calibration.h"

namespace apollo {
namespace drivers {
namespace velodyne {

using apollo::drivers::velodyne::VelodynePacket;
using apollo::drivers::velodyne::VelodyneScan;

constexpr double DEGRESS_TO_RADIANS = 3.1415926535897 / 180.0;

class OnlineCalibration {
 public:
  OnlineCalibration() {}
  ~OnlineCalibration() {}

  int decode(const std::shared_ptr<VelodyneScan>& scan_msgs);
  void dump(const std::string& file_path);
  void get_unit_index();
  bool inited() const { return inited_; }
  Calibration calibration() const { return calibration_; }

 private:
  bool inited_;
  Calibration calibration_;
  std::vector<uint8_t> status_types_;
  std::vector<uint8_t> status_values_;
  // store first two "unit#" value index
  std::vector<int> unit_indexs_;
};

}  // namespace velodyne
}  // namespace drivers
}  // namespace apollo


text:
require_relative '../helper'

describe "play" do
  before do
    @o = Object.new
    @t = pry_tester(@o)
  end

  describe "with an argument" do

    # can't think of a f*cking way to test this!!
    describe "implied file" do
      # it 'should play from the file associated with the current binding' do
      #   # require 'fixtures/play_helper'
      # end

      # describe "integer" do
      #   it "should process one line from _pry_.last_file" do
      #     @t.process_command 'play --lines 1', @eval_str
      #     @eval_str.should =~ /bing = :bing\n/
      #   end
      # end

      # describe "range" do
      #   it "should process multiple lines at once from _pry_.last_file" do
      #     @t.process_command 'play --lines 1..3', @eval_str
      #     [/bing = :bing\n/, /bang = :bang\n/, /bong = :bong\n/].each { |str|
      #       @eval_str.should =~ str
      #     }
      #   end
    end
  end

  describe "playing a file" do
    it 'should play a file' do
      @t.process_command 'play spec/fixtures/whereami_helper.rb'
      @t.eval_string.should == unindent(<<-STR)
        class Cor
          def a; end
          def b; end
          def c; end
          def d; end
        end
      STR
    end

    it 'should output file contents with print option' do
      @t.process_command 'play --print spec/fixtures/whereami_helper.rb'
      @t.last_output.should == unindent(<<-STR)
        1: class Cor
        2:   def a; end
        3:   def b; end
        4:   def c; end
        5:   def d; end
        6: end
      STR
    end
  end

  describe "whatever" do
    before do
      def @o.test_method
        :test_method_content
      end
    end

    it 'should play documentation with the -d switch' do
      # @v = 10
      # @y = 20
      def @o.test_method
        :test_method_content
      end

      @t.process_command 'play -d test_method'
      @t.eval_string.should == unindent(<<-STR)
        @v = 10
        @y = 20
      STR
    end

    it 'should restrict -d switch with --lines' do
      # @x = 0
      # @v = 10
      # @y = 20
      # @z = 30
      def @o.test_method
        :test_method_content
      end

      @t.process_command 'play -d test_method --lines 2..3'
      @t.eval_string.should == unindent(<<-STR)
        @v = 10
        @y = 20
      STR
    end

    it 'has pretty error messages when -d cant find object' do
      expect { @t.process_command "play -d sdfsdf" }.to raise_error(Pry::CommandError, /Cannot locate/)
    end

    it 'should play a method (a single line)' do
      @t.process_command 'play test_method --lines 2'
      @t.eval_string.should == ":test_method_content\n"
    end

    it 'should properly reindent lines' do
      def @o.test_method
        'hello world'
      end

      @t.process_command 'play test_method --lines 2'
      @t.eval_string.should == "'hello world'\n"
    end

    it 'should APPEND to the input buffer when playing a method line, not replace it' do
      @t.eval_string = unindent(<<-STR)
        def another_test_method
      STR

      @t.process_command 'play test_method --lines 2'

      @t.eval_string.should == unindent(<<-STR)
        def another_test_method
          :test_method_content
      STR
    end

    it 'should play a method (multiple lines)' do
      def @o.test_method
        @var0 = 10
        @var1 = 20
        @var2 = 30
        @var3 = 40
      end

      @t.process_command 'play test_method --lines 3..4'
      @t.eval_string.should == unindent(<<-STR, 0)
        @var1 = 20
        @var2 = 30
      STR
    end

    describe "play -i" do
      it 'should play multi-ranged input expressions' do
        a = b = c = d = e = 0
        redirect_pry_io(InputTester.new('a += 1', 'b += 1',
                                        'c += 1', 'd += 1', 'e += 1',
                                        "play -i 1..3"), StringIO.new) do
          binding.pry
        end

        [a, b, c].all? { |v| v.should == 2 }
        d.should == 1
      end
    end

    describe "play -e" do
      it 'should run an expression from given line number' do
        def @o.test_method
          @s = [
            1,2,3,
            4,5,6
          ]
        end

        @t.process_command 'play test_method -e 2'
        @t.eval_string.should == unindent(<<-STR, 0)
          @s = [
            1,2,3,
            4,5,6
          ]
        STR
      end
    end
  end
end