text:
package gitbucket.core.service

import java.io.File

import gitbucket.core.model.CommitComment
import gitbucket.core.model.Profile._
import gitbucket.core.model.Profile.profile.blockingApi._
import gitbucket.core.model.Profile.dateColumnType
import gitbucket.core.util.Directory._
import gitbucket.core.util.{FileUtil, StringUtil}
import org.apache.commons.io.FileUtils

trait CommitsService {

  def getCommitComments(owner: String, repository: String, commitId: String, includePullRequest: Boolean)(
    implicit s: Session
  ) =
    CommitComments filter { t =>
      t.byCommit(owner, repository, commitId) && (t.issueId.isEmpty || includePullRequest)
    } list

  def getCommitComment(owner: String, repository: String, commentId: String)(implicit s: Session) =
    if (commentId forall (_.isDigit))
      CommitComments filter { t =>
        t.byPrimaryKey(commentId.toInt) && t.byRepository(owner, repository)
      } firstOption
    else
      None

  def createCommitComment(
    owner: String,
    repository: String,
    commitId: String,
    loginUser: String,
    content: String,
    fileName: Option[String],
    oldLine: Option[Int],
    newLine: Option[Int],
    issueId: Option[Int]
  )(implicit s: Session): Int =
    CommitComments returning CommitComments.map(_.commentId) insert CommitComment(
      userName = owner,
      repositoryName = repository,
      commitId = commitId,
      commentedUserName = loginUser,
      content = content,
      fileName = fileName,
      oldLine = oldLine,
      newLine = newLine,
      registeredDate = currentDate,
      updatedDate = currentDate,
      issueId = issueId
    )

  def updateCommitCommentPosition(commentId: Int, commitId: String, oldLine: Option[Int], newLine: Option[Int])(
    implicit s: Session
  ): Unit =
    CommitComments
      .filter(_.byPrimaryKey(commentId))
      .map { t =>
        (t.commitId, t.oldLine, t.newLine)
      }
      .update(commitId, oldLine, newLine)

  def updateCommitComment(commentId: Int, content: String)(implicit s: Session) = {
    CommitComments
      .filter(_.byPrimaryKey(commentId))
      .map { t =>
        (t.content, t.updatedDate)
      }
      .update(content, currentDate)
  }

  def deleteCommitComment(commentId: Int)(implicit s: Session) =
    CommitComments filter (_.byPrimaryKey(commentId)) delete

  def saveCommitCommentDiff(
    owner: String,
    repository: String,
    commitId: String,
    fileName: String,
    oldLine: Option[Int],
    newLine: Option[Int],
    diffJson: String
  ): Unit = {
    val dir = new File(getDiffDir(owner, repository), FileUtil.checkFilename(commitId))
    if (!dir.exists) {
      dir.mkdirs()
    }
    val file = diffFile(dir, fileName, oldLine, newLine)
    FileUtils.write(file, diffJson, "UTF-8")
  }

  def loadCommitCommentDiff(
    owner: String,
    repository: String,
    commitId: String,
    fileName: String,
    oldLine: Option[Int],
    newLine: Option[Int]
  ): Option[String] = {
    val dir = new File(getDiffDir(owner, repository), FileUtil.checkFilename(commitId))
    val file = diffFile(dir, fileName, oldLine, newLine)
    if (file.exists) {
      Option(FileUtils.readFileToString(file, "UTF-8"))
    } else None
  }

  private def diffFile(dir: java.io.File, fileName: String, oldLine: Option[Int], newLine: Option[Int]): File = {
    new File(
      dir,
      StringUtil.sha1(
        fileName +
          "_oldLine:" + oldLine.map(_.toString).getOrElse("") +
          "_newLine:" + newLine.map(_.toString).getOrElse("")
      )
    )
  }

}


text:
package com.ebay.rtran.maven

import java.io.File

import org.apache.commons.io.FileUtils
import org.scalatest.{BeforeAndAfterEach, FlatSpecLike, Matchers}

class MavenRemoveRepositoriesRuleTest extends FlatSpecLike with Matchers with BeforeAndAfterEach {
  val projectRoot = new File(getClass.getClassLoader.getResource("mvnproject").getFile)
  val destProjectRoot = new File(projectRoot.getParentFile, projectRoot.getName + "-bak")

  override def beforeEach = {
    FileUtils.deleteQuietly(destProjectRoot)
    FileUtils.copyDirectory(projectRoot, destProjectRoot)
  }

