text:
package com.android.volley.toolbox;

import com.android.volley.NetworkResponse;
import com.android.volley.Response;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

@RunWith(RobolectricTestRunner.class) public class JsonRequestCharsetTest {

    /**
     * String in Czech - "Retezec v cestine."
     */
    private static final String TEXT_VALUE = "\u0158et\u011bzec v \u010de\u0161tin\u011b.";
    private static final String TEXT_NAME = "text";
    private static final int TEXT_INDEX = 0;

    /**
     * Copyright symbol has different encoding in utf-8 and ISO-8859-1,
     * and it doesn't exists in ISO-8859-2
     */
    private static final String COPY_VALUE = "\u00a9";
    private static final String COPY_NAME = "copyright";
    private static final int COPY_INDEX = 1;

    private static String jsonObjectString() throws Exception {
        JSONObject json = new JSONObject().put(TEXT_NAME, TEXT_VALUE).put(COPY_NAME, COPY_VALUE);
        return json.toString();
    }

    private static String jsonArrayString() throws Exception {
        JSONArray json = new JSONArray().put(TEXT_INDEX, TEXT_VALUE).put(COPY_INDEX, COPY_VALUE);
        return json.toString();
    }

    @Test public void defaultCharsetJsonObject() throws Exception {
        // UTF-8 is default charset for JSON
        byte[] data = jsonObjectString().getBytes(Charset.forName("UTF-8"));
        NetworkResponse network = new NetworkResponse(data);
        JsonObjectRequest objectRequest = new JsonObjectRequest("", null, null, null);
        Response<JSONObject> objectResponse = objectRequest.parseNetworkResponse(network);

        assertNotNull(objectResponse);
        assertTrue(objectResponse.isSuccess());
        assertEquals(TEXT_VALUE, objectResponse.result.getString(TEXT_NAME));
        assertEquals(COPY_VALUE, objectResponse.result.getString(COPY_NAME));
    }

    @Test public void defaultCharsetJsonArray() throws Exception {
        // UTF-8 is default charset for JSON
        byte[] data = jsonArrayString().getBytes(Charset.forName("UTF-8"));
        NetworkResponse network = new NetworkResponse(data);
        JsonArrayRequest arrayRequest = new JsonArrayRequest("", null, null);
        Response<JSONArray> arrayResponse = arrayRequest.parseNetworkResponse(network);

        assertNotNull(arrayResponse);
        assertTrue(arrayResponse.isSuccess());
        assertEquals(TEXT_VALUE, arrayResponse.result.getString(TEXT_INDEX));
        assertEquals(COPY_VALUE, arrayResponse.result.getString(COPY_INDEX));
    }

    @Test public void specifiedCharsetJsonObject() throws Exception {
        byte[] data = jsonObjectString().getBytes(Charset.forName("ISO-8859-1"));
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json; charset=iso-8859-1");
        NetworkResponse network = new NetworkResponse(data, headers);
        JsonObjectRequest objectRequest = new JsonObjectRequest("", null, null, null);
        Response<JSONObject> objectResponse = objectRequest.parseNetworkResponse(network);

        assertNotNull(objectResponse);
        assertTrue(objectResponse.isSuccess());
        //don't check the text in Czech, ISO-8859-1 doesn't support some Czech characters
        assertEquals(COPY_VALUE, objectResponse.result.getString(COPY_NAME));
    }

    @Test public void specifiedCharsetJsonArray() throws Exception {
        byte[] data = jsonArrayString().getBytes(Charset.forName("ISO-8859-2"));
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json; charset=iso-8859-2");
        NetworkResponse network = new NetworkResponse(data, headers);
        JsonArrayRequest arrayRequest = new JsonArrayRequest("", null, null);
        Response<JSONArray> arrayResponse = arrayRequest.parseNetworkResponse(network);

        assertNotNull(arrayResponse);
        assertTrue(arrayResponse.isSuccess());
        assertEquals(TEXT_VALUE, arrayResponse.result.getString(TEXT_INDEX));
        // don't check the copyright symbol, ISO-8859-2 doesn't have it, but it has Czech characters
    }
}

redpajama_set_name: RedPajamaGithub


text:
import sys

fh = open(sys.argv[1], 'w')

filenames = sys.argv[2:]

for filename in filenames:
  subfile = open(filename)
  data = subfile.read()
  subfile.close()
  fh.write(data)

fh.close()


text:
Types = {
    Messages: {
        HELLO: 0,
        WELCOME: 1,
        SPAWN: 2,
        DESPAWN: 3,
        MOVE: 4,
        LOOTMOVE: 5,
        AGGRO: 6,
        ATTACK: 7,
        HIT: 8,
        HURT: 9,
        HEALTH: 10,
        CHAT: 11,
        LOOT: 12,
        EQUIP: 13,
        DROP: 14,
        TELEPORT: 15,
        DAMAGE: 16,
        POPULATION: 17,
        KILL: 18,
        LIST: 19,
        WHO: 20,
        ZONE: 21,
        DESTROY: 22,
        HP: 23,
        BLINK: 24,
        OPEN: 25,
        CHECK: 26
    },

    Entities: {
        WARRIOR: 1,

        // Mobs
        RAT: 2,
        SKELETON: 3,
        GOBLIN: 4,
        OGRE: 5,
        SPECTRE: 6,
        CRAB: 7,
        BAT: 8,
        WIZARD: 9,
        EYE: 10,
        SNAKE: 11,
        SKELETON2: 12,
        BOSS: 13,
        DEATHKNIGHT: 14,

        // Armors
        FIREFOX: 20,
        CLOTHARMOR: 21,
        LEATHERARMOR: 22,
        MAILARMOR: 23,
        PLATEARMOR: 24,
        REDARMOR: 25,
        GOLDENARMOR: 26,

        // Objects
        FLASK: 35,
        BURGER: 36,
        CHEST: 37,
        FIREPOTION: 38,
        CAKE: 39,

        // NPCs
        GUARD: 40,
        KING: 41,
        OCTOCAT: 42,
        VILLAGEGIRL: 43,
        VILLAGER: 44,
        PRIEST: 45,
        SCIENTIST: 46,
        AGENT: 47,
        RICK: 48,
        NYAN: 49,
        SORCERER: 50,
        BEACHNPC: 51,
        FORESTNPC: 52,
        DESERTNPC: 53,
        LAVANPC: 54,
        CODER: 55,

        // Weapons
        SWORD1: 60,
        SWORD2: 61,
        REDSWORD: 62,
        GOLDENSWORD: 63,
        MORNINGSTAR: 64,
        AXE: 65,
        BLUESWORD: 66
    },

    Orientations: {
        UP: 1,
        DOWN: 2,
        LEFT: 3,
        RIGHT: 4
    }
};

var kinds = {
    warrior: [Types.Entities.WARRIOR, "player"],

    rat: [Types.Entities.RAT, "mob"],
    skeleton: [Types.Entities.SKELETON , "mob"],
    goblin: [Types.Entities.GOBLIN, "mob"],
    ogre: [Types.Entities.OGRE, "mob"],
    spectre: [Types.Entities.SPECTRE, "mob"],
    deathknight: [Types.Entities.DEATHKNIGHT, "mob"],
    crab: [Types.Entities.CRAB, "mob"],
    snake: [Types.Entities.SNAKE, "mob"],
    bat: [Types.Entities.BAT, "mob"],
    wizard: [Types.Entities.WIZARD, "mob"],
    eye: [Types.Entities.EYE, "mob"],
    skeleton2: [Types.Entities.SKELETON2, "mob"],
    boss: [Types.Entities.BOSS, "mob"],

    sword1: [Types.Entities.SWORD1, "weapon"],
    sword2: [Types.Entities.SWORD2, "weapon"],
    axe: [Types.Entities.AXE, "weapon"],
    redsword: [Types.Entities.REDSWORD, "weapon"],
    bluesword: [Types.Entities.BLUESWORD, "weapon"],
    goldensword: [Types.Entities.GOLDENSWORD, "weapon"],
    morningstar: [Types.Entities.MORNINGSTAR, "weapon"],

    firefox: [Types.Entities.FIREFOX, "armor"],
    clotharmor: [Types.Entities.CLOTHARMOR, "armor"],
    leatherarmor: [Types.Entities.LEATHERARMOR, "armor"],
    mailarmor: [Types.Entities.MAILARMOR, "armor"],
    platearmor: [Types.Entities.PLATEARMOR, "armor"],
    redarmor: [Types.Entities.REDARMOR, "armor"],
    goldenarmor: [Types.Entities.GOLDENARMOR, "armor"],

    flask: [Types.Entities.FLASK, "object"],
    cake: [Types.Entities.CAKE, "object"],
    burger: [Types.Entities.BURGER, "object"],
    chest: [Types.Entities.CHEST, "object"],
    firepotion: [Types.Entities.FIREPOTION, "object"],

    guard: [Types.Entities.GUARD, "npc"],
    villagegirl: [Types.Entities.VILLAGEGIRL, "npc"],
    villager: [Types.Entities.VILLAGER, "npc"],
    coder: [Types.Entities.CODER, "npc"],
    scientist: [Types.Entities.SCIENTIST, "npc"],
    priest: [Types.Entities.PRIEST, "npc"],
    king: [Types.Entities.KING, "npc"],
    rick: [Types.Entities.RICK, "npc"],
    nyan: [Types.Entities.NYAN, "npc"],
    sorcerer: [Types.Entities.SORCERER, "npc"],
    agent: [Types.Entities.AGENT, "npc"],
    octocat: [Types.Entities.OCTOCAT, "npc"],
    beachnpc: [Types.Entities.BEACHNPC, "npc"],
    forestnpc: [Types.Entities.FORESTNPC, "npc"],
    desertnpc: [Types.Entities.DESERTNPC, "npc"],
    lavanpc: [Types.Entities.LAVANPC, "npc"],

    getType: function(kind) {
        return kinds[Types.getKindAsString(kind)][1];
    }
};

Types.rankedWeapons = [
    Types.Entities.SWORD1,
    Types.Entities.SWORD2,
    Types.Entities.AXE,
    Types.Entities.MORNINGSTAR,
    Types.Entities.BLUESWORD,
    Types.Entities.REDSWORD,
    Types.Entities.GOLDENSWORD
];

Types.rankedArmors = [
    Types.Entities.CLOTHARMOR,
    Types.Entities.LEATHERARMOR,
    Types.Entities.MAILARMOR,
    Types.Entities.PLATEARMOR,
    Types.Entities.REDARMOR,
    Types.Entities.GOLDENARMOR
];

Types.getWeaponRank = function(weaponKind) {
    return _.indexOf(Types.rankedWeapons, weaponKind);
};

Types.getArmorRank = function(armorKind) {
    return _.indexOf(Types.rankedArmors, armorKind);
};

Types.isPlayer = function(kind) {
    return kinds.getType(kind) === "player";
};

Types.isMob = function(kind) {
    return kinds.getType(kind) === "mob";
};

Types.isNpc = function(kind) {
    return kinds.getType(kind) === "npc";
};

Types.isCharacter = function(kind) {
    return Types.isMob(kind) || Types.isNpc(kind) || Types.isPlayer(kind);
};

Types.isArmor = function(kind) {
    return kinds.getType(kind) === "armor";
};

Types.isWeapon = function(kind) {
    return kinds.getType(kind) === "weapon";
};

Types.isObject = function(kind) {
    return kinds.getType(kind) === "object";
};

Types.isChest = function(kind) {
    return kind === Types.Entities.CHEST;
};

Types.isItem = function(kind) {
    return Types.isWeapon(kind)
        || Types.isArmor(kind)
        || (Types.isObject(kind) && !Types.isChest(kind));
};

Types.isHealingItem = function(kind) {
    return kind === Types.Entities.FLASK
        || kind === Types.Entities.BURGER;
};

Types.isExpendableItem = function(kind) {
    return Types.isHealingItem(kind)
        || kind === Types.Entities.FIREPOTION
        || kind === Types.Entities.CAKE;
};

Types.getKindFromString = function(kind) {
    if(kind in kinds) {
        return kinds[kind][0];
    }
};

Types.getKindAsString = function(kind) {
    for(var k in kinds) {
        if(kinds[k][0] === kind) {
            return k;
        }
    }
};

Types.forEachKind = function(callback) {
    for(var k in kinds) {
        callback(kinds[k][0], k);
    }
};

Types.forEachArmor = function(callback) {
    Types.forEachKind(function(kind, kindName) {
        if(Types.isArmor(kind)) {
            callback(kind, kindName);
        }
    });
};

Types.forEachMobOrNpcKind = function(callback) {
    Types.forEachKind(function(kind, kindName) {
        if(Types.isMob(kind) || Types.isNpc(kind)) {
            callback(kind, kindName);
        }
    });
};

