text:
// ======================================================================== //
// Copyright 2009-2017 Intel 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.                                           //
// ======================================================================== //

#pragma once

#include "trianglei.h"
#include "triangle_intersector_moeller.h"
#include "triangle_intersector_pluecker.h"

namespace embree
{
  namespace isa
  {
    /*! Intersects M triangles with 1 ray */
    template<int M, int Mx, bool filter>
      struct TriangleMiIntersector1Moeller
    {
      typedef TriangleMi<M> Primitive;
      typedef Intersector1Precalculations<MoellerTrumboreIntersector1<Mx>> Precalculations;

      static __forceinline void intersect(const Precalculations& pre, Ray& ray, IntersectContext* context, const Primitive& tri)
      {
        STAT3(normal.trav_prims,1,1,1);
        Vec3<vfloat<M>> v0, v1, v2; tri.gather(v0,v1,v2,context->scene);
        pre.intersect(ray,v0,v1,v2,/*UVIdentity<Mx>(),*/Intersect1EpilogM<M,Mx,filter>(ray,context,tri.geomIDs,tri.primIDs));
      }

      static __forceinline bool occluded(const Precalculations& pre, Ray& ray, IntersectContext* context, const Primitive& tri)
      {
        STAT3(shadow.trav_prims,1,1,1);
        Vec3<vfloat<M>> v0, v1, v2; tri.gather(v0,v1,v2,context->scene);
        return pre.intersect(ray,v0,v1,v2,/*UVIdentity<Mx>(),*/Occluded1EpilogM<M,Mx,filter>(ray,context,tri.geomIDs,tri.primIDs));
      }

      /*! Intersect an array of rays with an array of M primitives. */
      static __forceinline size_t intersect(Precalculations* pre, size_t valid, Ray** rays, IntersectContext* context,  size_t ty, const Primitive* prim, size_t num)
      {
        size_t valid_isec = 0;
        do {
          const size_t i = __bscf(valid);
          const float old_far = rays[i]->tfar;
          for (size_t n=0; n<num; n++)
            intersect(pre[i],*rays[i],context,prim[n]);
          valid_isec |= (rays[i]->tfar < old_far) ? ((size_t)1 << i) : 0;
        } while(unlikely(valid));
        return valid_isec;
      }

    };

    /*! Intersects M triangles with K rays */
    template<int M, int Mx, int K, bool filter>
      struct TriangleMiIntersectorKMoeller
      {
        typedef TriangleMi<M> Primitive;
        typedef IntersectorKPrecalculations<K,MoellerTrumboreIntersectorK<Mx,K>> Precalculations;

        static __forceinline void intersect(const vbool<K>& valid_i, Precalculations& pre, RayK<K>& ray, IntersectContext* context, const Primitive& tri)
        {
          for (size_t i=0; i<Primitive::max_size(); i++)
          {
            if (!tri.valid(i)) break;
            STAT3(normal.trav_prims,1,popcnt(valid_i),RayK<K>::size());
            const Vec3f& p0 = *(const Vec3f*) context->scene->get<TriangleMesh>(tri.geomID(i))->vertexPtr(tri.v0[i]);
            const Vec3f& p1 = *(Vec3f*)((int*)&p0 + tri.v1[i]);
            const Vec3f& p2 = *(Vec3f*)((int*)&p0 + tri.v2[i]);
            const Vec3<vfloat<K>> v0 = Vec3<vfloat<K>>(p0);
            const Vec3<vfloat<K>> v1 = Vec3<vfloat<K>>(p1);
            const Vec3<vfloat<K>> v2 = Vec3<vfloat<K>>(p2);
            pre.intersectK(valid_i,ray,v0,v1,v2,/*UVIdentity<K>(),*/IntersectKEpilogM<M,K,filter>(ray,context,tri.geomIDs,tri.primIDs,i));
          }
        }

        static __forceinline vbool<K> occluded(const vbool<K>& valid_i, Precalculations& pre, RayK<K>& ray, IntersectContext* context, const Primitive& tri)
        {
          vbool<K> valid0 = valid_i;

          for (size_t i=0; i<Primitive::max_size(); i++)
          {
            if (!tri.valid(i)) break;
            STAT3(shadow.trav_prims,1,popcnt(valid_i),RayK<K>::size());
            const Vec3f& p0 = *(const Vec3f*) context->scene->get<TriangleMesh>(tri.geomID(i))->vertexPtr(tri.v0[i]);
            const Vec3f& p1 = *(Vec3f*)((int*)&p0 + tri.v1[i]);
            const Vec3f& p2 = *(Vec3f*)((int*)&p0 + tri.v2[i]);
            const Vec3<vfloat<K>> v0 = Vec3<vfloat<K>>(p0);
            const Vec3<vfloat<K>> v1 = Vec3<vfloat<K>>(p1);
            const Vec3<vfloat<K>> v2 = Vec3<vfloat<K>>(p2);
            pre.intersectK(valid0,ray,v0,v1,v2,/*UVIdentity<K>(),*/OccludedKEpilogM<M,K,filter>(valid0,ray,context,tri.geomIDs,tri.primIDs,i));
            if (none(valid0)) break;
          }
          return !valid0;
        }

        static __forceinline void intersect(Precalculations& pre, RayK<K>& ray, size_t k, IntersectContext* context, const Primitive& tri)
        {
          STAT3(normal.trav_prims,1,1,1);
          Vec3<vfloat<M>> v0, v1, v2; tri.gather(v0,v1,v2,context->scene);
          pre.intersect(ray,k,v0,v1,v2,/*UVIdentity<Mx>(),*/Intersect1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomIDs,tri.primIDs));
        }

        static __forceinline bool occluded(Precalculations& pre, RayK<K>& ray, size_t k, IntersectContext* context, const Primitive& tri)
        {
          STAT3(shadow.trav_prims,1,1,1);
          Vec3<vfloat<M>> v0, v1, v2; tri.gather(v0,v1,v2,context->scene);
          return pre.intersect(ray,k,v0,v1,v2,/*UVIdentity<Mx>(),*/Occluded1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomIDs,tri.primIDs));
        }
      };

    /*! Intersects M triangles with 1 ray */
    template<int M, int Mx, bool filter>
    struct TriangleMiIntersector1Pluecker
    {
      typedef TriangleMi<M> Primitive;
      typedef Intersector1Precalculations<PlueckerIntersector1<Mx>> Precalculations;

      static __forceinline void intersect(const Precalculations& pre, Ray& ray, IntersectContext* context, const Primitive& tri)
      {
        STAT3(normal.trav_prims,1,1,1);
        Vec3<vfloat<M>> v0, v1, v2; tri.gather(v0,v1,v2,context->scene);
        pre.intersect(ray,v0,v1,v2,UVIdentity<Mx>(),Intersect1EpilogM<M,Mx,filter>(ray,context,tri.geomIDs,tri.primIDs));
      }

      static __forceinline bool occluded(const Precalculations& pre, Ray& ray, IntersectContext* context, const Primitive& tri)
      {
        STAT3(shadow.trav_prims,1,1,1);
        Vec3<vfloat<M>> v0, v1, v2; tri.gather(v0,v1,v2,context->scene);
        return pre.intersect(ray,v0,v1,v2,UVIdentity<Mx>(),Occluded1EpilogM<M,Mx,filter>(ray,context,tri.geomIDs,tri.primIDs));
      }

      /*! Intersect an array of rays with an array of M primitives. */
      static __forceinline size_t intersect(Precalculations* pre, size_t valid, Ray** rays, IntersectContext* context,  size_t ty, const Primitive* prim, size_t num)
      {
        size_t valid_isec = 0;
        do {
          const size_t i = __bscf(valid);
          const float old_far = rays[i]->tfar;
          for (size_t n=0; n<num; n++)
            intersect(pre[i],*rays[i],context,prim[n]);
          valid_isec |= (rays[i]->tfar < old_far) ? ((size_t)1 << i) : 0;
        } while(unlikely(valid));
        return valid_isec;
      }

    };

    /*! Intersects M triangles with K rays */
    template<int M, int Mx, int K, bool filter>
      struct TriangleMiIntersectorKPluecker
      {
        typedef TriangleMi<M> Primitive;
        typedef IntersectorKPrecalculations<K,PlueckerIntersectorK<Mx,K>> Precalculations;

        static __forceinline void intersect(const vbool<K>& valid_i, Precalculations& pre, RayK<K>& ray, IntersectContext* context, const Primitive& tri)
        {
          for (size_t i=0; i<Primitive::max_size(); i++)
          {
            if (!tri.valid(i)) break;
            STAT3(normal.trav_prims,1,popcnt(valid_i),RayK<K>::size());
            const Vec3f& p0 = *(const Vec3f*) context->scene->get<TriangleMesh>(tri.geomID(i))->vertexPtr(tri.v0[i]);
            const Vec3f& p1 = *(Vec3f*)((int*)&p0 + tri.v1[i]);
            const Vec3f& p2 = *(Vec3f*)((int*)&p0 + tri.v2[i]);
            const Vec3<vfloat<K>> v0 = Vec3<vfloat<K>>(p0);
            const Vec3<vfloat<K>> v1 = Vec3<vfloat<K>>(p1);
            const Vec3<vfloat<K>> v2 = Vec3<vfloat<K>>(p2);
            pre.intersectK(valid_i,ray,v0,v1,v2,UVIdentity<K>(),IntersectKEpilogM<M,K,filter>(ray,context,tri.geomIDs,tri.primIDs,i));
          }
        }

        static __forceinline vbool<K> occluded(const vbool<K>& valid_i, Precalculations& pre, RayK<K>& ray, IntersectContext* context, const Primitive& tri)
        {
          vbool<K> valid0 = valid_i;

          for (size_t i=0; i<Primitive::max_size(); i++)
          {
            if (!tri.valid(i)) break;
            STAT3(shadow.trav_prims,1,popcnt(valid_i),RayK<K>::size());
            const Vec3f& p0 = *(const Vec3f*) context->scene->get<TriangleMesh>(tri.geomID(i))->vertexPtr(tri.v0[i]);
            const Vec3f& p1 = *(Vec3f*)((int*)&p0 + tri.v1[i]);
            const Vec3f& p2 = *(Vec3f*)((int*)&p0 + tri.v2[i]);
            const Vec3<vfloat<K>> v0 = Vec3<vfloat<K>>(p0);
            const Vec3<vfloat<K>> v1 = Vec3<vfloat<K>>(p1);
            const Vec3<vfloat<K>> v2 = Vec3<vfloat<K>>(p2);
            pre.intersectK(valid0,ray,v0,v1,v2,UVIdentity<K>(),OccludedKEpilogM<M,K,filter>(valid0,ray,context,tri.geomIDs,tri.primIDs,i));
            if (none(valid0)) break;
          }
          return !valid0;
        }

        static __forceinline void intersect(Precalculations& pre, RayK<K>& ray, size_t k, IntersectContext* context, const Primitive& tri)
        {
          STAT3(normal.trav_prims,1,1,1);
          Vec3<vfloat<M>> v0, v1, v2; tri.gather(v0,v1,v2,context->scene);
          pre.intersect(ray,k,v0,v1,v2,UVIdentity<Mx>(),Intersect1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomIDs,tri.primIDs));
        }

        static __forceinline bool occluded(Precalculations& pre, RayK<K>& ray, size_t k, IntersectContext* context, const Primitive& tri)
        {
          STAT3(shadow.trav_prims,1,1,1);
          Vec3<vfloat<M>> v0, v1, v2; tri.gather(v0,v1,v2,context->scene);
          return pre.intersect(ray,k,v0,v1,v2,UVIdentity<Mx>(),Occluded1KEpilogM<M,Mx,K,filter>(ray,k,context,tri.geomIDs,tri.primIDs));
        }
      };
  }
}


