text:
/* global assert, setup, suite, test, THREE */
var entityFactory = require('../helpers').entityFactory;
var components = require('index').components;
var registerComponent = require('index').registerComponent;

suite('animation', function () {
  var component;
  var el;

  setup(function (done) {
    this.done = false;
    el = entityFactory();
    el.setAttribute('animation', '');
    el.addEventListener('componentinitialized', function handler (evt) {
      if (evt.detail.name !== 'animation' || this.done) { return; }
      component = el.components.animation;
      this.done = true;
      el.removeEventListener('componentinitialized', handler);
      done();
    });
  });

  suite('basic animation', () => {
    test('sets from value', function () {
      el.setAttribute('animation', {property: 'light.intensity', from: 0.5, to: 1});
      component.tick(0, 20);
      assert.equal(el.getAttribute('light').intensity, 0.5);
    });

    test('sets between value', function () {
      el.setAttribute('animation', {property: 'light.intensity', from: 0.5, to: 1.0, dur: 500});
      component.tick(0, 100);
      component.tick(0, 100);
      assert.ok(el.getAttribute('light').intensity > 0.5);
      assert.ok(el.getAttribute('light').intensity < 1.0);
    });

    test('sets to value', function () {
      el.setAttribute('animation', {property: 'light.intensity', from: 0.5, to: 1.0, dur: 500});
      component.tick(0, 1);
      component.tick(0, 500);
      assert.equal(el.getAttribute('light').intensity, 1.0);
    });

    test('can infer from value', function () {
      el.setAttribute('light', 'intensity', 0.75);
      el.setAttribute('animation', {property: 'light.intensity', to: 1});
      assert.equal(component.config.targets.aframeProperty, 0.75);
    });

    test('handles non-truthy from value (i.e., 0)', function () {
      el.setAttribute('text', {value: 'supermedium'});
      el.setAttribute('animation', {
        property: 'components.text.material.uniforms.opacity.value',
        from: 0,
        to: 1,
        dur: 1000
      });
      component.tick(0, 1);
      assert.equal(el.components.text.material.uniforms.opacity.value, 0);
    });

    test('handles non-truthy to value (i.e., 0)', function () {
      el.setAttribute('animation', {
        property: 'object3D.scale.y',
        from: 1,
        to: 0,
        dur: 1000
      });
      component.tick(0, 1);
      assert.equal(el.object3D.scale.y, 1);
      component.tick(0, 1000);
      assert.equal(el.object3D.scale.y, 0);
    });
  });

  suite('direct component value animation', () => {
    test('can animate component value or member directly', function () {
      el.setAttribute('material', 'opacity', 0);
      el.setAttribute('animation', {
        property: 'components.material.material.opacity',
        dur: 1000,
        from: 0,
        to: 1
      });
      component.tick(0, 1);
      assert.equal(el.components.material.material.opacity, 0);
      component.tick(0, 500);
      assert.ok(el.components.material.material.opacity > 0);
      assert.ok(el.components.material.material.opacity < 1.0);
      component.tick(0, 500);
      assert.equal(el.components.material.material.opacity, 1.0);
    });

    test('can infer from value', function () {
      el.setAttribute('material', 'opacity', 0.75);
      el.setAttribute('animation', {
        property: 'components.material.material.opacity',
        dur: 1000,
        to: 1
      });
      assert.equal(component.config.targets.aframeProperty, 0.75);
    });
  });

  suite('direct object3D value animation', () => {
    test('can animate object3D value directly', function () {
      el.setAttribute('animation', {
        property: 'object3D.position.x',
        dur: 1000,
        from: 0,
        to: 10
      });
      component.tick(0, 1);
      assert.equal(el.object3D.position.x, 0);
      component.tick(0, 500);
      assert.ok(el.object3D.position.x > 0);
      assert.ok(el.object3D.position.x < 10);
      component.tick(0, 500);
      assert.equal(el.object3D.position.x, 10);
    });

    test('can infer from value', function () {
      el.object3D.position.z = 0.75;
      el.setAttribute('animation', {
        property: 'object3D.position.z',
        dur: 1000,
        to: 1
      });
      assert.equal(component.config.targets.aframeProperty, 0.75);
    });

    test('uses degrees for rotation', function () {
      el.setAttribute('animation', {
        property: 'object3D.rotation.x',
        dur: 1000,
        from: 0,
        to: 360
      });
      component.tick(0, 1);
      assert.equal(el.object3D.position.x, 0);
      component.tick(0, 500);
      assert.equal(THREE.MathUtils.degToRad(component.config.targets.aframeProperty),
                   el.object3D.rotation.x);
    });
  });

  suite('color animation', () => {
    test('can animate color object directly', function () {
      el.setAttribute('material', '');
      el.setAttribute('animation', {
        property: 'components.material.material.color',
        dur: 1000,
        from: 'blue',
        to: 'red',
        type: 'color'
      });
      component.tick(0, 1);
      assert.equal(el.components.material.material.color.b, 1);
      assert.equal(el.components.material.material.color.r, 0);
      component.tick(0, 500);
      assert.ok(el.components.material.material.color.b > 0);
      assert.ok(el.components.material.material.color.b < 1);
      assert.ok(el.components.material.material.color.r > 0);
      assert.ok(el.components.material.material.color.r < 1);
      component.tick(0, 500);
      assert.equal(el.components.material.material.color.b, 0);
      assert.equal(el.components.material.material.color.r, 1);
    });

    test('can infer from value', function () {
      el.setAttribute('material', '');
      el.components.material.material.color.r = 0.1;
      el.components.material.material.color.g = 0.2;
      el.components.material.material.color.b = 0.3;
      el.setAttribute('animation', {
        property: 'components.material.material.color',
        dur: 1000,
        to: '#FFF',
        type: 'color'
      });
      assert.equal(component.config.targets[0].r, 0.1);
      assert.equal(component.config.targets[0].g, 0.2);
      assert.equal(component.config.targets[0].b, 0.3);
    });
  });

  suite('vec3 animation', () => {
    setup(function () {
      components.dummy = undefined;
    });

    test('can animate vec3', function () {
      el.setAttribute('animation', {
        property: 'position',
        dur: 1000,
        from: '1 1 1',
        to: '0 0 0'
      });
      component.tick(0, 1);
      assert.equal(el.object3D.position.x, 1);
      assert.equal(el.object3D.position.y, 1);
      assert.equal(el.object3D.position.z, 1);
      component.tick(0, 500);
      assert.ok(el.object3D.position.x > 0);
      assert.ok(el.object3D.position.x < 1);
      component.tick(0, 500);
      assert.equal(el.object3D.position.x, 0);
      assert.equal(el.object3D.position.y, 0);
      assert.equal(el.object3D.position.z, 0);
    });

    test('can infer from value', function () {
      el.object3D.position.set(5, 5, 5);
      el.setAttribute('animation', {
        property: 'position',
        dur: 1000,
        to: '10 10 10'
      });
      assert.equal(component.config.targets[0].x, 5);
      assert.equal(component.config.targets[0].y, 5);
      assert.equal(component.config.targets[0].z, 5);
    });

    test('uses degrees for rotation', function () {
      el.setAttribute('animation', {
        property: 'rotation',
        dur: 1000,
        from: '0 0 0',
        to: '30 60 90'
      });
      component.tick(0, 1);
      component.tick(0, 1000);
      assert.equal(el.object3D.rotation.x, THREE.MathUtils.degToRad(30));
      assert.equal(el.object3D.rotation.y, THREE.MathUtils.degToRad(60));
      assert.equal(el.object3D.rotation.z, THREE.MathUtils.degToRad(90));
    });

    test('can animate vec3 single-property custom component', function () {
      registerComponent('dummy', {
        schema: {type: 'vec3'}
      });
      el.setAttribute('dummy');
      el.setAttribute('animation', {
        property: 'dummy',
        dur: 1000,
        from: '1 1 1',
        to: '0 0 0'
      });
      component.tick(0, 1);
      assert.equal(el.components.dummy.data.x, 1);
      assert.equal(el.components.dummy.data.y, 1);
      assert.equal(el.components.dummy.data.z, 1);
      component.tick(0, 500);
      assert.ok(el.components.dummy.data.x > 0);
      assert.ok(el.components.dummy.data.x < 1);
      component.tick(0, 500);
      assert.equal(el.components.dummy.data.x, 0);
      assert.equal(el.components.dummy.data.y, 0);
      assert.equal(el.components.dummy.data.z, 0);
    });

    test('can animate vec3 property of custom component', function () {
      registerComponent('dummy', {
        schema: {vector: {type: 'vec3'}}
      });
      el.setAttribute('dummy', '');
      el.setAttribute('animation', {
        property: 'dummy.vector',
        dur: 1000,
        from: '1 1 1',
        to: '0 0 0'
      });
      component.tick(0, 1);
      assert.equal(el.components.dummy.data.vector.x, 1);
      assert.equal(el.components.dummy.data.vector.y, 1);
      assert.equal(el.components.dummy.data.vector.z, 1);
      component.tick(0, 500);
      assert.ok(el.components.dummy.data.vector.x > 0);
      assert.ok(el.components.dummy.data.vector.x < 1);
      component.tick(0, 500);
      assert.equal(el.components.dummy.data.vector.x, 0);
      assert.equal(el.components.dummy.data.vector.y, 0);
      assert.equal(el.components.dummy.data.vector.z, 0);
    });
  });

  suite('boolean animation', () => {
    test('can toggle from false to true via strings', function () {
      el.setAttribute('animation', {property: 'visible', from: 'false', to: 'true', dur: 1000});
      component.tick(0, 1);
      assert.equal(el.object3D.visible, false);
      component.tick(0, 500);
      assert.equal(el.object3D.visible, false);
      component.tick(0, 500);
      assert.equal(el.object3D.visible, true);
    });

    test('can toggle from false to true via bools', function () {
      el.setAttribute('animation', {property: 'visible', from: false, to: true, dur: 1000});
      component.tick(0, 1);
      assert.equal(el.object3D.visible, false);
      component.tick(0, 500);
      assert.equal(el.object3D.visible, false);
      component.tick(0, 500);
      assert.equal(el.object3D.visible, true);
    });
  });

  suite('dir (direction)', () => {
    test('can reverse', function () {
      el.setAttribute('animation', {
        property: 'light.intensity',
        from: 0.5,
        to: 1,
        dir: 'reverse',
        dur: 1000
      });
      component.tick(0, 1);
      assert.equal(el.getAttribute('light').intensity, 1.0);
      component.tick(0, 500);
      assert.ok(el.getAttribute('light').intensity < 1.0);
      assert.ok(el.getAttribute('light').intensity > 0.5);
      component.tick(0, 500);
      assert.equal(el.getAttribute('light').intensity, 0.5);
    });

    test('can alternate', function () {
      el.setAttribute('animation', {
        property: 'object3D.rotation.x',
        from: 0,
        to: 360,
        dir: 'alternate',
        dur: 1000,
        loop: true
      });

      component.tick(0, 1);
      assert.equal(el.object3D.rotation.x, 0);

      // Now going up.
      component.tick(0, 1000);
      assert.equal(el.object3D.rotation.x, Math.PI * 2);

      // Now going down.
      component.tick(0, 500);
      assert.ok(el.object3D.rotation.x > 0);
      assert.ok(el.object3D.rotation.x < Math.PI * 2);
    });
  });

  suite('loop', () => {
    test('can loop', function () {
      el.setAttribute('animation', {
        property: 'light.intensity',
        from: 0,
        to: 1,
        loop: true,
        dur: 1000
      });
      component.tick(0, 1);
      assert.equal(el.getAttribute('light').intensity, 0);
      component.tick(0, 1000);
      assert.equal(el.getAttribute('light').intensity, 1.0);
      component.tick(0, 1);
      assert.equal(Math.round(el.getAttribute('light').intensity), 0);
      component.tick(0, 1000);
      assert.equal(el.getAttribute('light').intensity, 1.0);
    });
  });

  test('can set easing', function () {
    el.setAttribute('animation', {
      property: 'light.intensity',
      from: 0,
      to: 1,
      easing: 'easeInOutCubic'
    });
    assert.equal(component.config.easing, 'easeInOutCubic');
  });

  test('can set round', function () {
    el.setAttribute('animation', {
      property: 'light.intensity',
      from: 0,
      to: 1,
      round: true
    });
    assert.equal(component.config.round, true);
  });

  test('can set elasticity', function () {
    el.setAttribute('animation', {
      property: 'light.intensity',
      from: 0,
      to: 1,
      elasticity: 2
    });
    assert.equal(component.config.elasticity, 2);
  });

  suite('startAnimation', function () {
    test('plays by default', function () {
      el.setAttribute('animation', {property: 'position'});
      assert.ok(component.animationIsPlaying);
    });

    test('plays on delay', function (done) {
      el.setAttribute('animation', {property: 'position', delay: 100});
      assert.notOk(component.animationIsPlaying);
      setTimeout(() => {
        assert.ok(component.animationIsPlaying);
        done();
      }, 100);
    });

    test('does not play if startEvents', function () {
      el.setAttribute('animation', {property: 'position', startEvents: 'foo'});
      assert.notOk(component.animationIsPlaying);
    });

    test('does not play if not autoplay', function () {
      el.setAttribute('animation', {property: 'position', autoplay: false});
      assert.notOk(component.animationIsPlaying);
    });
  });

  suite('event listeners', () => {
    test('plays on startEvents', function (done) {
      el.setAttribute('animation', {property: 'position', startEvents: ['foo', 'far']});
      assert.notOk(component.animationIsPlaying);
      el.addEventListener('foo', function handler () {
        assert.ok(component.animationIsPlaying);
        el.removeEventListener('foo', handler);
        done();
      });
      el.emit('foo');
    });

    test('restarts animation on startEvents', function (done) {
      el.setAttribute('animation', {
        property: 'object3D.scale.z',
        from: 1,
        to: 2,
        startEvents: ['foo', 'foo2']
      });

      el.addEventListener('foo', function handler () {
        assert.ok(component.animationIsPlaying);
        assert.equal(el.object3D.scale.z, 1);
        component.tick(0, 1);
        component.tick(0, 550);
        assert.ok(el.object3D.scale.z > 1);
        el.emit('foo2');
        el.removeEventListener('foo', handler);
      });

      el.addEventListener('foo2', function handler2 () {
        component.tick(0, 1);
        assert.ok(component.animationIsPlaying);
        assert.equal(el.object3D.scale.z, 1);
        component.tick(0, 550);
        assert.ok(el.object3D.scale.z > 1);
        el.removeEventListener('foo2', handler2);
        done();
      });

      component.tick(0, 1);
      component.tick(0, 500);
      el.emit('foo');
    });

    test('pauses on pauseEvents', function (done) {
      el.setAttribute('animation', {property: 'position', pauseEvents: 'bar, boo'});
      assert.ok(component.animationIsPlaying);
      el.addEventListener('bar', function handler () {
        setTimeout(() => {
          assert.notOk(component.animationIsPlaying);
          el.removeEventListener('bar', handler);
          done();
        });
      });
      el.emit('bar');
    });

    test('resumes on resumeEvents', function (done) {
      el.setAttribute('text', {opacity: 0, value: 'supermedium'});
      el.setAttribute('animation', {
        property: 'components.text.material.uniforms.opacity.value',
        from: 0,
        to: 1,
        dur: 1000,
        pauseEvents: 'bar',
        resumeEvents: 'qux'
      });
      el.addEventListener('bar', function handler () {
        assert.notOk(component.animationIsPlaying);
        el.removeEventListener('bar', handler);
        el.emit('qux');
      });
      el.addEventListener('qux', function handler2 () {
        assert.ok(component.animationIsPlaying);
        assert.ok(el.components.text.material.uniforms.opacity.value > 0, 'More than 0');
        assert.ok(el.components.text.material.uniforms.opacity.value < 1, 'Less than 1');
        component.tick(0, 500);
        assert.equal(el.components.text.material.uniforms.opacity.value, 1);
        el.removeEventListener('qux', handler2);
        done();
      });

      assert.ok(component.animationIsPlaying, 'Should be playing');
      component.tick(0, 1);
      component.tick(0, 500);
      assert.ok(el.components.text.material.uniforms.opacity.value > 0, 'More than 0');
      assert.ok(el.components.text.material.uniforms.opacity.value < 1, 'Less than 1');
      el.emit('bar');
    });
  });

  suite('event emissions', function () {
    test('emits animationbegin event', function (done) {
      el.addEventListener('animationbegin', evt => { done(); });
      el.setAttribute('animation', {property: 'position', to: '2 2 2'});
    });

    test('emits animationcomplete event', function (done) {
      el.addEventListener('animationbegin', evt => {
        el.addEventListener('animationcomplete', evt => { done(); });
        component.tick(1, 1);
        component.tick(100000, 99999);
      });
      el.setAttribute('animation', {property: 'position', to: '2 2 2'});
    });

    test('emits animationcomplete event twice', function (done) {
      var calledOnce = false;
      el.addEventListener('animationbegin', evt => {
        component.tick(1, 1);
        component.tick(100000, 99999);
      });

      el.addEventListener('animationcomplete', evt => {
        if (calledOnce) {
          done();
        } else {
          calledOnce = true;
          component.el.emit('startAnimation');
        }
      });

      el.setAttribute('animation', {
        property: 'position',
        to: '2 2 2',
        startEvents: 'startAnimation'
      });
      component.el.emit('startAnimation');
    });
  });

  suite('tick', function () {
    test('only calls animejs animation.tick if playing', function () {
      el.setAttribute('animation', 'property', 'position');
      let animationTickSpy = this.sinon.spy(component.animation, 'tick');
      component.animationIsPlaying = false;
      component.tick(0, 10);
      assert.notOk(animationTickSpy.called);
      component.animationIsPlaying = true;
      component.tick(0, 10);
      assert.ok(animationTickSpy.called);
      assert.equal(animationTickSpy.getCalls()[0].args[0], 10);
    });
  });

  suite('remove', function () {
    test('stops animation', function () {
      el.setAttribute('animation', {property: 'position'});
      assert.ok(component.animationIsPlaying);
      el.removeAttribute('animation');
      assert.notOk(component.animationIsPlaying);
    });

    test('removes event listeners', function (done) {
      el.setAttribute('animation', {property: 'position', startEvents: 'foo'});
      el.removeAttribute('animation');
      el.emit('foo');
      setTimeout(() => {
        assert.notOk(component.animationIsPlaying);
        done();
      }, 10);
    });
  });

  suite('stopRelatedAnimations', function () {
    test('stops related animations', function (done) {
      el.setAttribute('animation__mouseenter', {
        property: 'position',
        startEvents: 'mouseenter',
        dur: 10000
      });

      el.setAttribute('animation__mouseleave', {
        property: 'position',
        startEvents: 'mouseleave',
        dur: 10000
      });

      let mouseenterComponent = el.components['animation__mouseenter'];
      let mouseleaveComponent = el.components['animation__mouseleave'];
      assert.notOk(mouseenterComponent.animationIsPlaying);
      assert.notOk(mouseleaveComponent.animationIsPlaying);

      el.emit('mouseenter');
      setTimeout(() => {
        assert.ok(mouseenterComponent.animationIsPlaying);
        assert.notOk(mouseleaveComponent.animationIsPlaying);
        el.emit('mouseleave');
        setTimeout(() => {
          assert.notOk(mouseenterComponent.animationIsPlaying);
          assert.ok(mouseleaveComponent.animationIsPlaying);
          done();
        }, 10);
      }, 10);
    });
  });

  test('exposes anime.js', () => {
    assert.ok(window.AFRAME.ANIME);
  });
});