Types.forEachArmorKind = function(callback) {
    Types.forEachKind(function(kind, kindName) {
        if(Types.isArmor(kind)) {
            callback(kind, kindName);
        }
    });
};

Types.getOrientationAsString = function(orientation) {
    switch(orientation) {
        case Types.Orientations.LEFT: return "left"; break;
        case Types.Orientations.RIGHT: return "right"; break;
        case Types.Orientations.UP: return "up"; break;
        case Types.Orientations.DOWN: return "down"; break;
    }
};

Types.getRandomItemKind = function(item) {
    var all = _.union(this.rankedWeapons, this.rankedArmors),
        forbidden = [Types.Entities.SWORD1, Types.Entities.CLOTHARMOR],
        itemKinds = _.difference(all, forbidden),
        i = Math.floor(Math.random() * _.size(itemKinds));

    return itemKinds[i];
};

Types.getMessageTypeAsString = function(type) {
    var typeName;
    _.each(Types.Messages, function(value, name) {
        if(value === type) {
            typeName = name;
        }
    });
    if(!typeName) {
        typeName = "UNKNOWN";
    }
    return typeName;
};

if(!(typeof exports === 'undefined')) {
    module.exports = Types;
}


text:
<?php

namespace Drupal\field;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityAccessControlHandler;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;

/**
 * Defines the access control handler for the field storage config entity type.
 *
 * @see \Drupal\field\Entity\FieldStorageConfig
 */
class FieldStorageConfigAccessControlHandler extends EntityAccessControlHandler {

  /**
   * {@inheritdoc}
   */
  protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
    /** \Drupal\field\FieldStorageConfigInterface $entity */
    if ($operation === 'delete') {
      if ($entity->isLocked()) {
        return AccessResult::forbidden()->addCacheableDependency($entity);
      }
      else {
        return AccessResult::allowedIfHasPermission($account, 'administer ' . $entity->getTargetEntityTypeId() . ' fields')->addCacheableDependency($entity);
      }
    }
    return AccessResult::allowedIfHasPermission($account, 'administer ' . $entity->getTargetEntityTypeId() . ' fields');
  }

}


text:
import React from 'react';
import AceEditor from 'react-ace';

import 'brace';
import 'brace/mode/javascript';
import 'brace/theme/chaos';
import 'brace/ext/language_tools';

import classNames from 'classnames';

export default class CodeEditor extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      code: this.props.code
    };

    this.handleKeyPress = this.handleKeyPress.bind(this);
    this.onChange = this.onChange.bind(this);
    this.exit = this.exit.bind(this);
    this.save = this.save.bind(this);
  }

  onChange(code) {
    this.setState({code});
  }

  get isDirty() {
    return this.state.code !== this.props.code;
  }

  exit() {
    if (!this.isDirty || confirm('Are you sure you want to discard your changes?')) {
      this.props.exit();
    }
  }

  save() {
    this.props.save(this.state.code);
  }

  handleKeyPress(e) {
    if (e.key === 'Escape') {
      this.exit();
    } else if (e.key === 's' && e.ctrlKey) {
      this.save();
      e.preventDefault();
    }
  }

  componentDidMount() {
    document.addEventListener('keydown', this.handleKeyPress, false);
  }

  componentWillUnmount() {
    document.removeEventListener('keydown', this.handleKeyPress, false);
  }

  renderTitleBar() {
    const saveButtonClassnames = classNames('save', {active: this.isDirty});

    return (

        editing script at position {this.props.index}{this.isDirty ? '*' : ' '}
         | press control+s to save, esc to go back to scene
        ✓

    );
  }

  renderAceEditor() {
    return (
      <AceEditor
        style={{
          position: 'absolute',
          top: '25px',
          left: 0,
          opacity: 0.95
        }}
        width="100%"
        height="calc(100% - 25px)"
        focus={true}
        fontSize={16}
        mode="javascript"
        theme="chaos"
        onChange={this.onChange}
        showPrintMargin={false}
        editorProps={{
          $blockScrolling: true
        }}
        setOptions={{
          enableBasicAutocompletion: true,
          enableLiveAutocompletion: true,
          enableSnippets: false,
          showLineNumbers: true,
          tabSize: 2
        }}
        value={this.state.code}
      />
    );
  }

  render() {
    return (

        {this.renderTitleBar()}
        {this.renderAceEditor()}

    );
  }
}


text:
package org.apache.beehive.netui.pageflow;

import javax.servlet.http.HttpServletRequest;

/**
 *
 */
public interface RequestParameterHandler
{
    public void process(HttpServletRequest request, String key, String expr, ProcessPopulate.ExpressionUpdateNode node);
}


text:
<manifest package="com.nobrain.android.colorparser">

    <application>

    </application>

</manifest>


text:
require 'dotenv'; Dotenv.load("../.env")
require 'boxr'
require 'twilio-ruby' #make sure you 'gem install twilio-ruby'

# Get your Account Sid, Auth Token, and phone number from twilio.com/user/account
TWILIO_PHONE_NUMBER= ENV['TWILIO_PHONE_NUMBER']
BOX_TRIGGER_EVENT = 'UPLOAD'

@twilio_client = Twilio::REST::Client.new(ENV['TWILIO_ACCOUNT_SID'], ENV['TWILIO_AUTH_TOKEN'])
@box_client = Boxr::Client.new(ENV['BOX_DEVELOPER_TOKEN'])

def send_sms_to_box_user(recipient, message)
  begin
    phone = @box_client.user(recipient, fields: [:phone]).phone
    unless phone.nil? || phone.empty?
      begin
        full_phone = "+1#{phone}"
        @twilio_client.account.messages.create(
          from: ENV['TWILIO_PHONE_NUMBER'],
          to: full_phone,
          body: message
        )
        puts "Sent SMS to user #{recipient.name} at #{full_phone}"
      rescue Twilio::REST::RequestError => e
        puts e.message
      end
    end
  rescue Boxr::BoxrError => e
    #most likely error is that a collaborator is an external user and Box threw a 404
    puts e.message
  end
end

#need to look back in time to make sure we get a valid stream position;
#normally your app will be persisting the last known stream position and you wouldn't have to look this up
now = Time.now.utc
start_date = now - (60*60*24) #one day ago
result = @box_client.enterprise_events(created_after: start_date, created_before: now)

#now that we have the latest stream position let's start monitoring in real-time
@box_client.enterprise_events_stream(result.next_stream_position, event_type: BOX_TRIGGER_EVENT, refresh_period: 5) do |result|
  if result.events.count==0
    puts "no new #{BOX_TRIGGER_EVENT} events..."
  else
    puts "detected #{result.events.count} new #{BOX_TRIGGER_EVENT}"
    result.events.each do |e|
      folder = @box_client.folder(e.source.parent)
      message = "Document '#{e.source.item_name}' uploaded to folder '#{folder.name}' by #{e.created_by.name}"

      #first notify the folder owner
      send_sms_to_box_user(folder.owned_by, message)

      #now notify collaborators
      user_collabs = @box_client.folder_collaborations(folder).select{|c| c.accessible_by.type=='user'}
      user_collabs.each{|c| send_sms_to_box_user(c.accessible_by, message)}
    end
  end
end


text:
2. Create a bare clone of the repository.
   ``` command-line
   $ git clone --bare https://{{ site.data.variables.command_line.codeblock }}/<em>exampleuser</em>/<em>old-repository</em>.git
   ```
3. Mirror-push to the new repository.
   ``` command-line
   $ cd <em>old-repository</em>.git
   $ git push --mirror https://{{ site.data.variables.command_line.codeblock }}/<em>exampleuser</em>/<em>new-repository</em>.git
   ```


text:
package com.melon.modules.jdk8.sys.entity;

import com.melon.common.persistence.TreeEntity;
import org.hibernate.validator.constraints.Length;

/**
 * 区域Entity
 *
 * @author melon
 * @version 2013-05-15
 */
public class Area extends TreeEntity<Area> {

    private static final long serialVersionUID = 1L;
    // private Area parent; // 父级编号
    // private String parentIds; // 所有父级编号
    private String code; // 区域编码
    // private String name; // 区域名称
    // private Integer sort; // 排序
    private String type; // 区域类型(1:国家;2:省份、直辖市;3:地市;4:区县)

    public Area() {
        super();
        this.sort = 30;
    }

    public Area(String id) {
        super(id);
    }

    // @JsonBackReference
    // @NotNull
    public Area getParent() {
        return parent;
    }

    public void setParent(Area parent) {
        this.parent = parent;
    }
    //
    // @Length(min=1, max=2000)
    // public String getParentIds() {
    // return parentIds;
    // }
    //
    // public void setParentIds(String parentIds) {
    // this.parentIds = parentIds;
    // }
    //
    // @Length(min=1, max=100)
    // public String getName() {
    // return name;
    // }
    //
    // public void setName(String name) {
    // this.name = name;
    // }
    //
    // public Integer getSort() {
    // return sort;
    // }
    //
    // public void setSort(Integer sort) {
    // this.sort = sort;
    // }

    @Length(min = 1, max = 1)
    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Length(min = 0, max = 100)
    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
    //
    // public String getParentId() {
    // return parent != null && parent.getId() != null ? parent.getId() : "0";
    // }

    @Override
    public String toString() {
        return name;
    }
}


text:
function ripple(fx,fy,angle,amplitude) {
    gl.ripple = gl.ripple || warpShader('\
        uniform vec4 xform;\
        uniform float amplitude;\
        uniform vec2 center;\
        mat2 mat=mat2(xform.xy,xform.zw);\
    ', '\
        coord -= center;\
        coord += amplitude*sin(mat*coord);\
        coord += center;\
    ');

    simpleShader.call(this, gl.ripple, {
        xform: [
           Math.cos(angle)*fx, Math.sin(angle)*fy,
          -Math.sin(angle)*fx, Math.cos(angle)*fy
        ],
        amplitude: amplitude,
        center: [this.width/2, this.height/2],
        texSize: [this.width, this.height]
    });

    return this;
}


text:
All Notable changes to `@@@package_name` will be documented in this file

## alpha - @@@data

### Added
- Initial release


text:
"""
collection of utility functions
"""

# Copyright (c) 2011 Yubico AB
# See the file COPYING for licence statement.

import struct

__all__ = [
    # constants
    # functions
    'hexdump',
    'group',
    'key_handle_to_int',
    # classes
]

import pyhsm.exception

def hexdump(src, length=8):
    """ Produce a string hexdump of src, for debug output."""
    if not src:
        return str(src)
    src = input_validate_str(src, 'src')
    offset = 0
    result = ''
    for this in group(src, length):
        hex_s = ' '.join(["%02x" % ord(x) for x in this])
        result += "%04X   %s\n" % (offset, hex_s)
        offset += length
    return result

def group(data, num):
    """ Split data into chunks of num chars each """
    return [data[i:i+num] for i in xrange(0, len(data), num)]

def key_handle_to_int(this):
    """
    Turn "123" into 123 and "KSM1" into 827151179
    (0x314d534b, 'K' = 0x4b, S = '0x53', M = 0x4d).

    YHSM is little endian, so this makes the bytes KSM1 appear
    in the most human readable form in packet traces.
    """
    try:
        num = int(this)
        return num
    except ValueError:
        if this[:2] == "0x":
            return int(this, 16)
        if (len(this) == 4):
            num = struct.unpack('<I', this)[0]
            return num
    raise pyhsm.exception.YHSM_Error("Could not parse key_handle '%s'" % (this))

def input_validate_str(string, name, max_len=None, exact_len=None):
    """ Input validation for strings. """
    if type(string) is not str:
        raise pyhsm.exception.YHSM_WrongInputType(name, str, type(string))
    if max_len != None and len(string) > max_len:
        raise pyhsm.exception.YHSM_InputTooLong(name, max_len, len(string))
    if exact_len != None and len(string) != exact_len:
        raise pyhsm.exception.YHSM_WrongInputSize(name, exact_len, len(string))
    return string

def input_validate_int(value, name, max_value=None):
    """ Input validation for integers. """
    if type(value) is not int:
        raise pyhsm.exception.YHSM_WrongInputType(name, int, type(value))
    if max_value != None and value > max_value:
        raise pyhsm.exception.YHSM_WrongInputSize(name, max_value, value)
    return value

