text:
// Modules
// =============================================================================
import { elementsToArray, classNamesToArray } from './util.js';

// Functions
// =============================================================================
/**
 * Add class name(s) to target element(s)
 *
 * @param {(array|element|htmlcollection|nodelist|string)} target -
 *   Element(s) to add class name(s) to
 * @param {(array|function|string)} classNames - Array, space-separated list,
 *  or function that returns array/string of class name(s)
 * @returns {(array|element)} - Target(s)
 */
function addClass(target, classNames) {
    const elms = elementsToArray(target);

    elms.forEach(function(elm, i) {
        const classArray = classNamesToArray(classNames instanceof Function ? classNames(elm, i) : classNames);

        if (classArray && classArray.length) {
            const elmClassArray   = elm.className.length ? elm.className.split(' ') : [];
            const newClassArray   = classArray.filter(className => elmClassArray.indexOf(className) === -1);
            const finalClassArray = elmClassArray.concat(newClassArray);

            elm.className = finalClassArray.join(' ');
        }
    });

    return elms.length === 1 ? elms[0] : elms;
}

// Exports
// =============================================================================
export default addClass;


text:
0.2.2 (December 15, 2014)
* Documented the whole gem
* Changed RuntimeError raising to ArgumentError
* Renamed gem to 'kerbalstuff'

0.2.1 (November 20, 2014)
* Added support for **POST** methods (Login, CreateMod, UpdateMod)
* All methods now return an array containing the info you need. Example: `["name=test", "id=1337"]`

0.2.0 (October 25, 2014)
* Added support for KerbalStuff **browse** methods
* Added links to Mod.background and ModVersion.download_path

redpajama_set_name: RedPajamaGithub


text:
module.exports.encode = function (data) {
  return new Buffer(JSON.stringify(data)).toString("base64")
}


text:
"""
Interactive Use

To prepare a terminal for interactive use:

    >>> from pyeda.inter import *
"""

# Disable "unused-import", since that's basically all this module is for.
# pylint: disable=W0611

from pyeda.util import clog2, parity

from pyeda.boolalg.boolfunc import (
    num2point, num2upoint, num2term,
    point2upoint, point2term,
    iter_points, iter_upoints, iter_terms,
    vpoint2point,
    Variable, Function,
)

from pyeda.boolalg.bdd import (
    bddvar, expr2bdd, bdd2expr, upoint2bddpoint, ite,
    BDDNode, BinaryDecisionDiagram, BDDConstant, BDDVariable,
)

from pyeda.boolalg.expr import (
    exprvar, expr,
    ast2expr, expr2dimacscnf, expr2dimacssat, upoint2exprpoint,
    Not, Or, And, Nor, Nand, Xor, Xnor, Equal, Unequal, Implies, ITE,
    Nor, Nand, OneHot0, OneHot, NHot, Majority, AchillesHeel,
    Mux, ForAll, Exists,
    Expression,
    NormalForm, DisjNormalForm, ConjNormalForm, DimacsCNF,
)

from pyeda.boolalg.table import (
    ttvar, truthtable, expr2truthtable, truthtable2expr,
    TruthTable, TTConstant, TTVariable,
)

from pyeda.boolalg.bfarray import (
    bddzeros, bddones, bddvars,
    exprzeros, exprones, exprvars,
    ttzeros, ttones, ttvars,
    uint2bdds, uint2exprs, uint2tts,
    int2bdds, int2exprs, int2tts,
    fcat,
    farray,
)

from pyeda.boolalg.minimization import espresso_exprs, espresso_tts

from pyeda.parsing.boolexpr import parse as parse_expr

from pyeda.parsing.dimacs import parse_cnf, parse_sat


text:
package apple.scenekit.struct;

import org.moe.natj.c.StructObject;
import org.moe.natj.c.ann.Structure;
import org.moe.natj.c.ann.StructureField;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.Generated;

@Generated
@Structure()
public final class SCNVector4 extends StructObject {
    private static long __natjCache;

    static {
        NatJ.register();
    }

    @Generated
    public SCNVector4() {
        super(SCNVector4.class);
    }

    @Generated
    protected SCNVector4(Pointer peer) {
        super(peer);
    }

    @Generated
    public SCNVector4(float x, float y, float z, float w) {
        super(SCNVector4.class);
        setX(x);
        setY(y);
        setZ(z);
        setW(w);
    }

    @Generated
    @StructureField(order = 0, isGetter = true)
    public native float x();

    @Generated
    @StructureField(order = 0, isGetter = false)
    public native void setX(float value);

    @Generated
    @StructureField(order = 1, isGetter = true)
    public native float y();

    @Generated
    @StructureField(order = 1, isGetter = false)
    public native void setY(float value);

    @Generated
    @StructureField(order = 2, isGetter = true)
    public native float z();

    @Generated
    @StructureField(order = 2, isGetter = false)
    public native void setZ(float value);

    @Generated
    @StructureField(order = 3, isGetter = true)
    public native float w();

    @Generated
    @StructureField(order = 3, isGetter = false)
    public native void setW(float value);
}


text:
#include <sol-network-util.h>
#include <sys/socket.h>

enum sol_network_family
sol_network_af_to_sol(int af)
{
    switch (af) {
    case AF_INET:
        return SOL_NETWORK_FAMILY_INET;
    case AF_INET6:
        return SOL_NETWORK_FAMILY_INET6;
    default:
        return SOL_NETWORK_FAMILY_UNSPEC;
    }
}

int
sol_network_sol_to_af(enum sol_network_family snf)
{
    switch (snf) {
    case SOL_NETWORK_FAMILY_INET:
        return AF_INET;
    case SOL_NETWORK_FAMILY_INET6:
        return AF_INET6;
    default:
        return AF_UNSPEC;
    }
}


text:
<!DOCTYPE html>

	<title>403 Forbsidden</title>

Directory access is forbidden.


text:
package org.talares.datatypes.items;

import org.talares.api.Talares;
import org.talares.datatypes.Metadata;
import scala.Option;

/**
 * The common class for all concrete content type's.
 *
 * @author Dennis Vis
 * @since 0.1.0
 */
public abstract class Item {

  private final org.talares.api.Talares api;
  private final Metadata metadata;
  private final int publicationId;

  public Item(final org.talares.api.Talares scalaApi, final org.talares.api.datatypes.items.Item scalaItem) {
    this.api = scalaApi;
    this.metadata = new Metadata(scalaItem.metadata());
    this.publicationId = scalaItem.publicationId();
  }

  @SuppressWarnings("unchecked")
  protected final <A, B> B asJava(final Option<A> option) {
    if (option.isDefined()) {
      A a = option.get();
      if (a instanceof scala.Boolean) return (B) Boolean.valueOf(scala.Boolean.unbox(a));
      if (a instanceof scala.Float) return (B) new Float(scala.Float.unbox(a));
      if (a instanceof scala.Int) return (B) new Integer(scala.Int.unbox(a));
      return (B) a;
    }
    return null;
  }

  public final Talares getApi() {
    return api;
  }

  public final Metadata getMetadata() {
    return metadata;
  }

  public final int getPublicationId() {
    return publicationId;
  }
}


text:
<form>

		Name: <input type="text" ng-model="widget.name">

		Description: <textarea ng-model="widget.description" rows="5" cols="60"></textarea>

		Color:
			<select ng-model="widget.color" ng-options="color.value as color.label for color in colors">
				<option value="">Select One</option>
			</select>

		Size:
			<select ng-model="widget.size" ng-options="size.value as size.label for size in sizes">
				<option value="">Select One</option>
			</select>

		Quantity: <input type="number" ng-model="widget.quantity">

	<button class="btn btn-primary" ng-click="saveWidget(widget)">Save Widget</button>
	<button class="btn btn-danger" ng-if="widget.id" ng-click="deleteWidget(widget.id)">Delete Widget</button>
	<button class="btn btn-default" ng-click="returnToList()">Return to List</button>

</form>


text:
"""
Testing package subcommands
"""

from .search import *
from .show import *


text:
class Component extends React.Component {
    constructor() {
        super();
        this.onClick = this.onClick.bind(this);
    }
    onClick() { }
}

class Component2 extends React.Component {
    constructor() {
        super();
        this.onClick = this.onClick.bind(this);
    }
    onClick() { }
}


text:
<!DOCTYPE html>

    <title>Script Load Test</title>

Script Load Test

This test checks the order in which script onloads are called. Hopefully
    only one script onload is fired at a time and it matches the just-evaluated
    script tag. If this does not work, then it means require.js files *must* specify
    a module name for a module definition call, instead of letting it be derived
    from the file path.

Check the console for output


text:
using System.Collections.Generic;
using Azure.Core;
using Azure.ResourceManager.EventGrid;

namespace Azure.ResourceManager.EventGrid.Models
{
    /// <summary> Result of the List EventSubscriptions operation. </summary>
    internal partial class EventSubscriptionsListResult
    {
        /// <summary> Initializes a new instance of EventSubscriptionsListResult. </summary>
        internal EventSubscriptionsListResult()
        {
            Value = new ChangeTrackingList<EventGridSubscriptionData>();
        }

        /// <summary> Initializes a new instance of EventSubscriptionsListResult. </summary>
        /// <param name="value"> A collection of EventSubscriptions. </param>
        /// <param name="nextLink"> A link for the next page of event subscriptions. </param>
        internal EventSubscriptionsListResult(IReadOnlyList<EventGridSubscriptionData> value, string nextLink)
        {
            Value = value;
            NextLink = nextLink;
        }