  "MavenRemoveRepositoriesRule" should "remove repository that matches given patterns" in {
    val ruleConfig = MavenRemoveRepositoriesRuleConfig(
      Set(
        ".*/content/repositories/releases[/]?",
        ".*/content/repositories/snapshots[/]?"
      )
    )
    val projectCtx = new MavenProjectCtx(destProjectRoot)
    val provider = new MultiModuleMavenModelProvider
    val rule = new MavenRemoveRepositoriesRule(ruleConfig)
    val model = provider create projectCtx
    provider save (rule transform model)

    val transformed = provider create projectCtx
    transformed.modules foreach { module =>
      module.pomModel.getRepositories.size should be (0)
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
namespace Facepunch {
    export namespace WebGame {
        export class ShadowCamera extends WebGame.OrthographicCamera {
            readonly game: Game;

            private readonly targetCamera: Camera;

            constructor(game: Game, targetCamera: Camera) {
                super(game, 1, 1, 0, 1);

                this.game = game;
                this.targetCamera = targetCamera;
            }

            private addToFrustumBounds(vec: Facepunch.Vector4, bounds: Facepunch.Box3): void {
                vec.applyMatrix4(this.targetCamera.getMatrix());
                vec.applyMatrix4(this.getInverseMatrix());

                bounds.addPoint(vec);
            }

            private static readonly getFrustumBounds_vec = new Facepunch.Vector4();
            private getFrustumBounds(near: number, far: number, bounds: Facepunch.Box3): void {
                bounds.min.set(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);
                bounds.max.set(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY);

                const perspCamera = this.targetCamera as PerspectiveCamera;
                if (perspCamera.getFov === undefined) {
                    throw "Not implement for non-perspective cameras";
                }

                const yScale = Math.tan(perspCamera.getFov() * 0.5);
                const xScale = yScale * perspCamera.getAspect();

                const xNear = xScale * near;
                const yNear = yScale * near;

                const xFar = xScale * far;
                const yFar = yScale * far;

                const vec = ShadowCamera.getFrustumBounds_vec;

                this.addToFrustumBounds(vec.set( xNear,  yNear, near, 1), bounds);
                this.addToFrustumBounds(vec.set(-xNear,  yNear, near, 1), bounds);
                this.addToFrustumBounds(vec.set( xNear, -yNear, near, 1), bounds);
                this.addToFrustumBounds(vec.set(-xNear, -yNear, near, 1), bounds);

                this.addToFrustumBounds(vec.set( xFar,  yFar, far, 1), bounds);
                this.addToFrustumBounds(vec.set(-xFar,  yFar, far, 1), bounds);
                this.addToFrustumBounds(vec.set( xFar, -yFar, far, 1), bounds);
                this.addToFrustumBounds(vec.set(-xFar, -yFar, far, 1), bounds);
            }

            private static readonly renderShadows_bounds = new Facepunch.Box3();
            private static readonly renderShadows_vec1 = new Facepunch.Vector3();
            private static readonly renderShadows_vec2 = new Facepunch.Vector3();
            bufferCascadeBegin(lightRotation: Facepunch.Quaternion, near: number, far: number): void {
                const bounds = ShadowCamera.renderShadows_bounds;
                const vec1 = ShadowCamera.renderShadows_vec1;
                const vec2 = ShadowCamera.renderShadows_vec2;

                vec1.set(0, 0, 1);
                this.targetCamera.applyRotationTo(vec1);
                vec1.multiplyScalar((near + far) * 0.5);

                this.targetCamera.getPosition(vec2);

                vec1.add(vec2);

                this.setRotation(lightRotation);
                this.setPosition(vec1);

                this.getFrustumBounds(near, far, bounds);

                const xDiff = bounds.max.x - bounds.min.x;
                const yDiff = bounds.max.y - bounds.min.y;
                const zDiff = bounds.max.z - bounds.min.z;

                // TODO: Reposition based on bounds
                this.setSize(zDiff);
                this.setAspect(xDiff / zDiff);
            }

            bufferCascadeEnd(): void {

            }
        }
    }
}


text:
{{ site.footer.location }}

                        {% for adress in site.address %}
                        {{ adress.line|raw }}

                        {% endfor %}

{{ site.footer.social }}

                        {% for network in site.social %}

                        {% endfor %}

                    Copyright © {{ site.footer.copyright|raw }} 20{{ site.time | date: '%y' }}


text:
from setuptools import setup, Extension

ext_modules = [
    Extension(
        name='queueing_tool.network.priority_queue',
        sources=['queueing_tool/network/priority_queue.c'],
    ),
    Extension(
        name='queueing_tool.queues.choice',
        sources=['queueing_tool/queues/choice.c'],
    ),
]

setup(ext_modules=ext_modules)


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Eventus.Domain;
using Eventus.Events;
using Eventus.Storage;

namespace Eventus.Logging
{
    public class EventStorageProviderLoggingDecorator : LoggingDecorator, IEventStorageProvider
    {
        private readonly IEventStorageProvider _decorated;

        protected override string TypeName => "Event Storage Provider";

        public EventStorageProviderLoggingDecorator(IEventStorageProvider decorated)
        {
            _decorated = decorated;
        }

        public Task<IEnumerable<IEvent>> GetEventsAsync(Type aggregateType, Guid aggregateId, int start, int count)
        {
            return LogMethodCallAsync(() => _decorated.GetEventsAsync(aggregateType, aggregateId, start, count), new object[] { aggregateType, aggregateId, start, count });
        }

        public Task<IEvent> GetLastEventAsync(Type aggregateType, Guid aggregateId)
        {
            return LogMethodCallAsync(() => _decorated.GetLastEventAsync(aggregateType, aggregateId), new object[] { aggregateType, aggregateId });
        }

        public Task CommitChangesAsync(Aggregate aggregate)
        {
            return LogMethodCallAsync(() => _decorated.CommitChangesAsync(aggregate), aggregate);
        }
    }
}


text:
<?php

namespace Urban\UserBundle\Event;

use Symfony\Component\EventDispatcher\Event;
use Urban\UserBundle\Entity\Interfaces\AbstractUserInterface;

class UserRegisterEvent extends Event
{
    /**
     * @var AbstractUserInterface
     *
     * User
     */
    protected $user;

    /**
     * Construct method
     *
     * @param AbstractUserInterface $user User
     */
    public function __construct(AbstractUserInterface $user)
    {
        $this->user = $user;
    }

    /**
     * @return AbstractUserInterface User
     */
    public function getUser()
    {
        return $this->user;
    }
}


text:
apiAttachAvailable = u'API disponible'
apiAttachNotAvailable = u'No disponible'
apiAttachPendingAuthorization = u'Autorizaci\xf3n pendiente'
apiAttachRefused = u'Rechazado'
apiAttachSuccess = u'Conectado'
apiAttachUnknown = u'Desconocido'
budDeletedFriend = u'Borrado de la lista de contactos'
budFriend = u'Contacto'
budNeverBeenFriend = u'Nunca estuvo en la lista de contactos'
budPendingAuthorization = u'Autorizaci\xf3n pendiente'
budUnknown = u'Desconocido'
cfrBlockedByRecipient = u'Llamada bloqueada por el destinatario'
cfrMiscError = u'Error de car\xe1cter general'
cfrNoCommonCodec = u'Ning\xfan c\xf3dec com\xfan'
cfrNoProxyFound = u'No se encontr\xf3 proxy'
cfrNotAuthorizedByRecipient = u'El usuario actual no est\xe1 autorizado por el destinatario'
cfrRecipientNotFriend = u'El destinatario no es un contacto'
cfrRemoteDeviceError = u'Existe un problema con el dispositivo de sonido remoto'
cfrSessionTerminated = u'Sesi\xf3n terminada'
cfrSoundIOError = u'Error de E/S de sonido'
cfrSoundRecordingError = u'Error de grabaci\xf3n de sonido'
cfrUnknown = u'Desconocido'
cfrUserDoesNotExist = u'El usuario o el n\xfamero telef\xf3nico no existen'
cfrUserIsOffline = u'Est\xe1 desconectado/a'
chsAllCalls = u'Di\xe1logos heredados'
chsDialog = u'Di\xe1logo'
chsIncomingCalls = u'Esperando aceptaci\xf3n grupal'
chsLegacyDialog = u'Di\xe1logos heredados'
chsMissedCalls = u'Di\xe1logo'
chsMultiNeedAccept = u'Esperando aceptaci\xf3n grupal'
chsMultiSubscribed = u'Grupal suscrita'
chsOutgoingCalls = u'Grupal suscrita'
chsUnknown = u'Desconocido'
chsUnsubscribed = u'No suscrito'
clsBusy = u'Ocupado'
clsCancelled = u'Cancelado'
clsEarlyMedia = u'Reproduciendo medios iniciales (Early Media)'
clsFailed = u'Perd\xf3n, llamada fallida!'
clsFinished = u'Finalizada'
clsInProgress = u'Llamada en curso'
clsLocalHold = u'En espera local'
clsMissed = u'Llamada perdida'
clsOnHold = u'En espera'
clsRefused = u'Rechazado'
clsRemoteHold = u'En espera remota'
clsRinging = u'helistanud'
clsRouting = u'Enrutando'
clsTransferred = u'Desconocido'
clsTransferring = u'Desconocido'
clsUnknown = u'Desconocido'
clsUnplaced = u'Nunca se realiz\xf3'
clsVoicemailBufferingGreeting = u'Almacenando saludo en el b\xfafer'
clsVoicemailCancelled = u'Mensaje de voz cancelado'
clsVoicemailFailed = u'Fallo del buz\xf3n del voz'
clsVoicemailPlayingGreeting = u'Reproduciendo saludo'
clsVoicemailRecording = u'Grabando mensaje de voz'
clsVoicemailSent = u'Mensaje de voz enviado'
clsVoicemailUploading = u'Cargando mensaje de voz'
cltIncomingP2P = u'Llamada recibida de par a par'
cltIncomingPSTN = u'Llamada recibida'
cltOutgoingP2P = u'Llamada realizada de par a par'
cltOutgoingPSTN = u'Llamada realizada'
cltUnknown = u'Desconocido'
cmeAddedMembers = u'Miembros agregados'
cmeCreatedChatWith = u'Conversaci\xf3n iniciada con'
cmeEmoted = u'Desconocido'
cmeLeft = u'Conversaci\xf3n abandonada'
cmeSaid = u'Dijo'
cmeSawMembers = u'Miembros vistos'
cmeSetTopic = u'Definici\xf3n del tema'
cmeUnknown = u'Desconocido'
cmsRead = u'Le\xeddo'
cmsReceived = u'Recibido'
cmsSending = u'Enviando...'
cmsSent = u'Enviado'
cmsUnknown = u'Desconocido'
conConnecting = u'Conectando'
conOffline = u'Desconectado'
conOnline = u'Conectado'
conPausing = u'En pausa'
conUnknown = u'Desconocido'
cusAway = u'Ausente'
cusDoNotDisturb = u'Ocupado'
cusInvisible = u'Invisible'
cusLoggedOut = u'Desconectado'
cusNotAvailable = u'No disponible'
cusOffline = u'Desconectado'
cusOnline = u'Conectado'
cusSkypeMe = u'Skyp\xe9ame'
cusUnknown = u'Desconocido'
cvsBothEnabled = u'Enviando y recibiendo video'
cvsNone = u'Sin video'
cvsReceiveEnabled = u'Recibiendo video'
cvsSendEnabled = u'Enviando video'
cvsUnknown = u''
grpAllFriends = u'Todos los contactos'
grpAllUsers = u'Todos los usuarios'
grpCustomGroup = u'Personalizado'
grpOnlineFriends = u'Contactos conectados'
grpPendingAuthorizationFriends = u'Autorizaci\xf3n pendiente'
grpProposedSharedGroup = u'Proposed Shared Group'
grpRecentlyContactedUsers = u'Usuarios contactados recientemente'
grpSharedGroup = u'Shared Group'
grpSkypeFriends = u'Contactos de Skype'
grpSkypeOutFriends = u'Contactos de SkypeOut'
grpUngroupedFriends = u'Contactos no agrupados'
grpUnknown = u'Desconocido'
grpUsersAuthorizedByMe = u'Autorizado por m\xed'
grpUsersBlockedByMe = u'Bloqueado por m\xed'
grpUsersWaitingMyAuthorization = u'Esperando mi autorizaci\xf3n'
leaAddDeclined = u'Agregado rechazado'
leaAddedNotAuthorized = u'La persona agregada deber estar autorizada'
leaAdderNotFriend = u'Quien agrega debe ser un contacto'
leaUnknown = u'Desconocido'
leaUnsubscribe = u'No suscrito'
leaUserIncapable = u'Usuario inhabilitado'
leaUserNotFound = u'No se encontr\xf3 el usuario'
olsAway = u'Ausente'
olsDoNotDisturb = u'Ocupado'
olsNotAvailable = u'No disponible'
olsOffline = u'Desconectado'
olsOnline = u'Conectado'
olsSkypeMe = u'Skyp\xe9ame'
olsSkypeOut = u'SkypeOut'
olsUnknown = u'Desconocido'
smsMessageStatusComposing = u'Composing'
smsMessageStatusDelivered = u'Delivered'
smsMessageStatusFailed = u'Failed'
smsMessageStatusRead = u'Read'
smsMessageStatusReceived = u'Received'
smsMessageStatusSendingToServer = u'Sending to Server'
smsMessageStatusSentToServer = u'Sent to Server'
smsMessageStatusSomeTargetsFailed = u'Some Targets Failed'
smsMessageStatusUnknown = u'Unknown'
smsMessageTypeCCRequest = u'Confirmation Code Request'
smsMessageTypeCCSubmit = u'Confirmation Code Submit'
smsMessageTypeIncoming = u'Incoming'
smsMessageTypeOutgoing = u'Outgoing'
smsMessageTypeUnknown = u'Unknown'
smsTargetStatusAcceptable = u'Acceptable'
smsTargetStatusAnalyzing = u'Analyzing'
smsTargetStatusDeliveryFailed = u'Delivery Failed'
smsTargetStatusDeliveryPending = u'Delivery Pending'
smsTargetStatusDeliverySuccessful = u'Delivery Successful'
smsTargetStatusNotRoutable = u'Not Routable'
smsTargetStatusUndefined = u'Undefined'
smsTargetStatusUnknown = u'Unknown'
usexFemale = u'Mujer'
usexMale = u'Hombre'
usexUnknown = u'Desconocido'
vmrConnectError = u'Error de conexi\xf3n'
vmrFileReadError = u'Error de lectura en archivo'
vmrFileWriteError = u'Error de escritura en archivo'
vmrMiscError = u'Error de car\xe1cter general'
vmrNoError = u'No se produjo error'
vmrNoPrivilege = u'Sin privilegio de mensaje de voz'
vmrNoVoicemail = u'Sin mensaje de voz'
vmrPlaybackError = u'Error de reproducci\xf3n'
vmrRecordingError = u'Error de grabaci\xf3n'
vmrUnknown = u'Desconocido'
vmsBlank = u'En blanco'
vmsBuffering = u'Almacenando'
vmsDeleting = u'Borrando'
vmsDownloading = u'Descargando'
vmsFailed = u'No enviado'
vmsNotDownloaded = u'No se descarg\xf3'
vmsPlayed = u'Reproducido'
vmsPlaying = u'Reproduciendo'
vmsRecorded = u'Grabado'
vmsRecording = u'Grabando mensaje de voz'
vmsUnknown = u'Desconocido'
vmsUnplayed = u'No se reprodujo'
vmsUploaded = u'Cargado'
vmsUploading = u'Cargando'
vmtCustomGreeting = u'Saludo personalizado'
vmtDefaultGreeting = u'Saludo predeterminado'
vmtIncoming = u'correo de voz entrante'
vmtOutgoing = u'Saliente'
vmtUnknown = u'Desconocido'
vssAvailable = u'Disponible'
vssNotAvailable = u'No disponible'
vssPaused = u'Interrumpida'
vssRejected = u'Rechazada'
vssRunning = u'En curso'
vssStarting = u'Iniciando'
vssStopping = u'Detenida'
vssUnknown = u'Desconocido'


text:
import { Link as RouterLink } from 'react-router-dom';
import { makeStyles } from 'tss-react/mui';

import { Link } from '@mui/material';

import { Breadcrumb as BreadcrumbModel } from './models';

const useStyles = makeStyles()(() => ({
  link: {
    '&:hover': {
      textDecoration: 'underline'
    },
    color: 'inherit',
    fontSize: 'small',
    textDecoration: 'none'
  }
}));

interface Props {
  breadcrumb: BreadcrumbModel;
  last: boolean;
}

const Breadcrumb = ({ last, breadcrumb }: Props): JSX.Element => {
  const { classes } = useStyles();

  return (
    <Link
      className={classes.link}
      color={last ? 'textPrimary' : 'inherit'}
      component={RouterLink}
      to={breadcrumb.link}
    >
      {breadcrumb.label}
    </Link>
  );
};

export default Breadcrumb;


text:
// XLA-specific Slice Op.

#include "absl/types/span.h"
#include "tensorflow/compiler/tf2xla/type_util.h"
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/lib/constants.h"
#include "tensorflow/compiler/xla/client/lib/dynamic_shaped_ops.h"
#include "tensorflow/compiler/xla/client/value_inference.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/ops_util.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/mem.h"

namespace tensorflow {
namespace {

class SliceOp : public XlaOpKernel {
 public:
  explicit SliceOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}

  void Compile(XlaOpKernelContext* ctx) override {
    const TensorShape input_shape = ctx->InputShape(0);
    const TensorShape begin_tensor_shape = ctx->InputShape(1);
    const TensorShape size_tensor_shape = ctx->InputShape(2);

    const int input_dims = input_shape.dims();
    OP_REQUIRES(
        ctx,
        TensorShapeUtils::IsVector(begin_tensor_shape) &&
            TensorShapeUtils::IsVector(size_tensor_shape) &&
            begin_tensor_shape.num_elements() == input_dims &&
            size_tensor_shape.num_elements() == input_dims,
        errors::InvalidArgument(
            "Expected begin and size arguments to be 1-D tensors of size ",
            input_dims, ", but got shapes ", begin_tensor_shape.DebugString(),
            " and ", size_tensor_shape.DebugString(), " instead."));

    std::vector<int64_t> begin;
    std::vector<int64_t> size;
    const bool all_begins_are_constant =
        ctx->ConstantInputAsIntVector(1, &begin).ok();
    const bool all_sizes_are_constant =
        ctx->ConstantInputAsIntVector(2, &size).ok();
    if (all_begins_are_constant && all_sizes_are_constant) {
      std::vector<int64_t> wrapped_size(size.size());
      // `begin` is a compile-time constant.
      for (int i = 0; i < input_dims; ++i) {
        if (size[i] == -1) {
          // A size[i] of -1 means "all elements from begin[i] to dim_size(i)".
          wrapped_size[i] = input_shape.dim_size(i) - begin[i];
        } else {
          wrapped_size[i] = size[i];
        }
      }

      for (int i = 0; i < input_dims; ++i) {
        int64_t b = begin[i];
        int64_t s = wrapped_size[i];
        if (input_shape.dim_size(i) == 0) {
          OP_REQUIRES(ctx, b == 0 && s == 0,
                      errors::InvalidArgument(
                          "Expected begin[", i, "] == 0 (got ", b,
                          ") and size[", i, "] == 0 ", "(got ", s, ") when ",
                          "input_shape.dim_size(", i, ") == 0"));
        } else {
          OP_REQUIRES(ctx, 0 <= b && b <= input_shape.dim_size(i),
                      errors::InvalidArgument("Expected begin[", i, "] in [0, ",
                                              input_shape.dim_size(i),
                                              "], but got ", b));
          OP_REQUIRES(ctx, 0 <= s && b + s <= input_shape.dim_size(i),
                      errors::InvalidArgument("Expected size[", i, "] in [0, ",
                                              input_shape.dim_size(i) - b,
                                              "], but ", "got ", s));
        }
      }

      std::vector<int64_t> limits;
      limits.reserve(begin.size());
      for (int i = 0; i < begin.size(); ++i) {
        limits.push_back(begin[i] + wrapped_size[i]);
      }
      std::vector<int64_t> strides(begin.size(), 1);
      auto slice = xla::Slice(ctx->Input(0), begin, limits, strides);
      // Check for slice on dynamic dimensions.
      std::vector<bool> size_is_dynamic;
      OP_REQUIRES_OK(
          ctx, ctx->ResolveInputDynamismIntoPredVector(2, &size_is_dynamic));

      for (int64_t i = 0; i < size.size(); ++i) {
        if (size_is_dynamic[i]) {
          if (size[i] != -1) {
            // If there is a dynamic dimension, properly set dimension size of
            // the slice.
            auto dynamic_size =
                xla::Reshape(xla::Slice(ctx->Input(2), {i}, {i + 1}, {1}), {});

            slice = xla::SetDimensionSize(slice, dynamic_size, i);
          }
        }
      }
      ctx->SetOutput(0, slice);
    } else {
      // When a size is -1, we take rest of the dimension according to
      // https://www.tensorflow.org/api_docs/python/tf/slice.
      // This essentially makes size as dynamic.
      bool constant_size_is_minus_one = false;
      // `begin` or `size` is not a compile-time constant.
      if (all_sizes_are_constant) {
        for (int i = 0; i < input_dims; ++i) {
          if (size[i] < 0) {
            OP_REQUIRES(ctx, size[i] == -1,
                        errors::InvalidArgument(
                            "Negative size of slice operator can only be -1"));
            constant_size_is_minus_one = true;
          }

          OP_REQUIRES(ctx, size[i] <= input_shape.dim_size(i),
                      errors::InvalidArgument("Expected size[", i, "] in [0, ",
                                              input_shape.dim_size(i),
                                              "], but ", "got ", size[i]));
        }
      }

      absl::InlinedVector<xla::XlaOp, 4> begin_indices;
      begin_indices.reserve(input_dims);
      xla::XlaOp begin = ctx->Input("begin");
      for (int i = 0; i < input_dims; i++) {
        begin_indices.push_back(
            xla::Reshape(xla::Slice(begin, {i}, {i + 1}, {1}), {}));
      }
      if (all_sizes_are_constant && !constant_size_is_minus_one) {
        xla::XlaOp input = ctx->Input(0);
        ctx->SetOutput(0, xla::DynamicSlice(input, begin_indices, size));
      } else {
        // Size is not constant, use input size as upperbound and then set
        // dimension size on it.

        // First pad input with input size to avoid OOB -- dynamic slice with
        // OOB slice produces undesired results.
        xla::PaddingConfig padding_config;
        xla::XlaOp input = ctx->Input(0);
        for (int64_t i = 0; i < input_dims; ++i) {
          auto* dims = padding_config.add_dimensions();
          dims->set_edge_padding_low(0);
          dims->set_edge_padding_high(input_shape.dim_size(i));
          dims->set_interior_padding(0);
          input = xla::RemoveDynamicDimension(input, i);
        }
        auto padded_input =
            xla::Pad(input, xla::Zero(ctx->builder(), ctx->input_xla_type(0)),
                     padding_config);
        // Slice full size out of the input starting from the offsets.
        auto sliced = xla::DynamicSlice(padded_input, begin_indices,
                                        input_shape.dim_sizes());
        for (int i = 0; i < input_dims; i++) {
          xla::XlaOp dynamic_size =
              xla::Reshape(xla::Slice(ctx->Input(2), {i}, {i + 1}, {1}), {});
          if (constant_size_is_minus_one && size[i] == -1) {
            // size = input_.dim_size(i) - begin[i]
            dynamic_size = xla::ConstantR0<int32>(ctx->builder(),
                                                  input_shape.dim_size(i)) -
                           begin_indices[i];
          }
          auto constant_size = ctx->value_inference().AnalyzeConstant(
              dynamic_size, xla::ValueInferenceMode::kValue);
          OP_REQUIRES_OK(ctx, constant_size.status());
          if (constant_size->AllValid()) {
            // Slice size on this dimension is constant. This branch is
            // triggered when some dimensions's slice sizes are constant while
            // some are dynamic.
            sliced = xla::SliceInDim(
                sliced, 0, constant_size->Get<int32>({}).value(), 1, i);
          } else {
            // We gave a generous bound (same as input) to the output, try reset
            // the bound if a tighter one can be found.
            auto status = xla::SetDimensionSizeWithRebound(
                &ctx->value_inference(), sliced, dynamic_size, i);
            OP_REQUIRES_OK(ctx, status.status());
            sliced = status.value();
          }
        }
        ctx->SetOutput(0, sliced);
      }
    }
  }
};

REGISTER_XLA_OP(Name("Slice")
                    .CompileTimeConstantInput("begin")
                    .CompileTimeConstantInput("size"),
                SliceOp);

}  // namespace
}  // namespace tensorflow


text:
/*
 * EIoSessionInputStream.cpp
 *
 *  Created on: 2016-6-1
 *      Author: cxxjava@163.com
 */

#include "../inc/EIoSessionInputStream.hh"

namespace efc {
namespace eio {

EIoSessionInputStream::~EIoSessionInputStream() {
	delete buf;
	delete exception;
}

EIoSessionInputStream::EIoSessionInputStream(): closed(false), released(false), exception(null) {
	buf = EIoBuffer::allocate(16);
	buf->setAutoExpand(true);
	buf->limit(0);
}

void EIoSessionInputStream::write(EIoBuffer* src) {
	ES_ASSERT(src);
	SYNCHRONIZED(this) {
		if (closed) {
			return;
		}

		if (buf->hasRemaining()) {
			this->buf->compact();
			this->buf->put(src);
			this->buf->flip();
		} else {
			this->buf->clear();
			this->buf->put(src);
			this->buf->flip();
			this->notifyAll();
		}
    }}
}

void EIoSessionInputStream::throwException(EIOException& e) {
	SYNCHRONIZED(this) {
		if (exception == null) {
			exception = new EIOException(e);

			this->notifyAll();
		}
    }}
}

int EIoSessionInputStream::read(void* b, int len) {
	SYNCHRONIZED(this) {
		if (!waitForData()) {
			return -1;
		}

		int readBytes;

		if (len > buf->remaining()) {
			readBytes = buf->remaining();
		} else {
			readBytes = len;
		}

		buf->get(b, len, readBytes);

		return readBytes;
    }}
}

int EIoSessionInputStream::read() {
	SYNCHRONIZED(this) {
		if (!waitForData()) {
			return -1;
		}

		return buf->get() & 0xff;
    }}
}