def input_validate_nonce(nonce, name='nonce', pad = False):
    """ Input validation for nonces. """
    if type(nonce) is not str:
        raise pyhsm.exception.YHSM_WrongInputType( \
            name, str, type(nonce))
    if len(nonce) > pyhsm.defines.YSM_AEAD_NONCE_SIZE:
        raise pyhsm.exception.YHSM_InputTooLong(
            name, pyhsm.defines.YSM_AEAD_NONCE_SIZE, len(nonce))
    if pad:
        return nonce.ljust(pyhsm.defines.YSM_AEAD_NONCE_SIZE, chr(0x0))
    else:
        return nonce

def input_validate_key_handle(key_handle, name='key_handle'):
    """ Input validation for key_handles. """
    if type(key_handle) is not int:
        try:
            return key_handle_to_int(key_handle)
        except pyhsm.exception.YHSM_Error:
            raise pyhsm.exception.YHSM_WrongInputType(name, int, type(key_handle))
    return key_handle

def input_validate_yubikey_secret(data, name='data'):
    """ Input validation for YHSM_YubiKeySecret or string. """
    if isinstance(data, pyhsm.aead_cmd.YHSM_YubiKeySecret):
        data = data.pack()
    return input_validate_str(data, name)

def input_validate_aead(aead, name='aead', expected_len=None, max_aead_len = pyhsm.defines.YSM_AEAD_MAX_SIZE):
    """ Input validation for YHSM_GeneratedAEAD or string. """
    if isinstance(aead, pyhsm.aead_cmd.YHSM_GeneratedAEAD):
        aead = aead.data
    if expected_len != None:
        return input_validate_str(aead, name, exact_len = expected_len)
    else:
        return input_validate_str(aead, name, max_len=max_aead_len)

def validate_cmd_response_int(name, got, expected):
    """
    Check that some value returned in the response to a command matches what
    we put in the request (the command).
    """
    if got != expected:
        raise(pyhsm.exception.YHSM_Error("Bad %s in response (got %i, expected %i)" \
                                             % (name, got, expected)))
    return got

def validate_cmd_response_hex(name, got, expected):
    """
    Check that some value returned in the response to a command matches what
    we put in the request (the command).
    """
    if got != expected:
        raise(pyhsm.exception.YHSM_Error("Bad %s in response (got 0x%x, expected 0x%x)" \
                                             % (name, got, expected)))
    return got

def validate_cmd_response_str(name, got, expected, hex_encode=True):
    """
    Check that some value returned in the response to a command matches what
    we put in the request (the command).
    """
    if got != expected:
        if hex_encode:
            got_s = got.encode('hex')
            exp_s = expected.encode('hex')
        else:
            got_s = got
            exp_s = expected
        raise(pyhsm.exception.YHSM_Error("Bad %s in response (got %s, expected %s)" \
                                             % (name, got_s, exp_s)))
    return got

def validate_cmd_response_nonce(got, used):
    """
    Check that the returned nonce matches nonce used in request.

    A request nonce of 000000000000 means the HSM should generate a nonce internally though,
    so if 'used' is all zeros we actually check that 'got' does NOT match 'used'.
    """
    if used == '000000000000'.decode('hex'):
        if got == used:
            raise(pyhsm.exception.YHSM_Error("Bad nonce in response (got %s, expected HSM generated nonce)" \
                                                 % (got.encode('hex'))))
        return got
    return validate_cmd_response_str('nonce', got, used)


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright (C) 2008 Maurice Zeijen <maurice@zeijen.net>

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

            http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<mule xmlns="http://www.mulesoft.org/schema/mule/core"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:stdio="http://www.mulesoft.org/schema/mule/stdio"
      xmlns:vm="http://www.mulesoft.org/schema/mule/vm"
	  xmlns:smooks="http://www.muleforge.org/smooks/schema/mule-module-smooks"
      xsi:schemaLocation="
        http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/3.1/mule.xsd
        http://www.mulesoft.org/schema/mule/stdio http://www.mulesoft.org/schema/mule/stdio/3.1/mule-stdio.xsd
        http://www.mulesoft.org/schema/mule/vm http://www.mulesoft.org/schema/mule/vm/3.1/mule-vm.xsd
		http://www.muleforge.org/smooks/schema/mule-module-smooks http://dist.muleforge.org/smooks/schema/mule-module-smooks/1.3/mule-module-smooks.xsd
	">

    <description>
        This config for testing the namespace handler
    </description>

	<smooks:transformer
		name="smooksTransformer"
		configFile="/transformer-smooks-config.xml"
		profile="someProfile"
		profileMessagePropertyKey="smooksProfile"
		executionContextAsMessageProperty="true"
		executionContextMessagePropertyKey="smooks.executionContext"
		excludeNonSerializables="false"
		resultType="JAVA"
		javaResultBeanId="a"
		resultClass="javax.xml.transform.dom.DOMResult"
		resultFactoryClass="test.DummyResultFactory"
		reportPath="target/smooks-report/report.html"
	/>

    <model name="test">
        <service name="TestUMO">
            <inbound>
                <vm:inbound-endpoint path="messageInput" transformer-refs="smooksTransformer"/>
            </inbound>

            <outbound>
            	<smooks:router
            		configFile="/router-smooks-config.xml"
            		profile="someProfile"
					profileMessagePropertyKey="smooksProfile"
					executionContextAsMessageProperty="true"
					executionContextMessagePropertyKey="smooks.executionContext"
					excludeNonSerializables="false"
					reportPath="target/smooks-report/report.html"
					>

					<stdio:outbound-endpoint name="endpoint1" system="OUT" />
            		<stdio:outbound-endpoint name="endpoint2" system="OUT" />

            	</smooks:router>
           	</outbound>
        </service>
    </model>
</mule>


text:
Tutorial showing several common Git problems and their respective solutions using the Git on the command line.

[Notes](Notes.md)


text:
FROM node:8.5.0
RUN mkdir /app
WORKDIR /app
COPY package.json /app
RUN npm install
COPY . /app
EXPOSE 3030
CMD ["npm", "start"]


text:
package org.apache.spark.status

import java.io.File
import java.util.{List => JList}

import scala.collection.JavaConverters._
import scala.collection.mutable.HashMap

import org.apache.spark.{JobExecutionStatus, SparkConf, SparkContext}
import org.apache.spark.internal.config.History.HybridStoreDiskBackend
import org.apache.spark.internal.config.Status.LIVE_UI_LOCAL_STORE_DIR
import org.apache.spark.status.api.v1
import org.apache.spark.storage.FallbackStorage.FALLBACK_BLOCK_MANAGER_ID
import org.apache.spark.ui.scope._
import org.apache.spark.util.Utils
import org.apache.spark.util.kvstore.KVStore

/**
 * A wrapper around a KVStore that provides methods for accessing the API data stored within.
 */