text:
package io.jumpon.api.library.se;

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

import org.json.JSONArray;
import org.json.JSONObject;

public class SuggestionsExtractor {

	public static Set<String> extract(JSONObject suggestions) {

		Set<String> sList = new HashSet<String>();

		JSONObject webGroup = ((JSONArray)suggestions.get("suggestionGroups")).getJSONObject(0);

		JSONArray suggList = (JSONArray)webGroup.get("searchSuggestions");

		Iterator<Object> oIt = suggList.iterator();

		while (oIt.hasNext()) {

			JSONObject s = (JSONObject)oIt.next();

			sList.add(s.getString("displayText"));

			//System.err.println(s.getString("displayText"));
		}

		return sList;

	}

}

redpajama_set_name: RedPajamaGithub


text:
#include "tool_setup.h"

#include "rawstr.h"

#define ENABLE_CURLX_PRINTF
/* use our own printf() functions */
#include "curlx.h"

#include "tool_cfgable.h"
#include "tool_msgs.h"
#include "tool_cb_hdr.h"

#include "memdebug.h" /* keep this as LAST include */

static char *parse_filename(const char *ptr, size_t len);

/*
** callback for CURLOPT_HEADERFUNCTION
*/

size_t tool_header_cb(void *ptr, size_t size, size_t nmemb, void *userdata)
{
  struct HdrCbData *hdrcbdata = userdata;
  struct OutStruct *outs = hdrcbdata->outs;
  struct OutStruct *heads = hdrcbdata->heads;
  const char *str = ptr;
  const size_t cb = size * nmemb;
  const char *end = (char*)ptr + cb;

  /*
   * Once that libcurl has called back tool_header_cb() the returned value
   * is checked against the amount that was intended to be written, if
   * it does not match then it fails with CURLE_WRITE_ERROR. So at this
   * point returning a value different from sz*nmemb indicates failure.
   */
  size_t failure = (size * nmemb) ? 0 : 1;

  if(!heads->config)
    return failure;

#ifdef DEBUGBUILD
  if(size * nmemb > (size_t)CURL_MAX_HTTP_HEADER) {
    warnf(heads->config->global, "Header data exceeds single call write "
          "limit!\n");
    return failure;
  }
#endif

  /*
   * Write header data when curl option --dump-header (-D) is given.
   */

  if(heads->config->headerfile && heads->stream) {
    size_t rc = fwrite(ptr, size, nmemb, heads->stream);
    if(rc != cb)
      return rc;
    /* flush the stream to send off what we got earlier */
    (void)fflush(heads->stream);
  }

  /*
   * This callback sets the filename where output shall be written when
   * curl options --remote-name (-O) and --remote-header-name (-J) have
   * been simultaneously given and additionally server returns an HTTP
   * Content-Disposition header specifying a filename property.
   */

  if(hdrcbdata->honor_cd_filename &&
     (cb > 20) && checkprefix("Content-disposition:", str)) {
    const char *p = str + 20;

    /* look for the 'filename=' parameter
       (encoded filenames (*=) are not supported) */
    for(;;) {
      char *filename;
      size_t len;

      while(*p && (p < end) && !ISALPHA(*p))
        p++;
      if(p > end - 9)
        break;

      if(memcmp(p, "filename=", 9)) {
        /* no match, find next parameter */
        while((p < end) && (*p != ';'))
          p++;
        continue;
      }
      p += 9;

      /* this expression below typecasts 'cb' only to avoid
         warning: signed and unsigned type in conditional expression
      */
      len = (ssize_t)cb - (p - str);
      filename = parse_filename(p, len);
      if(filename) {
        outs->filename = filename;
        outs->alloc_filename = TRUE;
        outs->is_cd_filename = TRUE;
        outs->s_isreg = TRUE;
        outs->fopened = FALSE;
        outs->stream = NULL;
        hdrcbdata->honor_cd_filename = FALSE;
        break;
      }
      else
        return failure;
    }
  }

  return cb;
}