text:
/*
  Web Component Mapper for issueForm.ejs
  This represents the issueForm, not an actual Issue
*/
var Status = require('../../database/status')
var Type = require('../../database/type')
var Severity = require('../../database/severity')
var User = require('../../database/user')
var Project = require('../../database/project')
// var Promise = require('bluebird')
var FormBase = require('./formBase.js')
var issueSearchForm = function (options) {
  var form = new FormBase(options, {
    text: {
      value: null,
      label: 'Text',
      inputType: FormBase.InputTypes.TextField,
      type: 'Text',
      required: false,
      minLength: 0,
      maxLength: 256
    },
    status: {
      value: null,
      label: 'Status',
      required: false,
      type: Status.getStatuses(),
      inputType: FormBase.InputTypes.DropDown
    },
    type: {
      value: null,
      label: 'Type',
      required: false,
      type: Type.getTypes(),
      inputType: FormBase.InputTypes.DropDown
    },
    severity: {
      value: null,
      label: 'Severity',
      required: false,
      type: Severity.getSeverities(),
      inputType: FormBase.InputTypes.DropDown
    },
    assignee: {
      value: null,
      label: 'Assignee',
      required: false,
      type: User.getAllUsers(),
      inputType: FormBase.InputTypes.DropDown
    },
    project: {
      value: null,
      label: 'Project',
      required: false,
      type: Project.getAllProjectPrefixes(),
      inputType: FormBase.InputTypes.DropDown
    }
  })
  return form
}
module.exports = issueSearchForm

redpajama_set_name: RedPajamaGithub


text:
/*jshint globalstrict:false, strict:false, maxlen:4000, unused:false */
/*global arango */

// /////////////////////////////////////////////////////////////////////////////
// @brief tests for dump/reload
//
// @file
//
// DISCLAIMER
//
// Copyright 2019 ArangoDB GmbH, Cologne, Germany
// Copyright 2010-2012 triagens GmbH, Cologne, Germany
//
// 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.
//
// Copyright holder is ArangoDB GmbH, Cologne, Germany
//
// @author Frank Celler
// /////////////////////////////////////////////////////////////////////////////

(function () {
  'use strict';
  var db = require("@arangodb").db;
  var i, c;

  try {
    db._dropDatabase("UnitTestsDumpSrc");
  } catch (err1) {
  }

  db._createDatabase("UnitTestsDumpSrc");
  db._useDatabase("UnitTestsDumpSrc");

  db._create("maskings1");

  db.maskings1.save({
    _key: "1",

    name: "Hallo World! This is a t0st a top-level",

    blub: {
      name: "Hallo World! This is a t0st in a sub-object",
    },

    email: [
      "testing arrays",
      "this is another one",
      { something: "something else" },
      { email: "within a subject" },
      { name: [ "emails within a subject", "as list" ] }
    ],

    sub: {
       name: "this is a name leaf attribute",
       email: [ "in this case as list", "with more than one entry" ]
    }
  });

  db._create("maskings2");

  db.maskings2.save({
    _key: "2",

    random: "a",
    zip: "12345",
    date: "2018-01-01",
    integer: 100,
    decimal: 100.12,
    ccard: "1234 1234 1234 1234",
    phone: "abcd 1234",
    email: "me@you.here"
  });
})();

return {
  status: true
};


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Rep. Tottori Mycol. Inst. 10: 177 (1973)

#### Original name
Prospodium vertiseptum J.F. Hennen & Cummins

### Remarks
null


text:
import React, {
  forwardRef,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useRef,
  useState,
} from 'react';
import { ThemeContext } from 'styled-components';
import { useLayoutEffect } from '../../utils/use-isomorphic-layout-effect';
import { defaultProps } from '../../default-props';
import { AnnounceContext } from '../../contexts/AnnounceContext';

import { Box } from '../Box';
import { Button } from '../Button';
import { Menu } from '../Menu';
import { Meter } from '../Meter';
import { Stack } from '../Stack';
import { Text } from '../Text';
import { Keyboard } from '../Keyboard';
import { containsFocus, useForwardedRef } from '../../utils';

import {
  StyledVideo,
  StyledVideoContainer,
  StyledVideoControls,
  StyledVideoScrubber,
} from './StyledVideo';
import { MessageContext } from '../../contexts/MessageContext';
import { VideoPropTypes } from './propTypes';

// Split the volume control into 6 segments. Empirically determined.
const VOLUME_STEP = 0.166667;

const formatTime = (time) => {
  let minutes = Math.round(time / 60);
  if (minutes < 10) {
    minutes = `0${minutes}`;
  }
  let seconds = Math.round(time) % 60;
  if (seconds < 10) {
    seconds = `0${seconds}`;
  }
  return `${minutes}:${seconds}`;
};