        /// <summary> A collection of EventSubscriptions. </summary>
        public IReadOnlyList<EventGridSubscriptionData> Value { get; }
        /// <summary> A link for the next page of event subscriptions. </summary>
        public string NextLink { get; }
    }
}


text:
'''Copyright 2011 Google Inc. All Rights Reserved.

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.'''

from client import db_api
from client import matcher

from google.appengine.api import app_identity
from google.appengine.api import backends
from google.appengine.api import oauth
from google.appengine.api import urlfetch
from google.appengine.api import users

from google.appengine.api.urlfetch import fetch

import cgi
import datetime
import json
import logging
import os
import pprint as pp
import random
import sys
import traceback
import urllib
import webapp2

# constants
_DEBUG = True
_JSON_ENCODER = json.JSONEncoder()

if _DEBUG:
  _JSON_ENCODER.indent = 4
  _JSON_ENCODER.sort_keys = True

if backends.get_backend() == 'matcher':
  _match_maker = matcher.MatchMaker()

_EMAIL_SCOPE = "https://www.googleapis.com/auth/userinfo.email"
_IS_DEVELOPMENT = os.environ['SERVER_SOFTWARE'].startswith('Development/')

#######################################################################
# common functions
#######################################################################

def tojson(python_object):
  """Helper function to output and optionally pretty print JSON."""
  return _JSON_ENCODER.encode(python_object)

def fromjson(msg):
  """Helper function to ingest JSON."""
  try:
    return json.loads(msg)
  except Exception, e:
    raise Exception('Unable to parse as JSON: %s' % msg)

_PAIRING_KEY = fromjson(open('shared/pairing-key.json').read())['key']

def fetchjson(url, deadline, payload=None):
  """Fetch a remote JSON payload."""

  method = "GET"
  headers = {}
  if payload:
    method = "POST"
    headers['Content-Type'] = 'application/json'
  result = fetch(url, method=method, payload=payload, headers=headers, deadline=deadline).content
  return fromjson(result)

def json_by_default_dispatcher(router, request, response):
  """WSGI router which defaults to 'application/json'."""

  response.content_type = 'application/json'
  return router.default_dispatcher(request, response)

def e(msg):
  """Convient method to raise an exception."""

  raise Exception(repr(msg))

def w(msg):
  """Log a warning message."""

  logging.warning('##### %s' % repr(msg))

#######################################################################
# frontend related stuff
#######################################################################

# frontend handler
class FrontendHandler(webapp2.RequestHandler):

  def determine_user(self):
    userID = self.request.get('userID')
    if userID:
      if _IS_DEVELOPMENT:
        return userID, self.request.get('displayName', userID)
      if userID.startswith('bot*'):
        # we'll use the userID as the displayName
        return userID, userID
    try:
      # TODO avoid http://en.wikipedia.org/wiki/Confused_deputy_problem
      user = oauth.get_current_user(_EMAIL_SCOPE)
      # TODO instead get a suitable displayName from https://www.googleapis.com/auth/userinfo.profile
      return user.user_id(), user.nickname() # '0', 'example@example.com' in dev_appserver
    except oauth.OAuthRequestError:
      raise Exception("""OAuth2 credentials -or- a valid 'bot*...' userID must be provided""")