long EIoSessionInputStream::available() {
	if (released) {
		return 0;
	}

	SYNCHRONIZED(this) {
		return buf->remaining();
    }}
}

void EIoSessionInputStream::close() {
	if (closed) {
		return;
	}

	SYNCHRONIZED(this) {
		closed = true;
		releaseBuffer();

		this->notifyAll();
    }}
}

boolean EIoSessionInputStream::waitForData() {
	if (released) {
		return false;
	}

	SYNCHRONIZED(this) {
		while (!released && buf->remaining() == 0 && exception == null) {
			try {
				this->wait();
			} catch (EInterruptedException& e) {
				EIOException ioe(__FILE__, __LINE__, "Interrupted while waiting for more data");
				throw ioe;
			}
		}
    }}

	if (exception != null) {
		releaseBuffer();
		throw (*exception);
	}

	if (closed && buf->remaining() == 0) {
		releaseBuffer();

		return false;
	}

	return true;
}

void EIoSessionInputStream::releaseBuffer() {
	if (released) {
		return;
	}

	released = true;
}

} /* namespace eio */
} /* namespace efc */


text:
int main()
{
  try
  {
    auto wrapper = Lib3MF::CWrapper::loadLibrary();
    Lib3MF_uint32 nMajor, nMinor, nMicro;
    wrapper->GetLibraryVersion(nMajor, nMinor, nMicro);
    std::cout << "Lib3MF.Version = " << nMajor << "." << nMinor << "." << nMicro;
    std::string sPreReleaseInfo;
    if (wrapper->GetPrereleaseInformation(sPreReleaseInfo)) {
      std::cout << "-" << sPreReleaseInfo;
    }
    std::string sBuildInfo;
    if (wrapper->GetBuildInformation(sBuildInfo)) {
      std::cout << "+" << sBuildInfo;
    }
    std::cout << std::endl;
  }
  catch (std::exception &e)
  {
    std::cout << e.what() << std::endl;
    return 1;
  }
  return 0;
}


text:
package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net"
	//"strconv"
	"time"

	"launchpad.net/goamz/aws"
	"launchpad.net/goamz/s3"
)

type Release struct {
	Version  string
	Revision string
	Date     time.Time
	Config   map[string]string
}

var (
	awsAuth aws.Auth = aws.Auth{awsKey, awsSecret}
)

func getS3Bucket() *s3.Bucket {
	return s3.New(awsAuth, awsRegion).Bucket(s3BucketName)
}

/*func getNextReleaseVersion(applicationName string) (string, error) {
	releases, err := getReleases(applicationName)
	if err != nil {
		return "", err
	}
	version := "v1"
	if len(releases) > 0 {
		v, err := strconv.Atoi(releases[0].Version[1:])
		if err != nil {
			return version, err
		}
		version = fmt.Sprint("v", v+1)
	}
	fmt.Printf("Next version for %v will be %v", applicationName, version)
	return version, nil
}*/