const Video = forwardRef(
  (
    {
      alignSelf,
      autoPlay,
      children,
      controls: controlsProp,
      gridArea,
      loop,
      margin,
      messages,
      mute,
      onDurationChange,
      onEnded,
      onPause,
      onPlay,
      onTimeUpdate,
      onVolumeChange,
      skipInterval,
      ...rest
    },
    ref,
  ) => {
    const theme = useContext(ThemeContext) || defaultProps.theme;
    const { format } = useContext(MessageContext);
    const announce = useContext(AnnounceContext);
    const [captions, setCaptions] = useState([]);
    const [currentTime, setCurrentTime] = useState();
    const [duration, setDuration] = useState();
    const [percentagePlayed, setPercentagePlayed] = useState();
    const [playing, setPlaying] = useState(false);
    const [announceAudioDescription, setAnnounceAudioDescription] =
      useState(false);
    const [scrubTime, setScrubTime] = useState();
    const [volume, setVolume] = useState();
    const [hasPlayed, setHasPlayed] = useState(false);
    const [interacting, setInteracting] = useState();
    const [height, setHeight] = useState();
    const [width, setWidth] = useState();
    const containerRef = useRef();
    const scrubberRef = useRef();
    const videoRef = useForwardedRef(ref);
    const controls = useMemo(() => {
      let result;
      if (
        typeof controlsProp === 'string' ||
        typeof controlsProp === 'boolean'
      ) {
        result = {
          items: ['volume', 'fullScreen'],
          position: controlsProp,
        };
      } else {
        result = {
          items: controlsProp?.items || ['volume', 'fullScreen'],
          position: controlsProp?.position || 'over',
        };
      }
      return result;
    }, [controlsProp]);

    // mute if needed
    useEffect(() => {
      const video = videoRef.current;
      if (video && mute) video.muted = true;
    }, [mute, videoRef]);

    // when the video is first rendered, set state from it where needed
    useEffect(() => {
      const video = videoRef.current;
      if (video) {
        // hide all captioning to start with
        const { textTracks } = video;
        for (let i = 0; i < textTracks.length; i += 1) {
          textTracks[i].mode = 'hidden';
        }

        setCurrentTime(video.currentTime);
        setPercentagePlayed((video.currentTime / video.duration) * 100);
        setVolume(videoRef.current.volume);
      }
    }, [videoRef]);

    // turn off interacting after a while
    useEffect(() => {
      const timer = setTimeout(() => {
        if (interacting && !containsFocus(containerRef.current)) {
          setInteracting(false);
        }
      }, 3000);
      return () => clearTimeout(timer);
    }, [interacting]);

    // track which audio description track is active
    const [activeTrack, setActiveTrack] = useState();

    useLayoutEffect(() => {
      const video = videoRef.current;
      if (video) {
        if (video.videoHeight) {
          // set the size based on the video aspect ratio
          const rect = video.getBoundingClientRect();
          const ratio = rect.width / rect.height;
          const videoRatio = video.videoWidth / video.videoHeight;
          if (videoRatio > ratio) {
            const nextHeight = rect.width / videoRatio;
            if (nextHeight !== height) {
              setHeight(nextHeight);
              setWidth(undefined);
            }
          } else {
            const nextWidth = rect.height * videoRatio;
            if (nextWidth !== width) {
              setHeight(undefined);
              setWidth(nextWidth);
            }
          }
        }

        // remember the state of the text tracks for subsequent rendering
        const { textTracks } = video;
        const nextCaptions = [];
        let set = false;
        // iterate through all of the tracks provided
        for (let i = 0; i < textTracks.length; i += 1) {
          const track = textTracks[i];
          const active = track.mode === 'showing';

          const getActiveTrack = (currentVideoTime) => {
            let nextActiveTrack;
            for (let j = 0; j < track.cues.length; j += 1) {
              if (
                currentVideoTime > track?.cues[j]?.startTime &&
                currentVideoTime < track?.cues[j]?.endTime
              ) {
                nextActiveTrack = track?.cues[j]?.text;
              }
            }

            return nextActiveTrack;
          };

          // track is an audio description
          if (track.kind === 'descriptions') {
            if (announceAudioDescription) {
              video.ontimeupdate = () => {
                const nextActiveTrack = getActiveTrack(video.currentTime);
                if (activeTrack !== nextActiveTrack) {
                  if (nextActiveTrack) {
                    announce(nextActiveTrack, 'assertive');
                  }
                  setActiveTrack(nextActiveTrack);
                }
              };
            }
          }

          // otherwise treat as captions
          else {
            nextCaptions.push({ label: track.label, active });
            if (!captions || !captions[i] || captions[i].active !== active) {
              set = true;
            }
            if (set) {
              setCaptions(nextCaptions);
            }
          }
        }
      }
    }, [
      activeTrack,
      announce,
      announceAudioDescription,
      captions,
      height,
      videoRef,
      width,
    ]);

    const play = useCallback(() => videoRef.current.play(), [videoRef]);

    const pause = useCallback(() => videoRef.current.pause(), [videoRef]);

    const scrub = useCallback(
      (event) => {
        if (scrubberRef.current) {
          const scrubberRect = scrubberRef.current.getBoundingClientRect();
          const percent =
            (event.clientX - scrubberRect.left) / scrubberRect.width;
          setScrubTime(duration * percent);
        }
      },
      [duration],
    );

    const seek = useCallback(
      (event) => {
        if (scrubberRef.current) {
          const scrubberRect = scrubberRef.current.getBoundingClientRect();
          const percent =
            (event.clientX - scrubberRect.left) / scrubberRect.width;
          if (duration) videoRef.current.currentTime = duration * percent;
        }
      },
      [duration, videoRef],
    );

    const seekForward = useCallback(() => {
      setInteracting(true);
      videoRef.current.currentTime +=
        skipInterval || theme.video.scrubber.interval;
    }, [skipInterval, theme.video.scrubber.interval, videoRef]);

    const seekBackward = useCallback(() => {
      setInteracting(true);
      videoRef.current.currentTime -=
        skipInterval || theme.video.scrubber.interval;
    }, [skipInterval, theme.video.scrubber.interval, videoRef]);

    const louder = useCallback(() => {
      videoRef.current.volume += VOLUME_STEP;
    }, [videoRef]);

    const quieter = useCallback(() => {
      videoRef.current.volume -= VOLUME_STEP;
    }, [videoRef]);

    const showCaptions = useCallback(
      (index) => {
        const { textTracks } = videoRef.current;
        for (let i = 0; i < textTracks.length; i += 1)
          textTracks[i].mode = i === index ? 'showing' : 'hidden';
      },
      [videoRef],
    );

    const fullscreen = useCallback(() => {
      const video = videoRef.current;
      if (video.requestFullscreen) {
        video.requestFullscreen();
      } else if (video.msRequestFullscreen) {
        video.msRequestFullscreen();
      } else if (video.mozRequestFullScreen) {
        video.mozRequestFullScreen();
      } else if (video.webkitRequestFullscreen) {
        video.webkitRequestFullscreen();
      } else {
        console.warn("This browser doesn't support fullscreen.");
      }
    }, [videoRef]);

    let controlsElement;
    if (controls?.position) {
      const over = controls.position === 'over';
      const background = over
        ? (theme.video.controls && theme.video.controls.background) || {
            color: 'background-back',
            opacity: 'strong',
            dark: true,
          }
        : undefined;
      const iconColor = over && (theme.video.icons.color || 'text');

      const formattedTime = formatTime(scrubTime || currentTime || duration);

      const Icons = {
        ClosedCaption: theme.video.icons.closedCaption,
        Configure: theme.video.icons.configure,
        FullScreen: theme.video.icons.fullScreen,
        Pause: theme.video.icons.pause,
        Play: theme.video.icons.play,
        ReduceVolume: theme.video.icons.reduceVolume,
        Volume: theme.video.icons.volume,
        Description: theme.video.icons.description,
      };

      const captionControls = captions.map((caption, index) => ({
        icon: caption.label ? undefined : (
          <Icons.ClosedCaption color={iconColor} />
        ),
        label: caption.label,
        active: caption.active,
        a11yTitle:
          caption.label ||
          format({
            id: 'video.captions',
            messages,
          }),
        onClick: () => {
          showCaptions(caption.active ? -1 : index);
          const updatedCaptions = [];
          for (let i = 0; i < captions.length; i += 1) {
            updatedCaptions.push(captions[i]);
            // set other captions to active=false
            if (i !== index && updatedCaptions[i].active)
              updatedCaptions[i].active = false;
            // set the currently selected captions to active
            else if (i === index)
              updatedCaptions[i].active = !captions[index].active;
          }
          setCaptions(updatedCaptions);
        },
      }));

      const descriptionControls = {
        icon: <Icons.Description color={iconColor} />,
        a11yTitle: format({
          id: 'video.audioDescriptions',
          messages,
        }),
        active: announceAudioDescription,
        onClick: () => setAnnounceAudioDescription(!announceAudioDescription),
      };

      const volumeControls = ['volume', 'reduceVolume'].map((control) => ({
        icon:
          control === 'volume' ? (
            <Icons.Volume color={iconColor} />
          ) : (
            <Icons.ReduceVolume color={iconColor} />
          ),
        a11yTitle: format({
          id: control === 'volume' ? 'video.volumeUp' : 'video.volumeDown',
          messages,
        }),
        onClick: () => {
          if (volume <= 1 - VOLUME_STEP && control === 'volume') {
            return louder();
          }
          if (volume >= VOLUME_STEP && control === 'reduceVolume') {
            return quieter();
          }
          return undefined;
        },
        close: false,
      }));

      const buttonProps = {
        captions: captionControls,
        descriptions: descriptionControls,
        volume: volumeControls,
        fullScreen: {
          icon: <Icons.FullScreen color={iconColor} />,
          a11yTitle: format({
            id: 'video.fullScreen',
            messages,
          }),
          onClick: fullscreen,
        },
        pause: {
          icon: <Icons.Pause color={iconColor} />,
          a11yTitle: format({
            id: 'video.pauseButton',
            messages,
          }),
          disabled: !playing,
          onClick: pause,
        },
        play: {
          icon: <Icons.Play color={iconColor} />,
          a11yTitle: format({
            id: 'video.playButton',
            messages,
          }),
          disabled: playing,
          onClick: play,
        },
      };

      const controlsMenuItems = [];

      controls.items?.map((item) => {
        if (item === 'volume') {
          volumeControls.map((control) => controlsMenuItems.push(control));
          return undefined;
        }
        if (item === 'captions' && typeof buttonProps[item] === 'object') {
          for (let i = 0; i < buttonProps[item].length; i += 1)
            controlsMenuItems.push(buttonProps[item][i]);
          return undefined;
        }
        if (item === 'descriptions') {
          controlsMenuItems.push(buttonProps[item]);
          return undefined;
        }
        if (typeof item === 'string') {
          return controlsMenuItems.push(buttonProps[item]);
        }
        return controlsMenuItems.push(item);
      });

      controlsElement = (
        <StyledVideoControls
          over={over}
          active={
            !hasPlayed || controls.position === 'below' || (over && interacting)
          }
          onBlur={() => {
            if (!containsFocus(containerRef.current)) setInteracting(false);
          }}
        >
          <Box
            direction="row"
            align="center"
            justify="between"
            background={background}
          >
            <Button
              icon={
                playing ? (
                  <Icons.Pause
                    color={iconColor}
                    a11yTitle={format({
                      id: 'video.pauseButton',
                      messages,
                    })}
                  />
                ) : (
                  <Icons.Play
                    color={iconColor}
                    a11yTitle={format({
                      id: 'video.playButton',
                      messages,
                    })}
                  />
                )
              }
              hoverIndicator="background"
              onClick={playing ? pause : play}
              onFocus={() => setInteracting(true)}
            />
            <Box direction="row" align="center" flex>
              <Box flex>
                <Stack>
                  <Meter
                    aria-label={format({
                      id: 'video.progressMeter',
                      messages,
                    })}
                    background={
                      over
                        ? (theme.video.scrubber &&
                            theme.video.scrubber.track &&
                            theme.video.scrubber.track.color) ||
                          'dark-3'
                        : undefined
                    }
                    size="full"
                    thickness="small"
                    values={[{ value: percentagePlayed || 0 }]}
                  />
                  <StyledVideoScrubber
                    aria-label={format({
                      id: 'video.scrubber',
                      messages,
                    })}
                    ref={scrubberRef}
                    tabIndex={0}
                    role="button"
                    value={
                      scrubTime
                        ? Math.round((scrubTime / duration) * 100)
                        : undefined
                    }
                    onMouseMove={scrub}
                    onMouseLeave={() => setScrubTime(undefined)}
                    onClick={seek}
                    onFocus={() => setInteracting(true)}
                  />
                </Stack>
              </Box>
              <Box pad={{ horizontal: 'small' }}>
                <Text margin="none">{formattedTime}</Text>
              </Box>
            </Box>
            <Menu
              icon={<Icons.Configure color={iconColor} />}
              dropAlign={{ bottom: 'top', right: 'right' }}
              dropBackground={background}
              messages={{
                openMenu: format({ id: 'video.openMenu', messages }),
                closeMenu: format({ id: 'video.closeMenu', messages }),
              }}
              items={[...controlsMenuItems]}
              onFocus={() => setInteracting(true)}
            />
          </Box>
        </StyledVideoControls>
      );
    }

    let mouseEventListeners;
    if (controls?.position === 'over') {
      mouseEventListeners = {
        onMouseEnter: () => setInteracting(true),
        onMouseMove: () => setInteracting(true),
        onTouchStart: () => setInteracting(true),
      };
    }

    let style;
    if (rest.fit === 'contain' && controls?.position === 'over') {
      // constrain the size to fit the aspect ratio so the controls
      // overlap correctly
      if (width) {
        style = { width };
      } else if (height) {
        style = { height };
      }
    }

    return (
      <Keyboard onLeft={seekBackward} onRight={seekForward}>
        <StyledVideoContainer
          ref={containerRef}
          {...mouseEventListeners}
          alignSelf={alignSelf}
          gridArea={gridArea}
          margin={margin}
          style={style}
          tabIndex="-1"
        >
          <StyledVideo
            {...rest}
            ref={videoRef}
            onDurationChange={(event) => {
              const video = videoRef.current;
              setDuration(video.duration);
              setPercentagePlayed((video.currentTime / video.duration) * 100);
              if (onDurationChange) onDurationChange(event);
            }}
            onEnded={(event) => {
              setPlaying(false);
              if (onEnded) onEnded(event);
            }}
            onPause={(event) => {
              setPlaying(false);
              if (onPause) onPause(event);
            }}
            onPlay={(event) => {
              setPlaying(true);
              setHasPlayed(true);
              if (onPlay) onPlay(event);
            }}
            onTimeUpdate={(event) => {
              const video = videoRef.current;
              setCurrentTime(video.currentTime);
              setPercentagePlayed((video.currentTime / video.duration) * 100);
              if (onTimeUpdate) onTimeUpdate(event);
            }}
            onVolumeChange={(event) => {
              setVolume(videoRef.current.volume);
              if (onVolumeChange) onVolumeChange(event);
            }}
            autoPlay={autoPlay || false}
            loop={loop || false}
          >
            {children}
          </StyledVideo>
          {controlsElement}
        </StyledVideoContainer>
      </Keyboard>
    );
  },
);

Video.defaultProps = {};

Video.displayName = 'Video';
Video.propTypes = VideoPropTypes;

export { Video };


text:
<?xml version="1.0" encoding="UTF-8"?><templates><template autoinsert="true" context="java" deleted="false" description="Test data interface" enabled="true" name="td">    /**
	 *
	 * @author ${user}
	 */
	public interface TD
	{

	}</template></templates>


text:
package com.linkedin.thirdeye.anomaly.alert.grouping;

import com.linkedin.thirdeye.api.DimensionMap;
import org.testng.Assert;
import org.testng.annotations.Test;

public class AlertGroupKeyTest {
  @Test
  public void testEqualsEmptyKey() {
    AlertGroupKey<DimensionMap> alertGroupKey = AlertGroupKey.emptyKey();
    Assert.assertEquals(alertGroupKey.getKey(), null);
    Assert.assertEquals(alertGroupKey, AlertGroupKey.emptyKey());
  }

  @Test
  public void testEqualsDimensionKey() {
    DimensionMap dimensionMap1 = new DimensionMap();
    dimensionMap1.put("D1", "V1");
    AlertGroupKey<DimensionMap> alertGroupKey1 = new AlertGroupKey<>(dimensionMap1);

    DimensionMap dimensionMap2 = new DimensionMap();
    dimensionMap2.put("D1", "V1");
    AlertGroupKey<DimensionMap> alertGroupKey2 = new AlertGroupKey<>(dimensionMap2);

    Assert.assertEquals(alertGroupKey1, alertGroupKey2);
  }
}


text:
package fi.cosky.sdk;
import java.util.Date;

/*
 * This file is subject to the terms and conditions defined in
 * file 'LICENSE.txt', which is part of this source code package.
 */

public class TimeWindowData extends BaseData {
    private Date Start;
    private Date End;

    public TimeWindowData(Date start, Date end) {
        this.Start = start;
        this.End = end;
    }

    public static TimeWindowData newTimeWindowDto() {
        Date d = new Date();
        return new TimeWindowData(d, new Date(d.getTime() +10000 ));
    }

    public Date getEnd() {
        return End;
    }

    public void setEnd(Date end) {
        End = end;
    }

    public Date getStart() {
        return Start;
    }

    public void setStart(Date start) {
        Start = start;
    }
}


text:
require 'rails_helper'