# frontend handler
class LoginHandler(FrontendHandler):

  def post(self):
    # for the admin only auth form
    self.get()

  def get(self):
     config = db_api.getConfig(self.request.host_url)
     if not config:
       self.request_init()
       return

     redirectUri = '%s/logup.html' % self.request.host_url
     authScope = 'https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/plus.me+https://www.googleapis.com/auth/plus.people.recommended';
     returnto = self.request.get('redirect_uri')
     authUri = 'http://accounts.google.com/o/oauth2/auth'
     authUri += '?scope=' + authScope
     authUri += '&redirect_uri=' + redirectUri
     authUri += '&response_type=token'
     authUri += '&client_id=' + str(config.client_id)
     #authUri += '&state=' + returnto

     self.response.headers['Access-Control-Allow-Origin'] = '*'
     logging.debug('authUri=%s' % authUri)
     self.redirect(authUri)

  def request_init(self):
     user = users.get_current_user()
     if user:
       if users.is_current_user_admin():
         client_id = self.request.get('client_id')
         client_secret = self.request.get('client_secret')
         api_key = self.request.get('api_key')
         if client_id and client_secret and api_key:
           db_api.setConfig(self.request.host_url, client_id, client_secret, api_key)
           body = 'Thank you! You may now reload this page.'
         else:
           body = """Please enter the following information from the
                     Developer Console %s project:

                     <form method="post">

Client ID for web applications

                       client_id:<input name="client_id">

                       client_secret:<input name="client_secret">

Simple API Access

                       api_key:<input name="api_key">

                       <input type="submit">
                     </form>""" % self.request.host_url
       else:
         body = 'You (%s) are not an admin. Please logout.' % (user.email(), users.create_logout_url(self.request.path))
     else:
       body = 'Please login as an admin.' % users.create_login_url(self.request.path)
     self.response.headers['Content-Type'] = 'text/html'
     self.response.write('
Datastore configuration
%s' % body)

# frontend handler
class Login(FrontendHandler):

  def post(self):
    self.response.headers['Access-Control-Allow-Origin'] = '*'
    userID, displayName = self.determine_user()

    usr = db_api.getUser(userID)
    if not usr:
      usr = db_api.newUser(userID, displayName)
    r = {'userID': userID, 'displayName': displayName}

    self.response.write(tojson(r) + '\n')

# frontend handler
class GritsService(FrontendHandler):

  # TODO per client (userID) throttling to limit abuse
  def post(self, fcn):
    logging.info('%s ...' % self.request.url)
    if not fcn:
      fcn = self.request.get('fcn')
      if fnc:
        # TODO remove once there are no more uses of ?fcn=... in our code
        logging.warning('Please use /grits/%s/?foo=... instead of /grits/?fcn=%s&foo=...' % (fnc, fnc))
    self.response.headers['Access-Control-Allow-Origin'] = '*'

    userID, displayName = self.determine_user()

    usr = db_api.getUser(userID)
    if not usr:
      if userID.startswith('bot*'):
        usr = db_api.newUser(userID, displayName)
      else:
        self.response.set_status(404)
        self.response.write('Grits userID not found: ' + userID)
        return

    if fcn == 'getProfile':
      r = {'userID': userID, 'credits': str(usr.credits), 'numWins': str(usr.numWins), 'virtualItems': usr.virtualItems}
      self.response.write(tojson(r))
    elif fcn == 'getFriends':
      self.getFriends(userID)
    elif fcn == 'buyItem':
      itemID = self.request.get('itemID')
      if not itemID:
        self.response.set_status(400)
        self.response.write('Grits itemID is required')
        return
      r = db_api.userAttemptToBuy(userID, itemID)
      self.response.write(tojson(r))
    elif fcn == 'findGame':
      self.findGame(userID)
    else:
      self.response.set_status(400)
      self.response.write('Bad grits request.')

  def findGame(self, userID):
    # forward the request to the matcher backend
    url = '%s/find-game/%s' % (backends.get_url(backend='matcher', instance=None, protocol='HTTP'), userID)
    payload = '{}'
    resp = urlfetch.fetch(url=url,
                          payload=payload,
                          method=urlfetch.POST,
                          headers={'Content-Type': 'application/json'})
    self.response.set_status(resp.status_code)
    self.response.headers.update(resp.headers)
    self.response.write(resp.content)
    logging.info('%s -> %s -> %s' % (repr(payload), url, resp.content))

  def getFriends(self, userID):
        config = db_api.getConfig(self.request.host_url)
        assert config.api_key
	token = self.request.get('accessToken')
	reqUri = 'https://www.googleapis.com/plus/v1games/people/me/people/recommended';
	reqUri += '?key=' + config.api_key;
	reqUri += '&access_token=' + token;
	result = fetchjson(reqUri, None)
	self.response.write(tojson(result))
	#self.response.headers['Content-Type'] = 'application/json'
	#self.response.headers['Access-Control-Allow-Origin'] = '*'
	#self.redirect(reqUri)

# frontend handler
class PurchaseService(FrontendHandler):

  def get(self):
    iap.serverPurchasePostback(self)

# frontend handler
class SharedJsonAssets(FrontendHandler):

  def get(self, filename):
    f = open(filename, 'r')
    self.response.write(f.read())
    f.close()

#######################################################################
# 'matcher' backend related stuff
#######################################################################

# 'matcher' backend handler
class JsonHandler(webapp2.RequestHandler):
  """Convenience class for handling JSON requests."""

  def handle(self, params, *args):
    raise Exception('subclasses must implement this method')

  def post(self, *args):
    logging.info('%s <- %s' % (self.request.path, self.request.body))
    try:
      if not self.request.body:
        raise Exception('Empty request')
      params = fromjson(self.request.body)
      r = self.handle(params, *args)
      if not r:
        raise Exception('Unexpected empty response from subclass')
      self.response.write(tojson(r))
    except:
      # clients must already be prepared to deal with non-JSON responses,
      # so a raw, human readable, stack trace is fine here
      self.response.set_status(500)
      tb = traceback.format_exc()
      logging.warn(tb)
      self.response.write(tb)

# 'matcher' backend handler
class FindGame(JsonHandler):

  def handle(self, params, userID):
    pingAll()
    return self.get_game(userID)

  def get_game(self, userID):
    # previously matched / player re-entering?
    player_game = _match_maker.lookup_player_game(userID)
    if player_game:
      return player_game

    # look for a new available game
    result = self._get_player_game(userID)

    # found a game?
    if result and 'game' in result:
      player_game = result
      usr = db_api.getUser(userID)
      addPlayers(player_game, userID, usr.displayName)
      return result

    # more players needed to start game?
    if result.get('players_needed_for_next_game', None) > 0:
      return result

    # start a new game
    game = startGame()
    if 'game_state' not in game:
      logging.info('RETURNING RESULT FROM startGame(): %s' % game)
      return game

    logging.info('RETURNING RESULT: %s' % result)
    return result

  def _get_player_game(self, userID):
    player_game = _match_maker.find_player_game(userID)
    return player_game

# 'matcher' backend handler
class UpdateGameState(JsonHandler):

  def handle(self, params, *args):
    serverid = params['serverid']
    new_game_state = params['game_state']
    game_name = new_game_state['name']
    _match_maker.update_player_names(serverid, game_name, new_game_state)
    return {'success': True,
            'backend': backends.get_backend()}

# 'matcher' backend handler
class RegisterController(JsonHandler):

  def handle(self, params, *args):
    if _PAIRING_KEY != params['pairing_key']:
      return {'success': False,
              'exception': 'bad pairing key'}
    controller_port = params['controller_port']
    ip = self.request.remote_addr
    controller_host = '%s:%d' % (ip, controller_port)
    params['controller_host'] = controller_host
    _match_maker.update_server_info(params)
    return {'success': True,
            'backend': backends.get_backend(),
            'controller_host': controller_host}

# 'matcher' backend handler
class ListGames(webapp2.RequestHandler):

  def get(self):
    self.response.write(tojson(pingAll()))

# 'matcher' backend handler
class Debug(webapp2.RequestHandler):

  def get(self):
    state = _match_maker.get_state()
    self.response.write(tojson(state))

# 'matcher' backend handler
class StartGame(webapp2.RequestHandler):

  def get(self):
    self.response.write(tojson(startGame()))

# 'matcher' backend handler
class LogFiles(webapp2.RequestHandler):

  def get(self):
    self.response.headers['Content-Type'] = 'text/html'
    self.response.write('
Log Files
')
    for serverid in _match_maker.get_game_servers():
      server_info = _match_maker.get_game_server_info(serverid)
      self.response.write('
%(id)s: '
                          'error '
                          'console '
                          'ping '
                          'enable-dedup '
                          'disable-dedup '
                          '
' %
                          {'id':serverid,
                           'svr':server_info['controller_host']})
    self.response.write('')

# 'matcher' backend handler
class GameOver(JsonHandler):

  def handle(self, params, *args):
    _match_maker.del_game(params['serverid'], params['name'])
    return {'success': True, 'backend': backends.get_backend()}

# 'matcher' backend helper function
def pingAll():
  removeserver = []
  # TODO use async urlfetch to parallelize url fetch calls
  for serverid in _match_maker.get_game_servers():
    server_info = _match_maker.get_game_server_info(serverid)
    url = 'http://%s/ping' % server_info['controller_host']
    try:
      r = fetchjson(url, 2)
      logging.debug('pingAll(): %s -> %s' % (url, r))
    except:
      logging.warn('pingAll(): EXCEPTION %s' % traceback.format_exc())
      removeserver.append(serverid)
    if r['serverid'] != serverid:
      removeserver.append(serverid)
      continue

    # check for games which have ended without our knowledge
    remotegameinfo = r['gameinfo']
    server_struct = _match_maker.get_game_server_struct(serverid)
    games = server_struct['games']
    removegame = []
    for name, game in games.iteritems():
      if name not in remotegameinfo:
        # the game is unexpectedly gone
        logging.warn('serverid %s unexpectedly lost game %s (did we miss a /game-over callback?)' % (serverid, name))
        removegame.append(name)
    for name in removegame:
      _match_maker.del_game(serverid, name)

  for serverid in removeserver:
    _match_maker.del_game_server(serverid)
  return _match_maker.get_game_servers()

# 'matcher' backend helper function
def rateUsage(r):
  return max(int(r['cpu']), int(r['mem']))

# 'matcher' backend helper function
def startGame():
  logging.debug('startGame()')
  best = None
  bestServer = None
  for serverid, server_struct in pingAll().iteritems():
    if not best or rateUsage(best) > rateUsage(r):
      server_info = server_struct['server_info']
      best = server_info
      bestServer = best['controller_host']
  if bestServer:
    url = 'http://%s/start-game?p=%s' % (bestServer, _PAIRING_KEY)
    game = fetchjson(url, 20)
    logging.debug('startGame(): %s -> %s' % (url, tojson(game)))
    if game.get('success', False):
      ip = bestServer.split(':')[0]
      game['gameURL'] = 'http://%s:%s/%s' % (ip, game['port'], game['name'])
      game['controller_host'] = bestServer
      game['serverid'] = best['serverid']
      _match_maker.update_game(game)
    return game
  else:
    return {'result': 'no-available-servers'}

def addPlayers(player_game, userID, displayName):
  logging.info('addPlayers(player_game=%s, userID=%s, displayName=%s)' % (player_game, userID, displayName))
  game = player_game['game']
  url = 'http://%s/add-players?p=%s' % (game['controller_host'], _PAIRING_KEY)
  player_game_key = player_game['player_game_key']
  msg = {
    'userID': userID,
    'displayName': displayName,
    'game_name' : game['name'],
    'player_game_key': player_game_key,
  }
  try:
    result = fetchjson(url, 20, payload=tojson(msg))
    logging.info('addPlayers(): %s -> %s -> %s' % (tojson(msg), url, tojson(result)))
    return {
      'game': game,
      'player_game_key': player_game_key,
      'success': True,
    }
  except:
    exc = traceback.format_exc()
    logging.info('addPlayers(): %s -> %s -> %s' % (tojson(msg), url, exc))
    return {
      'success' : False,
      'exception': exc,
    }

#######################################################################

# handler common to frontends and backends
handlers = [
]

if not backends.get_backend():
  # frontend specific handlers
  handlers.extend([
    ('/login', Login),
    ('/loginoauth', LoginHandler),
    ('/grits/(.*)', GritsService),
    ('/(shared/.*\.json)', SharedJsonAssets),
  ])
elif backends.get_backend() == 'matcher':
  # 'matcher' backend specific handlers
  handlers.extend([
    ('/find-game/(.*)', FindGame),
    ('/update-game-state', UpdateGameState),
    ('/register-controller', RegisterController),
    ('/list-games', ListGames),
    ('/debug', Debug),
    ('/start-game', StartGame),
    ('/game-over', GameOver),
    ('/log-files', LogFiles),
  ])

app = webapp2.WSGIApplication(handlers, debug=True)
app.router.set_dispatcher(json_by_default_dispatcher)


text:
import logging
from datetime import datetime

from api.models import Launch, Article, Events
from django.core.cache import cache
import pytz
from pyfcm import FCMNotification

from bot.utils.util import get_fcm_topics_v2, get_fcm_all_topics_v3, \
    get_fcm_strict_topics_v3, get_fcm_not_strict_topics_v3, get_flutter_topics_v3
from spacelaunchnow import config

logger = logging.getLogger(__name__)

# TODO refactor to separate files/modules per version

class NotificationHandler:
    def __init__(self, debug=None):
        if debug is None:
            self.DEBUG = config.DEBUG
        else:
            self.DEBUG = debug

    def send_notification(self, launch, notification_type, notification):
        current_time = datetime.now(tz=pytz.utc)
        launch_time = launch.net
        diff = int((launch_time - current_time).total_seconds())
        cache_key = str(launch.id) + notification_type
        launch_cooldown = cache.get(cache_key)
        global_cooldown = cache.get(notification_type)
        if launch_cooldown or global_cooldown:
            logger.error("Notification cooldown window for %s - Launch: %s Global: %s" % (
            launch.id, launch_cooldown, global_cooldown))
            return
        logger.info('Creating %s notification for %s' % (notification_type, launch.name))
        cache.set(cache_key, "ID: %s Net: %s Type: %s" % (launch.id, launch.net, notification_type), 60)
        cache.set(notification_type, "ID: %s Net: %s Type: %s" % (launch.id, launch.net, notification_type), 60)
        if notification_type == 'netstampChanged':
            if launch.status.id == 1:
                contents = 'UPDATE: New launch attempt scheduled on %s at %s.' % (launch.net.strftime("%A, %B %d"),
                                                                                launch.net.strftime("%H:%M UTC"))
            elif launch.status.id == 2 or launch.status.id == 5 or launch.status.id == 8:
                contents = 'UPDATE: Launch has slipped, new launch date is unconfirmed.'
            else:
                logger.error("Invalid state for sending a notification - Launch: %s" % launch)
                return
        elif notification_type == 'tenMinutes':
            minutes = round(diff / 60)
            if minutes is 0:
                minutes = "less than one"
            if launch.status.id == 1:
                contents = 'Launch attempt from %s in %s minute(s).' % (launch.pad.location.name, minutes)
            else:
                logger.error("Invalid state for sending a notification - Launch: %s" % launch)
                return
        elif notification_type == 'oneMinute':
            if launch.status.id == 1:
                contents = 'Launch attempt from %s in less than one minute.' % launch.pad.location.name
            else:
                logger.error("Invalid state for sending a notification - Launch: %s" % launch)
                return
        elif notification_type == 'twentyFourHour':
            hours = round(diff / 60 / 60)
            if hours is 23:
                hours = 24
            if launch.status.id == 1:
                contents = 'Launch attempt from %s in %s hours.' % (launch.pad.location.name, hours)
            elif launch.status.id == 2 or launch.status.id == 5:
                contents = 'Might be launching from %s in %s hours.' % (launch.pad.location.name, hours)
            else:
                logger.error("Invalid state for sending a notification - Launch: %s" % launch)
                return
        elif notification_type == 'oneHour':
            if launch.status.id == 1:
                contents = 'Launch attempt from %s in one hour.' % launch.pad.location.name
            elif launch.status.id == 2 or launch.status.id == 5:
                contents = 'Might be launching from %s in one hour.' % launch.pad.location.name
            else:
                logger.error("Invalid state for sending a notification - Launch: %s" % launch)
                return
        elif notification_type == 'success':
            if launch.mission is not None \
                    and launch.mission.orbit is not None \
                    and launch.mission.orbit.name is not None:
                contents = 'Successful launch to %s by %s' % (launch.mission.orbit.name,
                                                              launch.launch_service_provider.name)
            else:
                contents = 'Successful launch by %s' % launch.launch_service_provider.name

        elif notification_type == 'failure':
            contents = 'A launch failure has occurred.'

        elif notification_type == 'partial_failure':
            contents = 'A partial launch failure has occurred.'

        elif notification_type == 'inFlight':

            if launch.mission is not None \
                    and launch.mission.orbit is not None \
                    and launch.mission.orbit.name is not None:
                if (launch.mission.orbit.id == 15):
                    contents = 'Liftoff! %s is in a %s flight!' % (
                    launch.rocket.configuration.name, launch.mission.orbit.name)
                else:
                    contents = 'Liftoff! %s is in flight to %s!' % (
                    launch.rocket.configuration.name, launch.mission.orbit.name)
            else:
                contents = 'Liftoff! %s is in flight!' % launch.rocket.configuration.name

        elif notification_type == 'webcastLive':

            if launch.mission is not None and launch.mission.name is not None:
                contents = '%s %s webcast is live!' % (launch.rocket.configuration.name, launch.mission.name)
            else:
                contents = '%s webcast is live!' % launch.rocket.configuration.name

        else:
            launch_time = launch.net
            contents = 'Launch attempt from %s on %s at %s.' % (launch.pad.location.name,
                                                                launch_time.strftime("%A, %B %d"),
                                                                launch_time.strftime("%H:%M UTC"))

        time_since_last_notification = None
        if notification.last_notification_sent is not None:
            time_since_last_notification = datetime.now(tz=pytz.utc) - notification.last_notification_sent
        if time_since_last_notification is not None and time_since_last_notification.total_seconds() < 30 and not self.DEBUG:
            logger.info('Cannot send notification - too soon since last notification!')
        else:
            logger.info('----------------------------------------------------------')
            logger.info('Sending notification - %s' % contents)
            notification.last_notification_sent = datetime.now(tz=pytz.utc)
            notification.save()
            push_service = FCMNotification(api_key=config.keys['FCM_KEY'])
            self.send_v2_notification(launch, notification_type, push_service, contents)
            self.send_v3_notification(launch, notification_type, push_service, contents)

            logger.info('----------------------------------------------------------')

    def send_v2_notification(self, launch, notification_type, push_service, contents):
        flutter_topics_v2 = get_fcm_topics_v2(launch,
                                              notification_type=notification_type,
                                              debug=self.DEBUG,
                                              flutter=True)
        topics_v2 = get_fcm_topics_v2(launch,
                                      notification_type=notification_type,
                                      debug=self.DEBUG)

        if len(launch.vid_urls.all()) > 0:
            webcast = True
        else:
            webcast = False
        image = ''
        if launch.image_url:
            image = launch.image_url.url
        elif launch.launch_service_provider.image_url:
            image = launch.launch_service_provider.image_url.url
        elif launch.launch_service_provider.legacy_image_url:
            image = launch.launch_service_provider.legacy_image_url

        data = {"notification_type": notification_type,
                "launch_id": launch.launch_library_id,
                "launch_uuid": str(launch.id),
                "launch_name": launch.name,
                "launch_image": image,
                "launch_net": launch.net.strftime("%B %d, %Y %H:%M:%S %Z"),
                "launch_location": launch.pad.location.name,
                "webcast": webcast
                }

        # Send notifications to SLN Android after 3.0.0
        # Catch any issue with sending notification.
        try:
            logger.info('Android v2 Notification')
            logger.info('Notification v2 Data - %s' % data)
            logger.info('Topic Data v2- %s' % topics_v2)
            android_result_v2 = push_service.notify_topic_subscribers(data_message=data,
                                                                      condition=topics_v2,
                                                                      time_to_live=86400, )
            logger.info(android_result_v2)
        except Exception as e:
            logger.error(e)

        try:
            logger.info('Flutter v2 Notification')
            logger.info('Notification v2 Data - %s' % data)
            logger.info('Flutter Topic v2- %s' % flutter_topics_v2)
            flutter_result = push_service.notify_topic_subscribers(data_message=data,
                                                                   condition=flutter_topics_v2,
                                                                   time_to_live=86400,
                                                                   message_title=launch.name,
                                                                   message_body=contents)
            logger.debug(flutter_result)
        except Exception as e:
            logger.error(e)

    def send_v3_notification(self, launch, notification_type, push_service, contents):
        if len(launch.vid_urls.all()) > 0:
            webcast = True
        else:
            webcast = False
        image = ''
        if launch.image_url:
            image = launch.image_url.url
        elif launch.launch_service_provider.image_url:
            image = launch.launch_service_provider.image_url.url
        elif launch.launch_service_provider.legacy_image_url:
            image = launch.launch_service_provider.legacy_image_url

        data = {"notification_type": notification_type,
                "launch_id": launch.launch_library_id,
                "launch_uuid": str(launch.id),
                "launch_name": launch.name,
                "launch_image": image,
                "launch_net": launch.net.strftime("%B %d, %Y %H:%M:%S %Z"),
                "launch_location": launch.pad.location.name,
                "webcast": webcast
                }
        all_topics = get_fcm_all_topics_v3(debug=self.DEBUG, notification_type=notification_type)
        strict_topics = get_fcm_strict_topics_v3(launch, debug=self.DEBUG, notification_type=notification_type)
        not_strict_topics = get_fcm_not_strict_topics_v3(launch, debug=self.DEBUG, notification_type=notification_type)
        self.send_notif_v3(push_service, data, all_topics)
        self.send_notif_v3(push_service, data, strict_topics)
        self.send_notif_v3(push_service, data, not_strict_topics)
        logger.info("Topics:\n\nALL: %s\nStrict: %s\nNot Strict: %s" % (all_topics, strict_topics, not_strict_topics))
        # Reusing topics from v2 - not doing strict topics
        flutter_topics_v3 = get_flutter_topics_v3(launch,
                                                  notification_type=notification_type,
                                                  debug=self.DEBUG,
                                                  flutter=True)
        self.send_notif_v3(push_service, data, flutter_topics_v3, message_title=launch.name, message_body=contents)

    def send_notif_v3(self, push_service, data, topics, message_title=None, message_body=None):
        # Send notifications to SLN Android > v3.7.0
        # Catch any issue with sending notification.
        try:
            logger.info('Notification v3 Data - %s' % data)
            logger.info('Topic Data v3- %s' % topics)
            results = push_service.notify_topic_subscribers(data_message=data,
                                                            condition=topics,
                                                            time_to_live=86400,
                                                            message_title=message_title,
                                                            message_body=message_body)
            logger.info(results)
        except Exception as e:
            logger.error(e)

    def send_custom_ios_v2(self, pending):
        data = self.get_json_data(pending)

        if not self.DEBUG:
            flutter_topics = "'flutter_production_v2' in topics && 'custom' in topics"
        else:
            flutter_topics = "'flutter_debug_v2' in topics && 'custom' in topics"

        push_service = FCMNotification(api_key=config.keys['FCM_KEY'])

        logger.info('----------------------------------------------------------')
        logger.info('Sending iOS Custom Flutter notification - %s' % pending.title)
        try:
            logger.info('Custom Notification Data - %s' % data)
            logger.info('Topics - %s' % flutter_topics)
            flutter_results = push_service.notify_topic_subscribers(data_message=data,
                                                                    condition=flutter_topics,
                                                                    time_to_live=86400,
                                                                    message_title=pending.title,
                                                                    message_body=pending.message
                                                                    )
            logger.info(flutter_results)
        except Exception as e:
            logger.error(e)

        logger.info('----------------------------------------------------------')

    def send_custom_ios_v3(self, pending):
        data = self.get_json_data(pending)

        if not self.DEBUG:
            flutter_topics = "'flutter_production_v3' in topics && 'custom' in topics"
        else:
            flutter_topics = "'flutter_debug_v3' in topics && 'custom' in topics"

        push_service = FCMNotification(api_key=config.keys['FCM_KEY'])

        logger.info('----------------------------------------------------------')
        logger.info('Sending iOS Custom Flutter notification - %s' % pending.title)
        try:
            logger.info('Custom Notification Data - %s' % data)
            logger.info('Topics - %s' % flutter_topics)
            flutter_results = push_service.notify_topic_subscribers(data_message=data,
                                                                    condition=flutter_topics,
                                                                    time_to_live=86400,
                                                                    message_title=pending.title,
                                                                    message_body=pending.message
                                                                    )
            logger.info(flutter_results)
        except Exception as e:
            logger.error(e)

        logger.info('----------------------------------------------------------')

    def send_custom_android_v2(self, pending):
        data = self.get_json_data(pending)

        if not self.DEBUG:
            topics = "'prod_v2' in topics && 'custom' in topics"
        else:
            topics = "'debug_v2' in topics && 'custom' in topics"

        push_service = FCMNotification(api_key=config.keys['FCM_KEY'])

        logger.info('----------------------------------------------------------')
        logger.info('Sending Android Custom notification - %s' % pending.title)
        try:
            logger.info('Custom Notification Data - %s' % data)
            logger.info('Topics - %s' % topics)
            android_result = push_service.notify_topic_subscribers(data_message=data,
                                                                   condition=topics,
                                                                   time_to_live=86400, )
            logger.info(android_result)
        except Exception as e:
            logger.error(e)

        logger.info('----------------------------------------------------------')

    def send_custom_android_v3(self, pending):
        data = self.get_json_data(pending)

        if not self.DEBUG:
            topics = "'prod_v3' in topics && 'custom' in topics"
        else:
            topics = "'debug_v3' in topics && 'custom' in topics"

        push_service = FCMNotification(api_key=config.keys['FCM_KEY'])

        logger.info('----------------------------------------------------------')
        logger.info('Sending Android Custom notification - %s' % pending.title)
        try:
            logger.info('Custom Notification Data - %s' % data)
            logger.info('Topics - %s' % topics)
            android_result = push_service.notify_topic_subscribers(data_message=data,
                                                                   condition=topics,
                                                                   time_to_live=86400, )
            logger.info(android_result)
        except Exception as e:
            logger.error(e)

        logger.info('----------------------------------------------------------')

    def get_json_data(self, pending):
        data = {"notification_type": "custom",
                "click_action": "FLUTTER_NOTIFICATION_CLICK",
                "title": pending.title,
                "message": pending.message}

        if pending.launch_id is not None:
            launch = Launch.objects.get(id=pending.launch_id)

            image = ''
            if launch.image_url:
                image = launch.image_url.url
            elif launch.launch_service_provider.image_url:
                image = launch.launch_service_provider.image_url.url
            elif launch.launch_service_provider.legacy_image_url:
                image = launch.launch_service_provider.legacy_image_url

            data.update({
                "launch": {
                    "launch_id": launch.launch_library_id,
                    "launch_uuid": str(launch.id),
                    "launch_name": launch.name,
                    "launch_image": image,
                    "launch_net": launch.net.strftime("%B %d, %Y %H:%M:%S %Z"),
                    "launch_location": launch.pad.location.name,
                    "webcast": launch.webcast_live
                }
            })

        if pending.news_id is not None:
            news = Article.objects.get(id=pending.news_id)

            data.update({
                "news": {
                    "id": news.id,
                    "news_site_long": news.news_site,
                    "title": news.title,
                    "url": news.link,
                    "featured_image": news.featured_image
                }
            })

        if pending.event_id is not None:
            event = Events.objects.get(id=pending.event_id)

            feature_image = None
            if event.feature_image and hasattr(event.feature_image, 'url'):
                feature_image = event.feature_image.url
            data.update({
                "event": {
                    "id": event.id,
                    "name": event.name,
                    "description": event.description,
                    "type": {
                        "id": event.type.id,
                        "name": event.type.name,
                    },
                    "date": event.date.strftime("%B %d, %Y %H:%M:%S %Z"),
                    "location": event.location,
                    "news_url": event.news_url,
                    "video_url": event.video_url,
                    "webcast_live": event.webcast_live,
                    "feature_image": feature_image,
                },
            })
        return data


text:
> **:open_file_folder: Parent directory for `Product` API documentation.**

## Status

Please see [MVP35: Product](https://github.com/commonality/archetypes/milestone/5) for Sprint/milestone details.

---

[Apache-2.0][license-url] © [Greg Swindle](https://githbub.com/commonality)

[license-url]: /LICENSE


text:
The sample specification provided here demonstrates how to bind your generated API
with some externally defined types for schemas.

This [swagger specification](./example-external-types.yaml) illustrates the following use cases:

1. refer to an external type imported from some external package, as its own definition
2. refer to an external type imported from some external package, as part of another type (object, slice, map or tuple)
3. refer to an external type imported from the default location of models (i.e. besides generated models)
4. embed external type to add the Validatable interface.
5. use hints in annotations to solve nullable/struct vs interface issues
6. use hints in annotations to skip the validation of external types

> NOTE: due to the addition of the "additionalItems" clause to illustrate tuples, the spec is not formally
> valid against the swagger 2.0 schema.

[Reference documentation](../../docs/use/models/schemas.md#external-types)


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using static Roslyn.Test.Utilities.SigningTestHelpers;
using Xunit;
using Microsoft.CodeAnalysis.CSharp.Symbols;

namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
    [CompilerTrait(CompilerFeature.PrivateProtected)]
    public class PrivateProtected : CSharpTestBase
    {
        private static readonly string s_keyPairFile = SigningTestHelpers.KeyPairFile;
        private static readonly string s_publicKeyFile = SigningTestHelpers.PublicKeyFile;
        private static readonly ImmutableArray<byte> s_publicKey = SigningTestHelpers.PublicKey;

        [ConditionalFact(typeof(DesktopOnly))]
        public void RejectIncompatibleModifiers()
        {
            string source =
@"public class Base
{
    private internal int Field1;
    internal private int Field2;
    private internal protected int Field3;
    internal protected private int Field4;
    private public protected int Field5;
    private readonly protected int Field6; // ok
}
";
            CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
                .VerifyDiagnostics(
                // (3,26): error CS0107: More than one protection modifier
                //     private internal int Field1;
                Diagnostic(ErrorCode.ERR_BadMemberProtection, "Field1").WithLocation(3, 26),
                // (4,26): error CS0107: More than one protection modifier
                //     internal private int Field2;
                Diagnostic(ErrorCode.ERR_BadMemberProtection, "Field2").WithLocation(4, 26),
                // (5,36): error CS0107: More than one protection modifier
                //     private internal protected int Field3;
                Diagnostic(ErrorCode.ERR_BadMemberProtection, "Field3").WithLocation(5, 36),
                // (6,36): error CS0107: More than one protection modifier
                //     internal protected private int Field4;
                Diagnostic(ErrorCode.ERR_BadMemberProtection, "Field4").WithLocation(6, 36),
                // (7,34): error CS0107: More than one protection modifier
                //     private public protected int Field5;
                Diagnostic(ErrorCode.ERR_BadMemberProtection, "Field5").WithLocation(7, 34)
                );
        }

        [ConditionalFact(typeof(DesktopOnly))]
        public void AccessibleWhereRequired_01()
        {
            string source =
@"public class Base
{
    private protected int Field1;
    protected private int Field2;
}

public class Derived : Base
{
    void M()
    {
        Field1 = 1;
        Field2 = 2;
    }
}
";
            var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
                .VerifyDiagnostics(
                );
        }

        [ConditionalFact(typeof(DesktopOnly))]
        public void AccessibleWhereRequired_02()
        {
            string source1 =
@"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""WantsIVTAccess"")]
public class Base
{
    private protected const int Constant = 3;
    private protected int Field1;
    protected private int Field2;
    private protected void Method() { }
    private protected event System.Action Event1;
    private protected int Property1 { set {} }
    public int Property2 { private protected set {} get { return 4; } }
    private protected int this[int x] { set { } get { return 6; } }
    public int this[string x] { private protected set { } get { return 5; } }
    private protected Base() { Event1?.Invoke(); }
}";
            var baseCompilation = CreateCompilation(source1, parseOptions: TestOptions.Regular7_2,
                options: TestOptions.SigningReleaseDll,
                assemblyName: "Paul");
            var bb = (NamedTypeSymbol)baseCompilation.GlobalNamespace.GetMember("Base");
            foreach (var member in bb.GetMembers())
            {
                switch (member.Name)
                {
                    case "Property2":
                    case "get_Property2":
                    case "this[]":
                    case "get_Item":
                        break;
                    default:
                        Assert.Equal(Accessibility.ProtectedAndInternal, member.DeclaredAccessibility);
                        break;
                }
            }

            string source2 =
@"public class Derived : Base
{
    void M()
    {
        Field1 = Constant;
        Field2 = Constant;
        Method();
        Event1 += null;
        Property1 = Constant;
        Property2 = Constant;
        this[1] = 2;
        this[string.Empty] = 4;
    }
    Derived(int x) : base() {}
    Derived(long x) {} // implicit base()
}
";
            CreateCompilation(source2, parseOptions: TestOptions.Regular7_2,
                references: new[] { new CSharpCompilationReference(baseCompilation) },
                assemblyName: "WantsIVTAccessButCantHave",
                options: TestOptions.SigningReleaseDll)
            .VerifyDiagnostics(
                // (5,9): error CS0122: 'Base.Field1' is inaccessible due to its protection level
                //         Field1 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Field1").WithArguments("Base.Field1").WithLocation(5, 9),
                // (5,18): error CS0122: 'Base.Constant' is inaccessible due to its protection level
                //         Field1 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(5, 18),
                // (6,9): error CS0122: 'Base.Field2' is inaccessible due to its protection level
                //         Field2 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Field2").WithArguments("Base.Field2").WithLocation(6, 9),
                // (6,18): error CS0122: 'Base.Constant' is inaccessible due to its protection level
                //         Field2 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(6, 18),
                // (7,9): error CS0122: 'Base.Method()' is inaccessible due to its protection level
                //         Method();
                Diagnostic(ErrorCode.ERR_BadAccess, "Method").WithArguments("Base.Method()").WithLocation(7, 9),
                // (8,9): error CS0122: 'Base.Event1' is inaccessible due to its protection level
                //         Event1 += null;
                Diagnostic(ErrorCode.ERR_BadAccess, "Event1").WithArguments("Base.Event1").WithLocation(8, 9),
                // (8,9): error CS0122: 'Base.Event1.add' is inaccessible due to its protection level
                //         Event1 += null;
                Diagnostic(ErrorCode.ERR_BadAccess, "Event1 += null").WithArguments("Base.Event1.add").WithLocation(8, 9),
                // (9,9): error CS0122: 'Base.Property1' is inaccessible due to its protection level
                //         Property1 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Property1").WithArguments("Base.Property1").WithLocation(9, 9),
                // (9,21): error CS0122: 'Base.Constant' is inaccessible due to its protection level
                //         Property1 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(9, 21),
                // (10,9): error CS0272: The property or indexer 'Base.Property2' cannot be used in this context because the set accessor is inaccessible
                //         Property2 = Constant;
                Diagnostic(ErrorCode.ERR_InaccessibleSetter, "Property2").WithArguments("Base.Property2").WithLocation(10, 9),
                // (10,21): error CS0122: 'Base.Constant' is inaccessible due to its protection level
                //         Property2 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(10, 21),
                // (11,14): error CS1503: Argument 1: cannot convert from 'int' to 'string'
                //         this[1] = 2;
                Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "string").WithLocation(11, 14),
                // (12,9): error CS0272: The property or indexer 'Base.this[string]' cannot be used in this context because the set accessor is inaccessible
                //         this[string.Empty] = 4;
                Diagnostic(ErrorCode.ERR_InaccessibleSetter, "this[string.Empty]").WithArguments("Base.this[string]").WithLocation(12, 9),
                // (14,22): error CS0122: 'Base.Base()' is inaccessible due to its protection level
                //     Derived(int x) : base() {}
                Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("Base.Base()").WithLocation(14, 22),
                // (15,5): error CS0122: 'Base.Base()' is inaccessible due to its protection level
                //     Derived(long x) {} // implicit base()
                Diagnostic(ErrorCode.ERR_BadAccess, "Derived").WithArguments("Base.Base()").WithLocation(15, 5)
                );
            CreateCompilation(source2, parseOptions: TestOptions.Regular7_2,
                references: new[] { MetadataReference.CreateFromImage(baseCompilation.EmitToArray()) },
                assemblyName: "WantsIVTAccessButCantHave",
                options: TestOptions.SigningReleaseDll)
            .VerifyDiagnostics(
                // (5,9): error CS0122: 'Base.Field1' is inaccessible due to its protection level
                //         Field1 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Field1").WithArguments("Base.Field1").WithLocation(5, 9),
                // (5,18): error CS0122: 'Base.Constant' is inaccessible due to its protection level
                //         Field1 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(5, 18),
                // (6,9): error CS0122: 'Base.Field2' is inaccessible due to its protection level
                //         Field2 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Field2").WithArguments("Base.Field2").WithLocation(6, 9),
                // (6,18): error CS0122: 'Base.Constant' is inaccessible due to its protection level
                //         Field2 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(6, 18),
                // (7,9): error CS0122: 'Base.Method()' is inaccessible due to its protection level
                //         Method();
                Diagnostic(ErrorCode.ERR_BadAccess, "Method").WithArguments("Base.Method()").WithLocation(7, 9),
                // (8,9): error CS0122: 'Base.Event1' is inaccessible due to its protection level
                //         Event1 += null;
                Diagnostic(ErrorCode.ERR_BadAccess, "Event1").WithArguments("Base.Event1").WithLocation(8, 9),
                // (8,9): error CS0122: 'Base.Event1.add' is inaccessible due to its protection level
                //         Event1 += null;
                Diagnostic(ErrorCode.ERR_BadAccess, "Event1 += null").WithArguments("Base.Event1.add").WithLocation(8, 9),
                // (9,9): error CS0122: 'Base.Property1' is inaccessible due to its protection level
                //         Property1 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Property1").WithArguments("Base.Property1").WithLocation(9, 9),
                // (9,21): error CS0122: 'Base.Constant' is inaccessible due to its protection level
                //         Property1 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(9, 21),
                // (10,9): error CS0272: The property or indexer 'Base.Property2' cannot be used in this context because the set accessor is inaccessible
                //         Property2 = Constant;
                Diagnostic(ErrorCode.ERR_InaccessibleSetter, "Property2").WithArguments("Base.Property2").WithLocation(10, 9),
                // (10,21): error CS0122: 'Base.Constant' is inaccessible due to its protection level
                //         Property2 = Constant;
                Diagnostic(ErrorCode.ERR_BadAccess, "Constant").WithArguments("Base.Constant").WithLocation(10, 21),
                // (11,14): error CS1503: Argument 1: cannot convert from 'int' to 'string'
                //         this[1] = 2;
                Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "string").WithLocation(11, 14),
                // (12,9): error CS0272: The property or indexer 'Base.this[string]' cannot be used in this context because the set accessor is inaccessible
                //         this[string.Empty] = 4;
                Diagnostic(ErrorCode.ERR_InaccessibleSetter, "this[string.Empty]").WithArguments("Base.this[string]").WithLocation(12, 9),
                // (14,22): error CS0122: 'Base.Base()' is inaccessible due to its protection level
                //     Derived(int x) : base() {}
                Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("Base.Base()").WithLocation(14, 22),
                // (15,5): error CS0122: 'Base.Base()' is inaccessible due to its protection level
                //     Derived(long x) {} // implicit base()
                Diagnostic(ErrorCode.ERR_BadAccess, "Derived").WithArguments("Base.Base()").WithLocation(15, 5)
                );

            CreateCompilation(source2, parseOptions: TestOptions.Regular7_2,
                references: new[] { new CSharpCompilationReference(baseCompilation) },
                assemblyName: "WantsIVTAccess",
                options: TestOptions.SigningReleaseDll)
                .VerifyDiagnostics(
                );
            CreateCompilation(source2, parseOptions: TestOptions.Regular7_2,
                references: new[] { MetadataReference.CreateFromImage(baseCompilation.EmitToArray()) },
                assemblyName: "WantsIVTAccess",
                options: TestOptions.SigningReleaseDll)
                .VerifyDiagnostics(
                );
        }

        [ConditionalFact(typeof(DesktopOnly))]
        public void NotAccessibleWhereRequired()
        {
            string source =
@"public class Base
{
    private protected int Field1;
    protected private int Field2;
}

public class Derived // : Base
{
    void M()
    {
        Base b = null;
        b.Field1 = 1;
        b.Field2 = 2;
    }
}
";
            CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
                .VerifyDiagnostics(
                // (12,11): error CS0122: 'Base.Field1' is inaccessible due to its protection level
                //         b.Field1 = 1;
                Diagnostic(ErrorCode.ERR_BadAccess, "Field1").WithArguments("Base.Field1").WithLocation(12, 11),
                // (13,11): error CS0122: 'Base.Field2' is inaccessible due to its protection level
                //         b.Field2 = 2;
                Diagnostic(ErrorCode.ERR_BadAccess, "Field2").WithArguments("Base.Field2").WithLocation(13, 11)
                );
        }

        [ConditionalFact(typeof(DesktopOnly))]
        public void NotInStructOrNamespace()
        {
            string source =
@"protected private struct Struct
{
    private protected int Field1;
}
";
            CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
                .VerifyDiagnostics(
                // (1,18): error CS1527: Elements defined in a namespace cannot be explicitly declared as private, protected, protected internal, or private protected
                // protected private struct Struct
                Diagnostic(ErrorCode.ERR_NoNamespacePrivate, "Struct").WithLocation(1, 26),
                // (3,27): error CS0666: 'Struct.Field1': new protected member declared in struct
                //     private protected int Field1;
                Diagnostic(ErrorCode.ERR_ProtectedInStruct, "Field1").WithArguments("Struct.Field1").WithLocation(3, 27)
                );
        }

        [ConditionalFact(typeof(DesktopOnly))]
        public void NotInStaticClass()
        {
            string source =
@"static class C
{
    static private protected int Field1 = 2;
}
sealed class D
{
    static private protected int Field2 = 2;
}
";
            CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
                .VerifyDiagnostics(
                // (7,34): warning CS0628: 'D.Field2': new protected member declared in sealed type
                //     static private protected int Field2 = 2;
                Diagnostic(ErrorCode.WRN_ProtectedInSealed, "Field2").WithArguments("D.Field2").WithLocation(7, 34),
                // (3,34): error CS1057: 'C.Field1': static classes cannot contain protected members
                //     static private protected int Field1 = 2;
                Diagnostic(ErrorCode.ERR_ProtectedInStatic, "Field1").WithArguments("C.Field1").WithLocation(3, 34)
                );
        }

        [ConditionalFact(typeof(DesktopOnly))]
        public void NestedTypes()
        {
            string source =
@"class Outer
{
    private protected class Inner
    {
    }
}
class Derived : Outer
{
    public void M()
    {
        Outer.Inner x = null;
    }
}
class NotDerived
{
    public void M()
    {
        Outer.Inner x = null; // error: Outer.Inner not accessible
    }
}
struct Struct
{
    private protected class Inner // error: protected not allowed in struct
    {
    }
}
";
            CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
                .VerifyDiagnostics(
                // (23,29): error CS0666: 'Struct.Inner': new protected member declared in struct
                //     private protected class Inner // error: protected not allowed in struct
                Diagnostic(ErrorCode.ERR_ProtectedInStruct, "Inner").WithArguments("Struct.Inner").WithLocation(23, 29),
                // (11,21): warning CS0219: The variable 'x' is assigned but its value is never used
                //         Outer.Inner x = null;
                Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(11, 21),
                // (18,15): error CS0122: 'Outer.Inner' is inaccessible due to its protection level
                //         Outer.Inner x = null; // error: Outer.Inner not accessible
                Diagnostic(ErrorCode.ERR_BadAccess, "Inner").WithArguments("Outer.Inner").WithLocation(18, 15)
                );
        }

        [ConditionalFact(typeof(DesktopOnly))]
        public void PermittedAccessorProtection()
        {
            string source =
@"class Class
{
    public int Prop1 { get; private protected set; }
    protected internal int Prop2 { get; private protected set; }
    protected int Prop3 { get; private protected set; }
    internal int Prop4 { get; private protected set; }
    private protected int Prop5 { get; private set; }
}";
            CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
                .VerifyDiagnostics(
                );
        }

        [ConditionalFact(typeof(DesktopOnly))]
        public void ForbiddenAccessorProtection_01()
        {
            string source =
@"class Class
{
    private protected int Prop1 { get; private protected set; }
    private int Prop2 { get; private protected set; }
}";
            CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
                .VerifyDiagnostics(
                // (3,58): error CS0273: The accessibility modifier of the 'Class.Prop1.set' accessor must be more restrictive than the property or indexer 'Class.Prop1'
                //     private protected int Prop1 { get; private protected set; }
                Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("Class.Prop1.set", "Class.Prop1").WithLocation(3, 58),
                // (4,48): error CS0273: The accessibility modifier of the 'Class.Prop2.set' accessor must be more restrictive than the property or indexer 'Class.Prop2'
                //     private int Prop2 { get; private protected set; }
                Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("Class.Prop2.set", "Class.Prop2").WithLocation(4, 48)
                );
        }

        [ConditionalFact(typeof(DesktopOnly))]
        public void ForbiddenAccessorProtection_02()
        {
            string source =
@"interface ISomething
{
    private protected int M();
}";
            CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
                .VerifyDiagnostics(
                // (3,27): error CS8503: The modifier 'private protected' is not valid for this item in C# 7.2. Please use language version '8.0' or greater.
                //     private protected int M();
                Diagnostic(ErrorCode.ERR_DefaultInterfaceImplementationModifier, "M").WithArguments("private protected", "7.2", "8.0").WithLocation(3, 27),
                // (3,27): error CS8707: Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface.
                //     private protected int M();
                Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, "M").WithLocation(3, 27)
                );
        }

        [ConditionalFact(typeof(DesktopOnly))]
        public void AtLeastAsRestrictivePositive_01()
        {
            string source =
@"
public class C
{
    internal class Internal {}
    protected class Protected {}
    private protected class PrivateProtected {}
    private protected void M(Internal x) {} // ok
    private protected void M(Protected x) {} // ok
    private protected void M(PrivateProtected x) {} // ok
    private protected class Nested
    {
        public void M(Internal x) {} // ok
        public void M(Protected x) {} // ok
        private protected void M(PrivateProtected x) {} // ok
    }
}
";
            CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
                .VerifyDiagnostics(
                );
        }

        [ConditionalFact(typeof(DesktopOnly))]
        public void AtLeastAsRestrictiveNegative_01()
        {
            string source =
@"
public class Container
{
    private protected class PrivateProtected {}
    internal void M1(PrivateProtected x) {} // error: conflicting access
    protected void M2(PrivateProtected x) {} // error: conflicting access
}
";
            CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
                .VerifyDiagnostics(
                // (6,20): error CS0051: Inconsistent accessibility: parameter type 'Container.PrivateProtected' is less accessible than method 'Container.M2(Container.PrivateProtected)'
                //     protected void M2(PrivateProtected x) {} // error: conflicting access
                Diagnostic(ErrorCode.ERR_BadVisParamType, "M2").WithArguments("Container.M2(Container.PrivateProtected)", "Container.PrivateProtected").WithLocation(6, 20),
                // (5,19): error CS0051: Inconsistent accessibility: parameter type 'Container.PrivateProtected' is less accessible than method 'Container.M1(Container.PrivateProtected)'
                //     internal void M1(PrivateProtected x) {} // error: conflicting access
                Diagnostic(ErrorCode.ERR_BadVisParamType, "M1").WithArguments("Container.M1(Container.PrivateProtected)", "Container.PrivateProtected").WithLocation(5, 19)
                );
        }

        [ConditionalFact(typeof(DesktopOnly))]
        public void DuplicateAccessInBinder()
        {
            string source =
@"
public class Container
{
    private public int Field;                           // 1
    private public int Property { get; set; }           // 2
    private public int M() => 1;                        // 3
    private public class C {}                           // 4
    private public struct S {}                          // 5
    private public enum E {}                            // 6
    private public event System.Action V;               // 7
    private public interface I {}                       // 8
    private public int this[int index] => 1;            // 9
    void Q() { V.Invoke(); V = null; }
}
";
            CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
                .VerifyDiagnostics(
                // (7,26): error CS0107: More than one protection modifier
                //     private public class C {}                           // 4
                Diagnostic(ErrorCode.ERR_BadMemberProtection, "C").WithLocation(7, 26),
                // (8,27): error CS0107: More than one protection modifier
                //     private public struct S {}                          // 5
                Diagnostic(ErrorCode.ERR_BadMemberProtection, "S").WithLocation(8, 27),
                // (9,25): error CS0107: More than one protection modifier
                //     private public enum E {}                            // 6
                Diagnostic(ErrorCode.ERR_BadMemberProtection, "E").WithLocation(9, 25),
                // (11,30): error CS0107: More than one protection modifier
                //     private public interface I {}                       // 8
                Diagnostic(ErrorCode.ERR_BadMemberProtection, "I").WithLocation(11, 30),
                // (4,24): error CS0107: More than one protection modifier
                //     private public int Field;                           // 1
                Diagnostic(ErrorCode.ERR_BadMemberProtection, "Field").WithLocation(4, 24),
                // (5,24): error CS0107: More than one protection modifier
                //     private public int Property { get; set; }           // 2
                Diagnostic(ErrorCode.ERR_BadMemberProtection, "Property").WithLocation(5, 24),
                // (6,24): error CS0107: More than one protection modifier
                //     private public int M() => 1;                        // 3
                Diagnostic(ErrorCode.ERR_BadMemberProtection, "M").WithLocation(6, 24),
                // (10,40): error CS0107: More than one protection modifier
                //     private public event System.Action V;               // 7
                Diagnostic(ErrorCode.ERR_BadMemberProtection, "V").WithLocation(10, 40),
                // (12,24): error CS0107: More than one protection modifier
                //     private public int this[int index] => 1;            // 9
                Diagnostic(ErrorCode.ERR_BadMemberProtection, "this").WithLocation(12, 24),
                // (12,43): error CS0107: More than one protection modifier
                //     private public int this[int index] => 1;            // 9
                Diagnostic(ErrorCode.ERR_BadMemberProtection, "1").WithLocation(12, 43)
                );
        }

        [ConditionalFact(typeof(DesktopOnly))]
        public void NotInVersion71()
        {
            string source =
@"
public class Container
{
    private protected int Field;                           // 1
    private protected int Property { get; set; }           // 2
    private protected int M() => 1;                        // 3
    private protected class C {}                           // 4
    private protected struct S {}                          // 5
    private protected enum E {}                            // 6
    private protected event System.Action V;               // 7
    private protected interface I {}                       // 8
    private protected int this[int index] => 1;            // 9
    void Q() { V.Invoke(); V = null; }
}
";
            CreateCompilation(source, parseOptions: TestOptions.Regular7_1)
                .VerifyDiagnostics(
                // (7,29): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
                //     private protected class C {}                           // 4
                Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "C").WithArguments("private protected", "7.2").WithLocation(7, 29),
                // (8,30): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
                //     private protected struct S {}                          // 5
                Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "S").WithArguments("private protected", "7.2").WithLocation(8, 30),
                // (9,28): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
                //     private protected enum E {}                            // 6
                Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "E").WithArguments("private protected", "7.2").WithLocation(9, 28),
                // (11,33): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
                //     private protected interface I {}                       // 8
                Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "I").WithArguments("private protected", "7.2").WithLocation(11, 33),
                // (4,27): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
                //     private protected int Field;                           // 1
                Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "Field").WithArguments("private protected", "7.2").WithLocation(4, 27),
                // (5,27): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
                //     private protected int Property { get; set; }           // 2
                Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "Property").WithArguments("private protected", "7.2").WithLocation(5, 27),
                // (6,27): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
                //     private protected int M() => 1;                        // 3
                Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "M").WithArguments("private protected", "7.2").WithLocation(6, 27),
                // (10,43): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
                //     private protected event System.Action V;               // 7
                Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "V").WithArguments("private protected", "7.2").WithLocation(10, 43),
                // (12,27): error CS8302: Feature 'private protected' is not available in C# 7.1. Please use language version 7.2 or greater.
                //     private protected int this[int index] => 1;            // 9
                Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_1, "this").WithArguments("private protected", "7.2").WithLocation(12, 27)
                );
            CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
                .VerifyDiagnostics(
                );
        }

        [ConditionalFact(typeof(DesktopOnly))]
        public void VerifyPrivateProtectedIL()
        {
            var text = @"
class Program
{
    private protected void M() {}
    private protected int F;
}
";
            var verifier = CompileAndVerify(
                text,
                parseOptions: TestOptions.Regular7_2,
                expectedSignatures: new[]
                {
                    Signature("Program", "M", ".method famandassem hidebysig instance System.Void M() cil managed"),
                    Signature("Program", "F", ".field famandassem instance System.Int32 F"),
                });
        }

        [ConditionalFact(typeof(DesktopOnly))]
        public void VerifyPartialPartsMatch()
        {
            var source =
@"class Outer
{
    private protected partial class Inner {}
    private           partial class Inner {}
}";
            CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
                .VerifyDiagnostics(
                // (3,37): error CS0262: Partial declarations of 'Outer.Inner' have conflicting accessibility modifiers
                //     private protected partial class Inner {}
                Diagnostic(ErrorCode.ERR_PartialModifierConflict, "Inner").WithArguments("Outer.Inner").WithLocation(3, 37)
                );
            source =
@"class Outer
{
    private protected partial class Inner {}
    private protected partial class Inner {}
}";
            CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
                .VerifyDiagnostics(
                );
        }

        [ConditionalFact(typeof(DesktopOnly))]
        public void VerifyProtectedSemantics()
        {
            var source =
@"class Base
{
    private protected void M()
    {
        System.Console.WriteLine(this.GetType().Name);
    }
}

class Derived : Base
{
    public void Main()
    {
        Derived derived = new Derived();
        derived.M();
        Base bb = new Base();
        bb.M(); // error 1
        Other other = new Other();
        other.M(); // error 2
    }
}

class Other : Base
{
}";
            CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
                .VerifyDiagnostics(
                // (16,12): error CS1540: Cannot access protected member 'Base.M()' via a qualifier of type 'Base'; the qualifier must be of type 'Derived' (or derived from it)
                //         bb.M(); // error 1
                Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M").WithArguments("Base.M()", "Base", "Derived").WithLocation(16, 12),
                // (18,15): error CS1540: Cannot access protected member 'Base.M()' via a qualifier of type 'Other'; the qualifier must be of type 'Derived' (or derived from it)
                //         other.M(); // error 2
                Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M").WithArguments("Base.M()", "Other", "Derived").WithLocation(18, 15)
                );
        }

        [ConditionalFact(typeof(DesktopOnly))]
        public void HidingAbstract()
        {
            var source =
@"abstract class A
{
    internal abstract void F();
}
abstract class B : A
{
    private protected new void F() { } // No CS0533
}";
            CreateCompilation(source, parseOptions: TestOptions.Regular7_2)
                .VerifyDiagnostics(
                );
        }

        [ConditionalFact(typeof(DesktopOnly))]
        public void HidingInaccessible()
        {
            string source1 =
@"public class A
{
    private protected void F() { }
}
";
            var compilation1 = CreateCompilation(source1, parseOptions: TestOptions.Regular7_2);
            compilation1.VerifyDiagnostics();

            string source2 =
@"class B : A
{
    new void F() { } // CS0109
}
";
            CreateCompilation(source2, parseOptions: TestOptions.Regular7_2,
                references: new[] { new CSharpCompilationReference(compilation1) })
            .VerifyDiagnostics(
                // (3,14): warning CS0109: The member 'B.F()' does not hide an accessible member. The new keyword is not required.
                //     new void F() { } // CS0109
                Diagnostic(ErrorCode.WRN_NewNotRequired, "F").WithArguments("B.F()").WithLocation(3, 14)
                );
        }

        [ConditionalFact(typeof(DesktopOnly))]
        public void UnimplementedInaccessible()
        {
            string source1 =
@"public abstract class A
{
    private protected abstract void F();
}
";
            var compilation1 = CreateCompilation(source1, parseOptions: TestOptions.Regular7_2);
            compilation1.VerifyDiagnostics();

            string source2 =
@"class B : A // CS0534
{
}
";
            CreateCompilation(source2, parseOptions: TestOptions.Regular7_2,
                references: new[] { new CSharpCompilationReference(compilation1) })
            .VerifyDiagnostics(
                // (1,7): error CS0534: 'B' does not implement inherited abstract member 'A.F()'
                // class B : A // CS0534
                Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.F()").WithLocation(1, 7)
                );
        }

        [ConditionalFact(typeof(DesktopOnly))]
        public void ImplementInaccessible()
        {
            string source1 =
@"public abstract class A
{
    private protected abstract void F();
}
";
            var compilation1 = CreateCompilation(source1, parseOptions: TestOptions.Regular7_2);
            compilation1.VerifyDiagnostics();

            string source2 =
@"class B : A // CS0534
{
    override private protected void F() {}
}
";
            CreateCompilation(source2, parseOptions: TestOptions.Regular7_2,
                references: new[] { new CSharpCompilationReference(compilation1) })
            .VerifyDiagnostics(
                // (3,37): error CS0115: 'B.F()': no suitable method found to override
                //     override private protected void F() {}
                Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F").WithArguments("B.F()").WithLocation(3, 37),
                // (1,7): error CS0534: 'B' does not implement inherited abstract member 'A.F()'
                // class B : A // CS0534
                Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.F()").WithLocation(1, 7)
                );
        }

        [ConditionalFact(typeof(DesktopOnly))]
        public void VerifyPPExtension()
        {
            string source = @"
static class Extensions
{
    static private protected void SomeExtension(this string s) { } // error: no pp in static class
}

class Client
{
    public static void M(string s)
    {
        s.SomeExtension(); // error: no accessible SomeExtension
    }
}
";
            CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Regular7_2)
            .VerifyDiagnostics(
                // (4,35): error CS1057: 'Extensions.SomeExtension(string)': static classes cannot contain protected members
                //     static private protected void SomeExtension(this string s) { } // error: no pp in static class
                Diagnostic(ErrorCode.ERR_ProtectedInStatic, "SomeExtension").WithArguments("Extensions.SomeExtension(string)").WithLocation(4, 35),
                // (11,11): error CS1061: 'string' does not contain a definition for 'SomeExtension' and no accessible extension method 'SomeExtension' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
                //         s.SomeExtension(); // error: no accessible SomeExtension
                Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "SomeExtension").WithArguments("string", "SomeExtension").WithLocation(11, 11)
                );
        }
    }
}


