text:
from collections import OrderedDict
import logging
import operator

from fumbbl_base import common_regex, crp, servertime
from fumbbl_trans.ffb_replay import Session

from fplusdb_main.custom_types import *
from fplusdb_main.scheme import *

logger = logging.getLogger(__name__)

_TEMP_POSTYPE = '_temp_position_type'

class ImportError(Exception):
  pass

def import_(replay_msgs, target=None, match_id=None):
  replay_objs = (Session.msg2obj(msg) for msg in replay_msgs)
  game_report_msg = next(replay_objs)
  result = import_from_game_report_msg(game_report_msg,
      target=target, match_id=match_id)
  return result

def import_from_game_report_msg(game_report_msg, target=None,
    match_id=None):
  target = (target if target is not None else {})
  assert game_report_msg['netCommandId'] == 'serverGameState'
  game = game_report_msg['game']
  match_row = _get_match_row(game, match_id)
  match_option_row = _get_match_option_row(game, match_id)
  team_data = _get_team_data(game)
  team_rows = _get_team_rows(team_data, match_id)
  team_assntf_setuprows = _get_team_assntf_setuprows(team_data,
      match_id)
  position_rows = _get_position_rows(team_data)
  player_rows = _get_player_rows(team_data, position_rows,
      match_id)

  # delete the temporary saved position types
  for r in position_rows:
    del r[_TEMP_POSTYPE]

  target[MATCH] = [match_row]
  target[MATCH_OPTION] = [match_option_row]
  target[TEAM] = team_rows
  target[ASSNSTF] = team_assntf_setuprows
  target[POSITION] = sorted(position_rows,
      key=operator.itemgetter(POSITION.ID))
  target[PLAYER] = sorted(player_rows,
      key=operator.itemgetter(PLAYER.MATCH_ID, PLAYER.AWAY,
          PLAYER.PHASE, PLAYER.NR, PLAYER.FLOW))
  return target

def _get_empty_pl_row(match_id=None):
  pl_row = {k: None for k in PLAYER.columns}
  pl_row[PLAYER.MATCH_ID] = match_id
  return pl_row

def _get_match_row(game, match_id=None):
  match_row = {MATCH.ID: match_id}
  for k, column in (
      ('scheduled', MATCH.SCHEDULED),
      ('started', MATCH.STARTED),
      ('finished', MATCH.FINISHED),
      ):
    if game.get(k) is not None:
      tstr = game[k] + '000'
      match_row[column] = servertime.tzize_string(tstr)
  for k, column in (
      ('gameTime', MATCH.GAME_TIME),
      ('gameId', MATCH.REPLAY_ID),
      ('half', MATCH.PERIODS),
      ):
    match_row[column] = game[k]
  return match_row

def _get_match_option_row(game, match_id):
  match_option_row = {MATCH_OPTION.MATCH_ID: match_id}
  for d in game['gameOptions']['gameOptionArray']:
    k = d['gameOptionId']
    v = d['gameOptionValue']
    if v == 'true':
      v = True
    elif v == 'false':
      v = False
    elif v.isdecimal():
      v = int(v)
    match_option_row[k] = v
  return match_option_row

def _get_player_rows(team_data, position_rows, match_id=None):
  player_rows = []
  pos_rows_by_id = {r[POSITION.ID]: r for r in position_rows}
  for i, d in enumerate(team_data):
    for player_id, pl_ros_d in d['player_rosters'].items():
      f_args = [match_id, team_data, pos_rows_by_id, i,
        player_id]
      pl_ffbtype = pl_ros_d['playerType']
      if pl_ffbtype in {'Regular', 'Big Guy', 'Irregular'}:
        pl_setuprow = _get_pl_setuprow_regular(*f_args)
        pl_prerow = None
      elif pl_ffbtype  == 'Mercenary':
        pl_setuprow = None
        pl_prerow = _get_pl_prerow_merc(*f_args)
      elif pl_ffbtype  == 'Star':
        pl_setuprow = None
        pl_prerow = _get_pl_prerow_star(*f_args)
      elif pl_ffbtype  == 'RaisedFromDead':
        pl_setuprow = None
        pl_prerow = None
      else:
        efs = 'unknown FFB player type: {!r}'
        raise ImportError(efs.format(pl_ffbtype))
      if pl_setuprow:
        player_rows.append(pl_setuprow)
      if pl_prerow:
        player_rows.append(pl_prerow)
      f_args += [pl_setuprow, pl_prerow]

      pl_regrow = pl_setuprow or pl_prerow

      misses_match = player_flow.MISSES_MATCH.value
      if pl_ffbtype != 'RaisedFromDead':
        if pl_regrow[PLAYER.FLOW] == misses_match:
          pl_matchrow = None
        else:
          pl_matchrow = _get_pl_matchrow(*f_args)
      else:
        pl_matchrow = _get_pl_matchrow_raised(*f_args)
      if pl_matchrow:
        player_rows.append(pl_matchrow)
      f_args.append(pl_matchrow)
      pl_postrow = _get_pl_postrow(*f_args)
      player_rows.append(pl_postrow)
  return player_rows

def _get_pl_matchrow(match_id, team_data, pos_rows_by_id, i,
    player_id, pl_setuprow, pl_prerow):
  pl_matchrow = _get_empty_pl_row(match_id)
  pl_regrow = pl_setuprow or pl_prerow
  pl_matchrow[PLAYER.AWAY] = bool(i)
  pl_matchrow[PLAYER.PHASE] = phase.MATCH.value
  pl_matchrow[PLAYER.NR] = pl_regrow[PLAYER.NR]
  pl_matchrow[PLAYER.FLOW] = player_flow.HERE.value
  pl_matchrow[PLAYER.TYPE] = pl_regrow[PLAYER.TYPE]
  _upd_pl_row_with_general_from_row(pl_matchrow, pl_regrow)
  _upd_pl_row_with_performances(pl_matchrow, team_data, i,
      player_id)
  _link_player_rows(pl_regrow, pl_matchrow)
  return pl_matchrow

def _get_pl_matchrow_raised(match_id, team_data, pos_rows_by_id,
    i, player_id, pl_setuprow, pl_prerow):
  pl_ros_d = team_data[i]['player_rosters'][player_id]
  pl_pos_row = pos_rows_by_id[int(pl_ros_d['positionId'])]
  pl_matchrow = _get_empty_pl_row(match_id)
  pl_matchrow[PLAYER.AWAY] = bool(i)
  pl_matchrow[PLAYER.PHASE] = phase.MATCH.value
  pl_matchrow[PLAYER.NR] = pl_ros_d['playerNr']
  pl_matchrow[PLAYER.FLOW] = player_flow.RAISED_FROM_DEAD.value
  pl_matchrow[PLAYER.TYPE] = player_type.REGULAR.value
  pl_matchrow[PLAYER.EARNED_SKILLS] = []
  pl_matchrow[PLAYER.BASE_VALUE] = pl_pos_row[POSITION.COST]
  _upd_pl_row_with_general(pl_matchrow, team_data, i, player_id,
      pl_ros_d, pl_pos_row)
  _upd_pl_row_with_performances(pl_matchrow, team_data, i,
      player_id)
  return pl_matchrow

def _get_pl_postrow(match_id, team_data, pos_rows_by_id, i,
    player_id, pl_setuprow, pl_prerow, pl_matchrow):
  pl_postrow = _get_empty_pl_row(match_id)
  pl_res_d = team_data[i]['player_results'][player_id]
  pl_regrow = pl_setuprow or pl_prerow or pl_matchrow
  pl_postrow[PLAYER.AWAY] = bool(i)
  pl_postrow[PLAYER.PHASE] = phase.POST_MATCH.value
  pl_postrow[PLAYER.NR] = pl_regrow[PLAYER.NR]
  si = pl_res_d['seriousInjury']
  if si:
    rem = common_regex.injury.match(si)
  if si and rem.group('effect') == 'RIP':
    pl_postrow[PLAYER.FLOW] = player_flow.DIED.value
  elif pl_regrow[PLAYER.TYPE] in {
      player_type.FREEBOOTER.value,
      player_type.JOURNEYMAN.value,
      player_type.MERCENARY.value,
      player_type.STAR.value,
      }:
    pl_postrow[PLAYER.FLOW] = player_flow.DONE_WITH_MATCH.value
  else:
    # I am unable to determine here, whether the player stays at
    # the team, is retired or got distracted. It can be derived
    # from the next match.
    pl_postrow[PLAYER.FLOW] = player_flow.UNKNOWN.value
  pl_postrow[PLAYER.TYPE] = pl_regrow[PLAYER.TYPE]
  _upd_pl_row_with_general_from_row(pl_postrow, pl_regrow)
  _link_player_rows(pl_regrow, pl_postrow)
  return pl_postrow

def _get_pl_prerow_merc(match_id, team_data, pos_rows_by_id, i,
    player_id):
  pl_ros_d = team_data[i]['player_rosters'][player_id]
  pl_pos_row = pos_rows_by_id[int(pl_ros_d['positionId'])]
  pl_prerow = _get_empty_pl_row(match_id)
  pl_prerow[PLAYER.AWAY] = bool(i)
  pl_prerow[PLAYER.PHASE] = phase.PRE_MATCH.value
  pl_prerow[PLAYER.FLOW] = player_flow.HIRED_FOR_MATCH.value
  pl_prerow[PLAYER.TYPE] = player_type.MERCENARY.value
  pos_cost = pl_pos_row[POSITION.COST]
  pl_prerow[PLAYER.BASE_VALUE] = pos_cost + crp.merc_extra_cost
  _upd_pl_row_with_general(pl_prerow, team_data, i, player_id,
      pl_ros_d, pl_pos_row)
  _upd_pl_row_with_properties(pl_prerow, pl_ros_d, pl_pos_row)
  _upd_pl_row_with_identical_performances(pl_prerow, 0)
  return pl_prerow

def _get_pl_prerow_star(match_id, team_data, pos_rows_by_id, i,
    player_id):
  pl_ros_d = team_data[i]['player_rosters'][player_id]
  position_id = int(pl_ros_d['positionId'])
  pl_pos_row = pos_rows_by_id.get(position_id, {})
  if not pl_pos_row:
    wfs = 'missing position ({}) info for player: {}'
    logger.warning(wfs.format(position_id, player_id))
  pl_prerow = _get_empty_pl_row(match_id)
  pl_prerow[PLAYER.AWAY] = bool(i)
  pl_prerow[PLAYER.PHASE] = phase.PRE_MATCH.value
  pl_prerow[PLAYER.FLOW] = player_flow.HIRED_FOR_MATCH.value
  pl_prerow[PLAYER.TYPE] = player_type.STAR.value
  pl_prerow[PLAYER.BASE_VALUE] = pl_pos_row.get(POSITION.COST)
  _upd_pl_row_with_general(pl_prerow, team_data, i, player_id,
      pl_ros_d, pl_pos_row)
  _upd_pl_row_with_properties(pl_prerow, pl_ros_d, pl_pos_row)
  _upd_pl_row_with_identical_performances(pl_prerow, 0)
  return pl_prerow