/*
 * Copies a file name part and returns an ALLOCATED data buffer.
 */
static char *parse_filename(const char *ptr, size_t len)
{
  char *copy;
  char *p;
  char *q;
  char  stop = '\0';

  /* simple implementation of strndup() */
  copy = malloc(len+1);
  if(!copy)
    return NULL;
  memcpy(copy, ptr, len);
  copy[len] = '\0';

  p = copy;
  if(*p == '\'' || *p == '"') {
    /* store the starting quote */
    stop = *p;
    p++;
  }
  else
    stop = ';';

  /* if the filename contains a path, only use filename portion */
  q = strrchr(copy, '/');
  if(q) {
    p = q + 1;
    if(!*p) {
      Curl_safefree(copy);
      return NULL;
    }
  }

  /* If the filename contains a backslash, only use filename portion. The idea
     is that even systems that don't handle backslashes as path separators
     probably want the path removed for convenience. */
  q = strrchr(p, '\\');
  if(q) {
    p = q + 1;
    if(!*p) {
      Curl_safefree(copy);
      return NULL;
    }
  }

  /* scan for the end letter and stop there */
  q = p;
  while(*q) {
    if(q[1] && (q[0] == '\\'))
      q++;
    else if(q[0] == stop)
      break;
    q++;
  }
  *q = '\0';

  /* make sure the file name doesn't end in \r or \n */
  q = strchr(p, '\r');
  if(q)
    *q = '\0';

  q = strchr(p, '\n');
  if(q)
    *q = '\0';

  if(copy != p)
    memmove(copy, p, strlen(p) + 1);

  /* in case we built debug enabled, we allow an evironment variable
   * named CURL_TESTDIR to prefix the given file name to put it into a
   * specific directory
   */
#ifdef DEBUGBUILD
  {
    char *tdir = curlx_getenv("CURL_TESTDIR");
    if(tdir) {
      char buffer[512]; /* suitably large */
      snprintf(buffer, sizeof(buffer), "%s/%s", tdir, copy);
      Curl_safefree(copy);
      copy = strdup(buffer); /* clone the buffer, we don't use the libcurl
                                aprintf() or similar since we want to use the
                                same memory code as the "real" parse_filename
                                function */
      curl_free(tdir);
    }
  }
#endif

  return copy;
}


text:
package org.apache.cassandra.repair;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.time.DurationFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.codahale.metrics.Timer;
import org.apache.cassandra.concurrent.ExecutorPlus;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.cql3.QueryOptions;
import org.apache.cassandra.cql3.QueryProcessor;
import org.apache.cassandra.cql3.UntypedResultSet;
import org.apache.cassandra.cql3.statements.SelectStatement;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.ConsistencyLevel;
import org.apache.cassandra.db.Keyspace;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.exceptions.RepairException;
import org.apache.cassandra.gms.FailureDetector;
import org.apache.cassandra.locator.EndpointsForRange;
import org.apache.cassandra.locator.InetAddressAndPort;
import org.apache.cassandra.locator.Replica;
import org.apache.cassandra.metrics.StorageMetrics;
import org.apache.cassandra.repair.messages.RepairOption;
import org.apache.cassandra.schema.SchemaConstants;
import org.apache.cassandra.schema.SystemDistributedKeyspace;
import org.apache.cassandra.service.ActiveRepairService;
import org.apache.cassandra.service.ActiveRepairService.ParentRepairStatus;
import org.apache.cassandra.service.ClientState;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.tracing.TraceKeyspace;
import org.apache.cassandra.tracing.TraceState;
import org.apache.cassandra.tracing.Tracing;
import org.apache.cassandra.transport.messages.ResultMessage;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.Throwables;
import org.apache.cassandra.utils.UUIDGen;
import org.apache.cassandra.utils.WrappedRunnable;
import org.apache.cassandra.utils.concurrent.Future;
import org.apache.cassandra.utils.progress.ProgressEvent;
import org.apache.cassandra.utils.progress.ProgressEventNotifier;
import org.apache.cassandra.utils.progress.ProgressEventType;
import org.apache.cassandra.utils.progress.ProgressListener;

import static org.apache.cassandra.concurrent.ExecutorFactory.Global.executorFactory;
import static org.apache.cassandra.service.QueryState.forInternalCalls;
import static org.apache.cassandra.utils.Clock.Global.currentTimeMillis;
import static org.apache.cassandra.utils.Clock.Global.nanoTime;

public class RepairRunnable implements Runnable, ProgressEventNotifier, RepairNotifier
{
    private static final Logger logger = LoggerFactory.getLogger(RepairRunnable.class);

    private final StorageService storageService;
    private final int cmd;
    private final RepairOption options;
    private final String keyspace;

    private final String tag;
    private final AtomicInteger progressCounter = new AtomicInteger();
    private final int totalProgress;

    private final long creationTimeMillis = currentTimeMillis();
    private final UUID parentSession = UUIDGen.getTimeUUID();

    private final List<ProgressListener> listeners = new ArrayList<>();

    private static final AtomicInteger threadCounter = new AtomicInteger(1);
    private final AtomicReference<Throwable> firstError = new AtomicReference<>(null);

    private TraceState traceState;

    public RepairRunnable(StorageService storageService, int cmd, RepairOption options, String keyspace)
    {
        this.storageService = storageService;
        this.cmd = cmd;
        this.options = options;
        this.keyspace = keyspace;

        this.tag = "repair:" + cmd;
        // get valid column families, calculate neighbors, validation, prepare for repair + number of ranges to repair
        this.totalProgress = 4 + options.getRanges().size();
    }

    @Override
    public void addProgressListener(ProgressListener listener)
    {
        listeners.add(listener);
    }

    @Override
    public void removeProgressListener(ProgressListener listener)
    {
        listeners.remove(listener);
    }

    protected void fireProgressEvent(ProgressEvent event)
    {
        for (ProgressListener listener : listeners)
        {
            listener.progress(tag, event);
        }
    }

    @Override
    public void notification(String msg)
    {
        logger.info(msg);
        fireProgressEvent(new ProgressEvent(ProgressEventType.NOTIFICATION, progressCounter.get(), totalProgress, msg));
    }

    @Override
    public void notifyError(Throwable error)
    {
        // exception should be ignored
        if (error instanceof SomeRepairFailedException)
            return;

        if (Throwables.anyCauseMatches(error, RepairException::shouldWarn))
        {
            logger.warn("Repair {} aborted: {}", parentSession, error.getMessage());
            if (logger.isDebugEnabled())
                logger.debug("Repair {} aborted: ", parentSession, error);
        }
        else
        {
            logger.error("Repair {} failed:", parentSession, error);
        }

        StorageMetrics.repairExceptions.inc();
        String errorMessage = String.format("Repair command #%d failed with error %s", cmd, error.getMessage());
        fireProgressEvent(new ProgressEvent(ProgressEventType.ERROR, progressCounter.get(), totalProgress, errorMessage));
        firstError.compareAndSet(null, error);

        // since this can fail, update table only after updating in-memory and notification state
        maybeStoreParentRepairFailure(error);
    }

    @Override
    public void notifyProgress(String message)
    {
        logger.info(message);
        fireProgressEvent(new ProgressEvent(ProgressEventType.PROGRESS,
                                            progressCounter.incrementAndGet(),
                                            totalProgress,
                                            message));
    }

    private void skip(String msg)
    {
        notification("Repair " + parentSession + " skipped: " + msg);
        success(msg);
    }

    private void success(String msg)
    {
        fireProgressEvent(new ProgressEvent(ProgressEventType.SUCCESS, progressCounter.get(), totalProgress, msg));
        ActiveRepairService.instance.recordRepairStatus(cmd, ActiveRepairService.ParentRepairStatus.COMPLETED,
                                                        ImmutableList.of(msg));
        complete(null);
    }

    private void fail(String reason)
    {
        if (reason == null)
        {
            Throwable error = firstError.get();
            reason = error != null ? error.getMessage() : "Some repair failed";
        }
        String completionMessage = String.format("Repair command #%d finished with error", cmd);

        // Note we rely on the first message being the reason for the failure
        // when inspecting this state from RepairRunner.queryForCompletedRepair
        ActiveRepairService.instance.recordRepairStatus(cmd, ParentRepairStatus.FAILED,
                                                        ImmutableList.of(reason, completionMessage));

        complete(completionMessage);
    }

    private void complete(String msg)
    {
        long durationMillis = currentTimeMillis() - creationTimeMillis;
        if (msg == null)
        {
            String duration = DurationFormatUtils.formatDurationWords(durationMillis, true, true);
            msg = String.format("Repair command #%d finished in %s", cmd, duration);
        }

        fireProgressEvent(new ProgressEvent(ProgressEventType.COMPLETE, progressCounter.get(), totalProgress, msg));
        logger.info(options.getPreviewKind().logPrefix(parentSession) + msg);

        ActiveRepairService.instance.removeParentRepairSession(parentSession);
        TraceState localState = traceState;
        if (options.isTraced() && localState != null)
        {
            for (ProgressListener listener : listeners)
                localState.removeProgressListener(listener);
            // Because ExecutorPlus#afterExecute and this callback
            // run in a nondeterministic order (within the same thread), the
            // TraceState may have been nulled out at this point. The TraceState
            // should be traceState, so just set it without bothering to check if it
            // actually was nulled out.
            Tracing.instance.set(localState);
            Tracing.traceRepair(msg);
            Tracing.instance.stopSession();
        }

        Keyspace.open(keyspace).metric.repairTime.update(durationMillis, TimeUnit.MILLISECONDS);
    }

    public void run()
    {
        try
        {
            runMayThrow();
        }
        catch (SkipRepairException e)
        {
            skip(e.getMessage());
        }
        catch (Exception | Error e)
        {
            notifyError(e);
            fail(e.getMessage());
        }
    }

    private void runMayThrow() throws Exception
    {
        ActiveRepairService.instance.recordRepairStatus(cmd, ParentRepairStatus.IN_PROGRESS, ImmutableList.of());

        List<ColumnFamilyStore> columnFamilies = getColumnFamilies();
        String[] cfnames = columnFamilies.stream().map(cfs -> cfs.name).toArray(String[]::new);

        this.traceState = maybeCreateTraceState(columnFamilies);

        notifyStarting();

        NeighborsAndRanges neighborsAndRanges = getNeighborsAndRanges();

        maybeStoreParentRepairStart(cfnames);

        prepare(columnFamilies, neighborsAndRanges.participants, neighborsAndRanges.shouldExcludeDeadParticipants);

        repair(cfnames, neighborsAndRanges);
    }