text:
#ifndef SkPathWriter_DEFINED
#define SkPathWriter_DEFINED

#include "SkPath.h"
#include "SkTArray.h"
#include "SkTDArray.h"

class SkOpPtT;

// Construct the path one contour at a time.
// If the contour is closed, copy it to the final output.
// Otherwise, keep the partial contour for later assembly.

class SkPathWriter {
public:
    SkPathWriter(SkPath& path);
    void assemble();
    void conicTo(const SkPoint& pt1, const SkOpPtT* pt2, SkScalar weight);
    void cubicTo(const SkPoint& pt1, const SkPoint& pt2, const SkOpPtT* pt3);
    bool deferredLine(const SkOpPtT* pt);
    void deferredMove(const SkOpPtT* pt);
    void finishContour();
    bool hasMove() const { return !fFirstPtT; }
    void init();
    bool isClosed() const;
    const SkPath* nativePath() const { return fPathPtr; }
    void quadTo(const SkPoint& pt1, const SkOpPtT* pt2);

private:
    bool changedSlopes(const SkOpPtT* pt) const;
    void close();
    const SkTDArray<const SkOpPtT*>& endPtTs() const { return fEndPtTs; }
    void lineTo();
    bool matchedLast(const SkOpPtT*) const;
    void moveTo();
    const SkTArray<SkPath>& partials() const { return fPartials; }
    bool someAssemblyRequired();
    SkPoint update(const SkOpPtT* pt);