private[spark] class AppStatusStore(
    val store: KVStore,
    val listener: Option[AppStatusListener] = None) {

  def applicationInfo(): v1.ApplicationInfo = {
    try {
      // The ApplicationInfo may not be available when Spark is starting up.
      Utils.tryWithResource(
        store.view(classOf[ApplicationInfoWrapper])
          .max(1)
          .closeableIterator()
      ) { it =>
        it.next().info
      }
    } catch {
      case _: NoSuchElementException =>
        throw new NoSuchElementException("Failed to get the application information. " +
          "If you are starting up Spark, please wait a while until it's ready.")
    }
  }

  def environmentInfo(): v1.ApplicationEnvironmentInfo = {
    val klass = classOf[ApplicationEnvironmentInfoWrapper]
    store.read(klass, klass.getName()).info
  }

  def resourceProfileInfo(): Seq[v1.ResourceProfileInfo] = {
    KVUtils.mapToSeq(store.view(classOf[ResourceProfileWrapper]))(_.rpInfo)
  }

  def jobsList(statuses: JList[JobExecutionStatus]): Seq[v1.JobData] = {
    val it = KVUtils.mapToSeq(store.view(classOf[JobDataWrapper]).reverse())(_.info)
    if (statuses != null && !statuses.isEmpty()) {
      it.filter { job => statuses.contains(job.status) }
    } else {
      it
    }
  }

  def job(jobId: Int): v1.JobData = {
    store.read(classOf[JobDataWrapper], jobId).info
  }

  // Returns job data and associated SQL execution ID of certain Job ID.
  // If there is no related SQL execution, the SQL execution ID part will be None.
  def jobWithAssociatedSql(jobId: Int): (v1.JobData, Option[Long]) = {
    val data = store.read(classOf[JobDataWrapper], jobId)
    (data.info, data.sqlExecutionId)
  }

  def executorList(activeOnly: Boolean): Seq[v1.ExecutorSummary] = {
    val base = store.view(classOf[ExecutorSummaryWrapper])
    val filtered = if (activeOnly) {
      base.index("active").reverse().first(true).last(true)
    } else {
      base
    }
    KVUtils.mapToSeq(filtered)(_.info)
      .filter(_.id != FALLBACK_BLOCK_MANAGER_ID.executorId)
      .map(replaceExec)
  }

  private def replaceExec(origin: v1.ExecutorSummary): v1.ExecutorSummary = {
    if (origin.id == SparkContext.DRIVER_IDENTIFIER) {
      replaceDriverGcTime(origin, extractGcTime(origin), extractAppTime)
    } else {
      origin
    }
  }

  private def replaceDriverGcTime(source: v1.ExecutorSummary,
    totalGcTime: Option[Long], totalAppTime: Option[Long]): v1.ExecutorSummary = {
    new v1.ExecutorSummary(source.id, source.hostPort, source.isActive, source.rddBlocks,
      source.memoryUsed, source.diskUsed, source.totalCores, source.maxTasks, source.activeTasks,
      source.failedTasks, source.completedTasks, source.totalTasks,
      totalAppTime.getOrElse(source.totalDuration),
      totalGcTime.getOrElse(source.totalGCTime),
      source.totalInputBytes, source.totalShuffleRead,
      source.totalShuffleWrite, source.isBlacklisted, source.maxMemory, source.addTime,
      source.removeTime, source.removeReason, source.executorLogs, source.memoryMetrics,
      source.blacklistedInStages, source.peakMemoryMetrics, source.attributes, source.resources,
      source.resourceProfileId, source.isExcluded, source.excludedInStages)
  }

  private def extractGcTime(source: v1.ExecutorSummary): Option[Long] = {
    source.peakMemoryMetrics.map(_.getMetricValue("TotalGCTime"))
  }

  private def extractAppTime: Option[Long] = {
    var startTime = 0L
    // -1 when SparkListenerApplicationStart event written to kvStore
    // event time when SparkListenerApplicationStart event written to kvStore
    var endTime = 0L
    try {
      val appInfo = applicationInfo()
      startTime = appInfo.attempts.head.startTime.getTime()
      endTime = appInfo.attempts.head.endTime.getTime()
    } catch {
      //  too early to get appInfo, should wait a while
      case _: NoSuchElementException =>
    }
    if (endTime == 0) {
      None
    } else if (endTime < 0) {
      Option(System.currentTimeMillis() - startTime)
    } else {
      Option(endTime - startTime)
    }
  }

  def miscellaneousProcessList(activeOnly: Boolean): Seq[v1.ProcessSummary] = {
    val base = store.view(classOf[ProcessSummaryWrapper])
    val filtered = if (activeOnly) {
      base.index("active").reverse().first(true).last(true)
    } else {
      base
    }
    KVUtils.mapToSeq(filtered)(_.info)
  }

  def executorSummary(executorId: String): v1.ExecutorSummary = {
    store.read(classOf[ExecutorSummaryWrapper], executorId).info
  }

  /**
   * This is used by ConsoleProgressBar to quickly fetch active stages for drawing the progress
   * bar. It will only return anything useful when called from a live application.
   */
  def activeStages(): Seq[v1.StageData] = {
    listener.map(_.activeStages()).getOrElse(Nil)
  }

  def stageList(
    statuses: JList[v1.StageStatus],
    details: Boolean = false,
    withSummaries: Boolean = false,
    unsortedQuantiles: Array[Double] = Array.empty,
    taskStatus: JList[v1.TaskStatus] = List().asJava): Seq[v1.StageData] = {
    val quantiles = unsortedQuantiles.sorted
    val it = KVUtils.mapToSeq(store.view(classOf[StageDataWrapper]).reverse())(_.info)
    val ret = if (statuses != null && !statuses.isEmpty()) {
      it.filter { s => statuses.contains(s.status) }
    } else {
      it
    }

    ret.map { s =>
      newStageData(s, withDetail = details, taskStatus = taskStatus,
        withSummaries = withSummaries, unsortedQuantiles = quantiles)
    }
  }

  def stageData(
    stageId: Int,
    details: Boolean = false,
    taskStatus: JList[v1.TaskStatus] = List().asJava,
    withSummaries: Boolean = false,
    unsortedQuantiles: Array[Double] = Array.empty[Double]): Seq[v1.StageData] = {
    KVUtils.mapToSeq(store.view(classOf[StageDataWrapper]).index("stageId")
      .first(stageId).last(stageId)) { s =>
      newStageData(s.info, withDetail = details, taskStatus = taskStatus,
        withSummaries = withSummaries, unsortedQuantiles = unsortedQuantiles)
    }
  }

  def lastStageAttempt(stageId: Int): v1.StageData = {
    val it = store.view(classOf[StageDataWrapper])
      .index("stageId")
      .reverse()
      .first(stageId)
      .last(stageId)
      .closeableIterator()
    try {
      if (it.hasNext()) {
        it.next().info
      } else {
        throw new NoSuchElementException(s"No stage with id $stageId")
      }
    } finally {
      it.close()
    }
  }

  def stageAttempt(
      stageId: Int, stageAttemptId: Int,
      details: Boolean = false,
      taskStatus: JList[v1.TaskStatus] = List().asJava,
      withSummaries: Boolean = false,
      unsortedQuantiles: Array[Double] = Array.empty[Double]): (v1.StageData, Seq[Int]) = {
    val stageKey = Array(stageId, stageAttemptId)
    val stageDataWrapper = store.read(classOf[StageDataWrapper], stageKey)
    val stage = newStageData(stageDataWrapper.info, withDetail = details, taskStatus = taskStatus,
      withSummaries = withSummaries, unsortedQuantiles = unsortedQuantiles)
    (stage, stageDataWrapper.jobIds.toSeq)
  }

  def taskCount(stageId: Int, stageAttemptId: Int): Long = {
    store.count(classOf[TaskDataWrapper], "stage", Array(stageId, stageAttemptId))
  }

  def localitySummary(stageId: Int, stageAttemptId: Int): Map[String, Long] = {
    store.read(classOf[StageDataWrapper], Array(stageId, stageAttemptId)).locality
  }

  /**
   * Calculates a summary of the task metrics for the given stage attempt, returning the
   * requested quantiles for the recorded metrics.
   *
   * This method can be expensive if the requested quantiles are not cached; the method
   * will only cache certain quantiles (every 0.05 step), so it's recommended to stick to
   * those to avoid expensive scans of all task data.
   */
  def taskSummary(
      stageId: Int,
      stageAttemptId: Int,
      unsortedQuantiles: Array[Double]): Option[v1.TaskMetricDistributions] = {
    val stageKey = Array(stageId, stageAttemptId)
    val quantiles = unsortedQuantiles.sorted

    // We don't know how many tasks remain in the store that actually have metrics. So scan one
    // metric and count how many valid tasks there are. Use skip() instead of next() since it's
    // cheaper for disk stores (avoids deserialization).
    val count = {
      Utils.tryWithResource(
        store.view(classOf[TaskDataWrapper])
          .parent(stageKey)
          .index(TaskIndexNames.EXEC_RUN_TIME)
          .first(0L)
          .closeableIterator()
      ) { it =>
        var _count = 0L
        while (it.hasNext()) {
          _count += 1
          it.skip(1)
        }
        _count
      }
    }

    if (count <= 0) {
      return None
    }

    // Find out which quantiles are already cached. The data in the store must match the expected
    // task count to be considered, otherwise it will be re-scanned and overwritten.
    val cachedQuantiles = quantiles.filter(shouldCacheQuantile).flatMap { q =>
      val qkey = Array(stageId, stageAttemptId, quantileToString(q))
      asOption(store.read(classOf[CachedQuantile], qkey)).filter(_.taskCount == count)
    }

    // If there are no missing quantiles, return the data. Otherwise, just compute everything
    // to make the code simpler.
    if (cachedQuantiles.size == quantiles.size) {
      def toValues(fn: CachedQuantile => Double): IndexedSeq[Double] = cachedQuantiles.map(fn)

      val distributions = new v1.TaskMetricDistributions(
        quantiles = quantiles,
        duration = toValues(_.duration),
        executorDeserializeTime = toValues(_.executorDeserializeTime),
        executorDeserializeCpuTime = toValues(_.executorDeserializeCpuTime),
        executorRunTime = toValues(_.executorRunTime),
        executorCpuTime = toValues(_.executorCpuTime),
        resultSize = toValues(_.resultSize),
        jvmGcTime = toValues(_.jvmGcTime),
        resultSerializationTime = toValues(_.resultSerializationTime),
        gettingResultTime = toValues(_.gettingResultTime),
        schedulerDelay = toValues(_.schedulerDelay),
        peakExecutionMemory = toValues(_.peakExecutionMemory),
        memoryBytesSpilled = toValues(_.memoryBytesSpilled),
        diskBytesSpilled = toValues(_.diskBytesSpilled),
        inputMetrics = new v1.InputMetricDistributions(
          toValues(_.bytesRead),
          toValues(_.recordsRead)),
        outputMetrics = new v1.OutputMetricDistributions(
          toValues(_.bytesWritten),
          toValues(_.recordsWritten)),
        shuffleReadMetrics = new v1.ShuffleReadMetricDistributions(
          toValues(_.shuffleReadBytes),
          toValues(_.shuffleRecordsRead),
          toValues(_.shuffleRemoteBlocksFetched),
          toValues(_.shuffleLocalBlocksFetched),
          toValues(_.shuffleFetchWaitTime),
          toValues(_.shuffleRemoteBytesRead),
          toValues(_.shuffleRemoteBytesReadToDisk),
          toValues(_.shuffleTotalBlocksFetched)),
        shuffleWriteMetrics = new v1.ShuffleWriteMetricDistributions(
          toValues(_.shuffleWriteBytes),
          toValues(_.shuffleWriteRecords),
          toValues(_.shuffleWriteTime)))

      return Some(distributions)
    }

    // Compute quantiles by scanning the tasks in the store. This is not really stable for live
    // stages (e.g. the number of recorded tasks may change while this code is running), but should
    // stabilize once the stage finishes. It's also slow, especially with disk stores.
    val indices = quantiles.map { q => math.min((q * count).toLong, count - 1) }

    def scanTasks(index: String)(fn: TaskDataWrapper => Long): IndexedSeq[Double] = {
      Utils.tryWithResource(
        store.view(classOf[TaskDataWrapper])
          .parent(stageKey)
          .index(index)
          .first(0L)
          .closeableIterator()
      ) { it =>
        var last = Double.NaN
        var currentIdx = -1L
        indices.map { idx =>
          if (idx == currentIdx) {
            last
          } else {
            val diff = idx - currentIdx
            currentIdx = idx
            if (it.skip(diff - 1)) {
              last = fn(it.next()).toDouble
              last
            } else {
              Double.NaN
            }
          }
        }.toIndexedSeq
      }
    }

    val computedQuantiles = new v1.TaskMetricDistributions(
      quantiles = quantiles,
      duration = scanTasks(TaskIndexNames.DURATION) { t =>
        t.duration
      },
      executorDeserializeTime = scanTasks(TaskIndexNames.DESER_TIME) { t =>
        t.executorDeserializeTime
      },
      executorDeserializeCpuTime = scanTasks(TaskIndexNames.DESER_CPU_TIME) { t =>
        t.executorDeserializeCpuTime
      },
      executorRunTime = scanTasks(TaskIndexNames.EXEC_RUN_TIME) { t => t.executorRunTime },
      executorCpuTime = scanTasks(TaskIndexNames.EXEC_CPU_TIME) { t => t.executorCpuTime },
      resultSize = scanTasks(TaskIndexNames.RESULT_SIZE) { t => t.resultSize },
      jvmGcTime = scanTasks(TaskIndexNames.GC_TIME) { t => t.jvmGcTime },
      resultSerializationTime = scanTasks(TaskIndexNames.SER_TIME) { t =>
        t.resultSerializationTime
      },
      gettingResultTime = scanTasks(TaskIndexNames.GETTING_RESULT_TIME) { t =>
        t.gettingResultTime
      },
      schedulerDelay = scanTasks(TaskIndexNames.SCHEDULER_DELAY) { t => t.schedulerDelay },
      peakExecutionMemory = scanTasks(TaskIndexNames.PEAK_MEM) { t => t.peakExecutionMemory },
      memoryBytesSpilled = scanTasks(TaskIndexNames.MEM_SPILL) { t => t.memoryBytesSpilled },
      diskBytesSpilled = scanTasks(TaskIndexNames.DISK_SPILL) { t => t.diskBytesSpilled },
      inputMetrics = new v1.InputMetricDistributions(
        scanTasks(TaskIndexNames.INPUT_SIZE) { t => t.inputBytesRead },
        scanTasks(TaskIndexNames.INPUT_RECORDS) { t => t.inputRecordsRead }),
      outputMetrics = new v1.OutputMetricDistributions(
        scanTasks(TaskIndexNames.OUTPUT_SIZE) { t => t.outputBytesWritten },
        scanTasks(TaskIndexNames.OUTPUT_RECORDS) { t => t.outputRecordsWritten }),
      shuffleReadMetrics = new v1.ShuffleReadMetricDistributions(
        scanTasks(TaskIndexNames.SHUFFLE_TOTAL_READS) { m =>
          m.shuffleLocalBytesRead + m.shuffleRemoteBytesRead
        },
        scanTasks(TaskIndexNames.SHUFFLE_READ_RECORDS) { t => t.shuffleRecordsRead },
        scanTasks(TaskIndexNames.SHUFFLE_REMOTE_BLOCKS) { t => t.shuffleRemoteBlocksFetched },
        scanTasks(TaskIndexNames.SHUFFLE_LOCAL_BLOCKS) { t => t.shuffleLocalBlocksFetched },
        scanTasks(TaskIndexNames.SHUFFLE_READ_FETCH_WAIT_TIME) { t => t.shuffleFetchWaitTime },
        scanTasks(TaskIndexNames.SHUFFLE_REMOTE_READS) { t => t.shuffleRemoteBytesRead },
        scanTasks(TaskIndexNames.SHUFFLE_REMOTE_READS_TO_DISK) { t =>
          t.shuffleRemoteBytesReadToDisk
        },
        scanTasks(TaskIndexNames.SHUFFLE_TOTAL_BLOCKS) { m =>
          m.shuffleLocalBlocksFetched + m.shuffleRemoteBlocksFetched
        }),
      shuffleWriteMetrics = new v1.ShuffleWriteMetricDistributions(
        scanTasks(TaskIndexNames.SHUFFLE_WRITE_SIZE) { t => t.shuffleBytesWritten },
        scanTasks(TaskIndexNames.SHUFFLE_WRITE_RECORDS) { t => t.shuffleRecordsWritten },
        scanTasks(TaskIndexNames.SHUFFLE_WRITE_TIME) { t => t.shuffleWriteTime }))

    // Go through the computed quantiles and cache the values that match the caching criteria.
    computedQuantiles.quantiles.zipWithIndex
      .filter { case (q, _) => quantiles.contains(q) && shouldCacheQuantile(q) }
      .foreach { case (q, idx) =>
        val cached = new CachedQuantile(stageId, stageAttemptId, quantileToString(q), count,
          duration = computedQuantiles.duration(idx),
          executorDeserializeTime = computedQuantiles.executorDeserializeTime(idx),
          executorDeserializeCpuTime = computedQuantiles.executorDeserializeCpuTime(idx),
          executorRunTime = computedQuantiles.executorRunTime(idx),
          executorCpuTime = computedQuantiles.executorCpuTime(idx),
          resultSize = computedQuantiles.resultSize(idx),
          jvmGcTime = computedQuantiles.jvmGcTime(idx),
          resultSerializationTime = computedQuantiles.resultSerializationTime(idx),
          gettingResultTime = computedQuantiles.gettingResultTime(idx),
          schedulerDelay = computedQuantiles.schedulerDelay(idx),
          peakExecutionMemory = computedQuantiles.peakExecutionMemory(idx),
          memoryBytesSpilled = computedQuantiles.memoryBytesSpilled(idx),
          diskBytesSpilled = computedQuantiles.diskBytesSpilled(idx),

          bytesRead = computedQuantiles.inputMetrics.bytesRead(idx),
          recordsRead = computedQuantiles.inputMetrics.recordsRead(idx),

          bytesWritten = computedQuantiles.outputMetrics.bytesWritten(idx),
          recordsWritten = computedQuantiles.outputMetrics.recordsWritten(idx),

          shuffleReadBytes = computedQuantiles.shuffleReadMetrics.readBytes(idx),
          shuffleRecordsRead = computedQuantiles.shuffleReadMetrics.readRecords(idx),
          shuffleRemoteBlocksFetched =
            computedQuantiles.shuffleReadMetrics.remoteBlocksFetched(idx),
          shuffleLocalBlocksFetched = computedQuantiles.shuffleReadMetrics.localBlocksFetched(idx),
          shuffleFetchWaitTime = computedQuantiles.shuffleReadMetrics.fetchWaitTime(idx),
          shuffleRemoteBytesRead = computedQuantiles.shuffleReadMetrics.remoteBytesRead(idx),
          shuffleRemoteBytesReadToDisk =
            computedQuantiles.shuffleReadMetrics.remoteBytesReadToDisk(idx),
          shuffleTotalBlocksFetched = computedQuantiles.shuffleReadMetrics.totalBlocksFetched(idx),

          shuffleWriteBytes = computedQuantiles.shuffleWriteMetrics.writeBytes(idx),
          shuffleWriteRecords = computedQuantiles.shuffleWriteMetrics.writeRecords(idx),
          shuffleWriteTime = computedQuantiles.shuffleWriteMetrics.writeTime(idx))
        store.write(cached)
      }

    Some(computedQuantiles)
  }

  /**
   * Whether to cache information about a specific metric quantile. We cache quantiles at every 0.05
   * step, which covers the default values used both in the API and in the stages page.
   */
  private def shouldCacheQuantile(q: Double): Boolean = (math.round(q * 100) % 5) == 0

  private def quantileToString(q: Double): String = math.round(q * 100).toString

  def taskList(stageId: Int, stageAttemptId: Int, maxTasks: Int): Seq[v1.TaskData] = {
    val stageKey = Array(stageId, stageAttemptId)
    val taskDataWrapperSeq = KVUtils.viewToSeq(store.view(classOf[TaskDataWrapper]).index("stage")
      .first(stageKey).last(stageKey).reverse().max(maxTasks))
    constructTaskDataList(taskDataWrapperSeq).reverse
  }

  def taskList(
      stageId: Int,
      stageAttemptId: Int,
      offset: Int,
      length: Int,
      sortBy: v1.TaskSorting,
      statuses: JList[v1.TaskStatus]): Seq[v1.TaskData] = {
    val (indexName, ascending) = sortBy match {
      case v1.TaskSorting.ID =>
        (None, true)
      case v1.TaskSorting.INCREASING_RUNTIME =>
        (Some(TaskIndexNames.EXEC_RUN_TIME), true)
      case v1.TaskSorting.DECREASING_RUNTIME =>
        (Some(TaskIndexNames.EXEC_RUN_TIME), false)
    }
    taskList(stageId, stageAttemptId, offset, length, indexName, ascending, statuses)
  }

  def taskList(
      stageId: Int,
      stageAttemptId: Int,
      offset: Int,
      length: Int,
      sortBy: Option[String],
      ascending: Boolean,
      statuses: JList[v1.TaskStatus] = List().asJava): Seq[v1.TaskData] = {
    val stageKey = Array(stageId, stageAttemptId)
    val base = store.view(classOf[TaskDataWrapper])
    val indexed = sortBy match {
      case Some(index) =>
        base.index(index).parent(stageKey)

      case _ =>
        // Sort by ID, which is the "stage" index.
        base.index("stage").first(stageKey).last(stageKey)
    }

    val ordered = if (ascending) indexed else indexed.reverse()
    val taskDataWrapperSeq = if (statuses != null && !statuses.isEmpty) {
      val statusesStr = statuses.asScala.map(_.toString).toSet
      KVUtils.viewToSeq(ordered, offset, offset + length)(s => statusesStr.contains(s.status))
    } else {
      KVUtils.viewToSeq(ordered.skip(offset).max(length))
    }

    constructTaskDataList(taskDataWrapperSeq)
  }

  def executorSummary(stageId: Int, attemptId: Int): Map[String, v1.ExecutorStageSummary] = {
    val stageKey = Array(stageId, attemptId)
    KVUtils.mapToSeq(store.view(classOf[ExecutorStageSummaryWrapper])
      .index("stage").first(stageKey).last(stageKey)) { exec =>
      (exec.executorId -> exec.info)
    }.toMap
  }

  def speculationSummary(stageId: Int, attemptId: Int): Option[v1.SpeculationStageSummary] = {
    val stageKey = Array(stageId, attemptId)
    asOption(store.read(classOf[SpeculationStageSummaryWrapper], stageKey).info)
  }

  def rddList(cachedOnly: Boolean = true): Seq[v1.RDDStorageInfo] = {
    KVUtils.mapToSeq(store.view(classOf[RDDStorageInfoWrapper]))(_.info)
      .filter { rdd =>
        !cachedOnly || rdd.numCachedPartitions > 0
      }
  }

  /**
   * Calls a closure that may throw a NoSuchElementException and returns `None` when the exception
   * is thrown.
   */
  def asOption[T](fn: => T): Option[T] = {
    try {
      Some(fn)
    } catch {
      case _: NoSuchElementException => None
    }
  }

  def newStageData(
    stage: v1.StageData,
    withDetail: Boolean = false,
    taskStatus: JList[v1.TaskStatus] = List().asJava,
    withSummaries: Boolean = false,
    unsortedQuantiles: Array[Double] = Array.empty[Double]): v1.StageData = {
    if (!withDetail && !withSummaries) {
      stage
    } else {
      val quantiles = unsortedQuantiles.sorted
      val tasks: Option[Map[Long, v1.TaskData]] = if (withDetail) {
        val tasks =
          taskList(stage.stageId, stage.attemptId, 0, Int.MaxValue, None, false, taskStatus)
            .map { t => (t.taskId, t) }
            .toMap
        Some(tasks)
      } else {
        None
      }
      val executorSummaries: Option[Map[String, v1.ExecutorStageSummary]] = if (withDetail) {
        Some(executorSummary(stage.stageId, stage.attemptId))
      } else {
        None
      }
      val taskMetricsDistribution: Option[v1.TaskMetricDistributions] = if (withSummaries) {
        taskSummary(stage.stageId, stage.attemptId, quantiles)
      } else {
        None
      }
      val executorMetricsDistributions: Option[v1.ExecutorMetricsDistributions] =
        if (withSummaries) {
          stageExecutorSummary(stage.stageId, stage.attemptId, quantiles)
        } else {
          None
        }
      val speculationStageSummary: Option[v1.SpeculationStageSummary] = if (withDetail) {
        speculationSummary(stage.stageId, stage.attemptId)
      } else {
        None
      }

      new v1.StageData(
        status = stage.status,
        stageId = stage.stageId,
        attemptId = stage.attemptId,
        numTasks = stage.numTasks,
        numActiveTasks = stage.numActiveTasks,
        numCompleteTasks = stage.numCompleteTasks,
        numFailedTasks = stage.numFailedTasks,
        numKilledTasks = stage.numKilledTasks,
        numCompletedIndices = stage.numCompletedIndices,
        submissionTime = stage.submissionTime,
        firstTaskLaunchedTime = stage.firstTaskLaunchedTime,
        completionTime = stage.completionTime,
        failureReason = stage.failureReason,
        executorDeserializeTime = stage.executorDeserializeTime,
        executorDeserializeCpuTime = stage.executorDeserializeCpuTime,
        executorRunTime = stage.executorRunTime,
        executorCpuTime = stage.executorCpuTime,
        resultSize = stage.resultSize,
        jvmGcTime = stage.jvmGcTime,
        resultSerializationTime = stage.resultSerializationTime,
        memoryBytesSpilled = stage.memoryBytesSpilled,
        diskBytesSpilled = stage.diskBytesSpilled,
        peakExecutionMemory = stage.peakExecutionMemory,
        inputBytes = stage.inputBytes,
        inputRecords = stage.inputRecords,
        outputBytes = stage.outputBytes,
        outputRecords = stage.outputRecords,
        shuffleRemoteBlocksFetched = stage.shuffleRemoteBlocksFetched,
        shuffleLocalBlocksFetched = stage.shuffleLocalBlocksFetched,
        shuffleFetchWaitTime = stage.shuffleFetchWaitTime,
        shuffleRemoteBytesRead = stage.shuffleRemoteBytesRead,
        shuffleRemoteBytesReadToDisk = stage.shuffleRemoteBytesReadToDisk,
        shuffleLocalBytesRead = stage.shuffleLocalBytesRead,
        shuffleReadBytes = stage.shuffleReadBytes,
        shuffleReadRecords = stage.shuffleReadRecords,
        shuffleWriteBytes = stage.shuffleWriteBytes,
        shuffleWriteTime = stage.shuffleWriteTime,
        shuffleWriteRecords = stage.shuffleWriteRecords,
        name = stage.name,
        description = stage.description,
        details = stage.details,
        schedulingPool = stage.schedulingPool,
        rddIds = stage.rddIds,
        accumulatorUpdates = stage.accumulatorUpdates,
        tasks = tasks,
        executorSummary = executorSummaries,
        speculationSummary = speculationStageSummary,
        killedTasksSummary = stage.killedTasksSummary,
        resourceProfileId = stage.resourceProfileId,
        peakExecutorMetrics = stage.peakExecutorMetrics,
        taskMetricsDistributions = taskMetricsDistribution,
        executorMetricsDistributions = executorMetricsDistributions)
    }
  }

  def stageExecutorSummary(
    stageId: Int,
    stageAttemptId: Int,
    unsortedQuantiles: Array[Double]): Option[v1.ExecutorMetricsDistributions] = {
    val quantiles = unsortedQuantiles.sorted
    val summary = executorSummary(stageId, stageAttemptId)
    if (summary.isEmpty) {
      None
    } else {
      val values = summary.values.toIndexedSeq
      Some(new v1.ExecutorMetricsDistributions(
        quantiles = quantiles,
        taskTime = getQuantilesValue(values.map(_.taskTime.toDouble).sorted, quantiles),
        failedTasks = getQuantilesValue(values.map(_.failedTasks.toDouble).sorted, quantiles),
        succeededTasks = getQuantilesValue(values.map(_.succeededTasks.toDouble).sorted, quantiles),
        killedTasks = getQuantilesValue(values.map(_.killedTasks.toDouble).sorted, quantiles),
        inputBytes = getQuantilesValue(values.map(_.inputBytes.toDouble).sorted, quantiles),
        inputRecords = getQuantilesValue(values.map(_.inputRecords.toDouble).sorted, quantiles),
        outputBytes = getQuantilesValue(values.map(_.outputBytes.toDouble).sorted, quantiles),
        outputRecords = getQuantilesValue(values.map(_.outputRecords.toDouble).sorted, quantiles),
        shuffleRead = getQuantilesValue(values.map(_.shuffleRead.toDouble).sorted, quantiles),
        shuffleReadRecords =
          getQuantilesValue(values.map(_.shuffleReadRecords.toDouble).sorted, quantiles),
        shuffleWrite = getQuantilesValue(values.map(_.shuffleWrite.toDouble).sorted, quantiles),
        shuffleWriteRecords =
          getQuantilesValue(values.map(_.shuffleWriteRecords.toDouble).sorted, quantiles),
        memoryBytesSpilled =
          getQuantilesValue(values.map(_.memoryBytesSpilled.toDouble).sorted, quantiles),
        diskBytesSpilled =
          getQuantilesValue(values.map(_.diskBytesSpilled.toDouble).sorted, quantiles),
        peakMemoryMetrics =
          new v1.ExecutorPeakMetricsDistributions(quantiles,
            values.flatMap(_.peakMemoryMetrics))
      ))
    }
  }

  def getQuantilesValue(
    values: IndexedSeq[Double],
    quantiles: Array[Double]): IndexedSeq[Double] = {
    val count = values.size
    val indices = quantiles.map { q => math.min((q * count).toLong, count - 1) }
    indices.map(i => values(i.toInt)).toIndexedSeq
  }

  def rdd(rddId: Int): v1.RDDStorageInfo = {
    store.read(classOf[RDDStorageInfoWrapper], rddId).info
  }

  def streamBlocksList(): Seq[StreamBlockData] = {
    KVUtils.viewToSeq(store.view(classOf[StreamBlockData]))
  }

  def operationGraphForStage(stageId: Int): RDDOperationGraph = {
    store.read(classOf[RDDOperationGraphWrapper], stageId).toRDDOperationGraph()
  }

  def operationGraphForJob(jobId: Int): Seq[RDDOperationGraph] = {
    val job = store.read(classOf[JobDataWrapper], jobId)
    val stages = job.info.stageIds.sorted

    stages.map { id =>
      val g = store.read(classOf[RDDOperationGraphWrapper], id).toRDDOperationGraph()
      if (job.skippedStages.contains(id) && !g.rootCluster.name.contains("skipped")) {
        g.rootCluster.setName(g.rootCluster.name + " (skipped)")
      }
      g
    }
  }

  def pool(name: String): PoolData = {
    store.read(classOf[PoolData], name)
  }

  def appSummary(): AppSummary = {
    try {
      store.read(classOf[AppSummary], classOf[AppSummary].getName())
    } catch {
      case _: NoSuchElementException =>
        throw new NoSuchElementException("Failed to get the application summary. " +
          "If you are starting up Spark, please wait a while until it's ready.")
    }
  }

  def close(): Unit = {
    store.close()
  }

  def constructTaskDataList(taskDataWrapperIter: Iterable[TaskDataWrapper]): Seq[v1.TaskData] = {
    val executorIdToLogs = new HashMap[String, Map[String, String]]()
    taskDataWrapperIter.map { taskDataWrapper =>
      val taskDataOld: v1.TaskData = taskDataWrapper.toApi
      val executorLogs = executorIdToLogs.getOrElseUpdate(taskDataOld.executorId, {
        try {
          executorSummary(taskDataOld.executorId).executorLogs
        } catch {
          case e: NoSuchElementException =>
            Map.empty
        }
      })

      new v1.TaskData(taskDataOld.taskId, taskDataOld.index,
        taskDataOld.attempt, taskDataOld.partitionId,
        taskDataOld.launchTime, taskDataOld.resultFetchStart,
        taskDataOld.duration, taskDataOld.executorId, taskDataOld.host, taskDataOld.status,
        taskDataOld.taskLocality, taskDataOld.speculative, taskDataOld.accumulatorUpdates,
        taskDataOld.errorMessage, taskDataOld.taskMetrics,
        executorLogs,
        AppStatusUtils.schedulerDelay(taskDataOld),
        AppStatusUtils.gettingResultTime(taskDataOld))
    }.toSeq
  }
}