    private List<ColumnFamilyStore> getColumnFamilies() throws IOException
    {
        String[] columnFamilies = options.getColumnFamilies().toArray(new String[options.getColumnFamilies().size()]);
        Iterable<ColumnFamilyStore> validColumnFamilies = storageService.getValidColumnFamilies(false, false, keyspace, columnFamilies);
        progressCounter.incrementAndGet();

        if (Iterables.isEmpty(validColumnFamilies))
            throw new SkipRepairException(String.format("%s Empty keyspace, skipping repair: %s", parentSession, keyspace));
        return Lists.newArrayList(validColumnFamilies);
    }

    private TraceState maybeCreateTraceState(Iterable<ColumnFamilyStore> columnFamilyStores)
    {
        if (!options.isTraced())
            return null;

        StringBuilder cfsb = new StringBuilder();
        for (ColumnFamilyStore cfs : columnFamilyStores)
            cfsb.append(", ").append(cfs.keyspace.getName()).append(".").append(cfs.name);

        UUID sessionId = Tracing.instance.newSession(Tracing.TraceType.REPAIR);
        TraceState traceState = Tracing.instance.begin("repair", ImmutableMap.of("keyspace", keyspace, "columnFamilies",
                                                                                cfsb.substring(2)));
        traceState.enableActivityNotification(tag);
        for (ProgressListener listener : listeners)
            traceState.addProgressListener(listener);
        Thread queryThread = createQueryThread(sessionId);
        queryThread.setName("RepairTracePolling");
        return traceState;
    }

    private void notifyStarting()
    {
        String message = String.format("Starting repair command #%d (%s), repairing keyspace %s with %s", cmd, parentSession, keyspace,
                                       options);
        logger.info(message);
        Tracing.traceRepair(message);
        fireProgressEvent(new ProgressEvent(ProgressEventType.START, 0, 100, message));
    }

    private NeighborsAndRanges getNeighborsAndRanges() throws RepairException
    {
        Set<InetAddressAndPort> allNeighbors = new HashSet<>();
        List<CommonRange> commonRanges = new ArrayList<>();

        //pre-calculate output of getLocalReplicas and pass it to getNeighbors to increase performance and prevent
        //calculation multiple times
        Iterable<Range<Token>> keyspaceLocalRanges = storageService.getLocalReplicas(keyspace).ranges();

        for (Range<Token> range : options.getRanges())
        {
            EndpointsForRange neighbors = ActiveRepairService.getNeighbors(keyspace, keyspaceLocalRanges, range,
                                                                           options.getDataCenters(),
                                                                           options.getHosts());
            if (neighbors.isEmpty())
            {
                if (options.ignoreUnreplicatedKeyspaces())
                {
                    logger.info("{} Found no neighbors for range {} for {} - ignoring since repairing with --ignore-unreplicated-keyspaces", parentSession, range, keyspace);
                    continue;
                }
                else
                {
                    throw RepairException.warn(String.format("Nothing to repair for %s in %s - aborting", range, keyspace));
                }
            }
            addRangeToNeighbors(commonRanges, range, neighbors);
            allNeighbors.addAll(neighbors.endpoints());
        }

        if (options.ignoreUnreplicatedKeyspaces() && allNeighbors.isEmpty())
        {
            throw new SkipRepairException(String.format("Nothing to repair for %s in %s - unreplicated keyspace is ignored since repair was called with --ignore-unreplicated-keyspaces",
                                                        options.getRanges(),
                                                        keyspace));
        }

        progressCounter.incrementAndGet();

        boolean shouldExcludeDeadParticipants = options.isForcedRepair();

        if (shouldExcludeDeadParticipants)
        {
            Set<InetAddressAndPort> actualNeighbors = Sets.newHashSet(Iterables.filter(allNeighbors, FailureDetector.instance::isAlive));
            shouldExcludeDeadParticipants = !allNeighbors.equals(actualNeighbors);
            allNeighbors = actualNeighbors;
        }
        return new NeighborsAndRanges(shouldExcludeDeadParticipants, allNeighbors, commonRanges);
    }

    private void maybeStoreParentRepairStart(String[] cfnames)
    {
        if (!options.isPreview())
        {
            SystemDistributedKeyspace.startParentRepair(parentSession, keyspace, cfnames, options);
        }
    }

    private void maybeStoreParentRepairSuccess(Collection<Range<Token>> successfulRanges)
    {
        if (!options.isPreview())
        {
            SystemDistributedKeyspace.successfulParentRepair(parentSession, successfulRanges);
        }
    }

    private void maybeStoreParentRepairFailure(Throwable error)
    {
        if (!options.isPreview())
        {
            SystemDistributedKeyspace.failParentRepair(parentSession, error);
        }
    }

    private void prepare(List<ColumnFamilyStore> columnFamilies, Set<InetAddressAndPort> allNeighbors, boolean force)
    {
        try (Timer.Context ignore = Keyspace.open(keyspace).metric.repairPrepareTime.time())
        {
            ActiveRepairService.instance.prepareForRepair(parentSession, FBUtilities.getBroadcastAddressAndPort(), allNeighbors, options, force, columnFamilies);
            progressCounter.incrementAndGet();
        }
    }

    private void repair(String[] cfnames, NeighborsAndRanges neighborsAndRanges)
    {
        RepairTask task;
        if (options.isPreview())
        {
            task = new PreviewRepairTask(options, keyspace, this, parentSession, neighborsAndRanges.filterCommonRanges(keyspace, cfnames), cfnames);
        }
        else if (options.isIncremental())
        {
            task = new IncrementalRepairTask(options, keyspace, this, parentSession, neighborsAndRanges, cfnames);
        }
        else
        {
            task = new NormalRepairTask(options, keyspace, this, parentSession, neighborsAndRanges.filterCommonRanges(keyspace, cfnames), cfnames);
        }

        ExecutorPlus executor = createExecutor();
        Future<CoordinatedRepairResult> f = task.perform(executor);
        f.addCallback((result, failure) -> {
            try
            {
                if (failure != null)
                {
                    notifyError(failure);
                    fail(failure.getMessage());
                }
                else
                {
                    maybeStoreParentRepairSuccess(result.successfulRanges);
                    if (result.hasFailed())
                    {
                        fail(null);
                    }
                    else
                    {
                        success(task.name() + " completed successfully");
                        ActiveRepairService.instance.cleanUp(parentSession, neighborsAndRanges.participants);
                    }
                }
            }
            finally
            {
                executor.shutdownNow();
            }
        });
    }

    private ExecutorPlus createExecutor()
    {
        return executorFactory()
                .localAware()
                .withJmxInternal()
                .pooled("Repair#" + cmd, options.getJobThreads());
    }

    private static void addRangeToNeighbors(List<CommonRange> neighborRangeList, Range<Token> range, EndpointsForRange neighbors)
    {
        Set<InetAddressAndPort> endpoints = neighbors.endpoints();
        Set<InetAddressAndPort> transEndpoints = neighbors.filter(Replica::isTransient).endpoints();

        for (CommonRange commonRange : neighborRangeList)
        {
            if (commonRange.matchesEndpoints(endpoints, transEndpoints))
            {
                commonRange.ranges.add(range);
                return;
            }
        }

        List<Range<Token>> ranges = new ArrayList<>();
        ranges.add(range);
        neighborRangeList.add(new CommonRange(endpoints, transEndpoints, ranges));
    }

    private Thread createQueryThread(final UUID sessionId)
    {
        return executorFactory().startThread("Repair-Runnable-" + threadCounter.incrementAndGet(), new WrappedRunnable()
        {
            // Query events within a time interval that overlaps the last by one second. Ignore duplicates. Ignore local traces.
            // Wake up upon local trace activity. Query when notified of trace activity with a timeout that doubles every two timeouts.
            public void runMayThrow() throws Exception
            {
                TraceState state = Tracing.instance.get(sessionId);
                if (state == null)
                    throw new Exception("no tracestate");

                String format = "select event_id, source, source_port, activity from %s.%s where session_id = ? and event_id > ? and event_id < ?;";
                String query = String.format(format, SchemaConstants.TRACE_KEYSPACE_NAME, TraceKeyspace.EVENTS);
                SelectStatement statement = (SelectStatement) QueryProcessor.parseStatement(query).prepare(ClientState.forInternalCalls());

                ByteBuffer sessionIdBytes = ByteBufferUtil.bytes(sessionId);
                InetAddressAndPort source = FBUtilities.getBroadcastAddressAndPort();

                HashSet<UUID>[] seen = new HashSet[]{ new HashSet<>(), new HashSet<>() };
                int si = 0;
                UUID uuid;

                long tlast = currentTimeMillis(), tcur;

                TraceState.Status status;
                long minWaitMillis = 125;
                long maxWaitMillis = 1000 * 1024L;
                long timeout = minWaitMillis;
                boolean shouldDouble = false;

                while ((status = state.waitActivity(timeout)) != TraceState.Status.STOPPED)
                {
                    if (status == TraceState.Status.IDLE)
                    {
                        timeout = shouldDouble ? Math.min(timeout * 2, maxWaitMillis) : timeout;
                        shouldDouble = !shouldDouble;
                    }
                    else
                    {
                        timeout = minWaitMillis;
                        shouldDouble = false;
                    }
                    ByteBuffer tminBytes = ByteBufferUtil.bytes(UUIDGen.minTimeUUID(tlast - 1000));
                    ByteBuffer tmaxBytes = ByteBufferUtil.bytes(UUIDGen.maxTimeUUID(tcur = currentTimeMillis()));
                    QueryOptions options = QueryOptions.forInternalCalls(ConsistencyLevel.ONE, Lists.newArrayList(sessionIdBytes,
                                                                                tminBytes,
                                                                                tmaxBytes));
                    ResultMessage.Rows rows = statement.execute(forInternalCalls(), options, nanoTime());
                    UntypedResultSet result = UntypedResultSet.create(rows.result);

                    for (UntypedResultSet.Row r : result)
                    {
                        int port = DatabaseDescriptor.getStoragePort();
                        if (r.has("source_port"))
                            port = r.getInt("source_port");
                        InetAddressAndPort eventNode = InetAddressAndPort.getByAddressOverrideDefaults(r.getInetAddress("source"), port);
                        if (source.equals(eventNode))
                            continue;
                        if ((uuid = r.getUUID("event_id")).timestamp() > (tcur - 1000) * 10000)
                            seen[si].add(uuid);
                        if (seen[si == 0 ? 1 : 0].contains(uuid))
                            continue;
                        String message = String.format("%s: %s", r.getInetAddress("source"), r.getString("activity"));
                        notification(message);
                    }
                    tlast = tcur;

                    si = si == 0 ? 1 : 0;
                    seen[si].clear();
                }
            }
        });
    }

    private static final class SkipRepairException extends RuntimeException
    {
        SkipRepairException(String message)
        {
            super(message);
        }
    }

    static final class NeighborsAndRanges
    {
        final boolean shouldExcludeDeadParticipants;
        final Set<InetAddressAndPort> participants;
        final List<CommonRange> commonRanges;

        NeighborsAndRanges(boolean shouldExcludeDeadParticipants, Set<InetAddressAndPort> participants, List<CommonRange> commonRanges)
        {
            this.shouldExcludeDeadParticipants = shouldExcludeDeadParticipants;
            this.participants = participants;
            this.commonRanges = commonRanges;
        }