func getReleases(applicationName string) ([]Release, error) {
	var releases []Release
	bs, err := getS3Bucket().Get("/releases/" + applicationName + "/manifest.json")
	if err != nil {
		if err.Error() == "The specified key does not exist." {
			// The manifest.json file for this app was missing, fill in an empty releases list and continue on our way.
			err = setReleases(applicationName, []Release{})
			if err != nil {
				return releases, err
			}
			fmt.Printf("warn: getReleases S3 key was missing for application \"%v\", so an empty releases list was set", applicationName)
			return []Release{}, err
		}
		return releases, err
	}
	err = json.Unmarshal(bs, &releases)
	return releases, err
}
func setReleases(applicationName string, releases []Release) error {
	bs, err := json.Marshal(releases)
	if err != nil {
		return err
	}
	return getS3Bucket().Put(
		"/releases/"+applicationName+"/manifest.json",
		bs,
		"application/json",
		"private",
	)
}
func delReleases(applicationName string, logger io.Writer) error {
	bucket := getS3Bucket()
	keys, err := bucket.List("releases/"+applicationName, "/releases/"+applicationName, "", 999999)
	if err != nil {
		return err
	}
	fmt.Fprint(logger, "Purging application from S3..\n")
	for _, key := range keys.Contents {
		fmt.Fprintf(logger, "    Deleting key %v\n", key.Key)
		bucket.Del(key.Key)
	}
	return nil
}

func (this *Server) Releases_List(conn net.Conn, applicationName string) error {
	releases, err := getReleases(applicationName)
	if err != nil {
		Logf(conn, "%v", err)
		return err
	}
	for _, r := range releases {
		Logf(conn, "%v %v %v\n", r.Version, r.Revision, r.Date)
	}
	return nil
}
func (this *Server) Releases_Info(conn net.Conn, applicationName, version string) error {
	return fmt.Errorf("not implemented")
}


text:
require 'pathname'