describe ApplicationHelper, type: :helper do
  describe '#active_tab' do
    context 'when the passed path include the request path' do
      let(:request) { double(:request, path: '/resources/main') }

      it "returns 'active'" do
        allow(helper).to receive(:request).and_return(request)

        expect(helper.active_tab('/resources/main')).to eq 'active'
      end
    end

    context 'when the passed path does not includes the request path' do
      let(:request) { double(:request, path: '/resources/main') }

      it "returns ''" do
        allow(helper).to receive(:request).and_return(request)

        expect(helper.active_tab('/resources/show')).to eq ''
      end
    end
  end

  describe '#doc_email' do
    context 'when the doc has many emails' do
      let(:doc) { double(:doc, emails: emails) }

      context 'when one email is marked as primary' do
        let(:emails) do
          [
            {'type' => 'primary', 'email' => 'primary@email.com'},
            {'type' => 'secundary', 'email' => 'secundary@email.com'}
          ]
        end

        it 'returns the primary email address' do
          expect(helper.doc_email(doc)).to eq 'primary@email.com'
        end
      end

      context 'when there is no email marked as primary' do
        let(:emails) do
          [
            {'type' => 'secundary', 'email' => 'secundary@email.com'},
            {'type' => 'third', 'email' => 'primary@email.com'}
          ]
        end

        it 'returns the first email address' do
          expect(helper.doc_email(doc)).to eq 'secundary@email.com'
        end
      end
    end

    context "when the doc hasn't many emails" do
      let(:doc) { double(:doc, emails: nil, email: 'email@email.com') }

      it 'returns the only email address' do
        expect(helper.doc_email(doc)).to eq 'email@email.com'
      end
    end
  end

  describe '#doc_type' do
    context "when doc hasn't profile" do
      let(:doc) { double(:doc, profile: nil) }

      it "returns '(unknown)'" do
        expect(helper.doc_type(doc)).to eq '(unknown)'
      end
    end

    context 'when doc has profile' do
      let(:doc) { double(:doc, profile: [profile]) }

      context "when profile's href matches the pattern" do
        let(:profile) { double(:doc, href: '/resources/main') }

        it "returns the last string splited by '/'" do
          expect(helper.doc_type(doc)).to eq 'main'
        end
      end

      context "when profile's href  doesn't matches the pattern" do
        let(:profile) { double(:doc, href: '') }

        it "returns '(unknown)'" do
          expect(helper.doc_type(doc)).to eq '(unknown)'
        end
      end
    end
  end

  describe 'format_time' do
    context 'parsing a DateTime' do
      it 'returns a string specifying how much time passed' do
        expect(helper.format_time(DateTime.current - 1.day)).to eq '1 day ago'
      end
    end

    context 'parsing a object different from a DateTime' do
      it "returns '(unknown)'" do
        expect(helper.format_time('Some string')).to eq '(unknown)'
      end
    end
  end
end


text:
package org.openapitools.api;

import org.openapitools.api.*;
import org.openapitools.model.*;

import org.openapitools.model.Queue;

import java.util.List;
import org.openapitools.api.NotFoundException;

import java.io.InputStream;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;

@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaResteasyServerCodegen", date = "2022-06-04T08:09:04.819692Z[Etc/UTC]")
public interface QueueApiService {
      Response getQueue(SecurityContext securityContext)
      throws NotFoundException;
      Response getQueueItem(String number,SecurityContext securityContext)
      throws NotFoundException;
}


text:
using System;
using System.ComponentModel;
using System.Diagnostics;

namespace Hawk.Core.Utils.MVVM
{
    public class PropertyChangeNotifier : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public virtual void OnPropertyChanged(string propName)
        {

            //this.VerifyPropertyName(propName);
            if (null != PropertyChanged)
            {
                ControlExtended.UIInvoke(() => PropertyChanged(this, new PropertyChangedEventArgs(propName)));

            }
        }

        /// <summary>
        /// Returns whether an exception is thrown, or if a Debug.Fail() is used
        /// when an invalid property name is passed to the VerifyPropertyName method.
        /// The default value is false, but subclasses used by unit tests might
        /// override this property's getter to return true.
        /// </summary>
        protected virtual bool ThrowOnInvalidPropertyName { get; set; }

        public void InformPropertyChanged(string propName)
        {
            OnPropertyChanged(propName);
        }
        /// <summary>
        /// Warns the developer if this object does not have
        /// a public property with the specified name. This
        /// method does not exist in a Release build.
        /// </summary>
        [Conditional("DEBUG")]
        [DebuggerStepThrough]
        public void VerifyPropertyName(string propertyName)
        {
            // Verify that the property name matches a real,
            // public, instance property on this object.
            if (TypeDescriptor.GetProperties(this)[propertyName] == null)
            {
                string msg = "Invalid property name: " + propertyName;

                if (this.ThrowOnInvalidPropertyName)
                    throw new Exception(msg);
                else
                    System.Diagnostics.Debug.Fail(msg);
            }
        }
    }
}


text:
<?php

namespace WordPressBundle\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 *
 * @ApiResource(attributes={
        "filters"={
            "term_relationship.search"
        }
    }
)
 * @ORM\Entity
 * @ORM\Table(name="wp_term_relationships", indexes={@ORM\Index(name="term_taxonomy_id", columns={"term_taxonomy_id"})})
 */
class TermRelationship
{

    /**
     * @var integer
     *
     * @ORM\Column(name="term_taxonomy_id", type="bigint", options={"unsigned"=true})
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     */
    protected $termTaxonomyId;

    /**
     * @var integer
     *
     * @ORM\Column(name="term_order", type="integer", nullable=false)
     */
    protected $termOrder = '0';

    /**
     * @var integer
     *
     * @ORM\Column(name="object_id", type="bigint", options={"unsigned"=true})
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     */
    protected $objectId;

    /**
     * Set termOrder
     *
     * @param integer $termOrder
     *
     * @return TermRelationship
     */
    public function setTermOrder($termOrder)
    {
        $this->termOrder = $termOrder;

        return $this;
    }

    /**
     * Get termOrder
     *
     * @return integer
     */
    public function getTermOrder()
    {
        return $this->termOrder;
    }

    /**
     * Set objectId
     *
     * @param integer $objectId
     *
     * @return TermRelationship
     */
    public function setObjectId($objectId)
    {
        $this->objectId = $objectId;

        return $this;
    }

    /**
     * Get objectId
     *
     * @return integer
     */
    public function getObjectId()
    {
        return $this->objectId;
    }

    /**
     * Set termTaxonomyId
     *
     * @param integer $termTaxonomyId
     *
     * @return TermRelationship
     */
    public function setTermTaxonomyId($termTaxonomyId)
    {
        $this->termTaxonomyId = $termTaxonomyId;

        return $this;
    }

    /**
     * Get termTaxonomyId
     *
     * @return integer
     */
    public function getTermTaxonomyId()
    {
        return $this->termTaxonomyId;
    }
}


text:
/*
** NOTE: This file is generated by Gulp and should not be edited directly!
** Any changes made directly to this file will be overwritten next time its asset group is processed by Gulp.
*/

/* http://keith-wood.name/calendars.html
   Khmer initialisation for calendars datepicker for jQuery.
   Written by Sovichet Tep (sovichet.tep@gmail.com). */
(function ($) {
    $.calendarsPicker.regionalOptions['km'] = {
        renderer: $.calendarsPicker.defaultRenderer,
        prevText: 'ថយក្រោយ', prevStatus: '',
        prevJumpText: '<<', prevJumpStatus: '',
        nextText: 'ទៅមុខ', nextStatus: '',
        nextJumpText: '>>', nextJumpStatus: '',
        currentText: 'ថ្ងៃនេះ', currentStatus: '',
        todayText: 'ថ្ងៃនេះ', todayStatus: '',
        clearText: 'X', clearStatus: '',
        closeText: 'រួចរាល់', closeStatus: '',
        yearStatus: '', monthStatus: '',
        weekText: 'Wk', weekStatus: '',
        dayStatus: 'DD d MM', defaultStatus: '',
        isRTL: false
    };
    $.calendarsPicker.setDefaults($.calendarsPicker.regionalOptions['km']);
})(jQuery);


text:
package com.ligati.apipixie.http;

import com.ligati.apipixie.exception.APIHTTPException;
import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.Charset;

public class APIHttpUtil {
	private static final Logger logger = Logger.getLogger(APIHttpUtil.class);

	public static <T> T performGet(Class<T> clazz, String url, Header... headers) {
		HttpGet get = new HttpGet(url);
		return performRequest(get, clazz, headers);
	}

	public static <T> T performPut(Class<T> clazz, String url, JSONObject json, Header... headers) {
		HttpPut put = new HttpPut(url);
		put.setEntity(new StringEntity(json.toString(), Charset.forName("UTF-8")));
		put.setHeader("Content-Type", "application/json");
		return performRequest(put, clazz, headers);
	}

	public static <T> T performPost(Class<T> clazz, String url, JSONObject json, Header... headers) {
		HttpPost post = new HttpPost(url);
		post.setEntity(new StringEntity(json.toString(), Charset.forName("UTF-8")));
		post.setHeader("Content-Type", "application/json");
		return performRequest(post, clazz, headers);
	}

	public static <T> T performDelete(String url, Header... headers) {
		HttpDelete delete = new HttpDelete(url);
		return performRequest(delete, null, headers);
	}

	private static <T> T performRequest(HttpUriRequest req, Class<T> clazz, Header... headers) {
		try {
			DefaultHttpClient client = new DefaultHttpClient();
			addHeaders(req, headers);
			HttpResponse res = client.execute(req);
			analyzeStatusCode(res, req);
			// case of DELETE for 204 http status codes
			if (clazz == null)
				return null;
			InputStream stream = res.getEntity().getContent();
			String jsonStr = IOUtils.toString(stream);
			logger.debug("String received from the API: " + jsonStr);
			return clazz.getConstructor(String.class).newInstance(jsonStr);
		} catch (IOException | NoSuchMethodException | InstantiationException
				| IllegalAccessException | IllegalArgumentException
				| InvocationTargetException | SecurityException e) {
			if (logger.isDebugEnabled())
				e.printStackTrace();
			throw new APIHTTPException("An unexpected exception occurred while performing a request.", e);
		}
	}

	private static void addHeaders(HttpUriRequest req, Header... headers) {
		if (headers != null)
			for (Header header : headers)
				req.addHeader(header);
	}

	private static void analyzeStatusCode(HttpResponse res, HttpUriRequest req) {
		String url = req.getURI().toString();
		int statusCode = res.getStatusLine().getStatusCode();
		logger.debug("Status code received from the API: " + statusCode);
		if (100 <= statusCode && statusCode < 200) {
			// TODO do something?
		} else if (300 <= statusCode && statusCode < 400) {
			// TODO do something?
		} else if (400 <= statusCode) {
			String content = null;
			try {
				content = IOUtils.toString(res.getEntity().getContent());
			} catch (Exception e) {
			}
			throw new APIHTTPException(statusCode, res.getStatusLine()
					.getReasonPhrase(), content, url, req);
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">MediaStore_</string>
    <string name="hello_world">Hello world!</string>

</resources>


text:
package org.apache.nifi.components.validation;

import java.util.Collection;

import org.apache.nifi.components.ValidationResult;

public class ValidationState {
    private final ValidationStatus status;
    private final Collection<ValidationResult> validationErrors;

    public ValidationState(final ValidationStatus status, final Collection<ValidationResult> validationErrors) {
        this.status = status;
        this.validationErrors = validationErrors;
    }

    public ValidationStatus getStatus() {
        return status;
    }

    public Collection<ValidationResult> getValidationErrors() {
        return validationErrors;
    }

    public String toString() {
        return status.toString();
    }
}


text:
package com.jeequan.jeepay.pay.exception;

import com.jeequan.jeepay.pay.rqrs.msg.ChannelRetMsg;
import lombok.Getter;

/*
* 请求渠道侧异常 exception
* 抛出此异常: 仅支持:  未知状态(需查单) 和 系统内异常
*
* @author terrfly
* @site https://www.jeequan.com
* @date 2021/6/8 17:28
*/
@Getter
public class ChannelException extends RuntimeException{

	private static final long serialVersionUID = 1L;

	private ChannelRetMsg channelRetMsg;

	/** 业务自定义异常 **/
	private ChannelException(ChannelRetMsg channelRetMsg) {
		super(channelRetMsg != null ? channelRetMsg.getChannelErrMsg() : null);
		this.channelRetMsg = channelRetMsg;
	}

	/** 未知状态 **/
	public static ChannelException unknown(String channelErrMsg){
		return new ChannelException(ChannelRetMsg.unknown(channelErrMsg));
	}

	/** 系统内异常 **/
	public static ChannelException sysError(String channelErrMsg){
		return new ChannelException(ChannelRetMsg.sysError(channelErrMsg));
	}

}


text:
package cgo

import (
	"testing"

	"github.com/gonum/lapack/testlapack"
)

var impl = Implementation{}

func TestDpotrf(t *testing.T) {
	testlapack.DpotrfTest(t, impl)
}


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.ProviderHub.Models
{
    public partial class CustomRolloutSpecificationCanary : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsCollectionDefined(Regions))
            {
                writer.WritePropertyName("regions");
                writer.WriteStartArray();
                foreach (var item in Regions)
                {
                    writer.WriteStringValue(item);
                }
                writer.WriteEndArray();
            }
            writer.WriteEndObject();
        }

        internal static CustomRolloutSpecificationCanary DeserializeCustomRolloutSpecificationCanary(JsonElement element)
        {
            Optional<IList<string>> regions = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("regions"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<string> array = new List<string>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(item.GetString());
                    }
                    regions = array;
                    continue;
                }
            }
            return new CustomRolloutSpecificationCanary(Optional.ToList(regions));
        }
    }
}