        /**
         * When in the force mode, removes dead nodes from common ranges (not contained within `allNeighbors`),
         * and exludes ranges left without any participants
         * When not in the force mode, no-op.
         */
        List<CommonRange> filterCommonRanges(String keyspace, String[] tableNames)
        {
            if (!shouldExcludeDeadParticipants)
            {
                return commonRanges;
            }
            else
            {
                logger.debug("force flag set, removing dead endpoints if possible");

                List<CommonRange> filtered = new ArrayList<>(commonRanges.size());

                for (CommonRange commonRange : commonRanges)
                {
                    Set<InetAddressAndPort> endpoints = ImmutableSet.copyOf(Iterables.filter(commonRange.endpoints, participants::contains));
                    Set<InetAddressAndPort> transEndpoints = ImmutableSet.copyOf(Iterables.filter(commonRange.transEndpoints, participants::contains));
                    Preconditions.checkState(endpoints.containsAll(transEndpoints), "transEndpoints must be a subset of endpoints");

                    // this node is implicitly a participant in this repair, so a single endpoint is ok here
                    if (!endpoints.isEmpty())
                    {
                        Set<InetAddressAndPort> skippedReplicas = Sets.difference(commonRange.endpoints, endpoints);
                        skippedReplicas.forEach(endpoint -> logger.info("Removing a dead node {} from repair for ranges {} due to -force", endpoint, commonRange.ranges));
                        filtered.add(new CommonRange(endpoints, transEndpoints, commonRange.ranges, !skippedReplicas.isEmpty()));
                    }
                    else
                    {
                        logger.warn("Skipping forced repair for ranges {} of tables {} in keyspace {}, as no neighbor nodes are live.",
                                    commonRange.ranges, Arrays.asList(tableNames), keyspace);
                    }
                }
                Preconditions.checkState(!filtered.isEmpty(), "Not enough live endpoints for a repair");
                return filtered;
            }
        }
    }
}


text:
package xccov

import (
	"testing"

	"gopkg.in/src-d/go-git.v4/plumbing/object"

	"github.com/codeclimate/test-reporter/env"
	"github.com/stretchr/testify/require"
)

func Test_Format(t *testing.T) {
	gb := env.GitBlob
	defer func() { env.GitBlob = gb }()
	env.GitBlob = func(s string, c *object.Commit) (string, error) {
		return s, nil
	}

	r := require.New(t)

	rb := Formatter{
		Path: "./xccov_example.json",
	}
	rep, err := rb.Format()
	r.NoError(err)

	r.InDelta(rep.CoveredPercent, 20.93, 1)

	sf := rep.SourceFiles["Documents/github/ww/ios-SuperApp/Pods/BundleA/BundleA/BundleA.m"]
	r.Equal(sf.CoveredPercent, 0.0)
	sfLc := sf.LineCounts
	r.Equal(sfLc.Covered, 0)
	r.Equal(sfLc.Missed, 10)
	r.Equal(sfLc.Total, 10)

	sf = rep.SourceFiles["Documents/github/ww/ios-SuperApp/Pods/SuperClass/SuperClass/SuperClass.m"]
	r.InDelta(sf.CoveredPercent, 22.68, 1)
	sfLc = sf.LineCounts
	r.Equal(sfLc.Covered, 27)
	r.Equal(sfLc.Missed, 92)
	r.Equal(sfLc.Total, 119)
}


text:
import {Component, Input} from '@angular/core';
import {WeightedFeatureCategory} from '../../shared/model/results/weighted-feature-category.model';

@Component({

  selector: 'app-weight-distribution',
  template: `

  `

})

/**
 * This component gives a visual representation of the content.
 */
export class WeightDistributionComponent {
  /**
   * List of refinement that are currently displayed.
   *
   * @type {Map<any, any>}
   */
  @Input() features: WeightedFeatureCategory[] = [];

  /**
   * Returns the total weightPercentage of all refinement currently known
   * to the component.
   *
   * @returns {number} Total weightPercentage of all refinement.
   */
  public getTotal(): number {
    return this.features
      .map(f => f.weightPercentage)
      .reduce((a, b) => a + b);
  }

  /**
   * Returns the width (in percent) of an individual feature.
   *
   * @param feature Feature for which the widht should be calculated.
   * @returns {number} Width in percent.
   */
  public getWidth(feature: WeightedFeatureCategory) {
    return (feature.weightPercentage / this.getTotal()) + '%';
  }
}


text:
"""
Abstract base classes used by the actual models
"""

from __future__ import print_function
import os
import os.path
import netCDF4
import sys
import platform
from datetime import datetime
from .dmp import DMP
from dmpr import __version__

class Model(object):
    """
    Base class of model processors

    .. py:attribute:: run_meta

        Dictionary for extra metadata to be added to the output file.
        ``run_meta['runid']`` is used to determine the output path

    .. py:attribute:: dmp

        :py:class:`~dmpr.dmp.DMP` attached to this model (may be ``None`` if
        not known yet)
    """

    def __init__(self):
        self.user = os.environ.get('USER', 'unknown')
        self.project = os.environ.get('PROJECT', 'unknown')
        self.dmp = None
        self.run_meta = {}
        self.attr_prefix = 'dmpr.'
        self.archivedir = os.path.join('/short',self.project,self.user,'dmp')

    def read_configs(self, rundir):
        """
        Read the run configuration, setting up run-based metadata

        To be overridden by model classes
        """
        raise NotImplementedError('To be overridden by the model class')

    def out_dir(self):
        """
        Returns the output directory for this model run
        """
        return os.path.join(self.archivedir, self.run_meta['runid'])

    def out_filename(self, infile):
        """
        Returns the base output filename

        May be overriden by the model class

        :param str infile: Filename of the input file as passed to ``dmpr post``

        >>> Model().out_filename('/path/to/foo.nc')
        'foo.nc'
        """
        return os.path.basename(infile)

    def post(self, infile, outfile=None):
        """
        Post-process a file and add metadata from the DMP

        Calls :py:meth:`~Model.post_impl()` to do the main processing, which
        gets overridden by model classes.

        :param str infile: Filename of the input file
        :param str outfile: Filename of the output file (defaults to :py:func:`~dmpr.base.Model.out_filename()`)
        :return: Path to the processed output file
        :rtype: str
        """
        outdir = self.out_dir()

        try:
            os.makedirs(outdir)
        except OSError:
            pass

        if outfile is None:
            outfile = self.out_filename(infile)

        outfile = os.path.join(outdir, outfile)
        self.post_impl(infile, outfile)

        self.add_meta(infile, outfile)

        return outfile

    def post_impl(self, infile, outfile):
        """
        Post-processing implementation

        Must be overridden by the model class

        :param str infile: Filename of the input file
        :param str outfile: Filename of the output file (created by this function)
        """
        raise NotImplementedError('To be overridden by the model class')

    def add_meta(self, infile, outfile):
        """
        Add file-level metadata to the processed file, including history and
        anything added to the dictionary :py:attr:`Model.run_meta`.

        :param str infile: Filename of the input file
        :param str outfile: Filename of the output file
        """
        with netCDF4.Dataset(outfile, mode="a") as f:
            if self.dmp is not None:
                f.setncatts(self.dmp.file_metadata())

            f.setncatts(self.run_meta)

            add_history(f, infile)

def add_history(dataset, infile):
    """
    Add history information to a dataset

    :param netCDF4.Dataset dataset: Dataset to modify
    :param str infile: Filename of the input file
    """
    try:
        history = dataset.getncattr('history')
    except AttributeError:
        history = ""
    history += "%s %s:%s(%s) post %s\n"%(
            datetime.now().isoformat(),
            platform.node(),
            sys.argv[0], __version__,
            infile)
    dataset.setncattr('history', history)


text:
'''
@Copyright:LintCode
@Author:   lilsweetcaligula
@Problem:  http://www.lintcode.com/problem/unique-characters
@Language: Python
@Datetime: 17-02-15 14:58
'''

class Solution:
    # @param s: a string
    # @return: a boolean
    def isUnique(self, s):
        ordered = sorted(s)

        for i in range(1, len(ordered)):
            if ordered[i] == ordered[i - 1]:
                return False

        return True


text:
({
shouldRender({geolocation}) {
  return Boolean(geolocation);
},
render({geolocation: {latitude, longitude}}) {
  return {latitude, longitude};
},
template: html`
<good-map flex zoom="12" latitude$="{{latitude}}" longitude$="{{longitude}}"></good-map>
`
});


text:
#ifndef _CORECRYPTO_CCDIGEST_PRIV_H_
#define _CORECRYPTO_CCDIGEST_PRIV_H_

#include <corecrypto/ccdigest.h>

void ccdigest_final_common(const struct ccdigest_info *di,
                           ccdigest_ctx_t ctx, void *digest);
void ccdigest_final_64be(const struct ccdigest_info *di, ccdigest_ctx_t,
                         unsigned char *digest);
void ccdigest_final_64le(const struct ccdigest_info *di, ccdigest_ctx_t,
                         unsigned char *digest);

#endif /* _CORECRYPTO_CCDIGEST_PRIV_H_ */


text:
<?php
namespace DAErp\Service\HumanResource\Recruitment;

use DACore\Service\AbstractCrudService;

class Curriculum extends AbstractCrudService
{

}


text:
this_dir = File.expand_path(File.dirname(__FILE__))
lib_dir = File.join(this_dir, 'lib')
$LOAD_PATH.unshift(lib_dir) unless $LOAD_PATH.include?(lib_dir)

require 'grpc'
require 'helloworld_services'

class GreeterServer < Helloworld::Greeter::Service
  def say_hello(hello_req, _unused_call)
    p "New Request: Hello #{hello_req.name}"
    Helloworld::HelloReply.new(message: "Hello #{hello_req.name}")
  end
end

def main
  s = GRPC::RpcServer.new
  s.add_http2_port('0.0.0.0:5000', :this_port_is_insecure)
  s.handle(GreeterServer)
  s.run_till_terminated
end

main


text:
package com.amazonaws.services.greengrass.model;

import javax.annotation.Generated;