# Base provider for Access Control List type
class Puppet::Provider::Acl
  module Windows # rubocop:disable Style/ClassAndModuleChildren  Required to use the longform module name due to dependencies
    # Provides the detailed implementation details for the provider and should shield the provider from legacy
    # support implementations that would happen here.
    #
    # For information on ACE masks see:
    # {https://docs.microsoft.com/en-gb/previous-versions/windows/desktop/secrcw32prov/win32-ace Win32_ACE Class},
    # {https://docs.microsoft.com/en-gb/windows/desktop/SecAuthZ/standard-access-rights Standard Access Rights},
    # {https://docs.microsoft.com/en-gb/windows/desktop/SecAuthZ/generic-access-rights Generic Access Rights}
    #
    module Base
      # We need this as the libraries will not load properly on non-Windows platforms
      if Puppet::Util::Platform.windows?
        require Pathname.new(__FILE__).dirname + '../../../../' + 'puppet/type/acl/ace'
        require 'puppet/util/windows/security'
      end

      # Used to specify to flush out the SD cache.
      REFRESH_SD        = true
      # Used to specify to flush out the SD cache.
      DO_NOT_REFRESH_SD = false

      # Grants all possible access rights.
      GENERIC_ALL                  = 0x10000000
      # Grants write access.
      GENERIC_WRITE                = 0x40000000
      # Grants read access.
      GENERIC_READ                 = 0x80000000
      # Grants execute access.
      GENERIC_EXECUTE              = 0x20000000
      # Grants delete access.
      DELETE                       = 0x00010000

      # Synchronizes access and allows a process to wait for an object to enter the signaled state.
      SYNCHRONIZE                 = 0x100000
      # Combines DELETE, READ_CONTROL, WRITE_DAC, and WRITE_OWNER access.
      STANDARD_RIGHTS_REQUIRED    = 0xf0000
      # Currently defined to equal READ_CONTROL.
      STANDARD_RIGHTS_READ        = 0x20000
      # Currently defined to equal READ_CONTROL.
      STANDARD_RIGHTS_WRITE       = 0x20000
      # Currently defined to equal READ_CONTROL.
      STANDARD_RIGHTS_EXECUTE     = 0x20000

      # Grants the right to read data from the file. For a directory, this value grants the right
      # to list the contents of the directory.
      FILE_READ_DATA               = 1
      # Grants the right to write data to the file. For a directory, this value grants the right
      # to create a file in the directory.
      FILE_WRITE_DATA              = 2
      # Grants the right to append data to the file. For a directory, this value grants the right
      # to create a subdirectory.
      FILE_APPEND_DATA             = 4
      # Grants the right to read extended attributes.
      FILE_READ_EA                 = 8
      # Grants the right to write extended attributes.
      FILE_WRITE_EA                = 16
      # Grants the right to execute a file. For a directory, the directory can be traversed.
      FILE_EXECUTE                 = 32
      # Grants the right to delete a directory and all the files it contains (its children), even
      # if the files are read-only.
      FILE_DELETE_CHILD            = 64
      # Grants the right to read file attributes.
      FILE_READ_ATTRIBUTES         = 128
      # Grants the right to change file attributes.
      FILE_WRITE_ATTRIBUTES        = 256

      # Grants full read, write and execute permissions.
      FILE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x1FF

      # A combination of masks providing a generic mask for reading files along with associated file and
      # extended attributes.
      FILE_GENERIC_READ =
        STANDARD_RIGHTS_READ |
        FILE_READ_DATA |
        FILE_READ_ATTRIBUTES |
        FILE_READ_EA |
        SYNCHRONIZE

      # A combination of masks providing a generic mask for writing files along with associated file and
      # extended attributes.
      FILE_GENERIC_WRITE =
        STANDARD_RIGHTS_WRITE |
        FILE_WRITE_DATA |
        FILE_WRITE_ATTRIBUTES |
        FILE_WRITE_EA |
        FILE_APPEND_DATA |
        SYNCHRONIZE

      # A combination of masks providing a generic mask for executing files.
      FILE_GENERIC_EXECUTE =
        STANDARD_RIGHTS_EXECUTE |
        FILE_READ_ATTRIBUTES |
        FILE_EXECUTE |
        SYNCHRONIZE

      @security_descriptor = nil

      # Converts an account name into an SID string
      #
      # @param [String] name Name+SID string
      # @return [Puppet::Util::Windows::SID] Converted SID
      #
      # @note Puppet 3.7 deprecated methods at old locations in favor of SID class
      def name_to_sid(name)
        if Puppet::Util::Windows::SID.respond_to?(:name_to_sid)
          Puppet::Util::Windows::SID.name_to_sid(name)
        else
          Puppet::Util::Windows::Security.name_to_sid(name)
        end
      end

      # Converts an SID string to an account name.
      #
      # @param [String] value SID string
      # @return [String] Extracted name
      def sid_to_name(value)
        if Puppet::Util::Windows::SID.respond_to?(:sid_to_name)
          Puppet::Util::Windows::SID.sid_to_name(value)
        else
          Puppet::Util::Windows::Security.sid_to_name(value)
        end
      end

      # Checks if supplied SID string is valid
      #
      # @param [String] string_sid SID string
      # @return [Bool] Whether supplied string is a valid SID
      def valid_sid?(string_sid)
        if Puppet::Util::Windows::SID.respond_to?(:valid_sid?)
          Puppet::Util::Windows::SID.valid_sid?(string_sid)
        else
          Puppet::Util::Windows::Security.valid_sid?(string_sid)
        end
      end

      # Retrieves permissions of current instance.
      #
      # @return [Array] ACEs of current instance.
      def get_current_permissions
        sd = get_security_descriptor(DO_NOT_REFRESH_SD)
        permissions = []
        unless sd.nil?
          permissions if sd.dacl.nil?
          sd.dacl.each do |ace|
            permissions << Puppet::Type::Acl::Ace.new(convert_to_permissions_hash(ace), self)
          end
        end
        permissions
      end

      # Converts an Ace object into a hash.
      #
      # @param [Puppet::Util::Windows::AccessControlEntry] ace
      # @return [Hash] Supplied ACE in the form of a hash.
      def convert_to_permissions_hash(ace)
        return {} if ace.nil?

        sid = ace.sid
        identity = sid_to_name(sid)
        rights = get_ace_rights_from_mask(ace)
        ace_type = get_ace_type(ace)
        child_types = get_ace_child_types(ace)
        affects = get_ace_propagation(ace)
        is_inherited = ace.inherited?
        hash = { 'identity' => identity.to_s, 'id' => sid.to_s, 'rights' => rights,
                 'perm_type' => ace_type, 'child_types' => child_types,
                 'affects' => affects, 'is_inherited' => is_inherited,
                 'mask' => ace.mask.to_s }

        hash
      end

      # Retrieves the access rights from an ACE's access mask.
      #
      # @param [Ace] ace
      # @return [Array] Collection of symbols corresponding to AccessRights
      def get_ace_rights_from_mask(ace)
        # TODO: v2 check that this is a file type and respond appropriately
        rights = []
        return rights if ace.nil?
        mask_specific_remainder = ace.mask

        # full
        if (ace.mask & GENERIC_ALL) == GENERIC_ALL ||
           (ace.mask & FILE_ALL_ACCESS) == FILE_ALL_ACCESS
          rights << :full
          mask_specific_remainder = 0
        end

        if rights == []
          if (ace.mask & FILE_GENERIC_WRITE) == FILE_GENERIC_WRITE
            rights << :write
            mask_specific_remainder &= ~FILE_GENERIC_WRITE
          end
          if (ace.mask & GENERIC_WRITE) == GENERIC_WRITE
            rights << :write
            mask_specific_remainder &= ~GENERIC_WRITE
          end

          if (ace.mask & FILE_GENERIC_READ) == FILE_GENERIC_READ
            rights << :read
            mask_specific_remainder &= ~FILE_GENERIC_READ
          end
          if (ace.mask & GENERIC_READ) == GENERIC_READ
            rights << :read
            mask_specific_remainder &= ~GENERIC_READ
          end

          if (ace.mask & FILE_GENERIC_EXECUTE) == FILE_GENERIC_EXECUTE
            rights << :execute
            mask_specific_remainder &= ~FILE_GENERIC_EXECUTE
          end
          if (ace.mask & GENERIC_EXECUTE) == GENERIC_EXECUTE
            rights << :execute
            mask_specific_remainder &= ~GENERIC_EXECUTE
          end
        end

        # modify
        # if the rights appending changes above, we'll
        # need to ensure this check is still good
        if rights == [:write, :read, :execute] &&
           (ace.mask & DELETE) == DELETE
          rights = [:modify]
          mask_specific_remainder &= ~DELETE
        end

        # rights are too specific, use mask
        if rights == []
          rights << :mask_specific
        elsif mask_specific_remainder != 0
          Puppet.debug("Remainder from #{ace.mask} is #{mask_specific_remainder}")
          rights = [:mask_specific]
        end

        rights
      end
      module_function :get_ace_rights_from_mask

      # Retrieves the type of a supplied ACE.
      #
      # @param [Puppet::Util::Windows::AccessControlEntry] ace
      # @return [Symbol] Type of supplied ACE
      def get_ace_type(ace)
        return :allow if ace.nil?

        ace_type = case ace.type
                   when Puppet::Util::Windows::AccessControlEntry::ACCESS_ALLOWED_ACE_TYPE then :allow
                   when Puppet::Util::Windows::AccessControlEntry::ACCESS_DENIED_ACE_TYPE then :deny
                   end

        ace_type
      end
      module_function :get_ace_type

      # Returns child types of supplied ACE.
      #
      # @param [Puppet::Util::Windows::AccessControlEntry] ace
      # @return [Symbol] Child types of supplied ACE.
      def get_ace_child_types(ace)
        return :all if ace.nil?

        # the order is on purpose
        child_types = :none
        child_types = :objects if ace.object_inherit?
        child_types = :containers if ace.container_inherit?
        child_types = :all if ace.object_inherit? && ace.container_inherit?

        child_types
      end
      module_function :get_ace_child_types

      # Retrieves propagation of supplied ACE.
      #
      # @param [Puppet::Util::Windows::AccessControlEntry] ace
      # @return [Symbol] Propagation rule of supplied ACE.
      def get_ace_propagation(ace)
        # http://msdn.microsoft.com/en-us/library/ms229747.aspx
        return :all if ace.nil?

        targets_self = true unless ace.inherit_only?
        targets_children = true if ace.object_inherit? || ace.container_inherit?
        targets_children_only = true if ace.inherit_only?

        # the order is on purpose
        affects = :self_only if targets_self
        affects = :children_only if targets_children_only
        affects = :all if targets_self && targets_children

        # Puppet::Util::Windows::AccessControlEntry defines the propagation flag but doesn't provide a method
        # http://msdn.microsoft.com/en-us/library/windows/desktop/ms692524(v=vs.85).aspx
        no_propagate_flag = 0x4
        propagate = ace.flags & no_propagate_flag != no_propagate_flag
        unless propagate
          affects = :self_and_direct_children_only if targets_self && targets_children
          affects = :direct_children_only if targets_children_only
        end

        affects
      end
      module_function :get_ace_propagation

      # TODO
      def are_permissions_insync?(current_permissions, specified_permissions, purge_value = :false)
        return false if current_permissions.nil? && !specified_permissions.nil? && purge_value != :listed_permissions

        purge_value = purge_value.to_s.downcase.to_sym unless purge_value.is_a?(Symbol)
        should_purge = purge_value == :true
        remove_permissions = purge_value == :listed_permissions
        current_local_permissions = if current_permissions.nil?
                                      []
                                    else
                                      current_permissions.reject { |p| p.inherited? }
                                    end

        if should_purge
          current_local_permissions == specified_permissions
        elsif remove_permissions
          return true if specified_permissions.nil?
          (specified_permissions & current_local_permissions) == []
        else
          return true if specified_permissions.nil?

          # intersect will return order by left item in intersect
          #  order is guaranteed checked when specified_permissions
          (current_local_permissions & specified_permissions) == specified_permissions
        end
      end

      # Converts an array of permissions into a DACL object.
      #
      # @param [Array] permissions Array of ACEs.
      # @return [Puppet::Util::Windows::AccessControlList] ACL of supplied ACEs.
      def convert_to_dacl(permissions)
        dacl = Puppet::Util::Windows::AccessControlList.new
        return dacl if permissions.nil? || permissions.empty?

        permissions.each do |permission|
          sid = get_account_id(permission.identity)
          mask = get_account_mask(permission)
          flags = get_account_flags(permission)
          case permission.perm_type
          when :allow
            dacl.allow(sid, mask, flags)
          when :deny
            dacl.deny(sid, mask, flags)
          end
        end

        dacl
      end

      # Retrieves mask from a supplied ACE
      #
      # @param [Puppet::Util::Windows::AccessControlEntry] permission
      # @param [Symbol] target_resource_type
      # @return [Integer] Extracted account mask
      def get_account_mask(permission, target_resource_type = :file)
        return 0 if permission.nil?
        return permission.mask.to_i if permission.mask
        return 0 if permission.rights.nil? || permission.rights.empty?

        mask = case target_resource_type
               when :file
                 begin
                   if permission.rights.include?(:full)
                     return FILE_ALL_ACCESS
                   end

                   if permission.rights.include?(:modify)
                     return DELETE |
                            FILE_GENERIC_WRITE |
                            FILE_GENERIC_READ  |
                            FILE_GENERIC_EXECUTE
                   end

                   filemask = 0x0
                   if permission.rights.include?(:write)
                     filemask |= FILE_GENERIC_WRITE
                   end

                   if permission.rights.include?(:read)
                     filemask |= FILE_GENERIC_READ
                   end

                   if permission.rights.include?(:execute)
                     filemask |= FILE_GENERIC_EXECUTE
                   end

                   filemask
                 end
               end
        mask
      end
      module_function :get_account_mask

      # Retrieve the propagation rule flags from a specified ACE.
      #
      # @param [Puppet::Util::Windows::AccessControlEntry] permission
      # @return [Array] Flags associated with ACE.
      def get_account_flags(permission)
        # http://msdn.microsoft.com/en-us/library/ms229747.aspx
        flags = 0x0

        case permission.child_types
        when :all
          flags = flags |
                  Puppet::Util::Windows::AccessControlEntry::OBJECT_INHERIT_ACE |
                  Puppet::Util::Windows::AccessControlEntry::CONTAINER_INHERIT_ACE
        when :objects
          flags |= Puppet::Util::Windows::AccessControlEntry::OBJECT_INHERIT_ACE
        when :containers
          flags |= Puppet::Util::Windows::AccessControlEntry::CONTAINER_INHERIT_ACE
        end

        case permission.affects
        when :self_only
          flags = 0x0
        when :children_only
          flags |= Puppet::Util::Windows::AccessControlEntry::INHERIT_ONLY_ACE
        when :self_and_direct_children_only
          flags |= Puppet::Util::Windows::AccessControlEntry::NO_PROPAGATE_INHERIT_ACE
        when :direct_children_only
          flags = flags |
                  Puppet::Util::Windows::AccessControlEntry::NO_PROPAGATE_INHERIT_ACE |
                  Puppet::Util::Windows::AccessControlEntry::INHERIT_ONLY_ACE
        end

        if permission.child_types == :none && flags != 0x0
          flags = 0x0
        end

        flags
      end
      module_function :get_account_flags

      # Ensures that the supplied DACL matches the additional supplied parameters.
      #
      # @param [Puppet::Util::Windows::AccessControlList] current_dacl
      # @param [Array] should_aces
      # @param [Boolean] should_purge
      # @param [Boolean] remove_permissions
      # @return [Array] Matching ACEs.
      def sync_aces(current_dacl, should_aces, should_purge = false, remove_permissions = false)
        if remove_permissions
          kept_aces = []
          current_dacl.each do |ace|
            next if ace.inherited?

            current_ace = Puppet::Type::Acl::Ace.new(convert_to_permissions_hash(ace), self)
            existing_aces = should_aces.select { |a| a.same?(current_ace) }
            next unless existing_aces.empty?

            kept_aces << current_ace
          end

          should_aces = kept_aces
        else
          return should_aces if should_purge

          current_dacl.each do |ace|
            # TODO: v2 should we warn if we have an existing inherited ace that matches?
            next if ace.inherited?

            current_ace = Puppet::Type::Acl::Ace.new(convert_to_permissions_hash(ace), self)
            existing_aces = should_aces.select { |a| a.same?(current_ace) }
            next unless existing_aces.empty?

            # munge in existing unmanaged aces
            case current_ace.perm_type
            when :deny
              last_allow_index = should_aces.index { |a| a.perm_type == :allow }
              should_aces.insert(last_allow_index, current_ace) if last_allow_index
              should_aces << current_ace unless last_allow_index
            when :allow
              should_aces << current_ace
            end
          end
        end

        should_aces
      end

      # Retrieves owner from current instance's SecurityDescriptor.
      #
      # @return [String] SID owner.
      def get_current_owner
        sd = get_security_descriptor

        sd&.owner
      end

      # Retrieves group from current instance's SecurityDescriptor.
      #
      # @return [String] SID group.
      def get_current_group
        sd = get_security_descriptor

        sd&.group
      end

      # Compares two SIDs to determine if they contain the same account id.
      #
      # @param [Puppet::Util::Windows::SID] current
      # @param [Puppet::Util::Windows::SID] should
      # @return [Bool] True if `current` account id is `should` account id.
      def account_insync?(current, should)
        return false unless current

        should_empty = should.nil? || should.empty?
        return false if current.empty? != should_empty

        get_account_id(current) == get_account_id(should)
      end

      # Converts an account name into an SID.
      #
      # @param [String] name
      # @return [Puppet::Util::Windows::SID] Converted SID.
      def get_account_id(name)
        # sometimes the name will come in with a SID
        # which will return nil when we call name_to_sid
        # if the user no longer exists
        return unless name
        if valid_sid?(name)
          name
        else
          name_to_sid(name)
        end
      end

      # Retrieves name from SID
      #
      # @param [Puppet::Util::Windows::SID] current_value
      # @return [String] If `current_value` contains name returns this else return `current_value`.
      def get_account_name(current_value)
        name = sid_to_name(get_account_id(current_value))

        name ? name : current_value
      end
      alias get_group_name get_account_name

      def inheriting_permissions?
        sd = get_security_descriptor

        return !sd.protect unless sd.nil?

        # default true
        true
      end

      # Retrieves the SecurityDescriptor of the current instance
      #
      # @param [Bool] refresh_sd Whether to refresh the current instance's SecurityDescriptor.
      # @return [Puppet::Util::Windows::SecurityDescriptor] Instance's SecurityDescriptors.
      def get_security_descriptor(refresh_sd = DO_NOT_REFRESH_SD)
        refresh_sd ||= false
        if @security_descriptor.nil? || refresh_sd
          sd = nil
          case @resource[:target_type]
          when :file
            begin
              sd = Puppet::Util::Windows::Security.get_security_descriptor(@resource[:target])
            rescue => detail
              raise Puppet::Error, "Failed to get security descriptor for path '#{@resource[:target]}': #{detail}", detail.backtrace
            end
          end

          @security_descriptor = sd
        end

        @security_descriptor
      end

      # Sets the instance's SecurityDescriptor
      #
      # @param [Puppet::Util::Windows::SecurityDescriptor] security_descriptor
      # @return [Puppet::Util::Windows::SecurityDescriptor] Returns set SecurityDescriptor
      def set_security_descriptor(security_descriptor)
        case @resource[:target_type]
        when :file
          begin
            Puppet::Util::Windows::Security.set_security_descriptor(@resource[:target], security_descriptor)
          rescue => detail
            raise Puppet::Error, "Failed to set security descriptor for path '#{@resource[:target]}': #{detail}", detail.backtrace
          end
        end

        # flush out the cached sd
        get_security_descriptor(REFRESH_SD)
      end
    end
  end
end

# TODO: v2 legacy - check to see if method exists for Puppet::Util::Windows::Security.get_security_descriptor, if not - we'll need to create it


text:
import java.util.Scanner;
public class UsdToBgn {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        double radians = Double.parseDouble(scanner.nextLine());
        double deegrees = (radians*180) / Math.PI;
        System.out.println(Math.floor(deegrees));
    }
}


text:
include('chips');
include('item');
include('math.js');
include('array.js');
include('game-state.js');

/**
* averageDamageOnCell : Cell -> LeekState -> Int
*/
function averageDmgFromLeekOnCell(@cell) { return function(@leek) {
	var pos = leek[POS];
	var dist = getCellDistance(cell, pos) + (lineOfSight(cell, pos) ? 0 : 2) - leek[MP];
	var dmgMultiplier = (100 + leek[STR]) / 100;
	var poiMultiplier = (100 + leek[MAG]) / 100;
	var critMultiplier = 1 + 0.4 * (leek[AGI] / 1000);
	var dangerousItems =@ aFilter(lookup(cAttaques))(leek[CHIPS]);
	dangerousItems += leek[UNEQ];
	var eq = leek[EQ];
	if (eq !== null) { push(dangerousItems, eq); }
	dangerousItems =@ aFilter(compose(inferior(dist))(lookup(ITEM_MAX_RANGE)))(dangerousItems);
	var dmgAvg = defaultDiv(0)(sum(daMap(lookup(ITEM_DMG_TP))(dangerousItems)))(count(dangerousItems));
	return dmgAvg * dmgMultiplier * critMultiplier * leek[TP];
};}