text:
using System.Collections.Generic;

namespace Remotus.Web.Models
{
    public class MenuListViewModel
    {
        public ProfileItemViewModel Profile { get; set; }
        public IList<MenuListGroup> Groups { get; set; }
    }

    public class MenuListGroup
    {
        public IList<MenuListGroupItem> Items { get; set; }
        public string Text { get; set; }
    }

    public class MenuListGroupItem
    {
        public string Text { get; set; }
        public string Href { get; set; }
        public string ImgSrc { get; set; }
        public string Glyphicon { get; set; }
        public bool Disabled { get; set; }
        public bool Hidden { get; set; }
        public int BadgeCount { get; set; }
    }
}


text:
package compare

import (
	"bytes"
	"fmt"
	"time"

	"github.com/golang/protobuf/jsonpb"
	"github.com/pmezard/go-difflib/difflib"
)

// RouteDiff prints a diff between Pilot and Envoy routes to the passed writer
func (c *Comparator) RouteDiff() error {
	jsonm := &jsonpb.Marshaler{Indent: "   "}
	envoyBytes, pilotBytes := &bytes.Buffer{}, &bytes.Buffer{}
	envoyRouteDump, err := c.envoy.GetDynamicRouteDump(true)
	if err != nil {
		envoyBytes.WriteString(err.Error())
	} else if err := jsonm.Marshal(envoyBytes, envoyRouteDump); err != nil {
		return err
	}
	pilotRouteDump, err := c.pilot.GetDynamicRouteDump(true)
	if err != nil {
		pilotBytes.WriteString(err.Error())
	} else if err := jsonm.Marshal(pilotBytes, pilotRouteDump); err != nil {
		return err
	}
	diff := difflib.UnifiedDiff{
		FromFile: "Pilot Routes",
		A:        difflib.SplitLines(pilotBytes.String()),
		ToFile:   "Envoy Routes",
		B:        difflib.SplitLines(envoyBytes.String()),
		Context:  c.context,
	}
	text, err := difflib.GetUnifiedDiffString(diff)
	if err != nil {
		return err
	}
	lastUpdatedStr := ""
	if lastUpdated, err := c.envoy.GetLastUpdatedDynamicRouteTime(); err != nil {
		return err
	} else if lastUpdated != nil {
		loc, err := time.LoadLocation(c.location)
		if err != nil {
			loc, _ = time.LoadLocation("UTC")
		}
		lastUpdatedStr = fmt.Sprintf(" (RDS last loaded at %s)", lastUpdated.In(loc).Format(time.RFC1123))
	}
	if text != "" {
		fmt.Fprintln(c.w, fmt.Sprintf("Routes Don't Match%s", lastUpdatedStr))
		fmt.Fprintln(c.w, text)
	} else {
		fmt.Fprintln(c.w, fmt.Sprintf("Routes Match%s", lastUpdatedStr))
	}
	return nil
}


text:
namespace Evol.Test.Models
{
    public class FakeArticle : BaseEntity
    {
        public string Title { get; set; }

        public string Tag { get; set; }

        public string Content { get; set; }

        public string Author { get; set; }
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>cern.enice.jira.amh</groupId>
	<artifactId>elasticsearch-client</artifactId>
	<version>0.1.0</version>
	<packaging>bundle</packaging>
	<name>Elastic Search Client</name>
	<url>http://cern.ch</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.osgi</groupId>
			<artifactId>org.osgi.compendium</artifactId>
			<version>5.0.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.felix</groupId>
			<artifactId>org.apache.felix.framework</artifactId>
			<version>4.2.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.felix</groupId>
			<artifactId>org.apache.felix.dependencymanager</artifactId>
			<version>3.1.0</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.7.6</version>
		</dependency>
		<dependency>
			<groupId>cern.enice.jira.amh</groupId>
			<artifactId>api</artifactId>
			<version>0.1.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.servicemix.bundles</groupId>
			<artifactId>org.apache.servicemix.bundles.elasticsearch</artifactId>
			<version>1.4.1_1</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.1.3</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.felix</groupId>
				<artifactId>maven-bundle-plugin</artifactId>
				<version>2.3.7</version>
				<extensions>true</extensions>
				<configuration>
					<instructions>
						<Export-Package></Export-Package>
						<Bundle-Activator>cern.enice.jira.amh.elasticsearch.Activator</Bundle-Activator>
						<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
						<Bundle-Name>${project.name}</Bundle-Name>
						<Bundle-Description>${project.description}</Bundle-Description>
						<Bundle-Category>JIRA Advanced Mail Handler</Bundle-Category>
					</instructions>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<description>Elastic Search Client</description>
</project>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