/**
 * The minimum level of log statements that should be logged by the OTA Agent during an update.
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum UpdateAgentLogLevel {

    NONE("NONE"),
    TRACE("TRACE"),
    DEBUG("DEBUG"),
    VERBOSE("VERBOSE"),
    INFO("INFO"),
    WARN("WARN"),
    ERROR("ERROR"),
    FATAL("FATAL");

    private String value;

    private UpdateAgentLogLevel(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return UpdateAgentLogLevel corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static UpdateAgentLogLevel fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (UpdateAgentLogLevel enumEntry : UpdateAgentLogLevel.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
<?php
require_once __DIR__ . '/../vendor/view-components/testing-helpers/bootstrap/bootstrap.php';
use Illuminate\Database\Capsule\Manager as DB;
$capsule = new DB;
$capsule->addConnection([
    'driver'   => 'sqlite',
    'database' => __DIR__ . '/../db.sqlite',
    'prefix'   => '',
]);
$capsule->setAsGlobal();
$capsule->bootEloquent();
// set timezone for timestamps etc
date_default_timezone_set('UTC');


text:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using EasyHttpClient.Utilities;

namespace EasyHttpClient.Attributes
{
    public enum JTokenType
    {
        JObject, JArray
    }

    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
    public class JsonBodyAttribute : Attribute, IParameterScopeAttribute
    {
        public JsonBodyAttribute()
            : this(null)
        {

        }
        public JsonBodyAttribute(string name)
        {
            this.Name = name;
            this.JTokenType = JTokenType.JObject;
        }

        public ParameterScope Scope
        {
            get
            {
                return ParameterScope.Json;
            }
        }
        public string Name
        {
            get;
            set;
        }

        public JTokenType JTokenType
        {
            get;
            set;
        }
        private static readonly JsonMergeSettings JsonMergeSettings = new JsonMergeSettings()
        {
            MergeArrayHandling = MergeArrayHandling.Merge
        };

        internal void ProcessParameter(HttpRequestMessageBuilder requestBuilder, object parameterValue)
        {
            switch (this.JTokenType)
            {
                case JTokenType.JArray:
                    this.ProcessAsJArray(requestBuilder, null, parameterValue);
                    break;
                case JTokenType.JObject:
                    this.ProcessAsJObject(requestBuilder, null, parameterValue);
                    break;
            }
        }

        public void ProcessParameter(HttpRequestMessageBuilder requestBuilder, ParameterInfo parameterInfo, object parameterValue)
        {
            switch (this.JTokenType)
            {
                case JTokenType.JArray:
                    this.ProcessAsJArray(requestBuilder, parameterInfo, parameterValue);
                    break;
                case JTokenType.JObject:
                    this.ProcessAsJObject(requestBuilder, parameterInfo, parameterValue);
                    break;
            }
        }

        void ProcessAsJObject(HttpRequestMessageBuilder requestBuilder, ParameterInfo parameterInfo, object parameterValue)
        {
            var jObj = requestBuilder.JsonBody;
            var objectType = parameterValue != null ? parameterValue.GetType() : parameterInfo.ParameterType;
            var val = parameterValue;

            if (objectType.IsBulitInType() || objectType.IsEnumerableType())
            {
                val = new Dictionary<string, object>{
                {this.Name ?? parameterInfo.Name, parameterValue}
               };
            }

            if (val != null)
            {
                var jsonVal = JObject.FromObject(val, requestBuilder.JsonSerializer); ;
                if (jObj == null)
                {
                    jObj = jsonVal;
                }
                else
                {
                    if (!(jObj is JObject))
                    {
                        throw new NotSupportedException("Not support merge JObject and JArray");
                    }
                    jObj = mergeJsonObjects((JObject)jObj, jsonVal);
                }
            }
            requestBuilder.JsonBody = jObj;
        }

        void ProcessAsJArray(HttpRequestMessageBuilder requestBuilder, ParameterInfo parameterInfo, object parameterValue)
        {
            var jObj = requestBuilder.JsonBody;
            var objectType = parameterValue != null ? parameterValue.GetType() : parameterInfo.ParameterType;

            if (!objectType.IsEnumerableType())
            {
                throw new NotSupportedException("JsonArrayAttribute for IEnumerable parameter only");
            }
            var val = parameterValue;

            if (val != null)
            {
                var jsonVal = JArray.FromObject(val, requestBuilder.JsonSerializer); ;
                jObj = jsonVal;
            }
            requestBuilder.JsonBody = jObj;
        }

        private static JObject mergeJsonObjects(params JObject[] jObjects)
        {
            Dictionary<string, JToken> json = new Dictionary<string, JToken>();
            foreach (var jObject in jObjects)
            {
                foreach (var property in jObject)
                {
                    string name = property.Key;
                    JToken value = property.Value;

                    json[property.Key] = property.Value;
                }
            }
            var newJObject = new JObject();
            foreach (var j in json)
            {
                newJObject.Add(j.Key, j.Value);
            }
            return newJObject;
        }
    }
}


text:
require 'rails_helper'

RSpec.describe "Reports", type: :request do
  describe "GET /reports" do
    it "works! (now write some real specs)" do
      get reports_path
      expect(response).to have_http_status(200)
    end
  end
end


text:
require 'data_mapper'
require "#{File.dirname(__FILE__)}/config"

class Upload

  include DataMapper::Resource

  property :id, Serial
  property :branch, String
  property :ref, String
  property :prev, String
  property :user, String
  property :approver, String
  property :status, String
  property :received_at, DateTime
  property :completed_at, DateTime

  def log_file
    "upload-#{@id}.log"
  end

  def github_url
    MiseConfig.read_config(file)[:github_url]
  end

  def github_link
    if prev
      "#{github_url}/compare/#{prev}...#{ref}"
    else
      "#{github_url}/commit/#{ref}"
    end
  end

  def short_hashes
    if prev
      "#{prev[0...7]}..#{ref[0...7]}"
    else
      ref[0...7]
    end
  end

end


text:
<?php

/**
 * This function introduces the theme options into the 'Appearance' menu and into a top-level
 * 'global Theme' menu.
 */
function global_options_theme_menu() {

	$menu = add_menu_page(
		'Global Settings', 					// The title to be displayed in the browser window for this page.
		'Global Settings',					// The text to be displayed for this menu item
		'edit_pages',					// Which type of users can see this menu item
		'global_settings',			// The unique ID - that is, the slug - for this menu item
		'global_settings_display'				// The name of the function to call when rendering this menu's page
	);

	add_action('load-'.$menu, 'global_options_save');

	// add_menu_page(
	// 	'Global Theme Options',					// The value used to populate the browser's title bar when the menu page is active
	// 	'Global Theme Options',					// The text of the menu in the administrator's sidebar
	// 	'edit_pages',					// What roles are able to access the menu
	// 	'global_theme_menu',				// The ID used to bind submenu items to this menu
	// 	'global_settings_display'				// The callback function used to render this menu
	// );

	add_submenu_page(
		'global_theme_menu',				// The ID of the top-level menu page to which this submenu item belongs
		__( 'Display Options', 'global' ),			// The value used to populate the browser's title bar when the menu page is active
		__( 'Display Options', 'global' ),			// The label of this submenu item displayed in the menu
		'edit_pages',					// What roles are able to access this submenu item
		'global_settings_display_options',	               // The ID used to represent this submenu item
		'global_settings_display'			// The callback function used to render the options for this submenu item
	);

	add_submenu_page(
		'global_theme_menu',
		__( 'Social Options', 'global' ),
		__( 'Social Options', 'global' ),
		'edit_pages',
		'global_settings_social_options',
		create_function( null, 'global_settings_display( "social_options" );' )
	);

} // end global_options_theme_menu
add_action( 'admin_menu', 'global_options_theme_menu' );

// modify capability
function global_settings_display_options_capability( $capability ) {
	return 'edit_others_posts';
}
add_filter( 'option_page_capability_global_settings_display_options', 'global_settings_display_options_capability' );

// modify capability
function global_settings_social_options_capability( $capability ) {
	return 'edit_others_posts';
}
add_filter( 'option_page_capability_global_settings_social_options', 'global_settings_social_options_capability' );

function global_options_save() {
	if(isset($_GET['settings-updated']) && $_GET['settings-updated']) {
		$display_options = get_option('global_settings_display_options');
		$address = $display_options['address'];
		$city = $display_options['city'];
		$state = $display_options['state'];
		$zip = $display_options['zip'];

		$url = 'http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address='.urlencode($address).',%20'.$zip.'%20'.$city.'%20'.$state.'%20';

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

		$response = json_decode(curl_exec($ch), true);

		if(!empty($response['results'])) {
			$display_options['latitude'] = $response['results'][0]['geometry']['location']['lat'];
			$display_options['longitude'] = $response['results'][0]['geometry']['location']['lng'];

			update_option('global_settings_display_options', $display_options);
		}
	}
}

/**
 * Renders a simple page to display for the theme menu defined above.
 */
function global_settings_display( $active_tab = '' ) {
?>

<?php _e( 'Global Theme Options', 'global' ); ?>

		<?php settings_errors(); ?>

		<?php if( isset( $_GET[ 'tab' ] ) ) {
			$active_tab = $_GET[ 'tab' ];
		} else if( $active_tab == 'social_options' ) {
			$active_tab = 'social_options';
		} else {
			$active_tab = 'display_options';
		} // end if/else ?>

			<a href="?page=global_settings&tab=display_options" class="nav-tab <?php echo $active_tab == 'display_options' ? 'nav-tab-active' : ''; ?>"><?php _e( 'Display Options', 'global' ); ?>
			<a href="?page=global_settings&tab=social_options" class="nav-tab <?php echo $active_tab == 'social_options' ? 'nav-tab-active' : ''; ?>"><?php _e( 'Social Options', 'global' ); ?>

		<form method="post" action="options.php">
			<?php

				if( $active_tab == 'display_options' ) {

					settings_fields( 'global_settings_display_options' );
					do_settings_sections( 'global_settings_display_options' );

				} elseif( $active_tab == 'social_options' ) {

					settings_fields( 'global_settings_social_options' );
					do_settings_sections( 'global_settings_social_options' );

				} else {

				} // end if/else

				submit_button();

			?>
		</form>

<?php
} // end global_settings_display

/* ------------------------------------------------------------------------ *
 * Setting Registration
 * ------------------------------------------------------------------------ */

/**
 * Provides default values for the Social Options.
 */
function global_theme_default_social_options() {

	$defaults = array(
		'twitter' => '',
		'facebook' => '',
		'instagram'	=> '',
		'pinterest'	=> '',
		'linkedin'	=> '',
	);

	return apply_filters( 'global_theme_default_social_options', $defaults );

} // end global_theme_default_social_options

/**
 * Provides default values for the display Options.
 */
function global_theme_default_display_options() {

	$defaults = array(
		'phone'	=> '',
		'address' => '',
		'city' => '',
		'state' => '',
		'zip' => '',
		'latitude' => '',
		'longitude' => '',
		'email' => '',
		'lease_online' => '',
	);

	return apply_filters( 'global_theme_default_display_options', $defaults );

} // end global_theme_default_display_options

/**
 * Initializes the theme's display options page by registering the Sections,
 * Fields, and Settings.
 *
 * This function is registered with the 'admin_init' hook.
 */
function global_initialize_theme_options() {

	// If the theme options don't exist, create them.
	if( false == get_option( 'global_settings_display_options' ) ) {
		add_option( 'global_settings_display_options', apply_filters( 'global_theme_default_display_options', global_theme_default_display_options() ) );
	} // end if

	// First, we register a section. This is necessary since all future options must belong to a
	add_settings_section(
		'general_settings_section',			// ID used to identify this section and with which to register options
		__( 'display Options', 'global' ),		// Title to be displayed on the administration page
		'global_general_options_callback',	// Callback used to render the description of the section
		'global_settings_display_options'		// Page on which to add this section of options
	);

	// Next, we'll introduce the fields for toggling the visibility of content elements.
	add_settings_field(
		'phone',						// ID used to identify the field throughout the theme
		__( 'Phone Number', 'global' ),							// The label to the left of the option interface element
		'global_phone_callback',	// The name of the function responsible for rendering the option interface
		'global_settings_display_options',	// The page on which this option will be displayed
		'general_settings_section',			// The name of the section to which this field belongs
		array()								// The array of arguments to pass to the callback. In this case, just a description.
	);

	add_settings_field(
		'address',
		__( 'Address', 'global' ),
		'global_address_callback',
		'global_settings_display_options',
		'general_settings_section',
		array()
	);

	add_settings_field(
		'city',
		__( 'City', 'global' ),
		'global_city_callback',
		'global_settings_display_options',
		'general_settings_section',
		array()
	);

	add_settings_field(
		'state',
		__( 'State', 'global' ),
		'global_state_callback',
		'global_settings_display_options',
		'general_settings_section',
		array()
	);

	add_settings_field(
		'zip',
		__( 'Zip Code', 'global' ),
		'global_zip_callback',
		'global_settings_display_options',
		'general_settings_section',
		array()
	);

	add_settings_field(
		'latitude',
		__( 'Latitude', 'global' ),
		'global_latitude_callback',
		'global_settings_display_options',
		'general_settings_section',
		array()
	);

	add_settings_field(
		'longitude',
		__( 'Longitude', 'global' ),
		'global_longitude_callback',
		'global_settings_display_options',
		'general_settings_section',
		array()
	);

	add_settings_field(
		'email',
		__( 'Email', 'global' ),
		'global_email_callback',
		'global_settings_display_options',
		'general_settings_section',
		array()
	);

	// Finally, we register the fields with WordPress
	register_setting(
		'global_settings_display_options',
		'global_settings_display_options'
	);

} // end global_initialize_theme_options
add_action( 'admin_init', 'global_initialize_theme_options' );