def _get_pl_setuprow_regular(match_id, team_data,
    pos_rows_by_id, i, player_id):
  pl_ros_d = team_data[i]['player_rosters'][player_id]
  pl_res_d = team_data[i]['player_results'][player_id]
  position_id = int(pl_ros_d['positionId'])
  pl_pos_row = pos_rows_by_id.get(position_id, {})
  pl_setuprow = _get_empty_pl_row(match_id)
  pl_setuprow[PLAYER.AWAY] = bool(i)
  pl_setuprow[PLAYER.PHASE] = phase.SETUP.value
  pl_ffbtype = pl_ros_d['playerType']
  if pl_ffbtype == 'Irregular':
    pl_setuprow[PLAYER.TYPE] = player_type.IRREGULAR.value
  else:
    pl_setuprow[PLAYER.TYPE] = player_type.REGULAR.value
  _upd_pl_row_with_general(pl_setuprow, team_data, i, player_id,
      pl_ros_d, pl_pos_row)
  # this function switches player type to journeyman if needed
  _upd_pl_row_with_properties(pl_setuprow, pl_ros_d, pl_pos_row)
  if pl_ros_d['recoveringInjury']:
    pl_setuprow[PLAYER.FLOW] = player_flow.MISSES_MATCH.value
  # handling freebuters here is considered a note
  elif pl_setuprow[PLAYER.TYPE] in {
      player_type.JOURNEYMAN.value,
      player_type.FREEBOOTER.value,
      }:
    pl_setuprow[PLAYER.FLOW] = player_flow.HIRED_FOR_MATCH.value
  else:
    # Unfortunately it is not known whether this is a new team.
    # If yes, flow would be HIRED, else HERE.
    pl_setuprow[PLAYER.FLOW] = player_flow.UNKNOWN.value
  base_value = pl_pos_row.get(POSITION.COST, -1)
  if pl_setuprow[PLAYER.TYPE] != player_type.FREEBOOTER.value:
    pl_setuprow[PLAYER.BASE_VALUE] = base_value
  else:
    pl_setuprow[PLAYER.BASE_VALUE] = base_value // 2
  # unfortunately there is no overall data of comp, td, int,
  # cas, mvp, blocks, passing, rushing, and turns, only spp is
  # present
  _upd_pl_row_with_identical_performances(pl_setuprow, None)
  pl_setuprow[PLAYER.SPP] = pl_res_d['currentSpps']
  return pl_setuprow

def _get_position_rows(team_data):
  position_rows = []
  position_ids = {}
  for i, d in enumerate(team_data):
    roster = d['roster']
    for position_id, pos_d, in d['roster_positions'].items():
      pos_row = position_ids.setdefault(position_id, {})
      if pos_row:
        exists = True
      else:
        exists = False
      # I want to book position type in the player table, so I
      # make a temporary dict to save them.
      _temp_postype_l = pos_row.setdefault(_TEMP_POSTYPE,
          [None, None])
      player_type = pos_d['playerType']
      qty = pos_d['quantity']
      if player_type == 'Regular' and 12 <= qty:
        _temp_postype_l[i] = position_type.LINEMEN.value
      elif player_type == 'Regular':
        _temp_postype_l[i] = position_type.POSITIONAL.value
      elif player_type == 'Big Guy':
        _temp_postype_l[i] = position_type.BIGGUY.value
      elif player_type == 'Star':
        _temp_postype_l[i] = position_type.STAR.value
      elif player_type == 'Irregular':
        _temp_postype_l[i] = position_type.IRREGULAR.value
      else:
        efs = 'unknown player type: {!r}'
        raise ImportError(efs.format(player_type))
      if exists:
        continue
      pos_row[POSITION.ID] = position_id
      if pos_d['race']:
        pos_row[POSITION.RACE_NAME] = pos_d['race']
      elif pos_d['playerType'] != 'Star':
        pos_row[POSITION.RACE_NAME] = roster['rosterName']
      else:
        pos_row[POSITION.RACE_NAME] = pos_d['race']
      pos_row[POSITION.QTY] = qty
      pos_row[POSITION.TITLE] = pos_d['positionName']
      pos_row[POSITION.COST] = pos_d['cost']
      pos_row[POSITION.MA] = pos_d['movement']
      pos_row[POSITION.ST] = pos_d['strength']
      pos_row[POSITION.AG] = pos_d['agility']
      pos_row[POSITION.AV] = pos_d['armour']
      pos_row[POSITION.SKILLS] = pos_d.get('skillArray', [])
      # this asserts I have all skill category registered
      # properly in the skillcat enum type
      skillcats = set(crp.skillcat_order.keys())
      normals = {skillcat[catname]
        for catname in pos_d['skillCategoriesNormal']}
      pos_row[POSITION.NORMAL] = sorted(
        (x.value for x in normals),
        key = lambda x: crp.skillcat_order[skillcat(x)])
      # workaround FUMBBL BUG #2190:
      # some rosters are missing explicitely listed doubles
      mutation = {crp.skillcat.MUTATION}
      expected_doubles = skillcats - normals - mutation
      explicit_doubles = {skillcat[catname]
        for catname in pos_d['skillCategoriesDouble']}
      doubles = expected_doubles | explicit_doubles
      pos_row[POSITION.DOUBLE] = sorted(
        (x.value for x in doubles),
        key = lambda x: crp.skillcat_order[skillcat(x)])
      # this line asserts that I have registered all genders
      # in the player_gender enum type
      gender = player_gender[pos_d['playerGender']].value
      pos_row[POSITION.GENDER] = gender
      pos_row[POSITION.UNDEAD] = pos_d['undead']
      pos_row[POSITION.THRALL] = pos_d['thrall']
      position_ids[position_id] = pos_row
      position_rows.append(pos_row)
  return position_rows

def _get_skill_value(skill, player_type_, pl_pos_row):
  loner_types = {player_type.JOURNEYMAN.value,
      player_type.MERCENARY.value}
  if skill == 'Loner' and player_type_ in loner_types:
    return 0
  elif skill in crp.stat_value:
    return crp.stat_value[skill]
  else:
    skillcat = crp.skillcat_by_skill[skill]
    normals = pl_pos_row.get(POSITION.NORMAL)
    if normals is None:
      return -1
    if skillcat in normals:
      if player_type_ == player_type.MERCENARY:
        return crp.merc_normal_skill_value
      else:
        return crp.normal_skill_value
    elif skillcat in pl_pos_row[POSITION.DOUBLE]:
      return crp.double_skill_value
    else:
      wfs = 'unable to get {!r} skill value for position: {!r}'
      position_id = pl_pos_row[POSITION.ID]
      logger.warning(wfs.format(skill, position_id))
      return -1

def _get_team_data(game):
  team_data = [{}, {}]
  ha_names = 'Home', 'Away'
  results_d = game['gameResult']
  for i, ha_name in enumerate(ha_names):
    ha = bool(i)
    ros_d = game['team{}'.format(ha_name)]
    roster = ros_d['roster']
    roster_positions = {int(pos_d['positionId']): pos_d
        for pos_d in roster['positionArray']}
    res_d = results_d['teamResult{}'.format(ha_name)]
    pl_rosters = {pl_ros_d['playerId']: pl_ros_d
        for pl_ros_d in ros_d['playerArray']}
    pl_results = {pl_res_d['playerId']: pl_res_d
        for pl_res_d in res_d['playerResults']}
    team_data[i] = {
      'i': i,
      'ha_name': ha_name,
      'roster': roster,
      'roster_positions': roster_positions,
      'roster_data': ros_d,
      'result_data': res_d,
      'player_results': pl_results,
      'player_rosters': pl_rosters,
      }
  for i, d in enumerate(team_data):
    for k, v in d.items():
      team_data[1 - i]['opp_' + k] = v
  return team_data

def _get_team_rows(team_data, match_id=None):
  team_rows = [{TEAM.MATCH_ID: match_id},
      {TEAM.MATCH_ID: match_id}]
  for i, d in enumerate(team_data):
    team_row = team_rows[i]
    ros_d = d['roster_data']
    res_d = d['result_data']
    opp_res_d = d['opp_result_data']
    team_row[TEAM.AWAY] = bool(i)
    team_row[TEAM.NAME] = ros_d['teamName']
    team_row[TEAM.ID] = int(ros_d['teamId'])
    team_row[TEAM.RACE_NAME] = ros_d['race']
    # race ID can not be obtained here (FUMBBL BUG #2173)
    team_row[TEAM.COACH_NAME] = ros_d['coach']
    team_row[TEAM.TV] = ros_d['teamValue']
    score = res_d['score']
    oppscore = opp_res_d['score']
    result = (score > oppscore) - (score < oppscore)
    team_row[TEAM.RESULT] = result
    team_row[TEAM.CONCEDED] = res_d['conceded']
    team_row[TEAM.SCORE] = score
    team_row[TEAM.FAME] = res_d['fame']
    team_row[TEAM.CAS_INFLICTED] = [
        opp_res_d['badlyHurtSuffered'],
        opp_res_d['seriousInjurySuffered'],
        opp_res_d['ripSuffered'],
        ]
    team_row[TEAM.WINNINGS] = res_d['winnings']
    team_row[TEAM.SPIRALLING_EXPENSES] = \
        res_d['spirallingExpenses']
    team_row[TEAM.FANS] = res_d['spectators']
    team_row[TEAM.FANFACTOR_DELTA] = res_d['fanFactorModifier']
  return team_rows

def _get_team_assntf_setuprows(team_data, match_id=None):
  assntf_setuprows = [{ASSNSTF.MATCH_ID: match_id},
      {ASSNSTF.MATCH_ID: match_id}]
  for i, d in enumerate(team_data):
    ros_d = d['roster_data']
    roster = d['roster']
    assntf_setuprow = assntf_setuprows[i]
    assntf_setuprow[ASSNSTF.AWAY] = bool(i)
    assntf_setuprow[ASSNSTF.PHASE] = phase.SETUP.value
    assntf_setuprow[ASSNSTF.TREASURY] = ros_d['treasury']
    assntf_setuprow[ASSNSTF.PETTY_CASH] = 0
    rerolls = ros_d['reRolls']
    assntf_setuprow[ASSNSTF.RR] = rerolls
    rerolls_value = roster['reRollCost']
    assntf_setuprow[ASSNSTF.RR_VAL] = rerolls_value * rerolls
    ff = ros_d['fanFactor']
    assntf_setuprow[ASSNSTF.FF] = ff
    assntf_setuprow[ASSNSTF.FF_VAL] = ff * crp.fanfactor_value
    acoaches = ros_d['assistantCoaches']
    assntf_setuprow[ASSNSTF.ACOACHES] = acoaches
    acoaches_value = acoaches * crp.acoach_value
    assntf_setuprow[ASSNSTF.ACOACHES_VAL] = acoaches_value
    cheerleaders = ros_d['cheerleaders']
    assntf_setuprow[ASSNSTF.CHEERLEADERS] = cheerleaders
    cheerl_value = cheerleaders * crp.cheerleader_value
    assntf_setuprow[ASSNSTF.CHEERLEADERS_VAL] = cheerl_value
    apothecaries = ros_d['apothecaries']
    assntf_setuprow[ASSNSTF.APOTHECARIES] = apothecaries
    apoth_value = apothecaries * crp.apothecary_value
    assntf_setuprow[ASSNSTF.APOTHECARIES_VAL] = apoth_value
    for key in (ASSNSTF.BABES, ASSNSTF.BABES_VAL,
        ASSNSTF.BRIBES, ASSNSTF.BRIBES_VAL, ASSNSTF.CHEF,
        ASSNSTF.CHEF_VAL, ASSNSTF.IGORS, ASSNSTF.IGORS_VAL,
        ASSNSTF.WIZARDS, ASSNSTF.WIZARDS_VAL, ASSNSTF.CARDS):
      assntf_setuprow[key] = 0
  return assntf_setuprows

def _link_player_rows(pl_row, next_pl_row):
  for keyname in ('MATCH_ID', 'AWAY', 'PHASE', 'NR', 'FLOW'):
    key = getattr(PLAYER, keyname)
    prev_key = getattr(PLAYER, 'PREV_' + keyname)
    next_key = getattr(PLAYER, 'PREV_' + keyname)
    if key in next_pl_row:
      pl_row[next_key] = next_pl_row[key]
    if key in pl_row:
      next_pl_row[prev_key] = pl_row[key]

def _upd_pl_row_with_general(pl_row, team_data, i, player_id,
    pl_ros_d, pl_pos_row):
  pl_row[PLAYER.NR] = pl_ros_d['playerNr']
  pl_row[PLAYER.NAME] = pl_ros_d['playerName']
  if pl_ros_d['playerId'].isdecimal():
    pl_row[PLAYER.ID] = int(pl_ros_d['playerId'])
  if pl_row[PLAYER.TYPE] != player_type.STAR.value:
    race = (pl_pos_row[POSITION.RACE_NAME]
        if pl_pos_row.get(POSITION.RACE_NAME)
        else team_data[i]['roster_data']['race'])
  else:
    race = pl_pos_row.get(POSITION.RACE_NAME)
  pl_row[PLAYER.RACE_NAME] = race
  position_title = pl_pos_row.get(POSITION.TITLE)
  pl_row[PLAYER.POSITION_TITLE] = position_title
  pl_row[PLAYER.POSITION_ID] = int(pl_ros_d['positionId'])
  # now I retrieve the temporary saved position type
  _temp_postype_l = pl_pos_row.get(_TEMP_POSTYPE)
  if _temp_postype_l:
    pl_row[PLAYER.POSITION_TYPE] = _temp_postype_l[i]
  else:
    pl_row[PLAYER.POSITION_TYPE] = None