   <TITLE>EXPORT_SPEC IXML_Element* ixmlDocument_getElementById</TITLE>
   <META NAME="GENERATOR" CONTENT="DOC++ 3.4.10">

EXPORT_SPEC IXML_Element* ixmlDocument_getElementById

(IXML_Document* doc,
   DOMString tagName )

Returns the Element whose <TT>ID</TT> matches that given id.

Documentation

Returns the Element whose <TT>ID</TT> matches that given id.

Parameters:
doc -   The owner Document of the
Element.

tagName -   The name of the Element.

Returns:
  [Element*] A pointer to the matching Element or
<TT>NULL</TT> on an error.

Alphabetic index

This page was generated with the help of DOC++.


text:
<?php
/**
 * A simple set of functions to check our version 1.0 update service.
 *
 * @package WordPress
 * @since 2.3.0
 */

/**
 * Check WordPress version against the newest version.
 *
 * The WordPress version, PHP version, and Locale is sent. Checks against the
 * WordPress server at api.wordpress.org server. Will only check if WordPress
 * isn't installing.
 *
 * @package WordPress
 * @since 2.3.0
 * @uses $wp_version Used to check against the newest WordPress version.
 *
 * @return mixed Returns null if update is unsupported. Returns false if check is too soon.
 */
function wp_version_check() {
	if ( defined('WP_INSTALLING') )
		return;

	global $wpdb, $wp_local_package;
	include ABSPATH . WPINC . '/version.php'; // include an unmodified $wp_version
	$php_version = phpversion();

	$current = get_site_transient( 'update_core' );
	if ( ! is_object($current) ) {
		$current = new stdClass;
		$current->updates = array();
		$current->version_checked = $wp_version;
	}

	$locale = apply_filters( 'core_version_check_locale', get_locale() );

	// Update last_checked for current to prevent multiple blocking requests if request hangs
	$current->last_checked = time();
	set_site_transient( 'update_core', $current );

	if ( method_exists( $wpdb, 'db_version' ) )
		$mysql_version = preg_replace('/[^0-9.].*/', '', $wpdb->db_version());
	else
		$mysql_version = 'N/A';

	if ( is_multisite( ) ) {
		$user_count = get_user_count( );
		$num_blogs = get_blog_count( );
		$wp_install = network_site_url( );
		$multisite_enabled = 1;
	} else {
		$user_count = count_users( );
		$multisite_enabled = 0;
		$num_blogs = 1;
		$wp_install = home_url( '/' );
	}

	$local_package = isset( $wp_local_package )? $wp_local_package : '';
	$url = "http://api.wordpress.org/core/version-check/1.6/?version=$wp_version&php=$php_version&locale=$locale&mysql=$mysql_version&local_package=$local_package&blogs=$num_blogs&users={$user_count['total_users']}&multisite_enabled=$multisite_enabled";

	$options = array(
		'timeout' => ( ( defined('DOING_CRON') && DOING_CRON ) ? 30 : 3 ),
		'user-agent' => 'WordPress/' . $wp_version . '; ' . home_url( '/' ),
		'headers' => array(
			'wp_install' => $wp_install,
			'wp_blog' => home_url( '/' )
		)
	);

	$response = wp_remote_get($url, $options);

	if ( is_wp_error( $response ) || 200 != wp_remote_retrieve_response_code( $response ) )
		return false;

	$body = trim( wp_remote_retrieve_body( $response ) );
	if ( ! $body = maybe_unserialize( $body ) )
		return false;
	if ( ! isset( $body['offers'] ) )
		return false;
	$offers = $body['offers'];

	foreach ( $offers as &$offer ) {
		foreach ( $offer as $offer_key => $value ) {
			if ( 'packages' == $offer_key )
				$offer['packages'] = (object) array_intersect_key( array_map( 'esc_url', $offer['packages'] ),
					array_fill_keys( array( 'full', 'no_content', 'new_bundled', 'partial' ), '' ) );
			elseif ( 'download' == $offer_key )
				$offer['download'] = esc_url( $value );
			else
				$offer[ $offer_key ] = esc_html( $value );
		}
		$offer = (object) array_intersect_key( $offer, array_fill_keys( array( 'response', 'download', 'locale',
			'packages', 'current', 'php_version', 'mysql_version', 'new_bundled', 'partial_version' ), '' ) );
	}

	$updates = new stdClass();
	$updates->updates = $offers;
	$updates->last_checked = time();
	$updates->version_checked = $wp_version;
	set_site_transient( 'update_core',  $updates);
}

/**
 * Check plugin versions against the latest versions hosted on WordPress.org.
 *
 * The WordPress version, PHP version, and Locale is sent along with a list of
 * all plugins installed. Checks against the WordPress server at
 * api.wordpress.org. Will only check if WordPress isn't installing.
 *
 * @package WordPress
 * @since 2.3.0
 * @uses $wp_version Used to notify the WordPress version.
 *
 * @return mixed Returns null if update is unsupported. Returns false if check is too soon.
 */
function wp_update_plugins() {
	include ABSPATH . WPINC . '/version.php'; // include an unmodified $wp_version

	if ( defined('WP_INSTALLING') )
		return false;

	// If running blog-side, bail unless we've not checked in the last 12 hours
	if ( !function_exists( 'get_plugins' ) )
		require_once( ABSPATH . 'wp-admin/includes/plugin.php' );

	$plugins = get_plugins();
	$active  = get_option( 'active_plugins', array() );
	$current = get_site_transient( 'update_plugins' );
	if ( ! is_object($current) )
		$current = new stdClass;

	$new_option = new stdClass;
	$new_option->last_checked = time();
	$timeout = 'load-plugins.php' == current_filter() ? 3600 : 43200; //Check for updated every 60 minutes if hitting the themes page, Else, check every 12 hours
	$time_not_changed = isset( $current->last_checked ) && $timeout > ( time() - $current->last_checked );

	$plugin_changed = false;
	foreach ( $plugins as $file => $p ) {
		$new_option->checked[ $file ] = $p['Version'];

		if ( !isset( $current->checked[ $file ] ) || strval($current->checked[ $file ]) !== strval($p['Version']) )
			$plugin_changed = true;
	}

	if ( isset ( $current->response ) && is_array( $current->response ) ) {
		foreach ( $current->response as $plugin_file => $update_details ) {
			if ( ! isset($plugins[ $plugin_file ]) ) {
				$plugin_changed = true;
				break;
			}
		}
	}

	// Bail if we've checked in the last 12 hours and if nothing has changed
	if ( $time_not_changed && !$plugin_changed )
		return false;

	// Update last_checked for current to prevent multiple blocking requests if request hangs
	$current->last_checked = time();
	set_site_transient( 'update_plugins', $current );

	$to_send = (object) compact('plugins', 'active');

	$options = array(
		'timeout' => ( ( defined('DOING_CRON') && DOING_CRON ) ? 30 : 3),
		'body' => array( 'plugins' => serialize( $to_send ) ),
		'user-agent' => 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' )
	);

	$raw_response = wp_remote_post('http://api.wordpress.org/plugins/update-check/1.0/', $options);

	if ( is_wp_error( $raw_response ) || 200 != wp_remote_retrieve_response_code( $raw_response ) )
		return false;

	$response = unserialize( wp_remote_retrieve_body( $raw_response ) );

	if ( false !== $response )
		$new_option->response = $response;
	else
		$new_option->response = array();

	set_site_transient( 'update_plugins', $new_option );
}

/**
 * Check theme versions against the latest versions hosted on WordPress.org.
 *
 * A list of all themes installed in sent to WP. Checks against the
 * WordPress server at api.wordpress.org. Will only check if WordPress isn't
 * installing.
 *
 * @package WordPress
 * @since 2.7.0
 * @uses $wp_version Used to notify the WordPress version.
 *
 * @return mixed Returns null if update is unsupported. Returns false if check is too soon.
 */
function wp_update_themes() {
	include ABSPATH . WPINC . '/version.php'; // include an unmodified $wp_version

	if ( defined( 'WP_INSTALLING' ) )
		return false;

	if ( !function_exists( 'get_themes' ) )
		require_once( ABSPATH . 'wp-includes/theme.php' );

	$installed_themes = get_themes( );
	$last_update = get_site_transient( 'update_themes' );
	if ( ! is_object($last_update) )
		$last_update = new stdClass;

	$timeout = 'load-themes.php' == current_filter() ? 3600 : 43200; //Check for updated every 60 minutes if hitting the themes page, Else, check every 12 hours
	$time_not_changed = isset( $last_update->last_checked ) && $timeout > ( time( ) - $last_update->last_checked );

	$themes = array();
	$checked = array();
	$exclude_fields = array('Template Files', 'Stylesheet Files', 'Status', 'Theme Root', 'Theme Root URI', 'Template Dir', 'Stylesheet Dir', 'Description', 'Tags', 'Screenshot');

	// Put slug of current theme into request.
	$themes['current_theme'] = get_option( 'stylesheet' );

	foreach ( (array) $installed_themes as $theme_title => $theme ) {
		$themes[$theme['Stylesheet']] = array();
		$checked[$theme['Stylesheet']] = $theme['Version'];

		$themes[$theme['Stylesheet']]['Name'] = $theme['Name'];
		$themes[$theme['Stylesheet']]['Version'] = $theme['Version'];

		foreach ( (array) $theme as $key => $value ) {
			if ( !in_array($key, $exclude_fields) )
				$themes[$theme['Stylesheet']][$key] = $value;
		}
	}

	$theme_changed = false;
	foreach ( $checked as $slug => $v ) {
		$update_request->checked[ $slug ] = $v;

		if ( !isset( $last_update->checked[ $slug ] ) || strval($last_update->checked[ $slug ]) !== strval($v) )
			$theme_changed = true;
	}

	if ( isset ( $last_update->response ) && is_array( $last_update->response ) ) {
		foreach ( $last_update->response as $slug => $update_details ) {
			if ( ! isset($checked[ $slug ]) ) {
				$theme_changed = true;
				break;
			}
		}
	}

	if ( $time_not_changed && !$theme_changed )
		return false;

	// Update last_checked for current to prevent multiple blocking requests if request hangs
	$last_update->last_checked = time();
	set_site_transient( 'update_themes', $last_update );

	$options = array(
		'timeout' => ( ( defined('DOING_CRON') && DOING_CRON ) ? 30 : 3),
		'body'			=> array( 'themes' => serialize( $themes ) ),
		'user-agent'	=> 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' )
	);

	$raw_response = wp_remote_post( 'http://api.wordpress.org/themes/update-check/1.0/', $options );

	if ( is_wp_error( $raw_response ) || 200 != wp_remote_retrieve_response_code( $raw_response ) )
		return false;

	$new_update = new stdClass;
	$new_update->last_checked = time( );
	$new_update->checked = $checked;

	$response = unserialize( wp_remote_retrieve_body( $raw_response ) );
	if ( false !== $response )
		$new_update->response = $response;

	set_site_transient( 'update_themes', $new_update );
}

function _maybe_update_core() {
	include ABSPATH . WPINC . '/version.php'; // include an unmodified $wp_version

	$current = get_site_transient( 'update_core' );

	if ( isset( $current->last_checked ) &&
		43200 > ( time() - $current->last_checked ) &&
		isset( $current->version_checked ) &&
		$current->version_checked == $wp_version )
		return;

	wp_version_check();
}
/**
 * Check the last time plugins were run before checking plugin versions.
 *
 * This might have been backported to WordPress 2.6.1 for performance reasons.
 * This is used for the wp-admin to check only so often instead of every page
 * load.
 *
 * @since 2.7.0
 * @access private
 */
function _maybe_update_plugins() {
	$current = get_site_transient( 'update_plugins' );
	if ( isset( $current->last_checked ) && 43200 > ( time() - $current->last_checked ) )
		return;
	wp_update_plugins();
}

/**
 * Check themes versions only after a duration of time.
 *
 * This is for performance reasons to make sure that on the theme version
 * checker is not run on every page load.
 *
 * @since 2.7.0
 * @access private
 */
function _maybe_update_themes( ) {
	$current = get_site_transient( 'update_themes' );
	if ( isset( $current->last_checked ) && 43200 > ( time( ) - $current->last_checked ) )
		return;

	wp_update_themes();
}

/**
 * Schedule core, theme, and plugin update checks.
 *
 * @since 3.1.0
 */
function wp_schedule_update_checks() {
	if ( !wp_next_scheduled('wp_version_check') && !defined('WP_INSTALLING') )
		wp_schedule_event(time(), 'twicedaily', 'wp_version_check');

	if ( !wp_next_scheduled('wp_update_plugins') && !defined('WP_INSTALLING') )
		wp_schedule_event(time(), 'twicedaily', 'wp_update_plugins');

	if ( !wp_next_scheduled('wp_update_themes') && !defined('WP_INSTALLING') )
		wp_schedule_event(time(), 'twicedaily', 'wp_update_themes');
}

if ( ! is_main_site() )
	return;

add_action( 'admin_init', '_maybe_update_core' );
add_action( 'wp_version_check', 'wp_version_check' );

add_action( 'load-plugins.php', 'wp_update_plugins' );
add_action( 'load-update.php', 'wp_update_plugins' );
add_action( 'load-update-core.php', 'wp_update_plugins' );
add_action( 'admin_init', '_maybe_update_plugins' );
add_action( 'wp_update_plugins', 'wp_update_plugins' );

add_action( 'load-themes.php', 'wp_update_themes' );
add_action( 'load-update.php', 'wp_update_themes' );
add_action( 'load-update-core.php', 'wp_update_themes' );
add_action( 'admin_init', '_maybe_update_themes' );
add_action( 'wp_update_themes', 'wp_update_themes' );

add_action('init', 'wp_schedule_update_checks');

?>


text:
Content

Content


text:
<Alloy>
	<Window id="dashboardWin" title="Dashboard">
		<Label id="weatherInfo"></Label>
		<Button id="checkIn" onClick="checkIn">Check in!</Button>
		<Button id="sendEmail" onClick="sendEmail">Send Message!</Button>
	</Window>
</Alloy>


text:
/**
 * Created by Rötzer on 11.11.2016.
 */

//Load Database file
const db = require('./models/db.js');

db.initDB();
setTimeout(db.insertTestData, 2000);


text:
.PHONY: clean-pyc clean-build docs

help:
	@echo "clean-build - remove build artifacts"
	@echo "clean-pyc - remove Python file artifacts"
	@echo "lint - check style with flake8"
	@echo "test - run tests quickly with the py.test"
	@echo "testall - run tests on every Python version with tox"
	@echo "coverage - check code coverage quickly with the default Python"
	@echo "docs - generate Sphinx HTML documentation, including API docs"
	@echo "release - package and upload a release"
	@echo "sdist - package"
	@echo "mkenv - Create a Virtual Environment and install basic packages"
	@echo "cenv - Change to the virtual environment"

clean: clean-build clean-pyc

clean-build:
	rm -fr build/
	rm -fr dist/
	rm -fr *.egg-info

clean-pyc:
	find . -name '*.pyc' -exec rm -f {} +
	find . -name '*.pyo' -exec rm -f {} +
	find . -name '*~' -exec rm -f {} +

lint:
	flake8 ScadaPandas tests > ScadaPandas_lint.txt

mkenv:
	mkvirtualenv ScadaPandas
	workon ScadaPandas
	pip install -r requirements.txt

cenv:
	workon ScadaPandas

test:
	py.test ScadaPandas

test-all:
	tox

coverage:
	coverage run --source ScadaPandas setup.py test
	coverage report -m
	coverage html
	open htmlcov/index.html

docs:
	rm -f docs/ScadaPandas.rst
	rm -f docs/modules.rst
	sphinx-apidoc -o docs/ ScadaPandas
	$(MAKE) -C docs clean
	$(MAKE) -C docs html
	open docs/_build/html/index.html

release: clean
	python setup.py sdist upload

sdist: clean
	python setup.py sdist
	ls -l dist


text:
  Montardit est
       un village
       géographiquement positionné dans le département de l'Ariège en Midi-Pyrénées. On dénombrait 178 habitants en 2008.

Si vous pensez venir habiter à Montardit, vous pourrez aisément trouver une maison à acheter.

À coté de Montardit sont localisées les villes de
Mérigon à 1 km, 121 habitants,
Barjac à 5 km, 39 habitants,
Lahitère située à 7 km, 51 habitants,
Tourtouse à 6 km, 165 habitants,
Camarade située à 7 km, 146 habitants,
Montesquieu-Avantès localisée à 5 km, 226 habitants,
 entre autres. De plus, Montardit est située à seulement quatorze km de La Trinité.

Le nombre de logements, à Montardit, était réparti en 2011 en dix appartements et 123 maisons soit
 un marché relativement équilibré.


text:
import os
import shutil
import tempfile
import unittest

from pptx import Presentation
from canvas.canvas import Canvas
from canvas.context.context import CanvasRenderingContext2D

class ContextTest(unittest.TestCase):
    """Tests for canvas."""

    def setUp(self):
        # Create a pptx presentation with a single blank slide
        prs = Presentation()
        blank_slide_layout = prs.slide_layouts[6]
        slide = prs.slides.add_slide(blank_slide_layout)

        self.canvas = Canvas(slide, prs.slide_height, prs.slide_width)
        self.context = self.canvas.getContext('2d')

    def test_is_instance(self):
        self.assertIsInstance(self.context, CanvasRenderingContext2D)