/**
* averageDmgFromLeeksOnCell : (LeekState -> Bool) -> Cell -> Array LeekState -> Int
*/
function averageDmgFromLeeksOnCell(@p) { return function(@cell) { return function(@leeks) {
	return arrayFoldLeft(leeks, function(@acc, @l) {
		return acc + (p(l) ? averageDmgFromLeekOnCell(cell)(l) : 0);
	}, 0);
};};}


text:
#ifndef LULLABY_UTIL_LAYOUT_H_
#define LULLABY_UTIL_LAYOUT_H_

#include <vector>

#include "mathfu/constants.h"
#include "mathfu/glsl_mappings.h"
#include "lullaby/generated/common_generated.h"
#include "lullaby/base/entity.h"
#include "lullaby/base/registry.h"
#include "lullaby/util/math.h"

namespace lull {

// Parameters used by ApplyLayout to determine how to layout Entities.
struct LayoutParams {
  // The virtual "canvas" on which the entities will be positioned.
  mathfu::vec2 canvas_size = mathfu::kZeros2f;

  // The spacing between entities.
  mathfu::vec2 spacing = mathfu::kZeros2f;

  // The order in which elements will be added to the canvas.
  LayoutFillOrder fill_order = LayoutFillOrder_RightDown;

  // The anchor at which the entities will be aligned relative to the canvas
  // horizontally.
  LayoutHorizontalAlignment horizontal_alignment =
      LayoutHorizontalAlignment_Left;
  // The anchor at which the entities will be aligned relative to the canvas
  // vertically.
  LayoutVerticalAlignment vertical_alignment = LayoutVerticalAlignment_Top;
  // The anchor at which entities will be aligned relative to their row within
  // the layout.
  LayoutVerticalAlignment row_alignment = LayoutVerticalAlignment_Top;
  // The anchor at which entities will be aligned relative to their col within
  // the layout.
  LayoutHorizontalAlignment column_alignment = LayoutHorizontalAlignment_Left;

  // The number of elements in the orders primary direction before wrapping.
  size_t elements_per_wrap = 0;

  // If true then the AABB of the layout will be set to the extent of the
  // layout's children. If false then it will be set to the size of the canvas.
  bool shrink_to_fit = false;
};

// Parameters used by ApplyRadialLayout
struct RadialLayoutParams {
  // The distance around the circumference between each entity.
  float degrees_per_element = 30.f;

  // The vector defining the major axis of the ellipse to place entities on.
  // An Entity at 0 degrees will be at |major_axis|, and at 180 degrees will be
  // - |major_axis|

  mathfu::vec3 major_axis = mathfu::kAxisX3f;
  // The vector defining the minor axis of the ellipse to place entities on.
  // An Entity at 90 degrees will be at |minor_axis|, and at 270 degrees will be
  // - |minor_axis|
  mathfu::vec3 minor_axis = mathfu::kAxisY3f;
};

// Data for each child element of a layout.  Elements without weight will
// will get their stated size.  The remaining unused size will get distributed
// proportionally to all elements with weight.  If there is no unused size all
// weighted children are disabled.
struct LayoutElement {
  explicit LayoutElement(Entity e) : entity(e) {}

  Entity entity = kNullEntity;

  // If horizontal_weight is non-zero, then this element will fill up available
  // space proportional to the total weight of all other weighted elements
  // horizontally up to canvas_size.x if non-zero.
  float horizontal_weight = 0.0f;

  // If vertical_weight is non-zero, then this element will fill up available
  // space proportional to the total weight of all other weighted elements
  // vertically up to canvas_size.y if non-zero.
  float vertical_weight = 0.0f;
};

// DEPRECATED
// Update the positions of the |entities| based on the |params|.  Returns
// the total AABB that is filled up by the entities.
Aabb ApplyLayout(Registry* registry, const LayoutParams& params,
                 const std::vector<Entity>& entities);

// Update the positions of the entities in |infos| based on the |params|.
// If |desired_source| is set it will also SetDesiredSize() in LayoutBoxSystem
// with that source.
// Returns the total AABB that is filled up by the entities.
Aabb ApplyLayout(Registry* registry, const LayoutParams& params,
                 const std::vector<LayoutElement>& elements,
                 Entity desired_source = kNullEntity);

// Update the positions of the |entities| based on the ellipse defined by the
// params.
void ApplyRadialLayout(Registry* registry, const std::vector<Entity>& entities,
                       const RadialLayoutParams& params);
}  // namespace lull

#endif  // LULLABY_UTIL_LAYOUT_H_


text:
/* This file was generated by upbc (the upb compiler) from the input
 * file:
 *
 *     google/protobuf/struct.proto
 *
 * Do not edit -- your changes will be discarded when the file is
 * regenerated. */

#include <stddef.h>
#include "upb/msg_internal.h"
#include "google/protobuf/struct.upb.h"

#include "upb/port_def.inc"

static const upb_MiniTable_Sub google_protobuf_Struct_submsgs[1] = {
  {.submsg = &google_protobuf_Struct_FieldsEntry_msginit},
};

static const upb_MiniTable_Field google_protobuf_Struct__fields[1] = {
  {1, UPB_SIZE(0, 0), UPB_SIZE(0, 0), 0, 11, kUpb_FieldMode_Map | (kUpb_FieldRep_Pointer << kUpb_FieldRep_Shift)},
};

const upb_MiniTable google_protobuf_Struct_msginit = {
  &google_protobuf_Struct_submsgs[0],
  &google_protobuf_Struct__fields[0],
  UPB_SIZE(4, 8), 1, kUpb_ExtMode_NonExtendable, 1, 255, 0,
};

static const upb_MiniTable_Sub google_protobuf_Struct_FieldsEntry_submsgs[1] = {
  {.submsg = &google_protobuf_Value_msginit},
};

static const upb_MiniTable_Field google_protobuf_Struct_FieldsEntry__fields[2] = {
  {1, UPB_SIZE(0, 0), UPB_SIZE(0, 0), kUpb_NoSub, 12, kUpb_FieldMode_Scalar | (kUpb_FieldRep_1Byte << kUpb_FieldRep_Shift)},
  {2, UPB_SIZE(8, 16), UPB_SIZE(0, 0), 0, 11, kUpb_FieldMode_Scalar | (kUpb_FieldRep_1Byte << kUpb_FieldRep_Shift)},
};

const upb_MiniTable google_protobuf_Struct_FieldsEntry_msginit = {
  &google_protobuf_Struct_FieldsEntry_submsgs[0],
  &google_protobuf_Struct_FieldsEntry__fields[0],
  UPB_SIZE(16, 32), 2, kUpb_ExtMode_NonExtendable, 2, 255, 0,
};

static const upb_MiniTable_Sub google_protobuf_Value_submsgs[2] = {
  {.submsg = &google_protobuf_Struct_msginit},
  {.submsg = &google_protobuf_ListValue_msginit},
};

static const upb_MiniTable_Field google_protobuf_Value__fields[6] = {
  {1, UPB_SIZE(8, 8), UPB_SIZE(-1, -1), kUpb_NoSub, 5, kUpb_FieldMode_Scalar | (kUpb_FieldRep_4Byte << kUpb_FieldRep_Shift)},
  {2, UPB_SIZE(8, 8), UPB_SIZE(-1, -1), kUpb_NoSub, 1, kUpb_FieldMode_Scalar | (kUpb_FieldRep_8Byte << kUpb_FieldRep_Shift)},
  {3, UPB_SIZE(8, 8), UPB_SIZE(-1, -1), kUpb_NoSub, 9, kUpb_FieldMode_Scalar | (kUpb_FieldRep_StringView << kUpb_FieldRep_Shift)},
  {4, UPB_SIZE(8, 8), UPB_SIZE(-1, -1), kUpb_NoSub, 8, kUpb_FieldMode_Scalar | (kUpb_FieldRep_1Byte << kUpb_FieldRep_Shift)},
  {5, UPB_SIZE(8, 8), UPB_SIZE(-1, -1), 0, 11, kUpb_FieldMode_Scalar | (kUpb_FieldRep_Pointer << kUpb_FieldRep_Shift)},
  {6, UPB_SIZE(8, 8), UPB_SIZE(-1, -1), 1, 11, kUpb_FieldMode_Scalar | (kUpb_FieldRep_Pointer << kUpb_FieldRep_Shift)},
};

const upb_MiniTable google_protobuf_Value_msginit = {
  &google_protobuf_Value_submsgs[0],
  &google_protobuf_Value__fields[0],
  UPB_SIZE(16, 24), 6, kUpb_ExtMode_NonExtendable, 6, 255, 0,
};

static const upb_MiniTable_Sub google_protobuf_ListValue_submsgs[1] = {
  {.submsg = &google_protobuf_Value_msginit},
};

static const upb_MiniTable_Field google_protobuf_ListValue__fields[1] = {
  {1, UPB_SIZE(0, 0), UPB_SIZE(0, 0), 0, 11, kUpb_FieldMode_Array | (kUpb_FieldRep_Pointer << kUpb_FieldRep_Shift)},
};

const upb_MiniTable google_protobuf_ListValue_msginit = {
  &google_protobuf_ListValue_submsgs[0],
  &google_protobuf_ListValue__fields[0],
  UPB_SIZE(4, 8), 1, kUpb_ExtMode_NonExtendable, 1, 255, 0,
};

static const upb_MiniTable *messages_layout[4] = {
  &google_protobuf_Struct_msginit,
  &google_protobuf_Struct_FieldsEntry_msginit,
  &google_protobuf_Value_msginit,
  &google_protobuf_ListValue_msginit,
};

const upb_MiniTable_File google_protobuf_struct_proto_upb_file_layout = {
  messages_layout,
  NULL,
  NULL,
  4,
  0,
  0,
};

#include "upb/port_undef.inc"


text:
(function() {

var thisFile = 'html_import.debug.js';
var scopeName = 'HTMLImports';
var modules = [
    'src/Parser.js',
    'src/HTMLImports.js',
    'src/boot.js'
];

// export

window[scopeName] = {
  entryPointName: thisFile,
  modules: modules
};

// bootstrap

var script = document.querySelector('script[src*="' + thisFile + '"]');
var src = script.attributes.src.value;
var basePath = src.slice(0, src.indexOf(thisFile));

if (!window.Loader) {
  var path = basePath + 'tools/loader/loader.js';
  document.write('<script src="' + path + '"></script>');
}
document.write('<script>Loader.load("' + scopeName + '")</script>');

})();


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

    </LinearLayout>

</FrameLayout>


text:
package org.fest.swing.driver;

import static org.fest.assertions.Assertions.assertThat;
import static org.fest.util.Lists.newArrayList;

import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

/**
 * Tests for {@link JTableHeaderLocation#pointAt(javax.swing.table.JTableHeader, int)}.
 *
 * @author Alex Ruiz
 * @author Yvonne Wang
 */
@RunWith(Parameterized.class)
public class JTableHeaderLocation_pointAtColumnByIndex_Test extends JTableHeaderLocation_TestCase {
  private final int index;

  @Parameters
  public static Collection<Object[]> indices() {
    return newArrayList(columnIndices());
  }