def _upd_pl_row_with_general_from_row(pl_row, source_pl_row):
  for key in (PLAYER.NR, PLAYER.NAME, PLAYER.ID,
      PLAYER.RACE_NAME, PLAYER.POSITION_TITLE,
      PLAYER.POSITION_ID, PLAYER.POSITION_TYPE):
    value = source_pl_row.get(key)
    if value is not None:
      pl_row[key] = value

def _upd_pl_row_with_identical_performances(pl_row, value):
  for key in (PLAYER.COMP, PLAYER.TD, PLAYER.INT, PLAYER.CAS,
      PLAYER.MVP, PLAYER.SPP, PLAYER.BLOCKS, PLAYER.PASSING,
      PLAYER.RUSHING, PLAYER.TURNS):
    pl_row[key] = value

def _upd_pl_row_with_performances(pl_row, team_data, i,
    player_id):
  pl_res_d = team_data[i]['player_results'][player_id]
  pl_row[PLAYER.COMP] = pl_res_d['completions']
  pl_row[PLAYER.TD] = pl_res_d['touchdowns']
  pl_row[PLAYER.INT] = pl_res_d['interceptions']
  pl_row[PLAYER.CAS] = pl_res_d['casualties']
  # MVP and SPP are registered in post-match sequence
  pl_row[PLAYER.BLOCKS] = pl_res_d['blocks']
  pl_row[PLAYER.PASSING] = pl_res_d['passing']
  pl_row[PLAYER.RUSHING] = pl_res_d['rushing']
  pl_row[PLAYER.TURNS] = pl_res_d['turnsPlayed']
  # TODO: handle multiple injuries (Decay) during event parsing
  #pl_row[PLAYER.INJURIES] = [list(common_regex.injury.match(
  #    pl_res_d['seriousInjury']).groups())]

def _upd_pl_row_with_properties(pl_row, pl_ros_d, pl_pos_row):
  pl_row[PLAYER.MA] = pl_ros_d['movement']
  pl_row[PLAYER.ST] = pl_ros_d['strength']
  pl_row[PLAYER.AG] = pl_ros_d['agility']
  pl_row[PLAYER.AV] = pl_ros_d['armour']
  earned_skills = [skill for skill in pl_ros_d['skillArray']
      if skill not in pl_pos_row.get(POSITION.SKILLS, [])]
  if (pl_row[PLAYER.PHASE] == phase.SETUP.value
      and pl_row[PLAYER.TYPE] == player_type.REGULAR.value
      and 'Loner' in earned_skills):
    pl_row[PLAYER.TYPE] = player_type.JOURNEYMAN.value
  earned_skills_with_values = [
      [skill, _get_skill_value(skill, pl_row[PLAYER.TYPE],
          pl_pos_row)]
      for skill in earned_skills]
  pl_row[PLAYER.EARNED_SKILLS] = earned_skills_with_values
  pl_row[PLAYER.INJURIES] = [
    list(common_regex.injury.match(inj_str).groups())
    for inj_str in pl_ros_d['lastingInjuries']]


text:
#region Apache License

//-----------------------------------------------------------------------
// <copyright file="IValidationBase.cs" company="StrixIT">
// Copyright 2015 StrixIT. Author R.G. Schurgers MA MSc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------

#endregion Apache License

using System.ComponentModel.DataAnnotations;

namespace StrixIT.Platform.Core
{
    /// <summary>
    /// The basic interface for all entities.
    /// </summary>
    public interface IValidationBase : IValidatableObject
    {
        #region Public Properties

        /// <summary>
        /// Gets a value indicating whether the entity is valid.
        /// </summary>
        bool IsValid { get; }

        #endregion Public Properties
    }
}

redpajama_set_name: RedPajamaGithub


text:
require_relative '../spec_helper'
require_relative '../fixtures/classes'

option_pack = 'i*'
platform_is :windows do
  option_pack = 's*'
end

describe "Socket::Option.linger" do
  it "creates a new Socket::Option for SO_LINGER" do
    so = Socket::Option.linger(1, 10)
    so.should be_an_instance_of(Socket::Option)

    so.family.should == Socket::Constants::AF_UNSPEC
    so.level.should == Socket::Constants::SOL_SOCKET
    so.optname.should == Socket::Constants::SO_LINGER

    so.data.should == [1, 10].pack(option_pack)
  end

  it "accepts boolean as onoff argument" do
    so = Socket::Option.linger(false, 0)
    so.data.should == [0, 0].pack(option_pack)

    so = Socket::Option.linger(true, 1)
    so.data.should == [1, 1].pack(option_pack)
  end
end

describe "Socket::Option#linger" do
  it "returns linger option" do
    so = Socket::Option.linger(0, 5)
    ary = so.linger
    ary[0].should be_false
    ary[1].should == 5

    so = Socket::Option.linger(false, 4)
    ary = so.linger
    ary[0].should be_false
    ary[1].should == 4

    so = Socket::Option.linger(1, 10)
    ary = so.linger
    ary[0].should be_true
    ary[1].should == 10

    so = Socket::Option.linger(true, 9)
    ary = so.linger
    ary[0].should be_true
    ary[1].should == 9
  end

  it "raises TypeError if not a SO_LINGER" do
    so = Socket::Option.int(:AF_UNSPEC, :SOL_SOCKET, :KEEPALIVE, 1)
    -> { so.linger }.should raise_error(TypeError)
  end

  it 'raises TypeError when called on a non SOL_SOCKET/SO_LINGER option' do
    opt = Socket::Option.int(:INET, :IP, :TTL, 4)

    -> { opt.linger }.should raise_error(TypeError)
  end

  platform_is_not :windows do
    it "raises TypeError if option has not good size" do
      so = Socket::Option.int(:AF_UNSPEC, :SOL_SOCKET, :LINGER, 1)
      -> { so.linger }.should raise_error(TypeError)
    end
  end

  it 'raises TypeError when called on a non linger option' do
    opt = Socket::Option.new(:INET, :SOCKET, :LINGER, '')

    -> { opt.linger }.should raise_error(TypeError)
  end
end


text:
require 'spec_helper'

describe Sidekiq::Status::Worker do

  let!(:job_id) { SecureRandom.hex(12) }

  describe ".perform_async" do
    it "generates and returns job id" do
      SecureRandom.should_receive(:hex).once.and_return(job_id)
      StubJob.perform_async().should == job_id
    end
  end

  describe ".expiration" do
    subject { StubJob.new }
    it "allows to set/get expiration" do
      expect(subject.expiration).to be_nil
      subject.expiration = :val
      expect(subject.expiration).to eq(:val)
    end
  end
end


text:
$(document).ready(function(e){
    $('.search-panel .dropdown-menu').find('a').click(function(e) {
        e.preventDefault();
        var param = $(this).attr("href").replace("#","");
        var concept = $(this).text();
        $('.search-panel span#search_concept').text(concept);
        $('.input-group #search_param').val(param);
    });
});


text:
using std::unordered_map;

#include <unordered_set>
using std::unordered_set;

#include <set>
using std::set;
using std::multiset;

#include <utility>
using std::pair;
using std::make_pair;

#include <vector>
using std::vector;

#include "base/basictypes.h"
#include "base/scoped_ptr.h"
#include "s2.h"
#include "s1angle.h"
#include "util/math/matrix3x3.h"

class S2Loop;
class S2Polygon;

// This is a simple class for assembling polygons out of edges.  It requires
// that no two edges cross.  It can handle both directed and undirected edges,
// and optionally it can also remove duplicate edge pairs (consisting of two
// identical edges or an edge and its reverse edge).  This is useful for
// computing seamless unions of polygons that have been cut into pieces.
//
// Here are some of the situations this class was designed to handle:
//
// 1. Computing the union of disjoint polygons that may share part of their
//    boundaries.  For example, reassembling a lake that has been split into
//    two loops by a state boundary.
//
// 2. Constructing polygons from input data that does not follow S2
//    conventions, i.e. where loops may have repeated vertices, or distinct
//    loops may share edges, or shells and holes have opposite or unspecified
//    orientations.
//
// 3. Computing the symmetric difference of a set of polygons whose edges
//    intersect only at vertices.  This can be used to implement a limited
//    form of polygon intersection or subtraction as well as unions.
//
// 4. As a tool for implementing other polygon operations by generating a
//    collection of directed edges and then assembling them into loops.
class S2PolygonBuilderOptions {
 public:
  S2PolygonBuilderOptions() :
    undirected_edges_(false), xor_edges_(true), validate_(false),
    vertex_merge_radius_(S1Angle::Radians(0)),
    edge_splice_fraction_(0.866) {}

  // These are the options that should be used for assembling well-behaved
  // input data into polygons.  All edges should be directed such that
  // "shells" and "holes" have opposite orientations (typically CCW shells and
  // clockwise holes), unless it is known that shells and holes do not share
  // any edges.
  inline static S2PolygonBuilderOptions DIRECTED_XOR();

  // These are the options that should be used for assembling polygons that do
  // not follow the conventions above, e.g. where edge directions may vary
  // within a single loop, or shells and holes are not oppositely oriented and
  // may share edges.
  inline static S2PolygonBuilderOptions UNDIRECTED_XOR();

  // These are the options that should be used for assembling edges where the
  // desired output is a collection of loops rather than a polygon, and edges
  // may occur more than once.  Edges are treated as undirected and are not
  // XORed together.
  inline static S2PolygonBuilderOptions UNDIRECTED_UNION();

  // Default value: false.
  //
  // If "undirected_edges" is false, then the input is assumed to consist of
  // edges that can be assembled into oriented loops without reversing any of
  // the edges.  Otherwise, "undirected_edges" should be set to true.
  bool undirected_edges() const { return undirected_edges_; }
  void set_undirected_edges(bool undirected_edges);

  // Default value: true.
  //
  // If "xor_edges" is true, then any duplicate edge pairs are removed.  This
  // is useful for computing the union of a collection of polygons whose
  // interiors are disjoint but whose boundaries may share some common edges
  // (e.g. computing the union of South Africa, Lesotho, and Swaziland).
  //
  // Note that for directed edges, a "duplicate edge pair" consists of an edge
  // and its corresponding reverse edge.  This means that either (a) "shells"
  // and "holes" must have opposite orientations, or (b) shells and holes do
  // not share edges.  Otherwise undirected_edges() should be specified.
  //
  // There are only two reasons to turn off xor_edges():
  //
  //  (1) AssemblePolygon() will be called, and you want to assert that there
  //      are no duplicate edge pairs in the input.
  //
  //  (2) AssembleLoops() will be called, and you want to keep abutting loops
  //      separate in the output rather than merging their regions together
  //      (e.g. assembling loops for Kansas City, KS and Kansas City, MO
  //      simultaneously).
  bool xor_edges() const { return xor_edges_; }
  void set_xor_edges(bool xor_edges);

  // Default value: false.
  //
  // If true, IsValid() is called on all loops and polygons before
  // constructing them.  If any loop is invalid (e.g. self-intersecting), it
  // is rejected and returned as a set of "unused edges".  Any remaining valid
  // loops are kept.  If the entire polygon is invalid (e.g. two loops
  // intersect), then all loops are rejected and returned as unused edges.
  bool validate() const { return validate_; }
  void set_validate(bool validate);