private[spark] object AppStatusStore {

  val CURRENT_VERSION = 2L

  /**
   * Create an in-memory store for a live application.
   */
  def createLiveStore(
      conf: SparkConf,
      appStatusSource: Option[AppStatusSource] = None): AppStatusStore = {
    val storePath = conf.get(LIVE_UI_LOCAL_STORE_DIR).map(new File(_))
    // For the disk-based KV store of live UI, let's simply make it ROCKSDB only for now,
    // instead of supporting both LevelDB and RocksDB. RocksDB is built based on LevelDB with
    // improvements on writes and reads.
    val kvStore = KVUtils.createKVStore(storePath, HybridStoreDiskBackend.ROCKSDB, conf)
    val store = new ElementTrackingStore(kvStore, conf)
    val listener = new AppStatusListener(store, conf, true, appStatusSource)
    new AppStatusStore(store, listener = Some(listener))
  }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mem. New York Bot. Gard. 35:655. 1982

#### Original name
Cassia orbiculata var. ustulata H.S.Irwin & Barneby

### Remarks
null


text:
namespace content {

namespace {

void RequestDesktopNotificationPermissionOnIO(
    const GURL& origin,
    const base::Callback<void(PermissionStatus)>& callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);

  LayoutTestNotificationManager* manager =
      LayoutTestContentBrowserClient::Get()->GetLayoutTestNotificationManager();
  PermissionStatus result = manager ? manager->RequestPermission(origin)
                                    : PERMISSION_STATUS_GRANTED;

  // The callback came from the UI thread, we need to run it from there again.
  BrowserThread::PostTask(
      BrowserThread::UI,
      FROM_HERE,
      base::Bind(callback, result));
}

}  // anonymous namespace

LayoutTestPermissionManager::LayoutTestPermissionManager()
    : ShellPermissionManager() {
}

LayoutTestPermissionManager::~LayoutTestPermissionManager() {
}

void LayoutTestPermissionManager::RequestPermission(
    PermissionType permission,
    WebContents* web_contents,
    int request_id,
    const GURL& requesting_origin,
    bool user_gesture,
    const base::Callback<void(PermissionStatus)>& callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  if (permission == PermissionType::NOTIFICATIONS) {
    BrowserThread::PostTask(
        BrowserThread::IO,
        FROM_HERE,
        base::Bind(&RequestDesktopNotificationPermissionOnIO,
                   requesting_origin,
                   callback));
    return;
  }

  ShellPermissionManager::RequestPermission(permission,
                                            web_contents,
                                            request_id,
                                            requesting_origin,
                                            user_gesture,
                                            callback);
}

}  // namespace content