/**
 * Initializes the theme's social options by registering the Sections,
 * Fields, and Settings.
 *
 * This function is registered with the 'admin_init' hook.
 */
function global_theme_initialize_social_options() {

	if( false == get_option( 'global_settings_social_options' ) ) {
		add_option( 'global_settings_social_options', apply_filters( 'global_theme_default_social_options', global_theme_default_social_options() ) );
	} // end if

	add_settings_section(
		'social_settings_section',			// ID used to identify this section and with which to register options
		__( 'Social Options', 'global' ),		// Title to be displayed on the administration page
		'global_social_options_callback',	// Callback used to render the description of the section
		'global_settings_social_options'		// Page on which to add this section of options
	);

	add_settings_field(
		'twitter',
		'Twitter',
		'global_twitter_callback',
		'global_settings_social_options',
		'social_settings_section'
	);

	add_settings_field(
		'facebook',
		'Facebook',
		'global_facebook_callback',
		'global_settings_social_options',
		'social_settings_section'
	);

	add_settings_field(
		'instagram',
		'Instagram',
		'global_instagram_callback',
		'global_settings_social_options',
		'social_settings_section'
	);

	add_settings_field(
		'pinterest',
		'Pinterest',
		'global_pinterest_callback',
		'global_settings_social_options',
		'social_settings_section'
	);

	add_settings_field(
		'linkedin',
		'LinkedIn',
		'global_linkedin_callback',
		'global_settings_social_options',
		'social_settings_section'
	);

	register_setting(
		'global_settings_social_options',
		'global_settings_social_options',
		'global_theme_sanitize_social_options'
	);

} // end global_theme_initialize_social_options
add_action( 'admin_init', 'global_theme_initialize_social_options' );

/* ------------------------------------------------------------------------ *
 * Section Callbacks
 * ------------------------------------------------------------------------ */

/**
 * This function provides a simple description for the General Options page.
 *
 * It's called from the 'global_initialize_theme_options' function by being passed as a parameter
 * in the add_settings_section function.
 */
function global_general_options_callback() {
	echo '
' . __( 'Provide your display website details', 'global' ) . '
';
} // end global_general_options_callback

/**
 * This function provides a simple description for the Social Options page.
 *
 * It's called from the 'global_theme_initialize_social_options' function by being passed as a parameter
 * in the add_settings_section function.
 */
function global_social_options_callback() {
	echo '
' . __( 'Provide the URL to the social networks you\'d like to display.', 'global' ) . '
';
} // end global_general_options_callback

/* ------------------------------------------------------------------------ *
 * Field Callbacks
 * ------------------------------------------------------------------------ */

function global_phone_callback($args) {

	$options = get_option( 'global_settings_display_options' );

	$value = '';
	if( isset( $options['phone'] ) ) {
		$value = $options['phone'];
	} // end if

	// Render the output
	echo '<input type="text" id="phone" name="global_settings_display_options[phone]" value="' . $value . '" />';

} // end global_phone_callback

function global_address_callback($args) {

	$options = get_option( 'global_settings_display_options' );

	$value = '';
	if( isset( $options['address'] ) ) {
		$value = $options['address'];
	} // end if

	// Render the output
	echo '<input type="text" id="address" name="global_settings_display_options[address]" value="' . $value . '" />';

} // end global_address_callback

function global_city_callback($args) {

	$options = get_option( 'global_settings_display_options' );

	$value = '';
	if( isset( $options['city'] ) ) {
		$value = $options['city'];
	} // end if

	// Render the output
	echo '<input type="text" id="city" name="global_settings_display_options[city]" value="' . $value . '" />';

} // end global_city_callback

function global_state_callback($args) {

	$options = get_option( 'global_settings_display_options' );

	$value = '';
	if( isset( $options['state'] ) ) {
		$value = $options['state'];
	} // end if

	// Render the output
	echo '<input type="text" id="state" name="global_settings_display_options[state]" value="' . $value . '" />';

} // end global_state_callback

function global_zip_callback($args) {

	$options = get_option( 'global_settings_display_options' );

	$value = '';
	if( isset( $options['zip'] ) ) {
		$value = $options['zip'];
	} // end if

	// Render the output
	echo '<input type="text" id="zip" name="global_settings_display_options[zip]" value="' . $value . '" />';

} // end global_zip_callback

function global_latitude_callback($args) {

	$options = get_option( 'global_settings_display_options' );

	$value = '';
	if( isset( $options['latitude'] ) ) {
		$value = $options['latitude'];
	} // end if

	// Render the output
	echo '<input type="text" id="latitude" name="global_settings_display_options[latitude]" value="' . $value . '" />';

} // end global_latitude_callback

function global_longitude_callback($args) {

	$options = get_option( 'global_settings_display_options' );

	$value = '';
	if( isset( $options['longitude'] ) ) {
		$value = $options['longitude'];
	} // end if

	// Render the output
	echo '<input type="text" id="longitude" name="global_settings_display_options[longitude]" value="' . $value . '" />';

} // end global_longitude_callback

function global_email_callback($args) {

	$options = get_option( 'global_settings_display_options' );

	$value = '';
	if( isset( $options['email'] ) ) {
		$value = $options['email'];
	} // end if

	// Render the output
	echo '<input type="text" id="email" name="global_settings_display_options[email]" value="' . $value . '" />';

} // end global_email_callback

function global_twitter_callback() {

	// First, we read the social options collection
	$options = get_option( 'global_settings_social_options' );

	// Next, we need to make sure the element is defined in the options. If not, we'll set an empty string.
	$url = '';
	if( isset( $options['twitter'] ) ) {
		$url = esc_url( $options['twitter'] );
	} // end if

	// Render the output
	echo '<input type="text" id="twitter" name="global_settings_social_options[twitter]" value="' . $url . '" />';

} // end global_twitter_callback

function global_facebook_callback() {

	$options = get_option( 'global_settings_social_options' );

	$url = '';
	if( isset( $options['facebook'] ) ) {
		$url = esc_url( $options['facebook'] );
	} // end if

	// Render the output
	echo '<input type="text" id="facebook" name="global_settings_social_options[facebook]" value="' . $url . '" />';

} // end global_facebook_callback

function global_instagram_callback() {

	$options = get_option( 'global_settings_social_options' );

	$url = '';
	if( isset( $options['instagram'] ) ) {
		$url = esc_url( $options['instagram'] );
	} // end if

	// Render the output
	echo '<input type="text" id="instagram" name="global_settings_social_options[instagram]" value="' . $url . '" />';

} // end global_instagram_callback

function global_pinterest_callback() {

	$options = get_option( 'global_settings_social_options' );

	$url = '';
	if( isset( $options['pinterest'] ) ) {
		$url = esc_url( $options['pinterest'] );
	} // end if

	// Render the output
	echo '<input type="text" id="pinterest" name="global_settings_social_options[pinterest]" value="' . $url . '" />';

} // end global_codepen_callback

function global_linkedin_callback() {

	$options = get_option( 'global_settings_social_options' );

	$url = '';
	if( isset( $options['linkedin'] ) ) {
		$url = esc_url( $options['linkedin'] );
	} // end if

	// Render the output
	echo '<input type="text" id="linkedin" name="global_settings_social_options[linkedin]" value="' . $url . '" />';

} // end global_linkedin_callback

/* ------------------------------------------------------------------------ *
 * Setting Callbacks
 * ------------------------------------------------------------------------ */

/**
 * Sanitization callback for the social options. Since each of the social options are text inputs,
 * this function loops through the incoming option and strips all tags and slashes from the value
 * before serializing it.
 *
 * @params	$input	The unsanitized collection of options.
 *
 * @returns			The collection of sanitized values.
 */
function global_theme_sanitize_social_options( $input ) {

	// Define the array for the updated options
	$output = array();

	// Loop through each of the options sanitizing the data
	foreach( $input as $key => $val ) {

		if( isset ( $input[$key] ) ) {
			$output[$key] = esc_url_raw( strip_tags( stripslashes( $input[$key] ) ) );
		} // end if

	} // end foreach

	// Return the new collection
	return apply_filters( 'global_theme_sanitize_social_options', $output, $input );

} // end global_theme_sanitize_social_options

?>


text:
package com.ryft.spark.connector.rdd

import com.fasterxml.jackson.core.JsonFactory
import com.ryft.spark.connector.rest.RyftRestConnectionComponent
import com.ryft.spark.connector.util.RyftStreamParser
import org.apache.spark.Logging

/**
 * An iterator that allows to iterate through the stream of JSON objects.
 * Used MessagePackFactory parser by default.
 *
 * `hasNext` reads next element from the stream to accumulator
 * and returns true if element exists
 *
 */
abstract class NextIterator[T, R](partition: RDDPartition,
    ryftRestConnection: RyftRestConnectionComponent,
    transform: Map[String, Any] => T)
    extends Iterator[R] with Logging {

  logInfo(s"Compute partition, idx: ${partition.idx}")

  private val is = ryftRestConnection.getInputStream
  private val parser = new JsonFactory().createParser(is)

  // scalastyle:off
  protected var accumulator = Map.empty[String, String]
  // scalastyle:on

  override def hasNext: Boolean = {
    val json = RyftStreamParser.parseNext(parser)
    json match {
      case acc: Map[String, String] =>
        val map = json.asInstanceOf[Map[String, String]]
        accumulator = map
        true
      case _ =>
        logInfo(s"Iterator processing ended for partition with idx: ${partition.idx}")
        is.close()
        false
    }
  }

  override def next(): R
}


text:
package util

import (
	"fmt"
	"os"
)

func Exists(path string) bool {
	_, err := os.Stat(path)
	if err == nil {
		return true
	}
	if os.IsNotExist(err) {
		return false
	}
	return true
}

func CleanLocks() error {

	var err error
	err = CleanLock("top")
	err = CleanLock("new")
	err = CleanLock("ask")
	err = CleanLock("jobs")
	err = CleanLock("show")
	return err
}

func CleanLock(storyType string) error {

	err := os.Remove(fmt.Sprintf("./storage/locks/%s.lock", storyType))
	return err
}