  // Default value: 0.
  //
  // If set to a positive value, all vertex pairs that are separated by less
  // than this distance will be merged together.  Note that vertices can move
  // arbitrarily far if there is a long chain of vertices separated by less
  // than this distance.
  //
  // This method is useful for assembling polygons out of input data where
  // vertices and/or edges may not be perfectly aligned.
  S1Angle vertex_merge_radius() const { return vertex_merge_radius_; }
  void set_vertex_merge_radius(S1Angle const& vertex_merge_radius);

  // Default value: 0.866 (approximately sqrt(3)/2).
  //
  // The edge splice radius is automatically set to this fraction of the vertex
  // merge radius.  If the edge splice radius is positive, then all vertices
  // that are closer than this distance to an edge are spliced into that edge.
  // Note that edges can move arbitrarily far if there is a long chain of
  // vertices in just the right places.
  //
  // You can turn off edge splicing by setting this value to zero.  This will
  // save some time if you don't need this feature, or you don't want vertices
  // to be spliced into nearby edges for some reason.
  //
  // Note that the edge splice fraction must be less than sqrt(3)/2 in order to
  // avoid infinite loops in the merge algorithm.  The default value is very
  // close to this maximum and therefore results in the maximum amount of edge
  // splicing for a given vertex merge radius.
  //
  // The only reason to reduce the edge splice fraction is if you want to limit
  // changes in edge direction due to splicing.  The direction of an edge can
  // change by up to asin(edge_splice_fraction) due to each splice.  Thus by
  // default, edges are allowed to change direction by up to 60 degrees per
  // splice.  However, note that most direction changes are much smaller than
  // this: the worst case occurs only if the vertex being spliced is just
  // outside the vertex merge radius from one of the edge endpoints.
  double edge_splice_fraction() const { return edge_splice_fraction_; }
  void set_edge_splice_fraction(double edge_splice_fraction);

 private:
  bool undirected_edges_;
  bool xor_edges_;
  bool validate_;
  S1Angle vertex_merge_radius_;
  double edge_splice_fraction_;
};

class S2PolygonBuilder {
 public:
  explicit S2PolygonBuilder(S2PolygonBuilderOptions const& options);
  ~S2PolygonBuilder();

  S2PolygonBuilderOptions const& options() const { return options_; }

  // Add the given edge to the polygon builder.  This method should be used
  // for input data that may not follow S2 polygon conventions.  Note that
  // edges are not allowed to cross each other.  Also note that as a
  // convenience, edges where v0 == v1 are ignored.
  //
  // Returns true if an edge was added, and false if an edge was erased
  // (due to XORing) or not added (if both endpoints were the same).
  bool AddEdge(S2Point const& v0, S2Point const& v1);

  // Add all edges in the given loop.  If the sign() of the loop is negative
  // (i.e. this loop represents a hole), the reverse edges are added instead.
  // This implies that "shells" are CCW and "holes" are CW, as required for
  // the directed edges convention described above.
  //
  // This method does not take ownership of the loop.
  void AddLoop(S2Loop const* loop);

  // Add all loops in the given polygon.  Shells and holes are added with
  // opposite orientations as described for AddLoop().
  //
  // This method does not take ownership of the polygon.
  void AddPolygon(S2Polygon const* polygon);

  // This type is used to return any edges that could not be assembled.
  typedef vector<pair<S2Point, S2Point> > EdgeList;

  // Assembles the given edges into as many non-crossing loops as possible.
  // When there is a choice about how to assemble the loops, then CCW loops
  // are preferred.  Returns true if all edges were assembled.  If
  // "unused_edges" is not NULL, it is initialized to the set of edges that
  // could not be assembled into loops.
  //
  // Note that if xor_edges() is false and duplicate edge pairs may be
  // present, then undirected_edges() should be specified unless all loops can
  // be assembled in a counter-clockwise direction.  Otherwise this method may
  // not be able to assemble all loops due to its preference for CCW loops.
  //
  // This method resets the S2PolygonBuilder state so that it can be reused.
  bool AssembleLoops(vector<S2Loop*>* loops, EdgeList* unused_edges);

  // Like AssembleLoops, but normalizes all the loops so that they enclose
  // less than half the sphere, and then assembles the loops into a polygon.
  //
  // For this method to succeed, there should be no duplicate edges in the
  // input.  If this is not known to be true, then the "xor_edges" option
  // should be set (which is true by default).
  //
  // Note that S2Polygons cannot represent arbitrary regions on the sphere,
  // because of the limitation that no loop encloses more than half of the
  // sphere.  For example, an S2Polygon cannot represent a 100km wide band
  // around the equator.  In such cases, this method will return the
  // *complement* of the expected region.  So for example if all the world's
  // coastlines were assembled, the output S2Polygon would represent the land
  // area (irrespective of the input edge or loop orientations).
  bool AssemblePolygon(S2Polygon* polygon, EdgeList* unused_edges);

  // This function is only for debugging.  If it is called, then points will
  // be transformed by the inverse of the given matrix before being printed as
  // lat-lng coordinates in degrees.  "m" should be orthonormal.
  void set_debug_matrix(Matrix3x3_d const& m);

 protected:
  // These functions print either a single vertex, all edges from a single
  // vertex, or all edges in the builder.
  void DumpVertex(S2Point const& v) const;
  void DumpEdges(S2Point const& v0) const;
  void Dump() const;

 private:

  // Return true if the given edge exists.
  bool HasEdge(S2Point const& v0, S2Point const& v1);

  // Erase an edge or an entire loop.  The edge/loop must exist.
  void EraseEdge(S2Point const& v0, S2Point const& v1);
  void EraseLoop(S2Point const* v, int n);

  // Assembles and returns a single loop starting with the given edge.
  // If a loop cannot be assembled starting from this edge, returns NULL
  // and updates "unused_edges".
  S2Loop* AssembleLoop(S2Point const& v0, S2Point const& v1,
                       EdgeList* unused_edges);

  // Adds all the given edges to "unused_edges".
  void RejectLoop(S2Point const* v, int n, EdgeList* unused_edges);

  // Builds a map indicating which vertices need to be moved from their
  // current position to a new position, and also returns a spatial index
  // containing all of the vertices that do not need to be moved.
  class PointIndex;
  typedef unordered_map<S2Point, S2Point> MergeMap;
  void BuildMergeMap(PointIndex* index, MergeMap* merge_map);

  // Moves a set of vertices from old to new positions.
  void MoveVertices(MergeMap const& merge_map);

  // Modifies each edge by splicing in any vertices whose distance to the edge
  // is at most (edge_splice_fraction() * vertex_merge_radius()).
  void SpliceEdges(PointIndex* index);

  S2PolygonBuilderOptions options_;

  // This is only used for debugging purposes.
  scoped_ptr<Matrix3x3_d> debug_matrix_;

  // The current set of edges, grouped by origin.  The set of destination
  // vertices is a multiset so that the same edge can be present more than
  // once.  We could have also used a multiset<pair<S2Point, S2Point> >,
  // but this representation is a bit more convenient.
  typedef multiset<S2Point> VertexSet;
  typedef unordered_map<S2Point, VertexSet> EdgeSet;
  scoped_ptr<EdgeSet> edges_;

  // Unique collection of the starting (first) vertex of all edges,
  // in the order they are added to edges_.
  vector<S2Point> starting_vertices_;
};

inline S2PolygonBuilderOptions S2PolygonBuilderOptions::DIRECTED_XOR() {
  return S2PolygonBuilderOptions();
}

inline S2PolygonBuilderOptions S2PolygonBuilderOptions::UNDIRECTED_XOR() {
  S2PolygonBuilderOptions options;
  options.set_undirected_edges(true);
  return options;
}

inline S2PolygonBuilderOptions S2PolygonBuilderOptions::UNDIRECTED_UNION() {
  S2PolygonBuilderOptions options;
  options.set_undirected_edges(true);
  options.set_xor_edges(false);
  return options;
}

#endif  // UTIL_GEOMETRY_S2POLYGONBUILDER_H__


text:
namespace Tweetinvi.Parameters
{
    /// <summary>
    /// For more information visit : https://developer.twitter.com/en/docs/basics/authentication/api-reference/invalidate_bearer_token
    /// </summary>
    public interface IInvalidateBearerTokenParameters : ICustomRequestParameters
    {
    }

    /// <inheritdoc/>
    public class InvalidateBearerTokenParameters : CustomRequestParameters, IInvalidateBearerTokenParameters
    {
    }
}


text:
#include <nano/lib/threading.hpp>
#include <nano/secure/blockstore.hpp>

nano::summation_visitor::summation_visitor (nano::transaction const & transaction_a, nano::block_store const & store_a, bool is_v14_upgrade_a) :
transaction (transaction_a),
store (store_a),
is_v14_upgrade (is_v14_upgrade_a)
{
}

void nano::summation_visitor::send_block (nano::send_block const & block_a)
{
	debug_assert (current->type != summation_type::invalid && current != nullptr);
	if (current->type == summation_type::amount)
	{
		sum_set (block_a.hashables.balance.number ());
		current->balance_hash = block_a.hashables.previous;
		current->amount_hash = 0;
	}
	else
	{
		sum_add (block_a.hashables.balance.number ());
		current->balance_hash = 0;
	}
}

void nano::summation_visitor::state_block (nano::state_block const & block_a)
{
	debug_assert (current->type != summation_type::invalid && current != nullptr);
	sum_set (block_a.hashables.balance.number ());
	if (current->type == summation_type::amount)
	{
		current->balance_hash = block_a.hashables.previous;
		current->amount_hash = 0;
	}
	else
	{
		current->balance_hash = 0;
	}
}

void nano::summation_visitor::receive_block (nano::receive_block const & block_a)
{
	debug_assert (current->type != summation_type::invalid && current != nullptr);
	if (current->type == summation_type::amount)
	{
		current->amount_hash = block_a.hashables.source;
	}
	else
	{
		nano::block_info block_info;
		if (!store.block_info_get (transaction, block_a.hash (), block_info))
		{
			sum_add (block_info.balance.number ());
			current->balance_hash = 0;
		}
		else
		{
			current->amount_hash = block_a.hashables.source;
			current->balance_hash = block_a.hashables.previous;
		}
	}
}

void nano::summation_visitor::open_block (nano::open_block const & block_a)
{
	debug_assert (current->type != summation_type::invalid && current != nullptr);
	if (current->type == summation_type::amount)
	{
		if (block_a.hashables.source != network_params.ledger.genesis_account)
		{
			current->amount_hash = block_a.hashables.source;
		}
		else
		{
			sum_set (network_params.ledger.genesis_amount);
			current->amount_hash = 0;
		}
	}
	else
	{
		current->amount_hash = block_a.hashables.source;
		current->balance_hash = 0;
	}
}

void nano::summation_visitor::change_block (nano::change_block const & block_a)
{
	debug_assert (current->type != summation_type::invalid && current != nullptr);
	if (current->type == summation_type::amount)
	{
		sum_set (0);
		current->amount_hash = 0;
	}
	else
	{
		nano::block_info block_info;
		if (!store.block_info_get (transaction, block_a.hash (), block_info))
		{
			sum_add (block_info.balance.number ());
			current->balance_hash = 0;
		}
		else
		{
			current->balance_hash = block_a.hashables.previous;
		}
	}
}

nano::summation_visitor::frame nano::summation_visitor::push (nano::summation_visitor::summation_type type_a, nano::block_hash const & hash_a)
{
	frames.emplace (type_a, type_a == summation_type::balance ? hash_a : 0, type_a == summation_type::amount ? hash_a : 0);
	return frames.top ();
}

void nano::summation_visitor::sum_add (nano::uint128_t addend_a)
{
	current->sum += addend_a;
	result = current->sum;
}

void nano::summation_visitor::sum_set (nano::uint128_t value_a)
{
	current->sum = value_a;
	result = current->sum;
}