    def test_is_canvas_read_only_property(self):
        with self.assertRaises(AttributeError):
            self.context.canvas = None

if __name__ == "__main__" and __package__ is None:
    unittest.main()  # pragma: no cover


text:
@interface MHProfileHeaderCell ()

/// 头像
@property (weak, nonatomic) IBOutlet UIImageView *avatarView;
/// 昵称
@property (weak, nonatomic) IBOutlet UILabel *nicknameLabel;
/// 微信号
@property (weak, nonatomic) IBOutlet UILabel *wechatNumLabel;

/// qrCodeView
@property (weak, nonatomic) IBOutlet UIImageView *qrCodeView;

/// arrowView
@property (weak, nonatomic) IBOutlet UIImageView *arrowImageView;

/// viewModel
@property (nonatomic, readwrite, strong) MHCommonProfileHeaderItemViewModel *viewModel;
@end

@implementation MHProfileHeaderCell

#pragma mark - Public Method
+ (instancetype)cellWithTableView:(UITableView *)tableView{
    static NSString *ID = @"ProfileHeaderCell";
    MHProfileHeaderCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) cell = [self mh_viewFromXib];
    return cell;
}

- (void)bindViewModel:(MHCommonProfileHeaderItemViewModel *)viewModel{
    self.viewModel = viewModel;
}
/// 防止Crash
- (void)setIndexPath:(NSIndexPath *)indexPath rowsInSection:(NSInteger)rows{}

#pragma mark - Privite Method
- (void)awakeFromNib {
    [super awakeFromNib];
    self.contentView.backgroundColor = [UIColor whiteColor];

    UIImage *image0 = [UIImage mh_svgImageNamed:@"icons_outlined_qr_code.svg" targetSize:CGSizeMake(24, 24) tintColor:MHColorFromHexString(@"#808080")];
    self.qrCodeView.image = image0;

    UIImage *image1 = [UIImage mh_svgImageNamed:@"icons_outlined_arrow.svg"];
    self.arrowImageView.image = image1;

    @weakify(self);
    /// 绑定数据 因为用户的数据可能随时改变的
    RAC(self.nicknameLabel , text) = RACObserve(self, viewModel.user.screenName);
    RAC(self.wechatNumLabel, text) = [RACObserve(self, viewModel.user.wechatId) map:^id(id value) {
        return [NSString stringWithFormat:@"微信号:%@", value];
    }];
    [[[[RACObserve(self, viewModel.user.profileImageUrl) ignore:nil] distinctUntilChanged] deliverOnMainThread] subscribeNext:^(NSURL * avatarUrl) {
        @strongify(self);
        [self.avatarView yy_setImageWithURL:avatarUrl placeholder:MHWebAvatarImagePlaceholder() options:MHWebImageOptionAutomatic completion:NULL];
    }];

}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
}

@end


text:
<?php

namespace Propel\Tests\Generator\Behavior\ConcreteInheritance;

use Propel\Tests\Helpers\Bookstore\BookstoreTestBase;

use Propel\Tests\Bookstore\Behavior\ConcreteArticle;
use Propel\Tests\Bookstore\Behavior\ConcreteArticleQuery;
use Propel\Tests\Bookstore\Behavior\ConcreteContent;
use Propel\Tests\Bookstore\Behavior\ConcreteContentQuery;
use Propel\Tests\Bookstore\Behavior\ConcreteQuizzQuery;

/**
 * Tests for ConcreteInheritanceParentBehavior class
 *
 * @author François Zaniontto
 *
 * @group database
 */
class ConcreteInheritanceParentBehaviorTest extends BookstoreTestBase
{
    public function testHasChildObject()
    {
        ConcreteArticleQuery::create()->deleteAll();
        ConcreteQuizzQuery::create()->deleteAll();
        ConcreteContentQuery::create()->deleteAll();
        $content = new ConcreteContent();
        $content->save();
        $this->assertFalse($content->hasChildObject());

        $article = new ConcreteArticle();
        $article->save();
        $content = $article->getConcreteContent();
        $this->assertTrue($content->hasChildObject());
    }

    public function testGetChildObject()
    {
        ConcreteArticleQuery::create()->deleteAll();
        ConcreteQuizzQuery::create()->deleteAll();
        ConcreteContentQuery::create()->deleteAll();

        $content = new ConcreteContent();
        $content->save();
        $this->assertNull($content->getChildObject());

        $article = new ConcreteArticle();
        $article->save();
        $content = $article->getConcreteContent();
        $this->assertEquals($article, $content->getChildObject());
    }

}