text:
package com.amazonaws.services.accessanalyzer.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum FindingStatus {

    ACTIVE("ACTIVE"),
    ARCHIVED("ARCHIVED"),
    RESOLVED("RESOLVED");

    private String value;

    private FindingStatus(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return FindingStatus corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static FindingStatus fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (FindingStatus enumEntry : FindingStatus.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
class Solution {
public:
    enum Color { WHITE, GRAY, BLACK };

    vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
        vector<int> result;
        unordered_map<int, Color> lookup;
        for (int i = 0; i < graph.size(); ++i) {
            if (dfs(graph, i, &lookup)) {
                result.emplace_back(i);
            }
        }
        return result;
    }

private:
    bool dfs(const vector<vector<int>>& graph, int node,
             unordered_map<int, Color> *lookup) {
        if ((*lookup)[node] != WHITE) {
            return (*lookup)[node] == BLACK;
        }
        (*lookup)[node] = GRAY;
        for (const auto& child : graph[node]) {
            if ((*lookup)[child] == BLACK) {
                continue;
            }
            if ((*lookup)[child] == GRAY ||
                !dfs(graph, child, lookup)) {
                return false;
            }
        }
        (*lookup)[node] = BLACK;
        return true;
    }
};


text:
#ifndef InspectorDOMAgent_h
#define InspectorDOMAgent_h

#include "EventTarget.h"
#include "InjectedScript.h"
#include "InjectedScriptManager.h"
#include "InspectorBaseAgent.h"
#include "InspectorFrontend.h"
#include "InspectorOverlay.h"
#include "InspectorValues.h"
#include "Timer.h"

#include <wtf/Deque.h>
#include <wtf/ListHashSet.h>
#include <wtf/HashMap.h>
#include <wtf/HashSet.h>
#include <wtf/OwnPtr.h>
#include <wtf/PassOwnPtr.h>
#include <wtf/RefPtr.h>
#include <wtf/Vector.h>
#include <wtf/text/AtomicString.h>

namespace WebCore {
class ContainerNode;
class CharacterData;
class DOMEditor;
class Document;
class Element;
class Event;
class InspectorFrontend;
class InspectorHistory;
class InspectorOverlay;
class InspectorPageAgent;
class HitTestResult;
class HTMLElement;
class InspectorState;
class InstrumentingAgents;
class NameNodeMap;
class Node;
class RevalidateStyleAttributeTask;
class ScriptValue;
class ShadowRoot;

struct HighlightConfig;

typedef String ErrorString;

#if ENABLE(INSPECTOR)

struct EventListenerInfo {
    EventListenerInfo(Node* node, const AtomicString& eventType, const EventListenerVector& eventListenerVector)
        : node(node)
        , eventType(eventType)
        , eventListenerVector(eventListenerVector)
    {
    }

    Node* node;
    const AtomicString eventType;
    const EventListenerVector eventListenerVector;
};

class InspectorDOMAgent : public InspectorBaseAgent<InspectorDOMAgent>, public InspectorBackendDispatcher::DOMCommandHandler {
    WTF_MAKE_NONCOPYABLE(InspectorDOMAgent);
public:
    struct DOMListener {
        virtual ~DOMListener()
        {
        }
        virtual void didRemoveDocument(Document*) = 0;
        virtual void didRemoveDOMNode(Node*) = 0;
        virtual void didModifyDOMAttr(Element*) = 0;
    };

    static PassOwnPtr<InspectorDOMAgent> create(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorState* inspectorState, InjectedScriptManager* injectedScriptManager, InspectorOverlay* overlay)
    {
        return adoptPtr(new InspectorDOMAgent(instrumentingAgents, pageAgent, inspectorState, injectedScriptManager, overlay));
    }

    static String toErrorString(const ExceptionCode&);

    ~InspectorDOMAgent();

    virtual void setFrontend(InspectorFrontend*);
    virtual void clearFrontend();
    virtual void restore();

    Vector<Document*> documents();
    void reset();

    // Methods called from the frontend for DOM nodes inspection.
    virtual void querySelector(ErrorString*, int nodeId, const String& selectors, int* elementId);
    virtual void querySelectorAll(ErrorString*, int nodeId, const String& selectors, RefPtr<TypeBuilder::Array<int> >& result);
    virtual void getDocument(ErrorString*, RefPtr<TypeBuilder::DOM::Node>& root);
    virtual void requestChildNodes(ErrorString*, int nodeId);
    virtual void setAttributeValue(ErrorString*, int elementId, const String& name, const String& value);
    virtual void setAttributesAsText(ErrorString*, int elementId, const String& text, const String* name);
    virtual void removeAttribute(ErrorString*, int elementId, const String& name);
    virtual void removeNode(ErrorString*, int nodeId);
    virtual void setNodeName(ErrorString*, int nodeId, const String& name, int* newId);
    virtual void getOuterHTML(ErrorString*, int nodeId, WTF::String* outerHTML);
    virtual void setOuterHTML(ErrorString*, int nodeId, const String& outerHTML);
    virtual void setNodeValue(ErrorString*, int nodeId, const String& value);
    virtual void getEventListenersForNode(ErrorString*, int nodeId, RefPtr<TypeBuilder::Array<TypeBuilder::DOM::EventListener> >& listenersArray);
    virtual void performSearch(ErrorString*, const String& whitespaceTrimmedQuery, String* searchId, int* resultCount);
    virtual void getSearchResults(ErrorString*, const String& searchId, int fromIndex, int toIndex, RefPtr<TypeBuilder::Array<int> >&);
    virtual void discardSearchResults(ErrorString*, const String& searchId);
    virtual void resolveNode(ErrorString*, int nodeId, const String* objectGroup, RefPtr<TypeBuilder::Runtime::RemoteObject>& result);
    virtual void getAttributes(ErrorString*, int nodeId, RefPtr<TypeBuilder::Array<String> >& result);
    virtual void setInspectModeEnabled(ErrorString*, bool enabled, const RefPtr<InspectorObject>* highlightConfig);
    virtual void requestNode(ErrorString*, const String& objectId, int* nodeId);
    virtual void pushNodeByPathToFrontend(ErrorString*, const String& path, int* nodeId);
    virtual void hideHighlight(ErrorString*);
    virtual void highlightRect(ErrorString*, int x, int y, int width, int height, const RefPtr<InspectorObject>* color, const RefPtr<InspectorObject>* outlineColor);
    virtual void highlightNode(ErrorString*, int nodeId, const RefPtr<InspectorObject>& highlightConfig);
    virtual void highlightFrame(ErrorString*, const String& frameId, const RefPtr<InspectorObject>* color, const RefPtr<InspectorObject>* outlineColor);
    virtual void moveTo(ErrorString*, int nodeId, int targetNodeId, const int* anchorNodeId, int* newNodeId);
    virtual void undo(ErrorString*);
    virtual void redo(ErrorString*);
    virtual void markUndoableState(ErrorString*);

    void getEventListeners(Node*, Vector<EventListenerInfo>& listenersArray, bool includeAncestors);

    // Methods called from the InspectorInstrumentation.
    void setDocument(Document*);
    void releaseDanglingNodes();

    void mainFrameDOMContentLoaded();
    void loadEventFired(Document*);

    void didInsertDOMNode(Node*);
    void didRemoveDOMNode(Node*);
    void willModifyDOMAttr(Element*, const AtomicString& oldValue, const AtomicString& newValue);
    void didModifyDOMAttr(Element*, const AtomicString& name, const AtomicString& value);
    void didRemoveDOMAttr(Element*, const AtomicString& name);
    void styleAttributeInvalidated(const Vector<Element*>& elements);
    void characterDataModified(CharacterData*);
    void didInvalidateStyleAttr(Node*);
    void didPushShadowRoot(Element* host, ShadowRoot*);
    void willPopShadowRoot(Element* host, ShadowRoot*);

    int pushNodeToFrontend(ErrorString*, int documentNodeId, Node*);
    Node* nodeForId(int nodeId);
    int boundNodeId(Node*);
    void setDOMListener(DOMListener*);

    static String documentURLString(Document*);

    PassRefPtr<TypeBuilder::Runtime::RemoteObject> resolveNode(Node*, const String& objectGroup);
    bool handleMousePress();
    bool handleTouchEvent(Node*);
    void mouseDidMoveOverElement(const HitTestResult&, unsigned modifierFlags);
    void inspect(Node*);
    void focusNode();

    InspectorHistory* history() { return m_history.get(); }

    // We represent embedded doms as a part of the same hierarchy. Hence we treat children of frame owners differently.
    // We also skip whitespace text nodes conditionally. Following methods encapsulate these specifics.
    static Node* innerFirstChild(Node*);
    static Node* innerNextSibling(Node*);
    static Node* innerPreviousSibling(Node*);
    static unsigned innerChildNodeCount(Node*);
    static Node* innerParentNode(Node*);
    static bool isWhitespace(Node*);

    Node* assertNode(ErrorString*, int nodeId);
    Element* assertElement(ErrorString*, int nodeId);
    Document* assertDocument(ErrorString*, int nodeId);

    // Methods called from other agents.
    InspectorPageAgent* pageAgent() { return m_pageAgent; }

private:
    InspectorDOMAgent(InstrumentingAgents*, InspectorPageAgent*, InspectorState*, InjectedScriptManager*, InspectorOverlay*);

    void setSearchingForNode(ErrorString*, bool enabled, InspectorObject* highlightConfig);
    PassOwnPtr<HighlightConfig> highlightConfigFromInspectorObject(ErrorString*, InspectorObject* highlightInspectorObject);

    // Node-related methods.
    typedef HashMap<RefPtr<Node>, int> NodeToIdMap;
    int bind(Node*, NodeToIdMap*);
    void unbind(Node*, NodeToIdMap*);

    Node* assertEditableNode(ErrorString*, int nodeId);
    Element* assertEditableElement(ErrorString*, int nodeId);

    int pushNodePathToFrontend(Node*);
    void pushChildNodesToFrontend(int nodeId);

    bool hasBreakpoint(Node*, int type);
    void updateSubtreeBreakpoints(Node* root, uint32_t rootMask, bool value);
    void descriptionForDOMEvent(Node* target, int breakpointType, bool insertion, PassRefPtr<InspectorObject> description);

    PassRefPtr<TypeBuilder::DOM::Node> buildObjectForNode(Node*, int depth, NodeToIdMap*);
    PassRefPtr<TypeBuilder::Array<String> > buildArrayForElementAttributes(Element*);
    PassRefPtr<TypeBuilder::Array<TypeBuilder::DOM::Node> > buildArrayForContainerChildren(Node* container, int depth, NodeToIdMap* nodesMap);
    PassRefPtr<TypeBuilder::DOM::EventListener> buildObjectForEventListener(const RegisteredEventListener&, const AtomicString& eventType, Node*);

    Node* nodeForPath(const String& path);

    void discardBindings();

    InspectorPageAgent* m_pageAgent;
    InjectedScriptManager* m_injectedScriptManager;
    InspectorOverlay* m_overlay;
    InspectorFrontend::DOM* m_frontend;
    DOMListener* m_domListener;
    NodeToIdMap m_documentNodeToIdMap;
    // Owns node mappings for dangling nodes.
    Vector<OwnPtr<NodeToIdMap> > m_danglingNodeToIdMaps;
    HashMap<int, Node*> m_idToNode;
    HashMap<int, NodeToIdMap*> m_idToNodesMap;
    HashSet<int> m_childrenRequested;
    int m_lastNodeId;
    RefPtr<Document> m_document;
    typedef HashMap<String, Vector<RefPtr<Node> > > SearchResults;
    SearchResults m_searchResults;
    OwnPtr<RevalidateStyleAttributeTask> m_revalidateStyleAttrTask;
    RefPtr<Node> m_nodeToFocus;
    bool m_searchingForNode;
    OwnPtr<HighlightConfig> m_inspectModeHighlightConfig;
    OwnPtr<InspectorHistory> m_history;
    OwnPtr<DOMEditor> m_domEditor;
    bool m_suppressAttributeModifiedEvent;
};

#endif // ENABLE(INSPECTOR)

} // namespace WebCore

#endif // !defined(InspectorDOMAgent_h)