nano::uint128_t nano::summation_visitor::compute_internal (nano::summation_visitor::summation_type type_a, nano::block_hash const & hash_a)
{
	push (type_a, hash_a);

	/*
	 Invocation loop representing balance and amount computations calling each other.
	 This is usually better done by recursion or something like boost::coroutine2, but
	 segmented stacks are not supported on all platforms so we do it manually to avoid
	 stack overflow (the mutual calls are not tail-recursive so we cannot rely on the
	 compiler optimizing that into a loop, though a future alternative is to do a
	 CPS-style implementation to enforce tail calls.)
	*/
	while (!frames.empty ())
	{
		current = &frames.top ();
		debug_assert (current->type != summation_type::invalid && current != nullptr);

		if (current->type == summation_type::balance)
		{
			if (current->awaiting_result)
			{
				sum_add (current->incoming_result);
				current->awaiting_result = false;
			}

			while (!current->awaiting_result && (!current->balance_hash.is_zero () || !current->amount_hash.is_zero ()))
			{
				if (!current->amount_hash.is_zero ())
				{
					// Compute amount
					current->awaiting_result = true;
					push (summation_type::amount, current->amount_hash);
					current->amount_hash = 0;
				}
				else
				{
					auto block (block_get (transaction, current->balance_hash));
					debug_assert (block != nullptr);
					block->visit (*this);
				}
			}

			epilogue ();
		}
		else if (current->type == summation_type::amount)
		{
			if (current->awaiting_result)
			{
				sum_set (current->sum < current->incoming_result ? current->incoming_result - current->sum : current->sum - current->incoming_result);
				current->awaiting_result = false;
			}

			while (!current->awaiting_result && (!current->amount_hash.is_zero () || !current->balance_hash.is_zero ()))
			{
				if (!current->amount_hash.is_zero ())
				{
					auto block = block_get (transaction, current->amount_hash);
					if (block != nullptr)
					{
						block->visit (*this);
					}
					else
					{
						if (current->amount_hash == network_params.ledger.genesis_account)
						{
							sum_set ((std::numeric_limits<nano::uint128_t>::max) ());
							current->amount_hash = 0;
						}
						else
						{
							debug_assert (false);
							sum_set (0);
							current->amount_hash = 0;
						}
					}
				}
				else
				{
					// Compute balance
					current->awaiting_result = true;
					push (summation_type::balance, current->balance_hash);
					current->balance_hash = 0;
				}
			}

			epilogue ();
		}
	}

	return result;
}

void nano::summation_visitor::epilogue ()
{
	if (!current->awaiting_result)
	{
		frames.pop ();
		if (!frames.empty ())
		{
			frames.top ().incoming_result = current->sum;
		}
	}
}

nano::uint128_t nano::summation_visitor::compute_amount (nano::block_hash const & block_hash)
{
	return compute_internal (summation_type::amount, block_hash);
}

nano::uint128_t nano::summation_visitor::compute_balance (nano::block_hash const & block_hash)
{
	return compute_internal (summation_type::balance, block_hash);
}

std::shared_ptr<nano::block> nano::summation_visitor::block_get (nano::transaction const & transaction_a, nano::block_hash const & hash_a) const
{
	return is_v14_upgrade ? store.block_get_v14 (transaction, hash_a) : store.block_get_no_sideband (transaction, hash_a);
}

nano::representative_visitor::representative_visitor (nano::transaction const & transaction_a, nano::block_store & store_a) :
transaction (transaction_a),
store (store_a),
result (0)
{
}

void nano::representative_visitor::compute (nano::block_hash const & hash_a)
{
	current = hash_a;
	while (result.is_zero ())
	{
		auto block (store.block_get (transaction, current));
		debug_assert (block != nullptr);
		block->visit (*this);
	}
}

void nano::representative_visitor::send_block (nano::send_block const & block_a)
{
	current = block_a.previous ();
}

void nano::representative_visitor::receive_block (nano::receive_block const & block_a)
{
	current = block_a.previous ();
}

void nano::representative_visitor::open_block (nano::open_block const & block_a)
{
	result = block_a.hash ();
}

void nano::representative_visitor::change_block (nano::change_block const & block_a)
{
	result = block_a.hash ();
}

void nano::representative_visitor::state_block (nano::state_block const & block_a)
{
	result = block_a.hash ();
}

nano::read_transaction::read_transaction (std::unique_ptr<nano::read_transaction_impl> read_transaction_impl) :
impl (std::move (read_transaction_impl))
{
}

void * nano::read_transaction::get_handle () const
{
	return impl->get_handle ();
}

void nano::read_transaction::reset () const
{
	impl->reset ();
}

void nano::read_transaction::renew () const
{
	impl->renew ();
}

void nano::read_transaction::refresh () const
{
	reset ();
	renew ();
}

nano::write_transaction::write_transaction (std::unique_ptr<nano::write_transaction_impl> write_transaction_impl) :
impl (std::move (write_transaction_impl))
{
	/*
	 * For IO threads, we do not want them to block on creating write transactions.
	 */
	debug_assert (nano::thread_role::get () != nano::thread_role::name::io);
}

void * nano::write_transaction::get_handle () const
{
	return impl->get_handle ();
}

void nano::write_transaction::commit () const
{
	impl->commit ();
}

void nano::write_transaction::renew ()
{
	impl->renew ();
}

bool nano::write_transaction::contains (nano::tables table_a) const
{
	return impl->contains (table_a);
}


text:
package cn.djd.common.cipher;

import java.security.MessageDigest;

/**
 * @Description: SHA加密
 * @author: jeasinlee
 * @date: 2017-01-12 11:15
 */
public class SHA {
    public static byte[] encrypt(byte[] data) throws Exception {
        MessageDigest sha = MessageDigest.getInstance(CipherType.SHA.getType());
        sha.update(data);
        return sha.digest();
    }
}


text:
#ifndef __PU_LIGHT_RENDERER_TOKENS_H__
#define __PU_LIGHT_RENDERER_TOKENS_H__

#include "ParticleUniversePrerequisites.h"
#include "ParticleUniverseRendererTokens.h"

namespace ParticleUniverse
{
	/** The LightRendererTranslator parses 'LightRenderer' tokens
	*/
	class _ParticleUniverseExport LightRendererTranslator : public ScriptTranslator
	{
		public:
			LightRendererTranslator(void){};
			~LightRendererTranslator(void){};
			virtual bool translateChildProperty(ScriptCompiler* compiler, const AbstractNodePtr &node);
			virtual bool translateChildObject(ScriptCompiler* compiler, const AbstractNodePtr &node);
	};
	//-------------------------------------------------------------------------
	//-------------------------------------------------------------------------
	//-------------------------------------------------------------------------

	/**
    */
	class _ParticleUniverseExport LightRendererWriter : public ParticleRendererWriter
	{
		protected:

		public:

			LightRendererWriter(void) {};
			virtual ~LightRendererWriter(void) {};

			/** @see
				ScriptWriter::write
			*/
			virtual void write(ParticleScriptSerializer* serializer, const IElement* element);
	};

}
#endif


text:
#import "LazyMenuSegmentedCell.h"

@interface SegmentedToolbarItemSegmentedCell : LazyMenuSegmentedCell
{
}

- (double)_menuDelayTimeForSegment:(long long)arg1;

@end


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Chapter 2 Example 2 - Simple line path</title>

    <script>

        var Debugger ={};

        Debugger.log = function(message){
            try{
                console.log(message);
            }catch(exception){
                return;
            }
        };

        window.addEventListener("load", eventWindowLoaded, false);

        function eventWindowLoaded(){
            Debugger.log('load event');
            canvasApp();
        }

        function canvasApp(){

            if(!canvasSupport()){
                return;
            };

            var theCanvas = document.getElementById("canvasOne");
            var context = theCanvas.getContext("2d");

            Debugger.log('loading canvas app');

            drawScreen();

            function canvasSupport(){
                return !!document.createElement("canvas").getContext;
            }

            function drawScreen(){
                Debugger.log('drawing screen');

                context.strokeStyle = "black";
                context.lineWidth = 20;
                context.lineCap = "square";
                context.beginPath();
                context.moveTo(20, 0);
                context.lineTo(100, 0);
                context.stroke();
                context.closePath();
            }
        }
    </script>
</head>
<body>
    <canvas id = "canvasOne">
        Your browser does not support HTML5 canvas.
    </canvas>
</body>
</html>


text:
package com.bitgirder.mingle;

import com.bitgirder.validation.Inputs;
import com.bitgirder.validation.State;

import com.bitgirder.log.CodeLoggers;

import com.bitgirder.lang.Range;
import com.bitgirder.lang.Lang;
import com.bitgirder.lang.PatternHelper;
import com.bitgirder.lang.Strings;

import java.util.TimeZone;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Date;

import java.util.regex.Pattern;
import java.util.regex.Matcher;

import java.sql.Timestamp;