  public JTableHeaderLocation_pointAtColumnByIndex_Test(int index) {
    this.index = index;
  }

  @Test
  public void should_return_point_at_column() {
    showWindow();
    assertThat(pointAt(index)).isEqualTo(expectedPoint(index));
  }
}


text:
import {Config} from '../config';

import {Binary, BinaryUrl, OS} from './binary';
import {GeckoDriverGithub} from './gecko_driver_github';

type StringMap = {
  [key: string]: string
};
type SuffixMap = {
  [key: string]: StringMap
};

export class GeckoDriver extends Binary {
  static id = 'gecko';
  static isDefault = true;
  static os = [OS.Windows_NT, OS.Linux, OS.Darwin];
  static versionDefault = Config.binaryVersions().gecko;
  private static suffixes: SuffixMap = {
    'Darwin': {'x64': '-macos.tar.gz'},
    'Linux': {'x64': '-linux64.tar.gz', 'ia32': '-linux32.tar.gz'},
    'Windows_NT': {
      'x64': '-win64.zip',
      'ia32': '-win32.zip',
    }
  };

  constructor(opt_alternativeCdn?: string) {
    super(opt_alternativeCdn || Config.cdnUrls().gecko);
    this.configSource = new GeckoDriverGithub();
    this.name = 'geckodriver';
    this.versionDefault = GeckoDriver.versionDefault;
    this.versionCustom = this.versionDefault;
  }

  id(): string {
    return GeckoDriver.id;
  }

  prefix(): string {
    return 'geckodriver-';
  }

  suffix(): string {
    if (this.ostype === 'Windows_NT') {
      return '.zip';
    } else {
      return '.tar.gz';
    }
  }

  getVersionList(): Promise<string[]> {
    if (this.alternativeDownloadUrl != null) {
      return Promise.resolve([]);
    } else {
      return this.configSource.getVersionList();
    }
  }
}


text:
class DelayedJobUtil
  def self.health_check
    count = ActiveRecord::Base.logger.silence do
      Delayed::Job.where('created_at < ? AND failed_at IS NULL', 10.minutes.ago).count
    end
    if count > 0
      # restart delayed_job and send an email
      Rails.logger.error("There are #{count} outstanding delayed_jobs. restarting daemon.")
      ExceptionNotifier.notify_exception(Exception.new('delayed_job error')) if Rails.env == "production"
      Rails.logger.info `/usr/bin/env RAILS_ENV=#{Rails.env} bundle exec bin/delayed_job restart`
    end
  end
end


text:
<?php
namespace App\Model\Entity;

use Cake\ORM\Entity;

/**
 * Permission Entity.
 *
 * @property int $id
 * @property string $name
 * @property string $path
 * @property \App\Model\Entity\UserPermission[] $user_permissions
 */
class Permission extends Entity
{

    /**
     * Fields that can be mass assigned using newEntity() or patchEntity().
     *
     * Note that when '*' is set to true, this allows all unspecified fields to
     * be mass assigned. For security purposes, it is advised to set '*' to false
     * (or remove it), and explicitly make individual fields accessible as needed.
     *
     * @var array
     */
    protected $_accessible = [
        '*' => true,
        'id' => false,
    ];

    protected function _getName()
    {
        return isset($this->_properties['name']) ? __($this->_properties['name']) : '';
    }
}


text:
class java::lang::Error : public ::java::lang::Throwable
{

public:
  Error();
  Error(::java::lang::String *);
  Error(::java::lang::String *, ::java::lang::Throwable *);
  Error(::java::lang::Throwable *);
private:
  static const jlong serialVersionUID = 4980196508277280342LL;
public:
  static ::java::lang::Class class$;
};

#endif // __java_lang_Error__


text:
 # ############################################################################
 #
 # Copyright (c) Microsoft Corporation.
 #
 # This source code is subject to terms and conditions of the Apache License, Version 2.0. A
 # copy of the license can be found in the License.html file at the root of this distribution. If
 # you cannot locate the Apache License, Version 2.0, please send an email to
 # vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
 # by the terms of the Apache License, Version 2.0.
 #
 # You must not remove this notice, or any other, from this software.
 #
 # ###########################################################################

import datetime
import os
import sys
import traceback

if sys.version_info[0] == 3:
    def to_str(value):
        return value.decode(sys.getfilesystemencoding())

    def execfile(path, global_dict):
        """Execute a file"""
        with open(path, 'r') as f:
            code = f.read()
        code = code.replace('\r\n', '\n') + '\n'
        exec(code, global_dict)
else:
    def to_str(value):
        return value.encode(sys.getfilesystemencoding())

def log(txt):
    """Logs fatal errors to a log file if WSGI_LOG env var is defined"""
    log_file = os.environ.get('WSGI_LOG')
    if log_file:
        f = open(log_file, 'a+')
        try:
            f.write('%s: %s' % (datetime.datetime.now(), txt))
        finally:
            f.close()

ptvsd_secret = os.getenv('WSGI_PTVSD_SECRET')
if ptvsd_secret:
    log('Enabling ptvsd ...\n')
    try:
        import ptvsd
        try:
            ptvsd.enable_attach(ptvsd_secret)
            log('ptvsd enabled.\n')
        except:
            log('ptvsd.enable_attach failed\n')
    except ImportError:
        log('error importing ptvsd.\n');

def get_wsgi_handler(handler_name):
    if not handler_name:
        raise Exception('WSGI_ALT_VIRTUALENV_HANDLER env var must be set')

    if not isinstance(handler_name, str):
        handler_name = to_str(handler_name)

    module_name, _, callable_name = handler_name.rpartition('.')
    should_call = callable_name.endswith('()')
    callable_name = callable_name[:-2] if should_call else callable_name
    name_list = [(callable_name, should_call)]
    handler = None
    last_tb = ''

    while module_name:
        try:
            handler = __import__(module_name, fromlist=[name_list[0][0]])
            last_tb = ''
            for name, should_call in name_list:
                handler = getattr(handler, name)
                if should_call:
                    handler = handler()
            break
        except ImportError:
            module_name, _, callable_name = module_name.rpartition('.')
            should_call = callable_name.endswith('()')
            callable_name = callable_name[:-2] if should_call else callable_name
            name_list.insert(0, (callable_name, should_call))
            handler = None
            last_tb = ': ' + traceback.format_exc()

    if handler is None:
        raise ValueError('"%s" could not be imported%s' % (handler_name, last_tb))

    return handler

activate_this = os.getenv('WSGI_ALT_VIRTUALENV_ACTIVATE_THIS')
if not activate_this:
    raise Exception('WSGI_ALT_VIRTUALENV_ACTIVATE_THIS is not set')

def get_virtualenv_handler():
    log('Activating virtualenv with %s\n' % activate_this)
    execfile(activate_this, dict(__file__=activate_this))

    log('Getting handler %s\n' % os.getenv('WSGI_ALT_VIRTUALENV_HANDLER'))
    handler = get_wsgi_handler(os.getenv('WSGI_ALT_VIRTUALENV_HANDLER'))
    log('Got handler: %r\n' % handler)
    return handler

def get_venv_handler():
    log('Activating venv with executable at %s\n' % activate_this)
    import site
    sys.executable = activate_this
    old_sys_path, sys.path = sys.path, []

    site.main()

    sys.path.insert(0, '')
    for item in old_sys_path:
        if item not in sys.path:
            sys.path.append(item)

    log('Getting handler %s\n' % os.getenv('WSGI_ALT_VIRTUALENV_HANDLER'))
    handler = get_wsgi_handler(os.getenv('WSGI_ALT_VIRTUALENV_HANDLER'))
    log('Got handler: %r\n' % handler)
    return handler


text:
import numpy as np
import scipy
import scipy.linalg

# Computes V * exp_wt * U.
# By construction the exponential of our matrices are always real-valued.
def Expm(V, exp_wt, U):
    return np.real(V.dot(np.diag(exp_wt)).dot(U))

# Computes the robot distribution after t.
def ComputeX(t_list, K, X_init):
  is_iterable = np.iterable(t_list)
  if not is_iterable:
    t_list = [t_list]
  num_nodes = X_init.shape[0]
  num_species = X_init.shape[1]
  X = np.zeros((len(t_list), num_nodes, num_species))
  # For each species, get transition matrix and calculate final distribution of robots.
  for s in range(num_species):
    Ks = K[:, :, s]
    x0 = X_init[:, s]
    # Perform eigen-decomposition to compute matrix exponential repeatedly.
    w, V = scipy.linalg.eig(Ks, right=True)
    U = scipy.linalg.inv(V)
    for i, t in enumerate(t_list):
      wt = w * t
      exp_wt = np.exp(wt)
      X[i, :, s] = Expm(V, exp_wt, U).dot(x0)
  if is_iterable:
    return X
  return X[0, :, :]

# Computes the trait distribution after t.
def ComputeY(t_list, K, X_init, Q):
  return ComputeX(t_list, K, X_init).dot(Q)

# Simulates random transitions.
def SimulateX(max_time, K, X_init, dt=None):
  num_nodes = X_init.shape[0]
  num_species = X_init.shape[1]
  if dt is None:
    dt = 0.1 / np.max(K)  # Auto-scale step.
  # Pre-compute transition probabilities.
  P = []
  for s in range(num_species):
    Ks = K[:, :, s]
    P.append(scipy.linalg.expm(dt * Ks))

  X = X_init.copy()
  Xs = [X]
  t = 0
  ts = [0]
  while t < max_time:
    new_X = np.zeros_like(X)
    for s in range(num_species):
      for m in range(num_nodes):
        transition_probabilities = P[s][:, m]
        num_robots_in_m = X[m, s]
        choices = np.random.choice(num_nodes, num_robots_in_m, p=transition_probabilities)
        for n in range(num_nodes):
          new_X[n, s] += np.sum(choices == n)
    X = new_X
    Xs.append(X)
    t += dt
    ts.append(t)
  return np.stack(Xs, axis=0), np.array(ts)

def SimulateY(max_time, K, X_init, Q, dt=None):
  X, ts = SimulateX(max_time, K, X_init, dt)
  return X.dot(Q), ts


text:
#ifndef CAPU_IPHONESIMULATOROS_X86_64_LIGHTWEIGHTMUTEX_H
#define CAPU_IPHONESIMULATOROS_X86_64_LIGHTWEIGHTMUTEX_H

#include <capu/os/iPhoneOS/LightweightMutex.h>

namespace capu
{
    namespace os
    {
        namespace arch
        {
            class LightweightMutex: public capu::iphoneos::LightweightMutex
            {
            };
        }
    }
}

#endif // CAPU_IPHONESIMULATOROS_X86_64_LIGHTWEIGHTMUTEX_H


text:
<?php
$permissionChecker = new ACL();
if ($permissionChecker->hasPermission("update_system")) {
    $version = ControllerRegistry::get("CoreUpgradeController")->checkForUpgrades();
    if ($version) {
        ?>

<?php translate("ONECLICK_UPGRADE"); ?>

<?php translate("an_upgrade_is_available", array("%version%" => $version)); ?>

<a href="<?= ModuleHelper::buildActionURL("UpgradeCheck"); ?>" class="btn btn-info">
                     <?php translate("show_more"); ?>

        <?php
    }
}


text:
import hashlib
import logging
from datetime import datetime, timedelta

from redis import Redis
from redis.exceptions import RedisError

from waterbutler.server import settings
from waterbutler.core.exceptions import WaterButlerRedisError