    SkPath fCurrent;  // contour under construction
    SkTArray<SkPath> fPartials;   // contours with mismatched starts and ends
    SkTDArray<const SkOpPtT*> fEndPtTs;  // possible pt values for partial starts and ends
    SkPath* fPathPtr;  // closed contours are written here
    const SkOpPtT* fDefer[2];  // [0] deferred move, [1] deferred line
    const SkOpPtT* fFirstPtT;  // first in current contour
};

#endif /* defined(__PathOps__SkPathWriter__) */


text:
using System.Runtime.Serialization;

namespace PromisesBaseFrameworkTest.TestPromiseSqlAction
{
    [DataContract]
    public class FRCTEntity
    {
        [DataMember(Name = "transactionCodeId")]
        public int TransactionCodeId { get; set; }

        [DataMember(Name = "siteId")]
        public int SiteId { get; set; }

        [DataMember(Name = "transactionCode")]
        public string TransactionCode { get; set; }

        [DataMember(Name = "description")]
        public string Description { get; set; }

        [DataMember(Name = "amount")]
        public decimal Amount { get; set; }

        [DataMember(Name = "glAccount")]
        public int GlAccount { get; set; }

        [DataMember(Name = "freq")]
        public int Freq { get; set; }

        [DataMember(Name = "avgAmount")]
        public decimal AvgAmount { get; set; }

        [DataMember(Name = "maxAmount")]
        public decimal MaxAmount { get; set; }

    }
}