public
final
class MingleTimestamp
implements MingleValue,
           Comparable< MingleTimestamp >
{
    private final static Inputs inputs = new Inputs();
    private final static State state = new State();

    private static void code( Object... msg ) { CodeLoggers.code( msg ); }

    private final static int ONE_MILLION = 1000000;

    private final static Range< Integer > PRECISION_RANGE =
        Range.closed( 0, 9 );

    private final static TimeZone TZ_UTC = TimeZone.getTimeZone( "UTC" );

    // This regex is actually more permissive than the rfc since it does not
    // check things such as valid days of month, etc. We can tighten this up as
    // our needs dictate it
    private final static Pattern STRICT_RFC3339_TIMESTAMP_PATTERN =
        PatternHelper.compile(
            "(\\d{4})-(\\d{2})-(\\d{2})[Tt](\\d{2}):(\\d{2}):(\\d{2})" +
            "(?:\\.(\\d+){1,9})?(?:([zZ])|([+\\-]\\d{2}:\\d{2}))"
        );

    private final static int RFC3339_GROUP_YEAR = 1;
    private final static int RFC3339_GROUP_MONTH = 2;
    private final static int RFC3339_GROUP_DATE = 3;
    private final static int RFC3339_GROUP_HOUR = 4;
    private final static int RFC3339_GROUP_MINUTE = 5;
    private final static int RFC3339_GROUP_SECONDS = 6;
    private final static int RFC3339_GROUP_FRAC_PART = 7;
    private final static int RFC3339_GROUP_TIME_ZONE_ZULU = 8;
    private final static int RFC3339_GROUP_TIME_ZONE_UTC_OFFSET = 9;

    private final long secs;
    private final int nanos;

    private
    MingleTimestamp( long secs,
                     int nanos )
    {
        this.secs = secs;
        this.nanos = inputs.nonnegativeI( nanos, "nanos" );
    }

    public
    int
    hashCode()
    {
        return ( (int) secs ) | nanos;
    }

    public
    boolean
    equals( Object other )
    {
        if ( other == this ) return true;
        if ( ! ( other instanceof MingleTimestamp ) ) return false;

        MingleTimestamp ts2 = (MingleTimestamp) other;
        return nanos == ts2.nanos && secs == ts2.secs;
    }

    public
    int
    compareTo( MingleTimestamp ts2 )
    {
        if ( ts2 == null ) throw new NullPointerException();
        if ( ts2 == this ) return 0;

        int res = secs < ts2.secs ? -1 : secs == ts2.secs ? 0 : 1;
        if ( res != 0 ) return res;

        res = nanos < ts2.nanos ? -1 : nanos == ts2.nanos ? 0 : 1;
        if ( secs < 0 ) res *= -1;

        return res;
    }

    public long seconds() { return secs; }
    public int nanos() { return nanos; }

    public
    long
    getTimeInMillis()
    {
        return ( secs * 1000L ) + ( nanos / ONE_MILLION );
    }

    private
    void
    appendTwoDigitPad( StringBuilder sb,
                       int val )
    {
        if ( val < 10 ) sb.append( '0' );
        sb.append( val );
    }

    private
    void
    appendRfc3339TimeZone( StringBuilder sb )
    {
        sb.append( "Z" );
    }

    private
    void
    appendPrecision( StringBuilder sb,
                     int precision )
    {
        if ( precision > 0 )
        {
            String decStr = String.format( "%1$09d", Math.max( nanos, 0 ) );
            decStr = decStr.substring( 0, precision );
            sb.append( '.' ).append( decStr );
        }
    }

    public
    String
    getRfc3339String( int precision )
    {
        inputs.inRange( precision, "precision", PRECISION_RANGE );

        StringBuilder res = new StringBuilder( 25 );

        GregorianCalendar cal = new GregorianCalendar();
        cal.setTimeZone( TZ_UTC );
        cal.setTimeInMillis( secs * 1000L ); // discard any fractional part

        res.append( cal.get( GregorianCalendar.YEAR ) );
        res.append( '-' );
        appendTwoDigitPad( res, cal.get( GregorianCalendar.MONTH ) + 1 );
        res.append( '-' );
        appendTwoDigitPad( res, cal.get( GregorianCalendar.DATE ) );
        res.append( 'T' );
        appendTwoDigitPad( res, cal.get( GregorianCalendar.HOUR_OF_DAY ) );
        res.append( ':' );
        appendTwoDigitPad( res, cal.get( GregorianCalendar.MINUTE ) );
        res.append( ':' );
        appendTwoDigitPad( res, cal.get( GregorianCalendar.SECOND ) );

        appendPrecision( res, precision );
        appendRfc3339TimeZone( res );

        return res.toString();
    }

    public
    String
    getRfc3339String()
    {
        return getRfc3339String( PRECISION_RANGE.max() );
    }

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

//    public
//    Timestamp
//    asSqlTimestamp()
//    {
//        // See javadocs for java.sql.Timestamp( long ) -- it ultimately stores
//        // it's integral/frac part as this class does
//        Timestamp res = new Timestamp( getTimeInMillis() );
//        res.setNanos( nanos );
//
//        return res;
//    }

    public
    static
    MingleTimestamp
    fromUnixNanos( long secs,
                   int ns )
    {
        return new MingleTimestamp( secs, ns );
    }

    public
    static
    MingleTimestamp
    fromMillis( long t )
    {
        long secs = t / 1000;
        int ns = Math.abs( (int) ( t % 1000L ) ) * ONE_MILLION;

        return fromUnixNanos( secs, ns );
    }

    public
    static
    MingleTimestamp
    fromDate( Date d )
    {
        return fromMillis( inputs.notNull( d, "d" ).getTime() );
    }

    public
    static
    MingleTimestamp
    now()
    {
        return fromMillis( System.currentTimeMillis() );
    }

    // We put the parsing in here rather than with the larger mingle parser code
    // since this is really just an rfc3339 parse and is well self-contained;
    // moreover, we want to be able to parse rfc3339 strings into instances of
    // this class as part of our larger parser test code (for Timestamp type
    // restrictions, namely).

    private
    static
    void
    setCalInt( GregorianCalendar c,
               Matcher m,
               int group,
               int calFld )
    {
        int val = Integer.parseInt( m.group( group ) );

        if ( calFld == GregorianCalendar.MONTH ) --val;
        c.set( calFld, val );
    }

    private
    static
    void
    setTimeZone( GregorianCalendar c,
                 Matcher m )
    {
        String tzStr;

        if ( m.group( RFC3339_GROUP_TIME_ZONE_ZULU ) == null )
        {
            tzStr = "GMT" + m.group( RFC3339_GROUP_TIME_ZONE_UTC_OFFSET );
        }
        else tzStr = "UTC";

        c.setTimeZone( TimeZone.getTimeZone( tzStr ) );
    }

    private
    static
    int
    getNanos( Matcher m )
    {
        String fracPart = m.group( RFC3339_GROUP_FRAC_PART );

        if ( fracPart == null ) return 0;

        int res = Integer.parseInt( fracPart );
        for ( int i = fracPart.length(); i < 9; ++i ) res *= 10;

        return res;
    }

    private
    static
    MingleTimestamp
    buildTimestamp( Matcher m )
    {
        GregorianCalendar c = new GregorianCalendar( Locale.US );

        setCalInt( c, m, RFC3339_GROUP_YEAR, GregorianCalendar.YEAR );
        setCalInt( c, m, RFC3339_GROUP_MONTH, GregorianCalendar.MONTH ); // -1
        setCalInt( c, m, RFC3339_GROUP_DATE, GregorianCalendar.DATE );
        setCalInt( c, m, RFC3339_GROUP_HOUR, GregorianCalendar.HOUR_OF_DAY );
        setCalInt( c, m, RFC3339_GROUP_MINUTE, GregorianCalendar.MINUTE );
        setCalInt( c, m, RFC3339_GROUP_SECONDS, GregorianCalendar.SECOND );

        int nanos = getNanos( m );
        c.set( GregorianCalendar.MILLISECOND, 0 );

        setTimeZone( c, m );

        return new MingleTimestamp( c.getTimeInMillis() / 1000, nanos );
    }

    public
    static
    MingleTimestamp
    parse( CharSequence str,
           int colOffset )
        throws MingleSyntaxException
    {
        inputs.notNull( str, "str" );
        inputs.nonnegativeI( colOffset, "colOffset" );

        Matcher m = STRICT_RFC3339_TIMESTAMP_PATTERN.matcher( str );

        if ( m.matches() ) return buildTimestamp( m );
        else
        {
            String msg = "Invalid timestamp: " + Lang.getRfc4627String( str );
            throw new MingleSyntaxException( msg, colOffset );
        }
    }

    public
    static
    MingleTimestamp
    parse( CharSequence str )
        throws MingleSyntaxException
    {
        return parse( str, 0 );
    }

    public
    static
    MingleTimestamp
    create( CharSequence str )
    {
        try { return parse( str ); }
        catch ( MingleSyntaxException se )
        {
            throw new IllegalArgumentException( se.getMessage(), se );
        }
    }
}


text:
import olMap from 'ol/Map';
import LayerGroup from 'ol/layer/Group';

/**
 * @function MapExtend
 * @description 扩展 OpenLayers 的一些原始方法。
 * @private
 */
export var MapExtend = function () {
    const fun = function (layer, coordinate, resolution, callback, pixel, e) {
        if (layer instanceof LayerGroup) {
            layer.getLayers().forEach(function (subLayer) {
                fun(subLayer, coordinate, resolution, callback, pixel, e)
            });
        } else {
            //当前高效率点图层满足筛选条件/并且可视时,可被选中:
            if (layer.getSource()._forEachFeatureAtCoordinate) {
                layer.getSource()._forEachFeatureAtCoordinate(coordinate, resolution, (feature) => {
                    callback(feature, layer)
                }, pixel, e);
            }
        }
    }
    olMap.prototype.forEachFeatureAtPixelDefault = olMap.prototype.forEachFeatureAtPixel;

    olMap.prototype.forEachFeatureAtPixel = olMap.prototype.Tc = function (pixel, callback, opt_options, e) {

        //如果满足高效率图层选取要求优先返回高效率图层选中结果
        const layerFilter = (opt_options && opt_options.layerFilter) ? opt_options.layerFilter : () => {
            return true;
        };

        const layers = this.getLayers().getArray();
        const resolution = this.getView().getResolution();
        const coordinate = this.getCoordinateFromPixel(pixel);

        for (let i = 0; i < layers.length; i++) {
            const layer = layers[i];
            if (layer.getVisible() && layerFilter.call(null, layer)) {
                fun(layer, coordinate, resolution, callback, pixel, e)
            }

        }
        return this.forEachFeatureAtPixelDefault(pixel, callback, opt_options);
    }
}();


text:
require 'minitest'
require 'minitest/autorun'
require 'mongoid'
require 'mongoid_ruby_or'

Mongoid.load!('test/mongoid.yml', :test)

class User
  include Mongoid::Document

  field :name,       type: String
  field :email,      type: String
  field :account_id, type: String
end

def assert_criteria(criteria)
  assert_equal criteria.to_a, criteria.ruby_or
end


text:
module ChiliProject
  module ApacheHelpers
    def common_url(ssl=@params[:force_ssl])
      if ssl
        port = ":#{@params[:https_port]}" unless @params[:https_port] == 443
        "https://#{@application_name}#{port}"
      else
        port = ":#{@params[:http_port]}" unless @params[:http_port] == 80
        "http://#{@application_name}#{port}"
      end
    end

    def load_chiliproject_pm
      return if @chiliproject_pm_loaded

      @chiliproject_pm_loaded = true
      if @params[:passenger_paths].values.any?{ |inst| inst['repository_hosting'].any? }
        "PerlLoadModule Apache::ChiliProject"
      end
    end
  end
end


text:
haskell-course
==============

CMC MSU Haskell course materials. Check out [haskell-course website](http://cmc-msu-ai.github.io/haskell-course/).


text:
IQDictionary
============
Smart Dictionary.

Fetures

1. sort the dictionary data
2. insert multi values
3. encryption and decryption data
4. sort allkeys or for the allkeys of an object
5. find the objects or objects count for key
6. sort the all values for the dictionary


text:
require 'spec_helper'

class WillPaginateDatatable < AjaxDatatablesRails::Base
  include AjaxDatatablesRails::Extensions::WillPaginate
end

describe WillPaginateDatatable do
  describe '#paginate_records' do
    let(:users_database) do
      double('User',
        :all => double('RecordCollection',
          :paginate => double('Array', :per_page => [])
        )
      )
    end

    let(:datatable) { WillPaginateDatatable.new(double('view', :params => {})) }
    let(:records) { users_database.all }

    it 'calls #page and #per_page on passed record collection' do
      records.should_receive(:paginate).with(:page=>1, :per_page=>10)
      datatable.send(:paginate_records, records)
    end
  end
end


text:
import { Component, OnInit, ViewEncapsulation, Output, EventEmitter } from '@angular/core';

@Component({
    selector: 'mw-dropdown-nav-item',
    templateUrl: './mw-dropdown-nav-item.component.html',
    styleUrls: ['./mw-dropdown-nav-item.component.scss'],
    encapsulation: ViewEncapsulation.None
})
export class MwDropdownNavItemComponent {
    @Output() menuItemClick = new EventEmitter();

    constructor() { }

    onMenuItemClick(event: Event) {
        event.preventDefault();

        this.menuItemClick.emit('MenuItemClicked');
    }
}


text:
"""Utility functions for opening a GCE URL and getting contents."""

import urllib2

from googlecloudsdk.core import properties

GOOGLE_GCE_METADATA_URI = 'http://metadata.google.internal/computeMetadata/v1'

GOOGLE_GCE_METADATA_DEFAULT_ACCOUNT_URI = (
    GOOGLE_GCE_METADATA_URI + '/instance/service-accounts/default/email')

GOOGLE_GCE_METADATA_PROJECT_URI = (
    GOOGLE_GCE_METADATA_URI + '/project/project-id')

GOOGLE_GCE_METADATA_NUMERIC_PROJECT_URI = (
    GOOGLE_GCE_METADATA_URI + '/project/numeric-project-id')

GOOGLE_GCE_METADATA_ACCOUNTS_URI = (
    GOOGLE_GCE_METADATA_URI + '/instance/service-accounts')

GOOGLE_GCE_METADATA_ACCOUNT_URI = (
    GOOGLE_GCE_METADATA_ACCOUNTS_URI + '/{account}/email')

GOOGLE_GCE_METADATA_ZONE_URI = (
    GOOGLE_GCE_METADATA_URI + '/instance/zone')

GOOGLE_GCE_METADATA_HEADERS = {'Metadata-Flavor': 'Google'}

def ReadNoProxy(uri):
  """Opens a URI with metadata headers, without a proxy, and reads all data.."""
  request = urllib2.Request(uri, headers=GOOGLE_GCE_METADATA_HEADERS)
  timeout_property = (
      properties.VALUES.compute.gce_metadata_read_timeout_sec.GetInt())
  return urllib2.build_opener(urllib2.ProxyHandler({})).open(
      request, timeout=timeout_property).read()


text:
public class BinaryTreePaths {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<>();
        String list = "";
        if (root != null)
            list = list + root.val;
        helper(root, result, list);
        return result;
    }

    private void helper(TreeNode root, List<String> result, String lst) {
        if (root == null)
            return;
        if (root.left == null && root.right == null) {
            result.add(lst);
            return;
        }
        if (root.left != null)
            helper(root.left, result, lst + "->" + root.left.val);
        if (root.right != null)
            helper(root.right, result, lst + "->" + root.right.val);
    }
}