logger = logging.getLogger(__name__)

class RateLimitingMixin:
    """ Rate-limiting WB API with Redis using the "Fixed Window" algorithm.
    """

    def __init__(self):

        self.WINDOW_SIZE = settings.RATE_LIMITING_FIXED_WINDOW_SIZE
        self.WINDOW_LIMIT = settings.RATE_LIMITING_FIXED_WINDOW_LIMIT
        self.redis_conn = Redis(host=settings.REDIS_HOST, port=settings.REDIS_PORT,
                                password=settings.REDIS_PASSWORD)

    def rate_limit(self):
        """ Check with the WB Redis server on whether to rate-limit a request.  Returns a tuple.
        First value is `True` if the limit is reached, `False` otherwise.  Second value is the
        rate-limiting metadata (nbr of requests remaining, time to reset, etc.) if the request was
        rate-limited.
        """

        limit_check, redis_key = self.get_auth_naive()
        logger.debug('>>> RATE LIMITING >>> check={} key={}'.format(limit_check, redis_key))
        if not limit_check:
            return False, None

        try:
            counter = self.redis_conn.incr(redis_key)
        except RedisError:
            raise WaterButlerRedisError('INCR {}'.format(redis_key))

        if counter > self.WINDOW_LIMIT:
            # The key exists and the limit has been reached.
            try:
                retry_after = self.redis_conn.ttl(redis_key)
            except RedisError:
                raise WaterButlerRedisError('TTL {}'.format(redis_key))
            logger.debug('>>> RATE LIMITING >>> FAIL >>> key={} '
                         'counter={} url={}'.format(redis_key, counter, self.request.full_url()))
            data = {
                'retry_after': int(retry_after),
                'remaining': 0,
                'reset': str(datetime.now() + timedelta(seconds=int(retry_after))),
            }
            return True, data
        elif counter == 1:
            # The key does not exist and `.incr()` returns 1 by default.
            try:
                self.redis_conn.expire(redis_key, self.WINDOW_SIZE)
            except RedisError:
                raise WaterButlerRedisError('EXPIRE {} {}'.format(redis_key, self.WINDOW_SIZE))
            logger.debug('>>> RATE LIMITING >>> NEW >>> key={} '
                         'counter={} url={}'.format(redis_key, counter, self.request.full_url()))
        else:
            # The key exists and the limit has not been reached.
            logger.debug('>>> RATE LIMITING >>> PASS >>> key={} '
                         'counter={} url={}'.format(redis_key, counter, self.request.full_url()))

        return False, None

    def get_auth_naive(self):
        """ Get the obfuscated authentication / authorization credentials from the request.  Return
        a tuple ``(limit_check, auth_key)`` that tells the rate-limiter 1) whether to rate-limit,
        and 2) if so, limit by what key.

        Refer to ``tornado.httputil.HTTPServerRequest`` for more info on tornado's request object:
            https://www.tornadoweb.org/en/stable/httputil.html#tornado.httputil.HTTPServerRequest

        This is a NAIVE implementation in which WaterButler rate-limiter only checks the existence
        of auth creds in the requests without further verifying them with the OSF.  Invalid creds
        will fail the next OSF auth part anyway even if it passes the rate-limiter.

        There are four types of auth: 1) OAuth access token, 2) basic auth w/ base64-encoded
        username/password, 3) OSF cookie, and 4) no auth.  The naive implementation checks each
        method in this order.  Only cookie-based auth is permitted to bypass the rate-limiter.
        This order does not care about the validity of the auth mechanism.  An invalid Basic auth
        header + an OSF cookie will be rate-limited according to the Basic auth header.

        TODO: check with OSF API auth to see how it deals with multiple auth options.
        """

        auth_hdrs = self.request.headers.get('Authorization', None)

        # CASE 1: Requests with a bearer token (PAT or OAuth)
        if auth_hdrs and auth_hdrs.startswith('Bearer '):  # Bearer token
            bearer_token = auth_hdrs.split(' ')[1] if auth_hdrs.startswith('Bearer ') else None
            logger.debug('>>> RATE LIMITING >>> AUTH:TOKEN >>> {}'.format(bearer_token))
            return True, 'TOKEN__{}'.format(self._obfuscate_creds(bearer_token))

        # CASE 2: Requests with basic auth using username and password
        if auth_hdrs and auth_hdrs.startswith('Basic '):  # Basic auth
            basic_creds = auth_hdrs.split(' ')[1] if auth_hdrs.startswith('Basic ') else None
            logger.debug('>>> RATE LIMITING >>> AUTH:BASIC >>> {}'.format(basic_creds))
            return True, 'BASIC__{}'.format(self._obfuscate_creds(basic_creds))

        # CASE 3: Requests with OSF cookies
        # SECURITY WARNING: Must check cookie last since it can only be allowed when used alone!
        cookies = self.request.cookies or None
        if cookies and cookies.get('osf'):
            osf_cookie = cookies.get('osf').value
            logger.debug('>>> RATE LIMITING >>> AUTH:COOKIE >>> {}'.format(osf_cookie))
            return False, 'COOKIE_{}'.format(self._obfuscate_creds(osf_cookie))

        # TODO: Work with DevOps to make sure that the `remote_ip` is the real IP instead of our
        #       load balancers.  In addition, check relevatn HTTP headers as well.
        # CASE 4: Requests without any expected auth (case 1, 2 or 3 above).
        remote_ip = self.request.remote_ip or 'NOI.PNO.IPN.OIP'
        logger.debug('>>> RATE LIMITING >>> AUTH:NONE >>> {}'.format(remote_ip))
        return True, 'NOAUTH_{}'.format(self._obfuscate_creds(remote_ip))

    @staticmethod
    def _obfuscate_creds(creds):
        """Obfuscate authentication/authorization credentials: cookie, access token and password.

        It is not recommended to store the plain OSF cookie or the OAuth bearer token as key and it
        is evil to store the base64-encoded username and password as key since it is reversible.
        """

        return hashlib.sha256(creds.encode('utf-8')).hexdigest().upper()


text:
package com.wyp.materialqqlite.qqclient.protocol.protocoldata;

import org.json.JSONObject;

public class GetC2CMsgSigResult {
	public int m_nRetCode;
	public int m_nType;
	public String m_strValue;
	public int m_nFlags;
	public int m_nGroupId;
	public int m_nQQUin;

	public void reset() {
		m_nRetCode = 0;
		m_nType = 0;
		m_strValue = "";
		m_nFlags = 0;
	}

	public boolean parse(byte[] bytData) {
		try {
			reset();

			if (bytData == null || bytData.length <= 0)
				return false;

			String strData = new String(bytData, "UTF-8");
			System.out.println(strData);

			JSONObject json = new JSONObject(strData);
			m_nRetCode = json.optInt("retcode");
			json = json.optJSONObject("result");

			m_nType = json.optInt("type");
			m_strValue = json.optString("value");
			m_nFlags = 0;	// 暂时不解析"flags":{"text":1,"pic":1,"file":1,"audio":1,"video":1}

			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
}


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

<title>A-Index</title>
<meta name="date" content="2015-10-06">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A C D F M P R S T W

A

append(Object) - Static method in class com.company.TalkLess

Takes the parameter the user passes in as a type of Object and
 calls the roundAppend() method passing Object t to it.

append(Object, int, int) - Static method in class com.company.TalkLess

Takes the parameters the user passes in as a type of Object, int, and int.

A C D F M P R S T W

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>twitter4j.examples.suggestedusers (twitter4j-examples 3.0.4 API)</title>
<meta name="date" content="2013-10-08">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package twitter4j.examples.suggestedusers

Class Summary

Class
Description

GetMemberSuggestions

Shows suggested users in specified category.

GetSuggestedUserCategories

Shows authenticated user's suggested user categories.

GetUserSuggestions

Shows suggested users in specified category.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Copyright © 2013. All Rights Reserved.


text:
#ifndef CFREMENGRIDEXP_H
#define CFREMENGRIDEXP_H

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "CTimerExp.h"
#include "CFrelementExp.h"

#define MAX_ID_LENGTH 100

/**
@author Tom Krajnik
*/

using namespace std;

class CFremenGrid
{
public:
    CFremenGrid(const char* name, float originX,float originY,float originZ,int dimX,int dimY,int dimZ,float cellSize);
    ~CFremenGrid();

    /*fills the grid borders*/
    void buildLimits(float* grid);

    /*state estimation: estimates the grid for the given time*/
    bool recalculate(uint32_t timeStamp);

    /*repopulates the set P - use to recover after map load*/
    void update();

    float getObtainedInformationLast();
    float getObtainedInformationPredicted();

    float estimateInformation(float x,float y,float z,float range,uint32_t t);
    float getClosestObstacle(float x,float y,float zlimit,float range);

    /*changes the model order*/
    void print(bool verbose);
    void save(const char*name,bool lossy = false,int forceOrder = -1);
    void saveSmart(const char*name,bool lossy = false,int forceOrder = -1);
    bool load(const char*name);
    bool loadHeader(const char*name);
    int numStatic(float tolerance = 0);

    float estimate(unsigned int index,uint32_t timeStamp);
    float retrieve(unsigned int index);
    float getDominant(unsigned int index,int period);

    float incorporate(float *x,float *y,float *z,float *d,int size,uint32_t t);
    int getIndex(float x,float y,float z);

    //center of the first cell
    float oX,oY,oZ;
    //size of the grid cells
    float resolution;
    //grid dimensions
    int xDim,yDim,zDim;
    float* probs;
    float* predicted;
    char *aux;
    int numCells;
    bool debug;

    char id[MAX_ID_LENGTH];
    uint32_t lastTimeStamp;
    float minProb,maxProb,residualEntropy,residualInformation;
    float lastPhiRange,lastPsiMin,lastPsiMax,lastRange;
    int *raycasters;
    int numRaycasters;
    float obtainedInformationLast;
    float obtainedInformationPredicted;
    CFrelement* frelements;
};

#endif


text:
'use strict';

var _ = require('underscore');
var extend = require('./extend');

var Vertex = function (name, payload) {
    this.name = name;
    this.payload = payload;
};
Vertex.extend = _.partial(extend, Vertex);

_.extend(Vertex.prototype, {
    getName: function () {
        return this.name;
    },

    getPayload: function () {
        return this.payload;
    },
});

module.exports = Vertex;


text:
package com.softwaremill.common.cdi.security;

/**
 * @author Adam Warski (adam at warski dot org)
 */
@Secure("#{var3 == true}")
public class SecureBeanCompoundContextual {
    @AccessIfVar1Set
    @Secure("#{var2 == true}")
    public void method1(@SecureVar("var1") boolean var1, @SecureVar("var2") boolean var2, @SecureVar("var3") boolean var3) { }
}


text:
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1251">

<select id="i1"></select>

            <input type="checkbox" id="i2"/>

<select id="i3"></select>

    <input id="i5" type="button" value="" onClick="back();"/>
    <input id="i4" type="button" value="" onClick="submit();"/>


text:
<!DOCTYPE html>

    <title></title>
    <link href="js-console/js-console.css" rel="stylesheet" />

    <input type="text" id="input1" />

    <button onclick="first()">1</button>
    <button onclick="second()">2</button>

        <button onclick="third()">3</button>
        <input type="checkbox" id="sensitive" checked=""/>
        Case sensitive

    <button onclick="fourth()">4</button>
    <button onclick="fifth()">5</button>
    <button onclick="sixth()">6</button>
    <button onclick="seventh()">7</button>