text:
[![Build Status](https://travis-ci.org/mxenabled/action_subscriber.svg?branch=master)](https://travis-ci.org/mxenabled/action_subscriber)
[![Code Climate](https://codeclimate.com/github/mxenabled/action_subscriber/badges/gpa.svg)](https://codeclimate.com/github/mxenabled/action_subscriber)
[![Dependency Status](https://gemnasium.com/mxenabled/action_subscriber.svg)](https://gemnasium.com/mxenabled/action_subscriber)
[![Join the chat at https://gitter.im/mxenabled/action_subscriber](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/mxenabled/action_subscriber?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

ActionSubscriber
=================
ActionSubscriber is a DSL for for easily intergrating your Rails app with a RabbitMQ messaging server.

Requirements
-----------------
I test on Ruby 2.2.1 and Jruby 9.x.  MRI 1.9 and jRuby 1.7 are still supported.

If you want to use MRI 1.9 you will need to lock down the `amq-protocol` and `bunny` gems to `< 2.0` since they both require ruby 2.0+.

Migrating from ActionSubscriber 3.X or earlier
----------------------------------------------

If you were using the `--mode=pop` from the 2.X or 3.X version of ActionSubscriber you can get the same sort of behavior by drawing your routes like this:

```ruby
::ActionSubscriber.draw_routes do
  # instead of creating custom threadpools you set the threadpool size of your connection here in the routes
  # you can set the threadpool size for the default connection via the `::ActionSubscriber.configuration.threadpool_size = 16`
  route UserSubscriber, :created,
    :prefetch => 1,
    :concurrency => 16,
    :acknowledgements => true

  # in user_subscriber.rb make sure to set `at_most_once!` like this
  #
  # class UserSubscriber < ::ActionSubscriber::Base
  #   at_most_once!
  # end

  # If you were previously using custom threadpools for different routes you can mimic that behavior by opening multiple connections
  connection(:slow_work, :threadpool_size => 32) do
    route UserSubscriber, :created,
      :prefetch => 1,
      :concurrency => 32,
      :acknowledgements => true
  end
end
```

That will give you a similar behavior to the old `--mode=pop` where messages polled from the server, but with reduced latency.

Supported Message Types
-----------------
ActionSubscriber support JSON and plain text out of the box, but you can easily
add support for any custom message type.

Example
-----------------
A subscriber is set up by creating a class that inherits from ActionSubscriber::Base.

```ruby
class UserSubscriber < ::ActionSubscriber::Base
  def created
    # do something when a user is created
  end
end
```

checkout the examples dir for more detailed examples.

Usage
-----------------

In your application setup you will draw your subscription routes. In a rails app this is usually done in `config/initializers/action_subscriber.rb`.

```ruby
::ActionSubscriber.draw_routes do
  # you can define routes one-by-one for fine-grained controled
  route UserSubscriber, :created

  # or you can setup default routes for all the public methods in a subscriber
  default_routes_for UserSubscriber
end
```

Now you can start your subscriber process with:

```
$ bundle exec action_subscriber start
```

This will connect your subscribers to the rabbitmq broker and allow it to push messages down to your subscribers.

### Around Filters
"around" filters are responsible for running their associated actions by yielding, similar to how Rack middlewares work (and Rails around filters work)

```ruby
class UserSubscriber < ::ActionSubscriber::Base
  around_filter :log_things

  def created
    # do something when a user is created
  end

  private

  def log_things
    puts "before I do some stuff"
    yield
    puts "I did some stuff"
  end
end
```

> Warning: an around filter will only be added once to the chain, duplicate around filters are not supported

Configuration
-----------------
ActionSubscriber needs to know how to connect to your rabbit server to start getting messages.

In an initializer, you can set the host and the port like this :

    ActionSubscriber.configure do |config|
      config.hosts = ["rabbit1", "rabbit2", "rabbit3"]
      config.port = 5672
    end

Other configuration options include :

* config.add_decoder - add a custom decoder for a custom content type
* config.allow_low_priority_methods - Subscribe to `*_low` queues in addition to normal queues.
* config.connection_reaping_interval - Connection reaping interval when using a project ActiveRecord
* config.connection_reaping_timeout_interval - Connection reaping timeout interval when using a project ActiveRecord
* config.default_exchange - set the default exchange that your queues will use, using the default RabbitMQ exchange is not recommended
* config.error_handler - handle error like you want to handle them!
* config.heartbeat - number of seconds between hearbeats (default 5) [see bunny documentation for more details](http://rubybunny.info/articles/connecting.html)
* config.hosts - an array of hostnames in your cluster (ie `["rabbit1.myapp.com", "rabbit2.myapp.com"]`)
* config.network_recovery_interval - reconnection interval for TCP connection failures (default 1)
* config.password - RabbitMQ password (default "guest")
* config.prefetch - number of messages to hold in the local queue in subscriber mode
* config.seconds_to_wait_for_graceful_shutdown - time to wait before force stopping server after shutdown signal
* config.threadpool_size - set the number of threads available to action_subscriber
* config.timeout - how many seconds to allow rabbit to respond before timing out
* config.tls - true/false whether to use TLS when connecting to the server
* config.tls_ca_certificats - a list of ca certificates to use for verifying the servers TLS certificate
* config.tls_cert - a client certificate to use during the TLS handshake
* config.tls_key - a key to use during the TLS handshake
* config.username - RabbitMQ username (default "guest")
* config.verify_peer - whether to attempt to validate the server's TLS certificate
* config.virtual_host - RabbitMQ virtual host (default "/")

> Note: TLS is not handled identically in `bunny` and `march_hare`. The configuration options we provide are passed through as provided. For details on expected behavior please check the `bunny` or `march_hare` documentation based on whether you are running in MRI or jRuby.

Message Acknowledgment
----------------------
### no_acknolwedgement!

This mode is the default. Rabbit is told to not expect any message acknowledgements so messages will be lost if an error occurs.
This also allows the broker to send messages as quickly as it wants down to your subscriber.

> Warning: If messages arrive very quickly this could cause your process to crash as your memory fills up with unprocessed message.
> We highly recommend you use `at_least_once!` mode to provide a throttle so the broker does not overwhelm your process with messages.

### manual_acknowledgement!

This mode leaves it up to the subscriber to handle acknowledging or rejecting messages. In your subscriber you can just call acknowledge, reject, or nack.

### at_most_once!

Rabbit is told to expect message acknowledgements, but sending the acknowledgement is left up to ActionSubscriber. We send the acknowledgement right before calling your subscriber.

### at_least_once!

Rabbit is told to expect message acknowledgements, but sending the acknowledgement is left up to ActionSubscriber.
We send the acknowledgement right after calling your subscriber.
If an error is raised your message will be retried on a sent back to rabbitmq and retried on an exponential backoff schedule.

### safe_nack
If you turn on acknowledgements and a message is not acknowledged by your code manually or using one of the filters above the `ErrorHandler` middleware
which wraps the entire block with call nack this is a last resort so the connection does not get backed up in cases of unexpected or
unhandled errors.

### redeliver

A message can be sent to "redeliver" with `::ActionSubscriber::MessageRetry.redeliver_message_with_backoff` or the DSL method `redeliver` and optionally
takes a "backoff schedule" which is a hash of backoff milliseconds for each redeliver, the default:

```ruby
  SCHEDULE = {
    2  =>        100,
    3  =>        500,
    4  =>      2_500,
    5  =>     12_500,
    6  =>     62_500,
    7  =>    312_500,
    8  =>  1_562_500,
    9  =>  7_812_500,
    10 => 39_062_500,
  }
```

when the schedule "returns" `nil` the message will not be retried

> Warning: If you use `redeliver` you need to handle reject/acknowledge according how errors are handled; if an error is caught and the
> ack/reject is already done then you may duplicate the message in `at_least_once!` mode

Testing
-----------------
ActionSubscriber includes support for easy unit testing with RSpec.

In your spec_helper.rb:

```
require 'action_subscriber/rspec'

RSpec.configure do |config|
  config.include ::ActionSubscriber::RSpec
end
```

In your_subscriber_spec.rb :
``` subject { mock_subscriber }```

Your test subject will be an instance of your subscriber class, and you can
easily test your public methods without dependence on data from Rabbit.  You can
optionally pass data for your mock subscriber to consume if you wish.

``` subject { mock_subscriber(:header => "test_header", :payload => "payload") } ```

Development
===========

If you want to work on `action_subscriber` you will need to have a rabbitmq instance running locally on port 5672 with a management plugin enabled on port 15672. Usually the easiest way to accomplish this is to use docker and run the command:

```
$ docker run --net=host --rm=true --hostname diagon --name rabbit rabbitmq:3.6.6-management
```

Now that rabbitmq is running you can clone this project and run:

```
$ cd action_subscriber
$ bundle install
$ bundle exec rspec
```


text:
<mxEditor>
    <include name="/js/visual-editor/config/keyhandler-commons.xml"/>
</mxEditor>


text:
<?php
class HeadhunAction extends CommonAction {
    public function index(){
		$userdata = M('userdata');
		import('ORG.Util.Page');
		$data['status'] = 1;
		$count = $userdata->where($data)->count();
		$page = new Page($count,10);
		$show = $page->show();
		$list = $userdata->where($data)->order('time')->limit($page->firstRow.','.$page->listRows)->select();
		$this->assign('page',$show);
		if($list==''){
		$this->assign('empty','抱歉!没有数据可查询~');
		}
		$this->assign('list',$list);
		$this->display();
    }
}


text:
/*

this should become the init or initLexer rule of the rules for the t language parser

     rules =
       {
          init: require('path/to/init/newline-single-space')
       }
     text = "some t language code"
     lexer = new Lexer({text}, rules)
 */
var processNewlineSpaces, searchHeadTab;

searchHeadTab = require('../../../rewrite/search-head-tab');

processNewlineSpaces = require('../../../rewrite/process-newline-spaces');

module.exports = function() {
  var line, lineInfo, newText, spacesInfo, text, _ref;
  text = this.text;
  if (!text) {
    return;
  }
  if ((line = searchHeadTab(text))) {
    this.error("line: " + (line + 1) + ": unexpected tab(" + "\t" + ") character", false);
  }
  this.cursor = 0;
  this.lineno = 1;
  _ref = processNewlineSpaces(text), newText = _ref[0], lineInfo = _ref[1], spacesInfo = _ref[2];
  this.originalText = text;
  this.text = newText;
  this.lineInfo = lineInfo;
  this.spacesInfo = spacesInfo;
  this.maxLine = lineInfo.length;
  return this;
};


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

namespace CpsDbHelper.Examples.Models
{
    public class Company
    {
        public string Name { get; set; }
        public Address Address { get; set; }
        public string PropertyWithNoMatchingColumn { get; set; }
    }
}


text:
/*!
 * MultiUpload for xheditor
 * @requires xhEditor
 *
 * @author Yanis.Wang<yanis.wang@gmail.com>
 * @site http://xheditor.com/
 * @licence LGPL(http://www.opensource.org/licenses/lgpl-license.php)
 *
 * @Version: 0.9.2 (build 100505)
 */
var swfu,selQueue=[],selectID,arrMsg=[],allSize=0,uploadSize=0;
function removeFile()
{
	var file;
	if(!selectID)return;
	for(var i in selQueue)
	{
		file=selQueue[i];
		if(file.id==selectID)
		{
			selQueue.splice(i,1);
			allSize-=file.size;
			swfu.cancelUpload(file.id);
			$('#'+file.id).remove();
			selectID=null;
			break;
		}
	}
	$('#btnClear').hide();
	if(selQueue.length==0)$('#controlBtns').hide();
}
function startUploadFiles()
{
	if(swfu.getStats().files_queued>0)
	{
		$('#controlBtns').hide();
		swfu.startUpload();
	}
	else alert('上传前请先添加文件');
}
function setFileState(fileid,txt)
{
	$('#'+fileid+'_state').text(txt);
}
function fileQueued(file)//队列添加成功
{
	for(var i in selQueue)if(selQueue[i].name==file.name){swfu.cancelUpload(file.id);return false;}//防止同名文件重复添加
	if(selQueue.length==0)$('#controlBtns').show();
	selQueue.push(file);
	allSize+=file.size;
	$('#listBody').append('
'+file.name+'	'+formatBytes(file.size)+'	就绪
');
	$('#'+file.id).hover(function(){$(this).addClass('hover');},function(){$(this).removeClass('hover');})
	.click(function(){selectID=file.id;$('#listBody tr').removeClass('select');$(this).removeClass('hover').addClass('select');$('#btnClear').show();})
}
function fileQueueError(file, errorCode, message)//队列添加失败
{
	var errorName='';
	switch (errorCode)
	{
		case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
			errorName = "只能同时上传 "+this.settings.file_upload_limit+" 个文件";
			break;
		case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
			errorName = "选择的文件超过了当前大小限制:"+this.settings.file_size_limit;
			break;
		case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
			errorName = "零大小文件";
			break;
		case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
			errorName = "文件扩展名必需为:"+this.settings.file_types_description+" ("+this.settings.file_types+")";
			break;
		default:
			errorName = "未知错误";
			break;
	}
	alert(errorName);
}
function uploadStart(file)//单文件上传开始
{
	setFileState(file.id,'上传中…');
}
function uploadProgress(file, bytesLoaded, bytesTotal)//单文件上传进度
{
	var percent=Math.ceil((uploadSize+bytesLoaded)/allSize*100);
	$('#progressBar span').text(percent+'% ('+formatBytes(uploadSize+bytesLoaded)+' / '+formatBytes(allSize)+')');
	$('#progressBar div').css('width',percent+'%');
}
function uploadSuccess(file, serverData)//单文件上传成功
{
	var data=Object;
	try{eval("data=" + serverData);}catch(ex){};
	if(data.err!=undefined&&data.msg!=undefined)
	{
		if(!data.err)
		{
			uploadSize+=file.size;
			arrMsg.push(data.msg);
			setFileState(file.id,'上传成功');
		}
		else
		{
			setFileState(file.id,'上传失败');
			alert(data.err);
		}
	}
	else setFileState(file.id,'上传失败!');
}
function uploadError(file, errorCode, message)//单文件上传错误
{
	setFileState(file.id,'上传失败!');
}
function uploadComplete(file)//文件上传周期结束
{
	if(swfu.getStats().files_queued>0)swfu.startUpload();
	else uploadAllComplete();
}
function uploadAllComplete()//全部文件上传成功
{
	callback(arrMsg);
}
function formatBytes(bytes) {
	var s = ['Byte', 'KB', 'MB', 'GB', 'TB', 'PB'];
	var e = Math.floor(Math.log(bytes)/Math.log(1024));
	return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+" "+s[e];
}


text:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@android:id/text1"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:textAppearance="?android:attr/textAppearanceListItemSmall"
          android:gravity="center_vertical"
          android:paddingLeft="16dp"
          android:paddingRight="16dp"
          android:textColor="#fff"
          android:fontFamily="sans-serif-light"
          android:background="@drawable/activated_background_indicator"
          android:minHeight="48dp"/>


text:
from django.test import TestCase

from scriptorium.elementor import bootstrap, standard

class TestListGroup(TestCase):
    def setUp(self):
        self.element = bootstrap.ListGroup()
        self.element.add_item(standard.ListItem('test'))
        super().setUp()

    def test_rendering(self):
        self.assertIn('
', self.element.render())
        self.assertIn('
test',
                      self.element.render())

class TestNavbarTabs(TestCase):
    def setUp(self):
        self.element = bootstrap.Navbar()

        super().setUp()

    def test_empty_rendering(self):
        self.assertIn('',
                      self.element.render())
        self.assertIn('
',
                      self.element.render())

    def test_text_item(self):
        self.element.add_item(bootstrap.Button("works"))

        self.assertIn('navbar-btn', self.element.render())
        self.assertIn('>works</', self.element.render())

class TestNav(TestCase):
    def setUp(self):
        self.element = bootstrap.Nav()
        super().setUp()

    def test_rendering(self):
        self.element.add_item(standard.ListItem('test'))
        self.element.add_item(standard.Link('test2'))

        self.assertIn('ul class="nav nav-default"', self.element.render())
        self.assertIn('
test
', self.element.render())
        self.assertIn('
<a', self.element.render())
        self.assertIn('test2test2',
                      self.element.render())

class TestDropdown(TestCase):
    def setUp(self):
        self.ele = bootstrap.Dropdown()
        super().setUp()

    def test_rendering(self):
        self.ele.add_item('test')
        self.assertIn('class="dropdown"', self.ele.render())
        self.assertIn('<ul', self.ele.render())
        self.assertIn('
test', self.ele.render())


text:
class CreateMotoWebEngineTests < ActiveRecord::Migration
  def change
    create_table :moto_web_engine_tests do |t|
      t.belongs_to :run
      t.string :name
      t.string :class_name
      t.text :log, limit: 2097152 #2MB
      t.text :parameters
      t.integer :result
      t.string :error
      t.text :failures
      t.string :env
      t.float :duration
      t.timestamps null: false
    end
  end
end


text:
package org.jbake.template;

import groovy.lang.GString;
import groovy.lang.Writable;
import groovy.text.Template;
import groovy.text.markup.MarkupTemplateEngine;
import groovy.text.markup.TemplateConfiguration;
import org.apache.commons.configuration.CompositeConfiguration;
import org.jbake.app.ContentStore;
import org.jbake.app.configuration.JBakeConfiguration;

import java.io.File;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

/**
 * Renders documents using the GroovyMarkupTemplateEngine.
 *

 * The file extension to activate this Engine is .tpl
 *
 * @see Groovy MarkupTemplateEngine Documentation
 */
public class GroovyMarkupTemplateEngine extends AbstractTemplateEngine {
    private TemplateConfiguration templateConfiguration;
    private MarkupTemplateEngine templateEngine;

    /**
     * @deprecated Use {@link #GroovyMarkupTemplateEngine(JBakeConfiguration, ContentStore)} instead
     *
     * @param config the {@link CompositeConfiguration} of jbake
     * @param db the {@link ContentStore}
     * @param destination the destination path
     * @param templatesPath the templates path
     */
    @Deprecated
    public GroovyMarkupTemplateEngine(final CompositeConfiguration config, final ContentStore db, final File destination, final File templatesPath) {
        super(config, db, destination, templatesPath);
        setupTemplateConfiguration();
        initializeTemplateEngine();
    }

    public GroovyMarkupTemplateEngine(final JBakeConfiguration config, final ContentStore db) {
        super(config, db);
        setupTemplateConfiguration();
        initializeTemplateEngine();
    }

    private void setupTemplateConfiguration() {
        templateConfiguration = new TemplateConfiguration();
        templateConfiguration.setUseDoubleQuotes(true);
        templateConfiguration.setAutoIndent(true);
        templateConfiguration.setAutoNewLine(true);
        templateConfiguration.setAutoEscape(true);
    }

    private void initializeTemplateEngine() {
        templateEngine = new MarkupTemplateEngine(MarkupTemplateEngine.class.getClassLoader(), config.getTemplateFolder(), templateConfiguration);
    }

    @Override
    public void renderDocument(final Map<String, Object> model, final String templateName, final Writer writer) throws RenderingException {
        try {
            Template template = templateEngine.createTemplateByPath(templateName);
            Map<String, Object> wrappedModel = wrap(model);
            Writable writable = template.make(wrappedModel);
            writable.writeTo(writer);
        } catch (Exception e) {
            throw new RenderingException(e);
        }
    }

    private Map<String, Object> wrap(final Map<String, Object> model) {
        return new HashMap<String, Object>(model) {
            @Override
            public Object get(final Object property) {
                if (property instanceof String || property instanceof GString) {
                    String key = property.toString();
                    try {
                        put(key, extractors.extractAndTransform(db, key, model, new TemplateEngineAdapter.NoopAdapter()));
                    } catch (NoModelExtractorException e) {
                        // should never happen, as we iterate over existing extractors
                    }
                }

                return super.get(property);
            }
        };
    }
}