text:
define('encodeCompare', ['codeCompareBase'], function(codeCompareBase) {
  'use strict';

  return codeCompareBase.buildCompareObject({
    codePrefix: '',
    codePostfix: '',
    codeName: 'character',
    translateFunctionName: 'encode'
  });
});


text:
<?php

namespace Sodium\Contract\Component;

interface ReferenceInterface
{
    public static function get();
}


text:
namespace egl
{
class Surface;
}

namespace gl
{
class Blit;
class Framebuffer;

enum
{
    // These are the maximums the implementation can support
    // The actual GL caps are limited by the device caps
    // and should be queried from the Context
    IMPLEMENTATION_MAX_TEXTURE_SIZE = 16384,
    IMPLEMENTATION_MAX_CUBE_MAP_TEXTURE_SIZE = 16384,

    IMPLEMENTATION_MAX_TEXTURE_LEVELS = 15   // 1+log2 of MAX_TEXTURE_SIZE
};

class Image
{
  public:
    Image();
    ~Image();

    bool redefine(GLenum format, GLsizei width, GLsizei height, GLenum type, bool forceRelease);
    void markDirty() {mDirty = true;}
    void markClean() {mDirty = false;}

    bool isRenderableFormat() const;
    D3DFORMAT getD3DFormat() const;

    GLsizei getWidth() const {return mWidth;}
    GLsizei getHeight() const {return mHeight;}
    GLenum getFormat() const {return mFormat;}
    GLenum getType() const {return mType;}
    bool isDirty() const {return mSurface && mDirty;}
    IDirect3DSurface9 *getSurface();

    void setManagedSurface(IDirect3DSurface9 *surface);
    void updateSurface(IDirect3DSurface9 *dest, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height);

    void loadData(GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum type,
                  GLint unpackAlignment, const void *input);

    void loadAlphaData(GLsizei width, GLsizei height,
                       int inputPitch, const void *input, size_t outputPitch, void *output) const;
    void loadAlphaDataSSE2(GLsizei width, GLsizei height,
                           int inputPitch, const void *input, size_t outputPitch, void *output) const;
    void loadAlphaFloatData(GLsizei width, GLsizei height,
                            int inputPitch, const void *input, size_t outputPitch, void *output) const;
    void loadAlphaHalfFloatData(GLsizei width, GLsizei height,
                                int inputPitch, const void *input, size_t outputPitch, void *output) const;
    void loadLuminanceData(GLsizei width, GLsizei height,
                           int inputPitch, const void *input, size_t outputPitch, void *output, bool native) const;
    void loadLuminanceFloatData(GLsizei width, GLsizei height,
                                int inputPitch, const void *input, size_t outputPitch, void *output) const;
    void loadLuminanceHalfFloatData(GLsizei width, GLsizei height,
                                    int inputPitch, const void *input, size_t outputPitch, void *output) const;
    void loadLuminanceAlphaData(GLsizei width, GLsizei height,
                                int inputPitch, const void *input, size_t outputPitch, void *output, bool native) const;
    void loadLuminanceAlphaFloatData(GLsizei width, GLsizei height,
                                     int inputPitch, const void *input, size_t outputPitch, void *output) const;
    void loadLuminanceAlphaHalfFloatData(GLsizei width, GLsizei height,
                                         int inputPitch, const void *input, size_t outputPitch, void *output) const;
    void loadRGBUByteData(GLsizei width, GLsizei height,
                          int inputPitch, const void *input, size_t outputPitch, void *output) const;
    void loadRGB565Data(GLsizei width, GLsizei height,
                        int inputPitch, const void *input, size_t outputPitch, void *output) const;
    void loadRGBFloatData(GLsizei width, GLsizei height,
                          int inputPitch, const void *input, size_t outputPitch, void *output) const;
    void loadRGBHalfFloatData(GLsizei width, GLsizei height,
                              int inputPitch, const void *input, size_t outputPitch, void *output) const;
    void loadRGBAUByteDataSSE2(GLsizei width, GLsizei height,
                               int inputPitch, const void *input, size_t outputPitch, void *output) const;
    void loadRGBAUByteData(GLsizei width, GLsizei height,
                           int inputPitch, const void *input, size_t outputPitch, void *output) const;
    void loadRGBA4444Data(GLsizei width, GLsizei height,
                          int inputPitch, const void *input, size_t outputPitch, void *output) const;
    void loadRGBA5551Data(GLsizei width, GLsizei height,
                          int inputPitch, const void *input, size_t outputPitch, void *output) const;
    void loadRGBAFloatData(GLsizei width, GLsizei height,
                           int inputPitch, const void *input, size_t outputPitch, void *output) const;
    void loadRGBAHalfFloatData(GLsizei width, GLsizei height,
                               int inputPitch, const void *input, size_t outputPitch, void *output) const;
    void loadBGRAData(GLsizei width, GLsizei height,
                      int inputPitch, const void *input, size_t outputPitch, void *output) const;
    void loadCompressedData(GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
                            const void *input);

    void copy(GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, IDirect3DSurface9 *renderTarget);

  private:
    DISALLOW_COPY_AND_ASSIGN(Image);

    void createSurface();

    HRESULT lock(D3DLOCKED_RECT *lockedRect, const RECT *rect);
    void unlock();

    GLsizei mWidth;
    GLsizei mHeight;
    GLenum mFormat;
    GLenum mType;

    bool mDirty;

    D3DPOOL mD3DPool;   // can only be D3DPOOL_SYSTEMMEM or D3DPOOL_MANAGED since it needs to be lockable.
    D3DFORMAT mD3DFormat;

    IDirect3DSurface9 *mSurface;
};

class TextureStorage
{
  public:
    explicit TextureStorage(DWORD usage);

    virtual ~TextureStorage();

    bool isRenderTarget() const;
    bool isManaged() const;
    D3DPOOL getPool() const;
    DWORD getUsage() const;
    unsigned int getTextureSerial() const;
    virtual unsigned int getRenderTargetSerial(GLenum target) const = 0;

  private:
    DISALLOW_COPY_AND_ASSIGN(TextureStorage);

    const DWORD mD3DUsage;
    const D3DPOOL mD3DPool;

    const unsigned int mTextureSerial;
    static unsigned int issueTextureSerial();

    static unsigned int mCurrentTextureSerial;
};

class Texture : public RefCountObject
{
  public:
    explicit Texture(GLuint id);

    virtual ~Texture();

    virtual void addProxyRef(const Renderbuffer *proxy) = 0;
    virtual void releaseProxy(const Renderbuffer *proxy) = 0;

    virtual GLenum getTarget() const = 0;

    bool setMinFilter(GLenum filter);
    bool setMagFilter(GLenum filter);
    bool setWrapS(GLenum wrap);
    bool setWrapT(GLenum wrap);
    bool setUsage(GLenum usage);

    GLenum getMinFilter() const;
    GLenum getMagFilter() const;
    GLenum getWrapS() const;
    GLenum getWrapT() const;
    GLenum getUsage() const;

    virtual bool isSamplerComplete() const = 0;

    IDirect3DBaseTexture9 *getTexture();
    virtual Renderbuffer *getRenderbuffer(GLenum target) = 0;

    virtual void generateMipmaps() = 0;
    virtual void copySubImage(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, Framebuffer *source) = 0;

    bool hasDirtyParameters() const;
    bool hasDirtyImages() const;
    void resetDirty();
    unsigned int getTextureSerial();
    unsigned int getRenderTargetSerial(GLenum target);

    bool isImmutable() const;

    static const GLuint INCOMPLETE_TEXTURE_ID = static_cast<GLuint>(-1);   // Every texture takes an id at creation time. The value is arbitrary because it is never registered with the resource manager.

  protected:
    void setImage(GLint unpackAlignment, const void *pixels, Image *image);
    bool subImage(GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels, Image *image);
    void setCompressedImage(GLsizei imageSize, const void *pixels, Image *image);
    bool subImageCompressed(GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *pixels, Image *image);

    GLint creationLevels(GLsizei width, GLsizei height) const;
    GLint creationLevels(GLsizei size) const;

    virtual IDirect3DBaseTexture9 *getBaseTexture() const = 0;
    virtual void createTexture() = 0;
    virtual void updateTexture() = 0;
    virtual void convertToRenderTarget() = 0;
    virtual IDirect3DSurface9 *getRenderTarget(GLenum target) = 0;

    int levelCount() const;

    static Blit *getBlitter();
    static bool copyToRenderTarget(IDirect3DSurface9 *dest, IDirect3DSurface9 *source, bool fromManaged);

    GLenum mMinFilter;
    GLenum mMagFilter;
    GLenum mWrapS;
    GLenum mWrapT;
    bool mDirtyParameters;
    GLenum mUsage;

    bool mDirtyImages;

    bool mImmutable;

  private:
    DISALLOW_COPY_AND_ASSIGN(Texture);

    virtual TextureStorage *getStorage(bool renderTarget) = 0;
};

class TextureStorage2D : public TextureStorage
{
  public:
    explicit TextureStorage2D(IDirect3DTexture9 *surfaceTexture);
    TextureStorage2D(int levels, D3DFORMAT format, DWORD usage, int width, int height);

    virtual ~TextureStorage2D();

    IDirect3DSurface9 *getSurfaceLevel(int level);
    IDirect3DBaseTexture9 *getBaseTexture() const;

    virtual unsigned int getRenderTargetSerial(GLenum target) const;

  private:
    DISALLOW_COPY_AND_ASSIGN(TextureStorage2D);

    IDirect3DTexture9 *mTexture;
    const unsigned int mRenderTargetSerial;
};

class Texture2D : public Texture
{
  public:
    explicit Texture2D(GLuint id);

    ~Texture2D();

    void addProxyRef(const Renderbuffer *proxy);
    void releaseProxy(const Renderbuffer *proxy);

    virtual GLenum getTarget() const;

    GLsizei getWidth(GLint level) const;
    GLsizei getHeight(GLint level) const;
    GLenum getInternalFormat(GLint level) const;
    D3DFORMAT getD3DFormat(GLint level) const;
    bool isCompressed(GLint level) const;
    bool isDepth(GLint level) const;