text:
// File: vogl_gl_state_snapshot.h
#ifndef VOGL_GL_STATE_SNAPSHOT_H
#define VOGL_GL_STATE_SNAPSHOT_H

#include "vogl_core.h"
#include "vogl_sparse_vector.h"
#include "vogl_md5.h"

#include "vogl_common.h"
#include "vogl_general_context_state.h"
#include "vogl_texture_state.h"
#include "vogl_buffer_state.h"
#include "vogl_fbo_state.h"
#include "vogl_sampler_state.h"
#include "vogl_shader_state.h"
#include "vogl_program_state.h"
#include "vogl_renderbuffer_state.h"
#include "vogl_query_state.h"
#include "vogl_vao_state.h"
#include "vogl_texenv_state.h"
#include "vogl_light_state.h"
#include "vogl_material_state.h"
#include "vogl_display_list_state.h"
#include "vogl_matrix_state.h"
#include "vogl_current_vertex_attrib_state.h"
#include "vogl_arb_program_state.h"
#include "vogl_handle_tracker.h"
#include "vogl_default_framebuffer_state.h"

//----------------------------------------------------------------------------------------------------------------------
// Types
//----------------------------------------------------------------------------------------------------------------------
typedef vogl::hash_map<GLuint, GLenum> vogl_handle_hash_map;
typedef vogl::hash_map<GLuint> vogl_handle_hash_set;
typedef vogl::hash_map<uint64_t, empty_type> vogl_sync_hash_set;

//----------------------------------------------------------------------------------------------------------------------
// vogl_handle_to_sync
//----------------------------------------------------------------------------------------------------------------------
inline GLsync vogl_handle_to_sync(uint64_t handle)
{
    GLsync sync = 0;
    memcpy(&sync, &handle, math::minimum<uint>(sizeof(GLsync), sizeof(uint64_t)));
    return sync;
}

//----------------------------------------------------------------------------------------------------------------------
// vogl_sync_to_handle
//----------------------------------------------------------------------------------------------------------------------
inline uint64_t vogl_sync_to_handle(GLsync sync)
{
    uint64_t handle = 0;
    memcpy(&handle, &sync, math::minimum<uint>(sizeof(GLsync), sizeof(uint64_t)));
    return handle;
}

//----------------------------------------------------------------------------------------------------------------------
// struct vogl_mapped_buffer_desc
//----------------------------------------------------------------------------------------------------------------------
struct vogl_mapped_buffer_desc
{
    // Handles and ptrs here are in the replay/GL domain
    GLuint m_buffer;
    GLenum m_target;
    vogl_trace_ptr_value m_offset;
    vogl_trace_ptr_value m_length;
    GLbitfield m_access;
    bool m_range;
    void *m_pPtr;

    vogl_mapped_buffer_desc()
    {
        clear();
    }

    void clear()
    {
        memset(this, 0, sizeof(*this));
    }
};

typedef vogl::vector<vogl_mapped_buffer_desc> vogl_mapped_buffer_desc_vec;

//----------------------------------------------------------------------------------------------------------------------
// class vogl_capture_context_params
// TODO: Rename this to vogl_context_state_shadow?
//----------------------------------------------------------------------------------------------------------------------
class vogl_capture_context_params
{
public:
    vogl_capture_context_params()
        : m_rbos(VOGL_NAMESPACE_RENDER_BUFFERS),
          m_textures(VOGL_NAMESPACE_TEXTURES),
          m_objs(VOGL_NAMESPACE_PROGRAMS),
          m_filter_program_handles(false)
    {
        VOGL_FUNC_TRACER
    }

    void clear()
    {
        VOGL_FUNC_TRACER

        m_query_targets.clear();
        m_buffer_targets.clear();
        m_samplers.clear();
        m_vaos.clear();
        m_syncs.clear();
        m_framebuffers.clear();
        m_display_lists.clear();
        m_arb_program_targets.clear();

        m_rbos.clear();
        m_textures.clear();
        m_objs.clear();

        m_linked_programs.clear();

        m_program_handles_filter.clear();
        m_filter_program_handles = false;
    }

    // During tracing: All handles live in the tracing GL namespace (there is no replay namespace).
    // During replay: Any handles here live in the actual GL namespace (i.e. the "replay" or native GL namespace, NOT the trace namespace).
    vogl_handle_hash_map m_query_targets;
    vogl_handle_hash_map m_buffer_targets;
    vogl_handle_hash_set m_samplers;
    vogl_handle_hash_set m_vaos;
    vogl_sync_hash_set m_syncs;
    vogl_handle_hash_set m_framebuffers;
    vogl_handle_hash_map m_arb_program_targets;

    // During replay: trace domain
    vogl_display_list_state m_display_lists;

    // During replay: replay domain
    vogl_linked_program_state m_linked_programs;
    vogl_mapped_buffer_desc_vec m_mapped_buffers;

    // During replay: These objects map from trace (non-inv) to replay (inv).
    // TODO: Transition ALL the above hash sets/maps to instances of vogl_handle_tracker.
    vogl_handle_tracker m_rbos;
    vogl_handle_tracker m_textures;
    vogl_handle_tracker m_objs;

    vogl_handle_hash_set m_program_handles_filter;
    bool m_filter_program_handles;
};

//----------------------------------------------------------------------------------------------------------------------
// class vogl_state_snapshot
//----------------------------------------------------------------------------------------------------------------------
class vogl_context_snapshot
{
    VOGL_NO_COPY_OR_ASSIGNMENT_OP(vogl_context_snapshot);

public:
    vogl_context_snapshot();
    ~vogl_context_snapshot();

    void clear();

    bool capture(const vogl_context_desc &desc, const vogl_context_info &info, const vogl_capture_context_params &capture_params, vogl_handle_remapper &remapper);

    bool is_valid() const
    {
        return m_is_valid;
    }

    const vogl_context_desc &get_context_desc() const
    {
        return m_context_desc;
    }
    const vogl_context_info &get_context_info() const
    {
        return m_context_info;
    }

    bool remap_handles(vogl_handle_remapper &remapper);

    const vogl_general_context_state &get_general_state() const
    {
        return m_general_state;
    }
    vogl_general_context_state &get_general_state()
    {
        return m_general_state;
    }

    const vogl_texenv_state &get_texenv_state() const
    {
        return m_texenv_state;
    }
    vogl_texenv_state &get_texenv_state()
    {
        return m_texenv_state;
    }

    const vogl_light_state &get_light_state() const
    {
        return m_light_state;
    }
    vogl_light_state &get_light_state()
    {
        return m_light_state;
    }

    const vogl_material_state &get_material_state() const
    {
        return m_material_state;
    }
    vogl_material_state &get_material_state()
    {
        return m_material_state;
    }

    const vogl_display_list_state &get_display_list_state() const
    {
        return m_display_list_state;
    }
    vogl_display_list_state &get_display_list_state()
    {
        return m_display_list_state;
    }

    const vogl_matrix_state &get_matrix_state() const
    {
        return m_matrix_state;
    }
    vogl_matrix_state &get_matrix_state()
    {
        return m_matrix_state;
    }

    const vogl_polygon_stipple_state &get_polygon_stipple_state() const
    {
        return m_polygon_stipple_state;
    }
    vogl_polygon_stipple_state &get_polygon_stipple_state()
    {
        return m_polygon_stipple_state;
    }

    const vogl_gl_object_state_ptr_vec &get_objects() const
    {
        return m_object_ptrs;
    }
    vogl_gl_object_state_ptr_vec &get_objects()
    {
        return m_object_ptrs;
    }

    const vogl_current_vertex_attrib_state &get_current_vertex_attrib_state() const
    {
        return m_current_vertex_attrib_state;
    }
    vogl_current_vertex_attrib_state &get_current_vertex_attrib_state()
    {
        return m_current_vertex_attrib_state;
    }

    const vogl_arb_program_environment_state &get_arb_program_environment_state() const
    {
        return m_arb_program_environment_state;
    }
    vogl_arb_program_environment_state &get_arb_program_environment_state()
    {
        return m_arb_program_environment_state;
    }

    void get_all_objects_of_category(vogl_gl_object_state_type state_type, vogl_gl_object_state_ptr_vec &obj_ptr_vec) const;

    bool serialize(json_node &node, vogl_blob_manager &blob_manager, const vogl_ctypes *pCtypes) const;
    bool deserialize(const json_node &node, const vogl_blob_manager &blob_manager, const vogl_ctypes *pCtypes);

private:
    vogl_context_desc m_context_desc;
    vogl_context_info m_context_info;