    void setImage(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
    void setCompressedImage(GLint level, GLenum format, GLsizei width, GLsizei height, GLsizei imageSize, const void *pixels);
    void subImage(GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
    void subImageCompressed(GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *pixels);
    void copyImage(GLint level, GLenum format, GLint x, GLint y, GLsizei width, GLsizei height, Framebuffer *source);
    virtual void copySubImage(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, Framebuffer *source);
    void storage(GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);

    virtual bool isSamplerComplete() const;
    virtual void bindTexImage(egl::Surface *surface);
    virtual void releaseTexImage();

    virtual void generateMipmaps();

    virtual Renderbuffer *getRenderbuffer(GLenum target);

  protected:
    friend class RenderbufferTexture2D;
    virtual IDirect3DSurface9 *getRenderTarget(GLenum target);
    virtual IDirect3DSurface9 *getDepthStencil(GLenum target);

  private:
    DISALLOW_COPY_AND_ASSIGN(Texture2D);

    virtual IDirect3DBaseTexture9 *getBaseTexture() const;
    virtual void createTexture();
    virtual void updateTexture();
    virtual void convertToRenderTarget();
    virtual TextureStorage *getStorage(bool renderTarget);

    bool isMipmapComplete() const;

    void redefineImage(GLint level, GLenum format, GLsizei width, GLsizei height, GLenum type);
    void commitRect(GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height);

    Image mImageArray[IMPLEMENTATION_MAX_TEXTURE_LEVELS];

    TextureStorage2D *mTexStorage;
    egl::Surface *mSurface;

    // A specific internal reference count is kept for colorbuffer proxy references,
    // because, as the renderbuffer acting as proxy will maintain a binding pointer
    // back to this texture, there would be a circular reference if we used a binding
    // pointer here. This reference count will cause the pointer to be set to NULL if
    // the count drops to zero, but will not cause deletion of the Renderbuffer.
    Renderbuffer *mColorbufferProxy;
    unsigned int mProxyRefs;
};

class TextureStorageCubeMap : public TextureStorage
{
  public:
    TextureStorageCubeMap(int levels, D3DFORMAT format, DWORD usage, int size);

    virtual ~TextureStorageCubeMap();

    IDirect3DSurface9 *getCubeMapSurface(GLenum faceTarget, int level);
    IDirect3DBaseTexture9 *getBaseTexture() const;

    virtual unsigned int getRenderTargetSerial(GLenum target) const;

  private:
    DISALLOW_COPY_AND_ASSIGN(TextureStorageCubeMap);

    IDirect3DCubeTexture9 *mTexture;
    const unsigned int mFirstRenderTargetSerial;
};

class TextureCubeMap : public Texture
{
  public:
    explicit TextureCubeMap(GLuint id);

    ~TextureCubeMap();

    void addProxyRef(const Renderbuffer *proxy);
    void releaseProxy(const Renderbuffer *proxy);

    virtual GLenum getTarget() const;

    GLsizei getWidth(GLenum target, GLint level) const;
    GLsizei getHeight(GLenum target, GLint level) const;
    GLenum getInternalFormat(GLenum target, GLint level) const;
    D3DFORMAT getD3DFormat(GLenum target, GLint level) const;
    bool isCompressed(GLenum target, GLint level) const;

    void setImagePosX(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
    void setImageNegX(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
    void setImagePosY(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
    void setImageNegY(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
    void setImagePosZ(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
    void setImageNegZ(GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);

    void setCompressedImage(GLenum face, GLint level, GLenum format, GLsizei width, GLsizei height, GLsizei imageSize, const void *pixels);

    void subImage(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
    void subImageCompressed(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *pixels);
    void copyImage(GLenum target, GLint level, GLenum format, GLint x, GLint y, GLsizei width, GLsizei height, Framebuffer *source);
    virtual void copySubImage(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, Framebuffer *source);
    void storage(GLsizei levels, GLenum internalformat, GLsizei size);

    virtual bool isSamplerComplete() const;

    virtual void generateMipmaps();

    virtual Renderbuffer *getRenderbuffer(GLenum target);

    static unsigned int faceIndex(GLenum face);

  protected:
    friend class RenderbufferTextureCubeMap;
    virtual IDirect3DSurface9 *getRenderTarget(GLenum target);

  private:
    DISALLOW_COPY_AND_ASSIGN(TextureCubeMap);

    virtual IDirect3DBaseTexture9 *getBaseTexture() const;
    virtual void createTexture();
    virtual void updateTexture();
    virtual void convertToRenderTarget();
    virtual TextureStorage *getStorage(bool renderTarget);

    bool isCubeComplete() const;
    bool isMipmapCubeComplete() const;

    void setImage(int faceIndex, GLint level, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint unpackAlignment, const void *pixels);
    void commitRect(int faceIndex, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height);
    void redefineImage(int faceIndex, GLint level, GLenum format, GLsizei width, GLsizei height, GLenum type);

    Image mImageArray[6][IMPLEMENTATION_MAX_TEXTURE_LEVELS];

    TextureStorageCubeMap *mTexStorage;

    // A specific internal reference count is kept for colorbuffer proxy references,
    // because, as the renderbuffer acting as proxy will maintain a binding pointer
    // back to this texture, there would be a circular reference if we used a binding
    // pointer here. This reference count will cause the pointer to be set to NULL if
    // the count drops to zero, but will not cause deletion of the Renderbuffer.
    Renderbuffer *mFaceProxies[6];
    unsigned int *mFaceProxyRefs[6];
};
}

#endif   // LIBGLESV2_TEXTURE_H_


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="title_dialog_training_create">สร้างการฝึกอบรมใหม่</string>
    <string name="title_dialog_training_delete">ลบการฝึกอบรมหรือไม่</string>
    <string name="text_dialog_training_delete_confirm">แน่ใจหรือไม่ว่าต้องการลบการฝึกอบรมนี้</string>
    <string name="title_dialog_training_completion_delete">ลบการสำเร็จการฝึกอบรมหรือไม่</string>
    <string name="text_dialog_training_completion_delete_confirm">แน่ใจหรือไม่ว่าต้องการลบการสำเร็จการฝึกอบรม</string>
    <!-- Training Dialog tabs-->
    <string name="tab_training_training">การฝึกอบรม</string>
    <string name="tab_training_stages">ขั้นตอน</string>
    <!-- Training Details Fragment-->
    <string name="label_training_name">ชื่อ</string>
    <string name="label_training_type">ประเภทการฝึกอบรม</string>
    <string name="label_training_date">วันที่</string>
    <string name="label_training_participants">ผู้เข้าร่วม</string>
    <string name="label_training_stage">ขั้นตอน</string>
    <string name="label_training_stage_date">วันที่</string>
    <string name="label_training_stage_participants">ผู้เข้าร่วม</string>
    <string name="btn_training_add_stage">เพิ่มขั้นตอน</string>
    <string name="btn_training_create">สร้าง</string>
</resources>


text:
package cl

import (
	"fmt"
	"math/big"

	"github.com/xlab-si/emmy/crypto/common"
	"github.com/xlab-si/emmy/crypto/df"
	"github.com/xlab-si/emmy/crypto/qr"
	"github.com/xlab-si/emmy/crypto/schnorr"
)

type CredRequest struct {
	Nym                      *big.Int
	KnownAttrs               []*big.Int
	CommitmentsOfAttrs       []*big.Int
	NymProof                 *schnorr.Proof
	U                        *big.Int
	UProof                   *qr.RepresentationProof
	CommitmentsOfAttrsProofs []*df.OpeningProof
	Nonce                    *big.Int
}

func NewCredRequest(nym *big.Int, knownAttrs, commitmentsOfAttrs []*big.Int, nymProof *schnorr.Proof,
	U *big.Int, UProof *qr.RepresentationProof,
	commitmentsOfAttrsProofs []*df.OpeningProof, nonce *big.Int) *CredRequest {
	return &CredRequest{
		Nym:                nym,
		KnownAttrs:         knownAttrs,
		CommitmentsOfAttrs: commitmentsOfAttrs,
		NymProof:           nymProof,
		U:                  U,
		UProof:             UProof,
		CommitmentsOfAttrsProofs: commitmentsOfAttrsProofs,
		Nonce: nonce,
	}
}

// computeU computes U = S^v1 * R_1^m_1 * ... * R_NumAttrs^m_NumAttrs (mod n) where only hiddenAttrs are used and
// where v1 is random from +-{0,1}^(NLength + SecParam)
func (m *CredManager) computeU() (*big.Int, *big.Int) {
	exp := big.NewInt(int64(m.Params.NLength + m.Params.SecParam))
	b := new(big.Int).Exp(big.NewInt(2), exp, nil)
	v1 := common.GetRandomIntAlsoNeg(b)

	group := qr.NewRSApecialPublic(m.PubKey.N)
	U := group.Exp(m.PubKey.S, v1)

	for i, attr := range m.Attrs.Hidden {
		t := group.Exp(m.PubKey.RsHidden[i], attr) // R_i^m_i
		U = group.Mul(U, t)
	}

	return U, v1
}

func (m *CredManager) getNymProver() (*schnorr.Prover, error) {
	// use Schnorr with two bases for proving that you know nym opening:
	bases := []*big.Int{
		m.PubKey.PedersenParams.Group.G,
		m.PubKey.PedersenParams.H,
	}
	committer := m.nymCommitter
	val, r := committer.GetDecommitMsg() // val is actually master key
	secrets := []*big.Int{val, r}

	prover, err := schnorr.NewProver(m.PubKey.PedersenParams.Group, secrets[:], bases[:],
		committer.Commitment)
	if err != nil {
		return nil, fmt.Errorf("error when creating Schnorr prover: %s", err)
	}

	return prover, nil
}

func (m *CredManager) getUProver(U *big.Int) *qr.RepresentationProver {
	group := qr.NewRSApecialPublic(m.PubKey.N)
	// secrets are [attr_1, ..., attr_L, v1]
	secrets := append(m.Attrs.Hidden, m.V1)

	// bases are [R_1, ..., R_L, S]
	bases := append(m.PubKey.RsHidden, m.PubKey.S)
	prover := qr.NewRepresentationProver(group, int(m.Params.SecParam),
		secrets[:], bases[:], U)
	return prover
}

func (m *CredManager) getUProofRandomData(prover *qr.RepresentationProver) (*big.Int, error) {
	// boundary for m_tilde
	b_m := m.Params.AttrBitLen + m.Params.SecParam + m.Params.HashBitLen + 1
	// boundary for v1
	b_v1 := m.Params.NLength + 2*m.Params.SecParam + m.Params.HashBitLen

	boundaries := make([]int, len(m.PubKey.RsHidden))
	for i := 0; i < len(m.PubKey.RsHidden); i++ {
		boundaries[i] = int(b_m)
	}
	boundaries = append(boundaries, int(b_v1))

	UTilde, err := prover.GetProofRandomDataGivenBoundaries(boundaries, true)
	if err != nil {
		return nil, fmt.Errorf("error when generating representation proof random data: %s", err)
	}

	return UTilde, nil
}

// Fiat-Shamir is used to generate a challenge, instead of asking verifier to generate it.
func (m *CredManager) getCredReqChallenge(U, nym, nonceOrg *big.Int) *big.Int {
	context := m.PubKey.GetContext()
	l := []*big.Int{context, U, nym, nonceOrg}
	l = append(l, m.CommitmentsOfAttrs...) // TODO: add other values

	return common.Hash(l...)
}

func (m *CredManager) getCredReqProvers(U *big.Int) (*schnorr.Prover,
	*qr.RepresentationProver, error) {
	nymProver, err := m.getNymProver()
	if err != nil {
		return nil, nil, fmt.Errorf("error when obtaining nym proof random data: %v", err)
	}
	uProver := m.getUProver(U)

	return nymProver, uProver, nil
}

func (m *CredManager) getCommitmentsOfAttrsProof(challenge *big.Int) []*df.OpeningProof {
	commitmentsOfAttrsProofs := make([]*df.OpeningProof, len(m.commitmentsOfAttrsProvers))
	for i, prover := range m.commitmentsOfAttrsProvers {
		proofRandomData := prover.GetProofRandomData()
		proofData1, proofData2 := prover.GetProofData(challenge)
		commitmentsOfAttrsProofs[i] = df.NewOpeningProof(proofRandomData, challenge,
			proofData1, proofData2)
	}

	return commitmentsOfAttrsProofs
}


text:
if [ -f paperjs.zip ]
then
	rm paperjs.zip
fi
# Create a temporary folder to copy all files in for zipping
mkdir zip
cd zip
BASE=../..
# Copy license over
cp $BASE/LICENSE.txt .
# Make library folder and copy paper.js there
mkdir dist
# Copy main library
cp $BASE/dist/paper-full.js dist/paper.js
# Copy all versions
cp $BASE/dist/paper-full.js dist
cp $BASE/dist/paper-full.min.js dist
cp $BASE/dist/paper-core.js dist
cp $BASE/dist/paper-core.min.js dist
# Copy examples over
cp -r $BASE/examples .
# Copy docs over
cp -r $BASE/dist/docs .
# Zip the whole thing
zip -9 -r $BASE/dist/paperjs.zip * LICENSE.txt -x "*/.DS_Store"
cd ..
# Remove the temporary folder again
rm -fr zip


text:
import { Meta, Story } from '@storybook/angular';

interface GridsVerticalAlignmentStory {}

export default {
	title: 'Documentation/Structure/Grids/Vertical Alignment',
} as Meta;

function getTemplate(args: GridsVerticalAlignmentStory): string {
	return `

Top

Middle

Bottom

	`;
}

const Template: Story<GridsVerticalAlignmentStory> = (args: GridsVerticalAlignmentStory) => ({
	props: args,
	template: getTemplate(args),
	styles: [
		`
		.grid-demo {
			background: #F3F5FC;
			margin-bottom: var(--spacings-small);
			padding: var(--spacings-small);
			border-radius: 1rem;
		}`,
	],
});

export const VerticalAlignment = Template.bind({});
VerticalAlignment.args = {};