    vogl_general_context_state m_general_state;
    vogl_texenv_state m_texenv_state;
    vogl_light_state m_light_state;
    vogl_material_state m_material_state;
    vogl_display_list_state m_display_list_state;
    vogl_matrix_state m_matrix_state;
    vogl_polygon_stipple_state m_polygon_stipple_state;
    vogl_current_vertex_attrib_state m_current_vertex_attrib_state;
    vogl_arb_program_environment_state m_arb_program_environment_state;

    vogl_gl_object_state_ptr_vec m_object_ptrs;

    bool capture_objects(vogl_gl_object_state_type state_type, const vogl_capture_context_params &capture_params, vogl_handle_remapper &remapper);

    bool m_is_valid;

    void destroy_objects();
};

typedef vogl::vector<vogl_context_snapshot *> vogl_context_snapshot_ptr_vec;

//----------------------------------------------------------------------------------------------------------------------
// struct vogl_client_side_array_desc
//----------------------------------------------------------------------------------------------------------------------
struct vogl_client_side_array_desc
{
    vogl_client_side_array_desc()
    {
    }
    vogl_client_side_array_desc(vogl_trace_ptr_value ptr, uint size)
        : m_ptr(ptr), m_size(size)
    {
    }

    void init(vogl_trace_ptr_value ptr, uint size)
    {
        m_ptr = ptr;
        m_size = size;
    }

    vogl_trace_ptr_value m_ptr;
    uint m_size;

    bool serialize(json_node &node, vogl_blob_manager &blob_manager) const
    {
        VOGL_FUNC_TRACER

        VOGL_NOTE_UNUSED(blob_manager);

        node.add_key_value("ptr", m_ptr);
        node.add_key_value("size", m_size);
        return true;
    }

    bool deserialize(const json_node &node, const vogl_blob_manager &blob_manager)
    {
        VOGL_FUNC_TRACER

        VOGL_NOTE_UNUSED(blob_manager);

        m_ptr = node.value_as_uint64("ptr");
        m_size = node.value_as_uint32("size");
        return true;
    }
};

typedef vogl::vector<vogl_client_side_array_desc> vogl_client_side_array_desc_vec;

//----------------------------------------------------------------------------------------------------------------------
// class vogl_gl_state_snapshot
//----------------------------------------------------------------------------------------------------------------------
class vogl_gl_state_snapshot
{
    VOGL_NO_COPY_OR_ASSIGNMENT_OP(vogl_gl_state_snapshot);

public:
    vogl_gl_state_snapshot();
    ~vogl_gl_state_snapshot();

    void clear();

    // frame_index indicates the beginning of frame X, at a swap boundary
    bool begin_capture(uint window_width, uint window_height, vogl_trace_ptr_value cur_context, uint frame_index, int64_t gl_call_counter, bool at_frame_boundary);

    void add_client_side_array_ptrs(const vogl_client_side_array_desc_vec &client_side_vertex_attrib_ptrs, const vogl_client_side_array_desc_vec &client_side_array_ptrs, const vogl_client_side_array_desc_vec &client_side_texcoord_ptrs);

    bool capture_context(
        const vogl_context_desc &desc, const vogl_context_info &info, vogl_handle_remapper &remapper,
        const vogl_capture_context_params &capture_params);

    bool end_capture();

    bool is_valid() const
    {
        return m_is_valid;
    }

    bool serialize(json_node &node, vogl_blob_manager &blob_manager, const vogl_ctypes *pCtypes) const;
    bool deserialize(const json_node &node, const vogl_blob_manager &blob_manager, const vogl_ctypes *pCtypes);

    md5_hash get_uuid() const
    {
        return m_uuid;
    }
    uint get_window_width() const
    {
        return m_window_width;
    }
    uint get_window_height() const
    {
        return m_window_height;
    }
    vogl_trace_ptr_value get_cur_trace_context() const
    {
        return m_cur_trace_context;
    }

    void set_frame_index(uint frame_index)
    {
        m_frame_index = frame_index;
    }
    uint get_frame_index() const
    {
        return m_frame_index;
    }
    int64_t get_gl_call_counter() const
    {
        return m_gl_call_counter;
    }
    bool get_at_frame_boundary() const
    {
        return m_at_frame_boundary;
    }

    bool get_is_restorable() const
    {
        return m_is_restorable;
    }
    void set_is_restorable(bool is_restorable)
    {
        m_is_restorable = is_restorable;
    }

    const vogl_client_side_array_desc_vec &get_client_side_vertex_attrib_ptrs() const
    {
        return m_client_side_vertex_attrib_ptrs;
    }
    const vogl_client_side_array_desc_vec &get_client_side_array_ptrs() const
    {
        return m_client_side_array_ptrs;
    }
    const vogl_client_side_array_desc_vec &get_client_side_texcoord_ptrs() const
    {
        return m_client_side_texcoord_ptrs;
    }

    const vogl_context_snapshot_ptr_vec &get_contexts() const
    {
        return m_context_ptrs;
    }
    vogl_context_snapshot_ptr_vec &get_contexts()
    {
        return m_context_ptrs;
    }

    const vogl_default_framebuffer_state &get_default_framebuffer() const
    {
        return m_default_framebuffer;
    }
    vogl_default_framebuffer_state &get_default_framebuffer()
    {
        return m_default_framebuffer;
    }

    vogl_context_snapshot* get_context(vogl_trace_ptr_value contextHandle) const
    {
        for (vogl_context_snapshot_ptr_vec::const_iterator iter = m_context_ptrs.begin(); iter != m_context_ptrs.end(); iter++)
        {
            if ((*iter)->get_context_desc().get_trace_context() == contextHandle)
            {
                return (*iter);
            }
        }
        return NULL;
    }

private:
    md5_hash m_uuid;
    uint m_window_width;
    uint m_window_height;
    vogl_trace_ptr_value m_cur_trace_context;
    uint m_frame_index;
    int64_t m_gl_call_counter;
    bool m_at_frame_boundary;
    bool m_is_restorable;

    vogl_client_side_array_desc_vec m_client_side_vertex_attrib_ptrs;
    vogl_client_side_array_desc_vec m_client_side_array_ptrs;
    vogl_client_side_array_desc_vec m_client_side_texcoord_ptrs;

    vogl_context_snapshot_ptr_vec m_context_ptrs;

    vogl_default_framebuffer_state m_default_framebuffer;

    bool m_captured_default_framebuffer;
    bool m_is_valid;

    void destroy_contexts()
    {
        for (uint i = 0; i < m_context_ptrs.size(); i++)
            vogl_delete(m_context_ptrs[i]);
        m_context_ptrs.clear();
    }
};

namespace vogl
{
    VOGL_DEFINE_BITWISE_MOVABLE(vogl_context_snapshot);
    VOGL_DEFINE_BITWISE_MOVABLE(vogl_gl_state_snapshot);
}

#endif // VOGL_GL_STATE_SNAPSHOT_H


text:
from django.conf.urls import include, url

from rest_framework.routers import SimpleRouter
from rest_framework_nested.routers import NestedSimpleRouter

from olympia.bandwagon.views import CollectionViewSet, CollectionAddonViewSet

from . import views

accounts = SimpleRouter()
accounts.register(r'account', views.AccountViewSet, base_name='account')

collections = NestedSimpleRouter(accounts, r'account', lookup='user')
collections.register(r'collections', CollectionViewSet,
                     base_name='collection')
sub_collections = NestedSimpleRouter(collections, r'collections',
                                     lookup='collection')
sub_collections.register('addons', CollectionAddonViewSet,
                         base_name='collection-addon')

notifications = NestedSimpleRouter(accounts, r'account', lookup='user')
notifications.register(r'notifications', views.AccountNotificationViewSet,
                       base_name='notification')

urlpatterns = [
    url(r'^authenticate/$', views.AuthenticateView.as_view(),
        name='accounts.authenticate'),
    url(r'^login/start/$',
        views.LoginStartView.as_view(),
        name='accounts.login_start'),
    url(r'^session/$', views.SessionView.as_view(),
        name='accounts.session'),
    url(r'', include(accounts.urls)),
    url(r'^profile/$', views.ProfileView.as_view(), name='account-profile'),
    url(r'^super-create/$', views.AccountSuperCreate.as_view(),
        name='accounts.super-create'),

    url(r'', include(collections.urls)),
    url(r'', include(sub_collections.urls)),
    url(r'', include(notifications.urls)),
]


text: Test that all nodes from the detached DOM tree will get into one group in the heap snapshot. Bug 107819.


text:
/**
 *
 */
package gov.nih.nci.calims2.business.inventory.containertype;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import javax.validation.ConstraintViolation;

import org.junit.Test;

import gov.nih.nci.calims2.business.util.validation.ValidationException;
import gov.nih.nci.calims2.business.util.validation.ValidationOperation;
import gov.nih.nci.calims2.business.util.validation.ValidatorFactoryMockup;
import gov.nih.nci.calims2.domain.inventory.ContainerType;

/**
 * @author connollym
 *
 */
public class ContainerTypeValidatorTest {

  private ContainerTypeValidator containerTypeValidator = new ContainerTypeValidator();
  private ValidatorFactoryMockup mockupValidatorFactory;

  /**
   * Tests the ContainerTypeValidator. The validator should throw an exception.
   */
  @Test
  public void testValidateContainerTypeFalse() {
    mockupValidatorFactory = new ValidatorFactoryMockup();
    mockupValidatorFactory.setValidator(new ContainerTypeValidatorMockup());
    containerTypeValidator.setValidatorFactory(mockupValidatorFactory);
    ContainerType containerType = new ContainerType();
    try {
    containerTypeValidator.validate(containerType, ValidationOperation.CREATE);
    fail("Validator should have thrown an exception");
    } catch (ValidationException ex) {
      ConstraintViolation<?> violation = ex.getViolations().iterator().next();
      assertEquals("Not a valid ContainerType.", violation.getMessage(), "Name required.");
    }
  }

 /**
  *  Tests the ContainerTypeValidator. The validator should not throw an exception.
  */
  @Test
public void testValidateContainerTypeTrue() {
  mockupValidatorFactory = new ValidatorFactoryMockup();
  mockupValidatorFactory.setValidator(new ContainerTypeValidatorMockup());

  containerTypeValidator.setValidatorFactory(mockupValidatorFactory);
  ContainerType containerType = new ContainerType();
  containerType.setName("JOE");
  try {
        containerTypeValidator.validate(containerType, ValidationOperation.CREATE);
  } catch (ValidationException ex) {
    fail("Validator no have thrown an exception");
  }
  }
}


text:
/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-2.0-xr-w32-bld/build/dom/interfaces/css/nsIDOMCSSStyleRule.idl
 */

#ifndef __gen_nsIDOMCSSStyleRule_h__
#define __gen_nsIDOMCSSStyleRule_h__

#ifndef __gen_nsIDOMCSSRule_h__
#include "nsIDOMCSSRule.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif

/* starting interface:    nsIDOMCSSStyleRule */
#define NS_IDOMCSSSTYLERULE_IID_STR "a6cf90bf-15b3-11d2-932e-00805f8add32"

#define NS_IDOMCSSSTYLERULE_IID \
  {0xa6cf90bf, 0x15b3, 0x11d2, \
    { 0x93, 0x2e, 0x00, 0x80, 0x5f, 0x8a, 0xdd, 0x32 }}

class NS_NO_VTABLE NS_SCRIPTABLE nsIDOMCSSStyleRule : public nsIDOMCSSRule {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMCSSSTYLERULE_IID)

  /* attribute DOMString selectorText; */
  NS_SCRIPTABLE NS_IMETHOD GetSelectorText(nsAString & aSelectorText) = 0;
  NS_SCRIPTABLE NS_IMETHOD SetSelectorText(const nsAString & aSelectorText) = 0;

  /* readonly attribute nsIDOMCSSStyleDeclaration style; */
  NS_SCRIPTABLE NS_IMETHOD GetStyle(nsIDOMCSSStyleDeclaration **aStyle) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMCSSStyleRule, NS_IDOMCSSSTYLERULE_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIDOMCSSSTYLERULE \
  NS_SCRIPTABLE NS_IMETHOD GetSelectorText(nsAString & aSelectorText); \
  NS_SCRIPTABLE NS_IMETHOD SetSelectorText(const nsAString & aSelectorText); \
  NS_SCRIPTABLE NS_IMETHOD GetStyle(nsIDOMCSSStyleDeclaration **aStyle);

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIDOMCSSSTYLERULE(_to) \
  NS_SCRIPTABLE NS_IMETHOD GetSelectorText(nsAString & aSelectorText) { return _to GetSelectorText(aSelectorText); } \
  NS_SCRIPTABLE NS_IMETHOD SetSelectorText(const nsAString & aSelectorText) { return _to SetSelectorText(aSelectorText); } \
  NS_SCRIPTABLE NS_IMETHOD GetStyle(nsIDOMCSSStyleDeclaration **aStyle) { return _to GetStyle(aStyle); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIDOMCSSSTYLERULE(_to) \
  NS_SCRIPTABLE NS_IMETHOD GetSelectorText(nsAString & aSelectorText) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSelectorText(aSelectorText); } \
  NS_SCRIPTABLE NS_IMETHOD SetSelectorText(const nsAString & aSelectorText) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetSelectorText(aSelectorText); } \
  NS_SCRIPTABLE NS_IMETHOD GetStyle(nsIDOMCSSStyleDeclaration **aStyle) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetStyle(aStyle); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsDOMCSSStyleRule : public nsIDOMCSSStyleRule
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIDOMCSSSTYLERULE

  nsDOMCSSStyleRule();

private:
  ~nsDOMCSSStyleRule();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS1(nsDOMCSSStyleRule, nsIDOMCSSStyleRule)

nsDOMCSSStyleRule::nsDOMCSSStyleRule()
{
  /* member initializers and constructor code */
}

nsDOMCSSStyleRule::~nsDOMCSSStyleRule()
{
  /* destructor code */
}

/* attribute DOMString selectorText; */
NS_IMETHODIMP nsDOMCSSStyleRule::GetSelectorText(nsAString & aSelectorText)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsDOMCSSStyleRule::SetSelectorText(const nsAString & aSelectorText)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* readonly attribute nsIDOMCSSStyleDeclaration style; */
NS_IMETHODIMP nsDOMCSSStyleRule::GetStyle(nsIDOMCSSStyleDeclaration **aStyle)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

#endif /* __gen_nsIDOMCSSStyleRule_h__ */


text:
$:.unshift 'lib'
$LOAD_PATH << File.dirname(__FILE__)

require 'helper'
require 'odesk/api/routers/activities/team'
require 'test/unit'
require 'mocha/test_unit'

class ActivitiesTeamTest < Test::Unit::TestCase
  include TestHelper

  def test_get_list
    api = Odesk::Api::Routers::Activities::Team.new(get_client_mock)
    assert api.get_list('company', 'team')
  end

  def test_get_specific_list
    api = Odesk::Api::Routers::Activities::Team.new(get_client_mock)
    assert api.get_specific_list('company', 'team', 'code')
  end

  def test_add_activity
    api = Odesk::Api::Routers::Activities::Team.new(get_client_mock)
    assert api.add_activity('company', 'team', {})
  end

  def test_update_activities
    api = Odesk::Api::Routers::Activities::Team.new(get_client_mock)
    assert api.update_activities('company', 'team', 'code', {})
  end

  def test_archive_activities
    api = Odesk::Api::Routers::Activities::Team.new(get_client_mock)
    assert api.archive_activities('company', 'team', 'code')
  end

  def test_unarchive_activities
    api = Odesk::Api::Routers::Activities::Team.new(get_client_mock)
    assert api.unarchive_activities('company', 'team', 'code')
  end

  def test_update_batch
    api = Odesk::Api::Routers::Activities::Team.new(get_client_mock)
    assert api.update_batch('company', 'data')
  end
end


text:
#import "BBASearchResponseMapper.h"
#import "BBAAPIErrors.h"
#import "BBAConnection.h"
#import "BBASearchService.h"
#import "BBASearchItem.h"
#import "BBASearchServiceResult.h"
#import "BBASearchSuggestionsResult.h"
#import <FastEasyMapping/FastEasyMapping.h>
#import "BBAMacros.h"

@interface BBASearchResponseMapper()

@property (nonatomic, copy) NSDictionary *statusCodeErrors;

@end

@implementation BBASearchResponseMapper

#pragma mark - Public methods
- (id) responseFromData:(NSData *)data
               response:(NSURLResponse *)response
                  error:(NSError **)error{
    NSInteger statusCode = ((NSHTTPURLResponse *)response).statusCode;

    if (statusCode != BBAHTTPSuccess) {
        if (error) {
            *error = self.statusCodeErrors[@(statusCode)];
        }
        return nil;
    }

    NSDictionary *responseData = [super responseFromData:data
                                                response:response
                                                   error:nil];
    if (!responseData){
        if (error){
            *error = [NSError errorWithDomain:BBASearchServiceErrorDomain
                                         code:BBAAPIUnreadableData
                                     userInfo:nil];
        }
        return nil;
    }

    NSString *type = responseData[@"type"];

    if ([type isEqualToString:@"urn:blinkboxbooks:schema:list"]) {
        FEMObjectMapping *mapping = [BBASearchSuggestionsResult searchSuggestionsResultMapping];
        BBASearchSuggestionsResult *result;
        result = [FEMObjectDeserializer deserializeObjectExternalRepresentation:responseData
                                                                   usingMapping:mapping];

        return result;

    }
    else if([type isEqualToString:@"urn:blinkboxbooks:schema:search"]){
        FEMObjectMapping *mapping = [BBASearchServiceResult searchServiceResultMapping];
        BBASearchServiceResult *result;
        result = [FEMObjectDeserializer deserializeObjectExternalRepresentation:responseData
                                                                   usingMapping:mapping];

        return result;
    }
    else{
        NSAssert(@"Unrecognised response type %@", type);
        return nil;
    }

}

#pragma mark - Private Methods

#pragma mark Getters

- (NSDictionary *) statusCodeErrors{

    if(!_statusCodeErrors){

        NSError *badRequestError;
        badRequestError = [NSError errorWithDomain:BBASearchServiceErrorDomain
                                              code:BBAAPIErrorBadRequest
                                          userInfo:nil];

        NSError *notFoundError;
        notFoundError = [NSError errorWithDomain:BBASearchServiceErrorDomain
                                              code:BBAAPIErrorNotFound
                                          userInfo:nil];

        NSError *serverError;
        serverError = [NSError errorWithDomain:BBASearchServiceErrorDomain
                                              code:BBAAPIServerError
                                          userInfo:nil];

        _statusCodeErrors = @{@(BBAHTTPBadRequest) : badRequestError,
                              @(BBAHTTPNotFound) : notFoundError,
                              @(BBAHTTPServerError) : serverError};
    }
    return _statusCodeErrors;
}

@end


text:
def count_between(list_of_integers, lower_bound, upper_bound)
  array = []
  list_of_integers.each do |x|
    if x > lower_bound && x < upper_bound
      array.push(x)
    end
  end

  p array.length
end


text:
[![Build Status](https://travis-ci.org/tikivn/ABTesting.svg?branch=master)](https://travis-ci.org/tikivn/ABTesting)

Solution to Remote config Firebase in reactive way

![](assets/logo.png)

## Sample Usage

 ```java

 public class ABApplication extends Application {

  @Override
  public void onCreate() {
    super.onCreate();

    FirebaseApp.initializeApp(this);

    ABTesting ab = new ABTesting(new AbSettings.Builder()
        .debug(BuildConfig.DEBUG)
        .cacheExpiration(2, TimeUnit.SECONDS)
        .defaults(defaultAbValues())
        .build());
  }
}

public class MainActivity extends AppCompatActivity {

  public void fetch(View view) {
    ABApplication.get(this).getAb()
        .request(this)
        .key("onboard_navigation")
        .timeout(5, TimeUnit.SECONDS)
        .build()
        .parseValue(Parser.BOOLEAN)
        .retry(3)
        .subscribe(new Action1<Boolean>() {
          @Override public void call(Boolean value) {
            if (value) {
              startActivity(new Intent(MainActivity.this, OnboardActivity.class));
            } else {
              startActivity(new Intent(MainActivity.this, HomeActivity.class));
            }
            finish();
          }
        });
  }

 ```

 Support primitive types

 ```
 Parser.BOOLEAN
 Parser.LONG
 Parser.DOUBLE
 Parser.FLOAT
 Parser.BYTE
 Parser.INTEGER
 ```

 if ``String``

 use ``.stringValue()`` instead of ``parseValue()``

## Avoid memory leak

 Memory leak is detected in ``FirebaseRemoteConfig`` so it's mandatory to pass your ``Activity`` as parameter in ``request`` method

## Download

Download [the latest JAR][1] or grab via Gradle:
```groovy
compile 'vn.tiki.ab:abtesting:1.0.2-SNAPSHOT'
```
or Maven:
```xml
<dependency>
  <groupId>vn.tiki.ab</groupId>
  <artifactId>abtesting</artifactId>
  <version>1.0.2-SNAPSHOT</version>
</dependency>
```

Snapshots of the development version are available in [Sonatype's `snapshots` repository][snap].

## ProGuard

No specific

## License

    Copyright 2016 Tiki Corp

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

 [1]: https://search.maven.org/remote_content?g=vn.tiki.noadapter&a=noadapter&v=LATEST
 [snap]: https://oss.sonatype.org/content/repositories/snapshots/


text:
/**
 * Controller for volunteering
 */
mikael.controller('volunteeringCtrl', function($scope) {
    $scope.tooltips();
});


text:
from bs4 import BeautifulSoup
import requests

def get_movie_details(movie):
	url=str(movie['url'])
	response=requests.get(url)
	response.raise_for_status()
	soup=BeautifulSoup(response.text,'html.parser')
	name=soup.findAll('h1',{'class':'__name'})[0].string
	synopsis=(soup.findAll('div',{'class':'synopsis'})[0].blockquote.findAll(text=True))
	synopsis=str(' '.join(synopsis))
	synopsis=synopsis.strip(' \t\n')
	critic_rating=soup.findAll('span',{'class':'__rating'})[0].ul.attrs['data-value']
	trailer_code=soup.findAll('div',{'class':'banner-main synopsis-banner'})[0].attrs['data-trailer-code']
	trailer_url="www.youtube.com/watch?v="+trailer_code
	cast_list=soup.findAll('span',{'itemprop':'actor'})
	cast=[]
	for cast_member in cast_list:
		cast_name=cast_member.a.div.attrs['content']
		cast.append(cast_name)
	booking_url_code=soup.findAll('div',{'class':'more-showtimes'})[0].a.attrs['href']
	booking_url="https://in.bookmyshow.com"+booking_url_code
	movie_detail={
		'name': name,
		'synopsis' : synopsis,
		'critic_rating' : critic_rating,
		'trailer-url': trailer_url,
		'lead_cast': cast[0:4],
		'booking_url': booking_url
	}
	return movie_detail

if __name__ == '__main__':
	from pprint import pprint
	from get_data import get_final_list
	location="kota"
	mlist=get_final_list(location)
	pprint(mlist[0])
	details=get_movie_details(mlist[0])
	pprint(details)


text:
/*jshint indent: 2 */
/*global angular: false */

(function () {
  'use strict';
  angular.module('ui.sortable', [])
    .constant('sortableConfig', {
      itemClass: 'as-sortable-item',
      handleClass: 'as-sortable-item-handle',
      placeHolderClass: 'as-sortable-placeholder',
      dragClass: 'as-sortable-drag',
      hiddenClass: 'as-sortable-hidden'
    });
}());


text:
package FIIT.VI.YAGO.ui;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.document.Document;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.store.SimpleFSDirectory;

import FIIT.VI.YAGO.index.WikiIndex;

/**
 * Main model
 * @author mm
 *
 */
public class MainModel {

	private WikiIndex indexFolder;

	private static SimpleFSDirectory indexDirection;
	private final static String INDEX = "/media/mm/Data/index";

	public MainModel() throws IOException {
		indexDirection = new SimpleFSDirectory(new File(INDEX));
		indexFolder = new WikiIndex(indexDirection);
	}

	/**
	 * Service of search index
	 * @param searchString search String
	 * @return list of lucene documents
	 */
	public List<Document> searchIndex(String searchString) {
		try {
			return indexFolder.searchIndex(searchString);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new ArrayList<Document>();
	}

}


text:
package com.invivoo.springboot.securedrestapi.entity;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity
public class Stock {
	private long id;
	private String name;
	private String isin;
	private List<StockQuote> stockQuotes;

	public Stock() {

	}

	public Stock(long id, String name, String isin, List<StockQuote> stockQuotes) {
		this.id = id;
		this.name = name;
		this.isin = isin;
		this.stockQuotes = stockQuotes;
	}

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getIsin() {
		return isin;
	}

	public void setIsin(String isin) {
		this.isin = isin;
	}

	@OneToMany(cascade = CascadeType.ALL)
	public List<StockQuote> getStockQuotes() {
		return stockQuotes;
	}

	public void setStockQuotes(List<StockQuote> stockQuotes) {
		this.stockQuotes = stockQuotes;
	}
}