text:
import os
import sys

import eventlet
eventlet.monkey_patch()

from oslo.config import cfg

from neutron.agent.common import config
from neutron.agent.linux import dhcp
from neutron.agent.linux import external_process
from neutron.agent.linux import interface
from neutron.agent.linux import ovs_lib  # noqa
from neutron.agent import rpc as agent_rpc
from neutron.common import config as common_config
from neutron.common import constants
from neutron.common import exceptions
from neutron.common import rpc as n_rpc
from neutron.common import topics
from neutron.common import utils
from neutron import context
from neutron import manager
from neutron.openstack.common import importutils
from neutron.openstack.common import log as logging
from neutron.openstack.common import loopingcall
from neutron.openstack.common import service
from neutron import service as neutron_service

LOG = logging.getLogger(__name__)

class DhcpAgent(manager.Manager):
    OPTS = [
        cfg.IntOpt('resync_interval', default=5,
                   help=_("Interval to resync.")),
        cfg.StrOpt('dhcp_driver',
                   default='neutron.agent.linux.dhcp.Dnsmasq',
                   help=_("The driver used to manage the DHCP server.")),
        cfg.BoolOpt('enable_isolated_metadata', default=False,
                    help=_("Support Metadata requests on isolated networks.")),
        cfg.BoolOpt('enable_metadata_network', default=False,
                    help=_("Allows for serving metadata requests from a "
                           "dedicated network. Requires "
                           "enable_isolated_metadata = True")),
        cfg.IntOpt('num_sync_threads', default=4,
                   help=_('Number of threads to use during sync process.')),
        cfg.StrOpt('metadata_proxy_socket',
                   default='$state_path/metadata_proxy',
                   help=_('Location of Metadata Proxy UNIX domain '
                          'socket')),
    ]

    def __init__(self, host=None):
        super(DhcpAgent, self).__init__(host=host)
        self.needs_resync_reasons = []
        self.conf = cfg.CONF
        self.cache = NetworkCache()
        self.root_helper = config.get_root_helper(self.conf)
        self.dhcp_driver_cls = importutils.import_class(self.conf.dhcp_driver)
        ctx = context.get_admin_context_without_session()
        self.plugin_rpc = DhcpPluginApi(topics.PLUGIN,
                                        ctx, self.conf.use_namespaces)
        # create dhcp dir to store dhcp info
        dhcp_dir = os.path.dirname("/%s/dhcp/" % self.conf.state_path)
        if not os.path.isdir(dhcp_dir):
            os.makedirs(dhcp_dir, 0o755)
        self.dhcp_version = self.dhcp_driver_cls.check_version()
        self._populate_networks_cache()

    def _populate_networks_cache(self):
        """Populate the networks cache when the DHCP-agent starts."""
        try:
            existing_networks = self.dhcp_driver_cls.existing_dhcp_networks(
                self.conf,
                self.root_helper
            )
            for net_id in existing_networks:
                net = dhcp.NetModel(self.conf.use_namespaces,
                                    {"id": net_id,
                                     "subnets": [],
                                     "ports": []})
                self.cache.put(net)
        except NotImplementedError:
            # just go ahead with an empty networks cache
            LOG.debug(
                _("The '%s' DHCP-driver does not support retrieving of a "
                  "list of existing networks"),
                self.conf.dhcp_driver
            )

    def after_start(self):
        self.run()
        LOG.info(_("DHCP agent started"))

    def run(self):
        """Activate the DHCP agent."""
        self.sync_state()
        self.periodic_resync()

    def call_driver(self, action, network, **action_kwargs):
        """Invoke an action on a DHCP driver instance."""
        LOG.debug(_('Calling driver for network: %(net)s action: %(action)s'),
                  {'net': network.id, 'action': action})
        try:
            # the Driver expects something that is duck typed similar to
            # the base models.
            driver = self.dhcp_driver_cls(self.conf,
                                          network,
                                          self.root_helper,
                                          self.dhcp_version,
                                          self.plugin_rpc)

            getattr(driver, action)(**action_kwargs)
            return True
        except exceptions.Conflict:
            # No need to resync here, the agent will receive the event related
            # to a status update for the network
            LOG.warning(_('Unable to %(action)s dhcp for %(net_id)s: there is '
                          'a conflict with its current state; please check '
                          'that the network and/or its subnet(s) still exist.')
                        % {'net_id': network.id, 'action': action})
        except Exception as e:
            self.schedule_resync(e)
            if (isinstance(e, n_rpc.RemoteError)
                and e.exc_type == 'NetworkNotFound'
                or isinstance(e, exceptions.NetworkNotFound)):
                LOG.warning(_("Network %s has been deleted."), network.id)
            else:
                LOG.exception(_('Unable to %(action)s dhcp for %(net_id)s.')
                              % {'net_id': network.id, 'action': action})

    def schedule_resync(self, reason):
        """Schedule a resync for a given reason."""
        self.needs_resync_reasons.append(reason)

    @utils.synchronized('dhcp-agent')
    def sync_state(self):
        """Sync the local DHCP state with Neutron."""
        LOG.info(_('Synchronizing state'))
        pool = eventlet.GreenPool(cfg.CONF.num_sync_threads)
        known_network_ids = set(self.cache.get_network_ids())

        try:
            if self.conf.dhcp_distributed:
                LOG.info('convert_from_centralized_to_distributed begin!')
                rtn = self.plugin_rpc.convert_from_centralized_to_distributed()
                if not rtn:
                    raise EnvironmentError('convert_from_centralized_to_distributed excpetion!')
                LOG.info('convert_from_centralized_to_distributed end!')
                self.plugin_rpc.distributed_schedule_networks()
                active_networks = self.plugin_rpc.get_distributed_active_networks_info()
            else:
                self.plugin_rpc.auto_schedule_networks()
                active_networks = self.plugin_rpc.get_active_networks_info()
            active_network_ids = set(network.id for network in active_networks)
            for deleted_id in known_network_ids - active_network_ids:
                try:
                    self.disable_dhcp_helper(deleted_id)
                except Exception as e:
                    self.schedule_resync(e)
                    LOG.exception(_('Unable to sync network state on deleted '
                                    'network %s'), deleted_id)

            for network in active_networks:
                pool.spawn(self.safe_configure_dhcp_for_network, network)

            pool.waitall()
            LOG.info(_('Synchronizing state complete'))

        except Exception as e:
            self.schedule_resync(e)
            LOG.exception(_('Unable to sync network state.'))

    @utils.synchronized('dhcp-agent')
    def check_processes(self):
        for network_id in self.cache.get_network_ids():
            network = self.cache.get_network_by_id(network_id)
            if network:
                self.call_driver('check_process', network)

    @utils.exception_logger()
    def _periodic_resync_helper(self):
        """Resync the dhcp state at the configured interval."""
        while True:
            eventlet.sleep(self.conf.resync_interval)
            if self.needs_resync_reasons:
                # be careful to avoid a race with additions to list
                # from other threads
                reasons = self.needs_resync_reasons
                self.needs_resync_reasons = []
                for r in reasons:
                    LOG.debug(_("resync: %(reason)s"),
                              {"reason": r})
                self.sync_state()
            self.check_processes()

    def periodic_resync(self):
        """Spawn a thread to periodically resync the dhcp state."""
        eventlet.spawn(self._periodic_resync_helper)

    def safe_get_network_info(self, network_id):
        try:
            if self.conf.dhcp_distributed:
                network = self.plugin_rpc.get_distributed_network_info(network_id)
            else:
                network = self.plugin_rpc.get_network_info(network_id)
            if not network:
                if not self.conf.dhcp_distributed:
                    LOG.warn(_('Network %s has been deleted.'), network_id)
            return network
        except Exception as e:
            self.schedule_resync(e)
            LOG.exception(_('Network %s info call failed.'), network_id)

    def enable_dhcp_helper(self, network_id):
        """Enable DHCP for a network that meets enabling criteria."""
        network = self.safe_get_network_info(network_id)
        if network:
            self.configure_dhcp_for_network(network)

    @utils.exception_logger()
    def safe_configure_dhcp_for_network(self, network):
        try:
            self.configure_dhcp_for_network(network)
        except (exceptions.NetworkNotFound, RuntimeError):
            LOG.warn(_('Network %s may have been deleted and its resources '
                       'may have already been disposed.'), network.id)

    def configure_dhcp_for_network(self, network):
        if not network.admin_state_up:
            return

        enable_metadata = self.dhcp_driver_cls.should_enable_metadata(
                self.conf, network)
        dhcp_network_enabled = False

        for subnet in network.subnets:
            if subnet.enable_dhcp:
                if self.call_driver('enable', network):
                    dhcp_network_enabled = True
                    self.cache.put(network)
                break

        if enable_metadata and dhcp_network_enabled:
            for subnet in network.subnets:
                if subnet.ip_version == 4 and subnet.enable_dhcp:
                    self.enable_isolated_metadata_proxy(network)
                    break

    def disable_dhcp_helper(self, network_id):
        """Disable DHCP for a network known to the agent."""
        network = self.cache.get_network_by_id(network_id)
        if network:
            if (self.conf.use_namespaces and
                self.conf.enable_isolated_metadata):
                # NOTE(jschwarz): In the case where a network is deleted, all
                # the subnets and ports are deleted before this function is
                # called, so checking if 'should_enable_metadata' is True
                # for any subnet is false logic here.
                self.disable_isolated_metadata_proxy(network)
            if self.call_driver('disable', network):
                self.cache.remove(network)

    def refresh_dhcp_helper(self, network_id):
        """Refresh or disable DHCP for a network depending on the current state
        of the network.
        """
        old_network = self.cache.get_network_by_id(network_id)
        if not old_network:
            # DHCP current not running for network.
            return self.enable_dhcp_helper(network_id)

        network = self.safe_get_network_info(network_id)
        if not network:
            return

        old_cidrs = set(s.cidr for s in old_network.subnets if s.enable_dhcp)
        new_cidrs = set(s.cidr for s in network.subnets if s.enable_dhcp)

        if new_cidrs and old_cidrs == new_cidrs:
            self.call_driver('reload_allocations', network)
            self.cache.put(network)
        elif new_cidrs:
            if self.call_driver('restart', network):
                self.cache.put(network)
        else:
            self.disable_dhcp_helper(network.id)

    @utils.synchronized('dhcp-agent')
    def network_create_end(self, context, payload):
        """Handle the network.create.end notification event."""
        network_id = payload['network']['id']
        self.enable_dhcp_helper(network_id)

    @utils.synchronized('dhcp-agent')
    def network_update_end(self, context, payload):
        """Handle the network.update.end notification event."""
        network_id = payload['network']['id']
        if payload['network']['admin_state_up']:
            self.enable_dhcp_helper(network_id)
        else:
            self.disable_dhcp_helper(network_id)

    @utils.synchronized('dhcp-agent')
    def network_delete_end(self, context, payload):
        """Handle the network.delete.end notification event."""
        self.disable_dhcp_helper(payload['network_id'])

    @utils.synchronized('dhcp-agent')
    def subnet_update_end(self, context, payload):
        """Handle the subnet.update.end notification event."""
        network_id = payload['subnet']['network_id']
        self.refresh_dhcp_helper(network_id)

    # Use the update handler for the subnet create event.
    subnet_create_end = subnet_update_end

    @utils.synchronized('dhcp-agent')
    def subnet_delete_end(self, context, payload):
        """Handle the subnet.delete.end notification event."""
        subnet_id = payload['subnet_id']
        network = self.cache.get_network_by_subnet_id(subnet_id)
        if network:
            self.refresh_dhcp_helper(network.id)

    @utils.synchronized('dhcp-agent')
    def port_update_end(self, context, payload):
        """Handle the port.update.end notification event."""
        updated_port = dhcp.DictModel(payload['port'])
        network = self.cache.get_network_by_id(updated_port.network_id)
        if network:
            self.cache.put_port(updated_port)
            self.call_driver('reload_allocations', network)

    # Use the update handler for the port create event.
    port_create_end = port_update_end

    @utils.synchronized('dhcp-agent')
    def port_delete_end(self, context, payload):
        """Handle the port.delete.end notification event."""
        port = self.cache.get_port_by_id(payload['port_id'])
        if port:
            network = self.cache.get_network_by_id(port.network_id)
            self.cache.remove_port(port)
            self.call_driver('reload_allocations', network)

    def enable_isolated_metadata_proxy(self, network):

        # The proxy might work for either a single network
        # or all the networks connected via a router
        # to the one passed as a parameter
        neutron_lookup_param = '--network_id=%s' % network.id
        # When the metadata network is enabled, the proxy might
        # be started for the router attached to the network
        if self.conf.enable_metadata_network:
            router_ports = [port for port in network.ports
                            if (port.device_owner ==
                                constants.DEVICE_OWNER_ROUTER_INTF)]
            if router_ports:
                # Multiple router ports should not be allowed
                if len(router_ports) > 1:
                    LOG.warning(_("%(port_num)d router ports found on the "
                                  "metadata access network. Only the port "
                                  "%(port_id)s, for router %(router_id)s "
                                  "will be considered"),
                                {'port_num': len(router_ports),
                                 'port_id': router_ports[0].id,
                                 'router_id': router_ports[0].device_id})
                neutron_lookup_param = ('--router_id=%s' %
                                        router_ports[0].device_id)

        def callback(pid_file):
            metadata_proxy_socket = cfg.CONF.metadata_proxy_socket
            proxy_cmd = ['neutron-ns-metadata-proxy',
                         '--pid_file=%s' % pid_file,
                         '--metadata_proxy_socket=%s' % metadata_proxy_socket,
                         neutron_lookup_param,
                         '--state_path=%s' % self.conf.state_path,
                         '--metadata_port=%d' % dhcp.METADATA_PORT]
            #Could not print log for VRM when debug is False
            if cfg.CONF.debug:
                proxy_cmd.extend(config.get_log_args(
                    cfg.CONF, 'neutron-ns-metadata-proxy-%s.log' % network.id))
            return proxy_cmd

        pm = external_process.ProcessManager(
            self.conf,
            network.id,
            self.root_helper,
            network.namespace)
        pm.enable(callback)

    def disable_isolated_metadata_proxy(self, network):
        pm = external_process.ProcessManager(
            self.conf,
            network.id,
            self.root_helper,
            network.namespace)
        pm.disable()

class DhcpPluginApi(n_rpc.RpcProxy):
    """Agent side of the dhcp rpc API.

    API version history:
        1.0 - Initial version.
        1.1 - Added get_active_networks_info, create_dhcp_port,
              and update_dhcp_port methods.

    """

    BASE_RPC_API_VERSION = '1.1'

    def __init__(self, topic, context, use_namespaces):
        super(DhcpPluginApi, self).__init__(
            topic=topic, default_version=self.BASE_RPC_API_VERSION)
        self.context = context
        self.host = cfg.CONF.host
        self.use_namespaces = use_namespaces

    def auto_schedule_networks(self):
            # add by FSP: Split auto_schedule_networks from get_active_networks_info
            # cause in 4000+ network, get_active_networks_info RPC called time out
            ret = self.call(self.context,
                                 self.make_msg('auto_schedule_networks',
                                               host=self.host),
                                 topic=self.topic)

    def get_active_networks_info(self):
        """Make a remote process call to retrieve all network info."""
        ret = self.call(self.context,
                             self.make_msg('get_active_networks_info',
                                           host=self.host))
        networks = ret['networks']
        subnets = ret['subnets']
        ports = ret['ports']
        for network in networks:
            network['subnets'] = [subnet for subnet in subnets
                                 if subnet['network_id'] == network['id']]
            network['ports'] = [port for port in ports
                               if port['network_id'] == network['id']]

        return [dhcp.NetModel(self.use_namespaces, n) for n in networks]

    def distributed_schedule_networks(self):
        self.call(self.context, self.make_msg('distributed_schedule_networks',
                                              host = self.host),
                                 topic = self.topic)

    def get_distributed_active_networks_info(self):
        ret = self.call(self.context,
                            self.make_msg('get_distributed_active_networks_info',
                                          host = self.host))
        networks = ret['networks']
        subnets = ret['subnets']
        ports = ret['ports']

        for network in networks:
            network['subnets'] = [subnet for subnet in subnets
                                 if subnet['network_id'] == network['id']]
            network['ports'] = [port for port in ports
                               if port['network_id'] == network['id']]

        return [dhcp.NetModel(self.use_namespaces, n) for n in networks]

    def get_distributed_network_info(self, network_id):
        """Make a remote process call to retrieve network info."""
        network = self.call(self.context,
                            self.make_msg('get_distributed_network_info',
                                          network_id=network_id,
                                          host=self.host))
        if network:
            return dhcp.NetModel(self.use_namespaces, network)

    def get_network_info(self, network_id):
        """Make a remote process call to retrieve network info."""
        network = self.call(self.context,
                            self.make_msg('get_network_info',
                                          network_id=network_id,
                                          host=self.host))
        if network:
            return dhcp.NetModel(self.use_namespaces, network)

    def get_dhcp_port(self, network_id, device_id):
        """Make a remote process call to get the dhcp port."""
        port = self.call(self.context,
                         self.make_msg('get_dhcp_port',
                                       network_id=network_id,
                                       device_id=device_id,
                                       host=self.host))
        if port:
            return dhcp.DictModel(port)

    def create_dhcp_port(self, port):
        """Make a remote process call to create the dhcp port."""
        port = self.call(self.context,
                         self.make_msg('create_dhcp_port',
                                       port=port,
                                       host=self.host))
        if port:
            return dhcp.DictModel(port)

    def update_dhcp_port(self, port_id, port):
        """Make a remote process call to update the dhcp port."""
        port = self.call(self.context,
                         self.make_msg('update_dhcp_port',
                                       port_id=port_id,
                                       port=port,
                                       host=self.host))
        if port:
            return dhcp.DictModel(port)

    def release_dhcp_port(self, network_id, device_id):
        """Make a remote process call to release the dhcp port."""
        return self.call(self.context,
                         self.make_msg('release_dhcp_port',
                                       network_id=network_id,
                                       device_id=device_id,
                                       host=self.host))

    def release_port_fixed_ip(self, network_id, device_id, subnet_id):
        """Make a remote process call to release a fixed_ip on the port."""
        return self.call(self.context,
                         self.make_msg('release_port_fixed_ip',
                                       network_id=network_id,
                                       subnet_id=subnet_id,
                                       device_id=device_id,
                                       host=self.host))

    def convert_from_centralized_to_distributed(self):
        return self.call(self.context,
                         self.make_msg('convert_from_centralized_to_distributed',
                                       host_id = self.host))

class NetworkCache(object):
    """Agent cache of the current network state."""
    def __init__(self):
        self.cache = {}
        self.subnet_lookup = {}
        self.port_lookup = {}

    def get_network_ids(self):
        return self.cache.keys()

    def get_network_by_id(self, network_id):
        return self.cache.get(network_id)

    def get_network_by_subnet_id(self, subnet_id):
        return self.cache.get(self.subnet_lookup.get(subnet_id))

    def get_network_by_port_id(self, port_id):
        return self.cache.get(self.port_lookup.get(port_id))

    def put(self, network):
        if network.id in self.cache:
            self.remove(self.cache[network.id])

        self.cache[network.id] = network

        for subnet in network.subnets:
            self.subnet_lookup[subnet.id] = network.id

        for port in network.ports:
            self.port_lookup[port.id] = network.id

    def remove(self, network):
        del self.cache[network.id]

        for subnet in network.subnets:
            del self.subnet_lookup[subnet.id]

        for port in network.ports:
            del self.port_lookup[port.id]

    def put_port(self, port):
        network = self.get_network_by_id(port.network_id)
        for index in range(len(network.ports)):
            if network.ports[index].id == port.id:
                network.ports[index] = port
                break
        else:
            network.ports.append(port)

        self.port_lookup[port.id] = network.id

    def remove_port(self, port):
        network = self.get_network_by_port_id(port.id)

        for index in range(len(network.ports)):
            if network.ports[index] == port:
                del network.ports[index]
                del self.port_lookup[port.id]
                break

    def get_port_by_id(self, port_id):
        network = self.get_network_by_port_id(port_id)
        if network:
            for port in network.ports:
                if port.id == port_id:
                    return port

    def get_state(self):
        net_ids = self.get_network_ids()
        num_nets = len(net_ids)
        num_subnets = 0
        num_ports = 0
        for net_id in net_ids:
            network = self.get_network_by_id(net_id)
            num_subnets += len(network.subnets)
            num_ports += len(network.ports)
        return {'networks': num_nets,
                'subnets': num_subnets,
                'ports': num_ports}

class DhcpAgentWithStateReport(DhcpAgent):
    def __init__(self, host=None):
        super(DhcpAgentWithStateReport, self).__init__(host=host)
        self.state_rpc = agent_rpc.PluginReportStateAPI(topics.PLUGIN)
        self.agent_state = {
            'binary': 'neutron-dhcp-agent',
            'host': host,
            'topic': topics.DHCP_AGENT,
            'configurations': {
                'dhcp_driver': cfg.CONF.dhcp_driver,
                'use_namespaces': cfg.CONF.use_namespaces,
                'dhcp_lease_duration': cfg.CONF.dhcp_lease_duration},
            'start_flag': True,
            'agent_type': constants.AGENT_TYPE_DHCP}
        report_interval = cfg.CONF.AGENT.report_interval
        self.use_call = True
        if report_interval:
            self.heartbeat = loopingcall.FixedIntervalLoopingCall(
                self._report_state)
            self.heartbeat.start(interval=report_interval)

    def _report_state(self):
        try:
            self.agent_state.get('configurations').update(
                self.cache.get_state())
            ctx = context.get_admin_context_without_session()
            self.state_rpc.report_state(ctx, self.agent_state, self.use_call)
            self.use_call = False
        except AttributeError:
            # This means the server does not support report_state
            LOG.warn(_("Neutron server does not support state report."
                       " State report for this agent will be disabled."))
            self.heartbeat.stop()
            self.run()
            return
        except Exception:
            LOG.exception(_("Failed reporting state!"))
            return
        if self.agent_state.pop('start_flag', None):
            self.run()

    def agent_updated(self, context, payload):
        """Handle the agent_updated notification event."""
        self.schedule_resync(_("Agent updated: %(payload)s") %
                             {"payload": payload})
        LOG.info(_("agent_updated by server side %s!"), payload)

    def after_start(self):
        LOG.info(_("DHCP agent started"))

def register_options():
    cfg.CONF.register_opts(DhcpAgent.OPTS)
    config.register_interface_driver_opts_helper(cfg.CONF)
    config.register_use_namespaces_opts_helper(cfg.CONF)
    config.register_agent_state_opts_helper(cfg.CONF)
    config.register_root_helper(cfg.CONF)
    cfg.CONF.register_opts(dhcp.OPTS)
    cfg.CONF.register_opts(interface.OPTS)

def main():
    register_options()
    common_config.init(sys.argv[1:])
    config.setup_logging()
    server = neutron_service.Service.create(
        binary='neutron-dhcp-agent',
        topic=topics.DHCP_AGENT,
        report_interval=cfg.CONF.AGENT.report_interval,
        manager='neutron.agent.dhcp_agent.DhcpAgentWithStateReport')
    service.launch(server).wait()


text:
import com.twilio.sdk.TwilioRestClient;
import com.twilio.sdk.TwilioRestException;
import com.twilio.sdk.resource.instance.sip.IpAccessControlListMapping;
import com.twilio.sdk.resource.list.sip.IpAccessControlListMappingList;

public class Example {

  // Find your Account Sid and Token at twilio.com/user/account
  public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  public static final String AUTH_TOKEN = "your_auth_token";

  public static void main(String[] args) throws TwilioRestException {
    TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);

    IpAccessControlListMappingList ipAccessControlListMappings = client.getAccount().getDomain("SD32a3c49700934481addd5ce1659f04d2").getIpAccessControlListMappings();

    // Loop over ipAccessControlListMappings and print out a property for each one.
    for (IpAccessControlListMapping ipAccessControlListMapping : ipAccessControlListMappings) {
      System.out.println(ipAccessControlListMapping.getFriendlyName());
    }

  }
}

redpajama_set_name: RedPajamaGithub


text:
package intellij.haskell.alex.lang.psi.impl;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static intellij.haskell.alex.lang.psi.AlexTypes.*;
import intellij.haskell.alex.lang.psi.*;

public class AlexIdentifierImpl extends AlexElementImpl implements AlexIdentifier {

  public AlexIdentifierImpl(ASTNode node) {
    super(node);
  }

  public void accept(@NotNull AlexVisitor visitor) {
    visitor.visitIdentifier(this);
  }

  public void accept(@NotNull PsiElementVisitor visitor) {
    if (visitor instanceof AlexVisitor) accept((AlexVisitor)visitor);
    else super.accept(visitor);
  }

}


text:
import Test.Hspec
import Test.HUnit

import FrameRenderer
import Graphics.HsExif
import Helpers (getTargetFolder)

main :: IO ()
main = hspec $
    describe "contents format parsing tests" runFormatParsingTests

runFormatParsingTests :: Spec
runFormatParsingTests = do
    testFile
    testDate
    testExif
    testPercent
    testComposite
    testShouldFail
    testShouldFail2
    testGetTargetFolder

testFile :: Spec
testFile = it "parses a file criteria" $
    assertEqual' (Right [Filename]) $ parseFormat "%file"

testDate :: Spec
testDate = it "parses a date" $
    assertEqual' (Right [DateFormat "%x HH:MM"]) $ parseFormat "%date{%x HH:MM}"

testExif :: Spec
testExif = it "parses an exif criteria" $
    assertEqual' (Right [ExifContents fnumber]) $ parseFormat "%aper"

testPercent :: Spec
testPercent = it "parses a percent sign" $
    assertEqual' (Right [StringContents "%"]) $ parseFormat "%%"

testComposite :: Spec
testComposite = it "parses a composite string" $
    assertEqual' (Right [StringContents "picture ", Filename,
            StringContents ", taken on: ", DateFormat "%x HH:MM",
            StringContents ". f/", ExifContents fnumber])
            $ parseFormat "picture %file, taken on: %date{%x HH:MM}. f/%aper"

testShouldFail :: Spec
testShouldFail = it "fails parsing a bad string" $
    assertBool "fails" $ isLeft $ parseFormat "%ss"

testShouldFail2 :: Spec
testShouldFail2 = it "fails parsing a bad string" $
    assertBool "fails" $ isLeft $ parseFormat "%file %ss"

testGetTargetFolder :: Spec
testGetTargetFolder = it "gets the target folder correctly" $ do
    assertEqual' "/home/emmanuel/Pictures/2010/imprint" $
        getTargetFolder ["/home/emmanuel/Pictures/2010/f1.jpg",
            "/home/emmanuel/Pictures/2010/f2.jpg",
            "/home/emmanuel/Pictures/2010/subfolder/f2.jpg"]
    assertEqual' "/home/emmanuel/Pictures/2011/subfolder/imprint" $
        getTargetFolder ["/home/emmanuel/Pictures/2011/subfolder/f1.jpg",
            "/home/emmanuel/Pictures/2011/subfolder/f2.jpg"]
    assertEqual' "/home/emmanuel/Pictures/2012/imprint" $
        getTargetFolder ["/home/emmanuel/Pictures/2012/subfolder/f1.jpg",
            "/home/emmanuel/Pictures/2012/subfolder2/f2.jpg"]

isLeft :: Either a b -> Bool
isLeft (Left _) = True
isLeft _        = False

assertEqual' :: (Show a, Eq a) => a -> a -> Assertion
assertEqual' = assertEqual "doesn't match"


text:
<?php
declare(strict_types=1);

require __DIR__ . '/../vendor/autoload.php';

use Symfony\Component\Console\Application;

/** @var \Interop\Container\ContainerInterface $container */
$container = require __DIR__ . '/../config/container.php';

$application = new Application('application-name-cli'); // todo application name

$commands = $container->get('config')['console']['commands'];

foreach ($commands as $command) {
    $application->add($container->get($command));
}

$application->run();


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true">
        <shape android:shape="rectangle">
            <solid android:color="@color/colorWhite" />
            <corners android:radius="5dp"/>
            <stroke android:width="1px" android:color="@color/colorMain" />
        </shape>
    </item>
    <item android:state_focused="false">
        <shape android:shape="rectangle">
            <solid android:color="@color/colorWhite" />
            <corners android:radius="5dp"/>
            <stroke android:width="1px" android:color="@color/colorGrayD" />
        </shape>
    </item>
</selector>


text:
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;

public class RunApp extends Panel {

    /**
	 *
	 */
	private static final long serialVersionUID = 1337L;
	static Frame frame;
    static GameSparker applet;
    public static ArrayList<Image> icons;
    static SexyMenu sexymenu;

    /**
    * Fetches icons of 16, 32 and 48 pixels from the 'data' folder.
    */
    public static ArrayList<Image> getIcons() {
        if (icons == null) {
            icons = new ArrayList<Image>();
            int[] resols = {16, 32, 48};
            for (int res : resols) {
                icons.add(Toolkit.getDefaultToolkit().createImage("data/ico_" + res + ".png"));
            }
        }
        return icons;
    }

    public static void main(String[] strings) {
        System.runFinalizersOnExit(true);
        System.out.println("Nfm2-Mod Console");//Change this to the messgae of your preference
        try {
            javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            System.out.println("Could not setup System Look&Feel: " + ex.toString());
        }
        startup();
        sexymenu = new SexyMenu(frame, applet, new RunApp());
        sexymenu.initSettings(applet.settings);
        sexymenu.initMenu();
        sexymenu.initSpeedoMenu();

    }

    static void startup() {
        frame = new Frame("My Need for Madness 2 Mod");//Change this to the name of your preference
        frame.setBackground(new Color(0, 0, 0));
        frame.setIgnoreRepaint(true);
        frame.setIconImages(getIcons());
        applet = new GameSparker();
        applet.setStub(new DesktopStub());
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent windowevent) {
                exitsequance();
            }
        });
        applet.setPreferredSize(new java.awt.Dimension(670, 460));//The resolution of your game goes here
        frame.add("Center", applet);
        frame.setResizable(false);//If you plan to make you game support changes in resolution, you can comment out this line.
        frame.pack();
        frame.setMinimumSize(frame.getSize());
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        applet.init();
        applet.start();
    }

    public static void exitsequance() {
        applet.stop();
        frame.removeAll();
        try {
            Thread.sleep(200L);
        } catch (Exception exception) {}
        applet.destroy();
        applet = null;
        System.exit(0);
    }

    public static String getString(String tag, String str, int id) {
        int k = 0;
        String s3 = "";
        for (int j = tag.length() + 1; j < str.length(); j++) {
            String s2 = "" + str.charAt(j);
            if (s2.equals(",") || s2.equals(")")) {
                k++;
                j++;
            }
            if (k == id) {
                s3 += str.charAt(j);
            }
        }
        return s3;
    }

    public static int getInt(String tag, String str, int id) {
        return Integer.parseInt(getString(tag, str, id));
    }
}


text:
namespace chrono {

class CH_PARALLEL_API ChLcpSolverParallel : public ChLcpIterativeSolver {
 public:
  virtual ~ChLcpSolverParallel();

  // Each child class must define its own solve method
  virtual double Solve(ChLcpSystemDescriptor& sysd) { return 0; }
  // Similarly, the run timestep function needs to be defined
  virtual void RunTimeStep() = 0;
  // This function computes the new velocities based on the lagrange multipliers
  virtual void ComputeImpulses() = 0;

  // Compute the inverse mass matrix and the term v+M_inv*hf
  void ComputeMassMatrix();
  // Solves just the bilaterals so that they can be warm started
  void PerformStabilization();

  real GetResidual() { return residual; }
  ChParallelDataManager* data_manager;
  ChSolverParallel* solver;

 protected:
  ChLcpSolverParallel(ChParallelDataManager* dc);

  real residual;
  ChConstraintBilateral bilateral;
};

class CH_PARALLEL_API ChLcpSolverParallelDVI : public ChLcpSolverParallel {
 public:
  ChLcpSolverParallelDVI(ChParallelDataManager* dc) : ChLcpSolverParallel(dc) {}

  virtual void RunTimeStep();
  virtual void ComputeImpulses();

  // Compute the constraint Jacobian matrix.
  void ComputeD();
  // Compute the compliance matrix.
  void ComputeE();
  // Compute the RHS vector. This will not change depending on the solve
  void ComputeR();
  // Compute the Shur matrix N.
  void ComputeN();
  // Set the RHS vector depending on the local solver mode
  void SetR();
  // This function computes an initial guess for each contact
  void PreSolve();
  // This function is used to change the solver algorithm.
  void ChangeSolverType(SOLVERTYPE type);

 private:
  ChConstraintRigidRigid rigid_rigid;
};

class CH_PARALLEL_API ChLcpSolverParallelDEM : public ChLcpSolverParallel {
 public:
  ChLcpSolverParallelDEM(ChParallelDataManager* dc) : ChLcpSolverParallel(dc) {}

  virtual void RunTimeStep();
  virtual void ComputeImpulses();

  // Compute the constraint Jacobian matrix.
  void ComputeD();
  // Compute the compliance matrix.
  void ComputeE();
  // Compute the RHS vector.
  void ComputeR();

  void ProcessContacts();

 private:
  void host_CalcContactForces(custom_vector<int>& ext_body_id,
                              custom_vector<real3>& ext_body_force,
                              custom_vector<real3>& ext_body_torque,
                              custom_vector<int2>& shape_pairs,
                              custom_vector<bool>& shear_touch);

  void host_AddContactForces(uint ct_body_count, const custom_vector<int>& ct_body_id);

  void host_SetContactForcesMap(uint ct_body_count, const custom_vector<int>& ct_body_id);
};
}
// end namespace chrono

#endif


text:
import re

def check_sexp(sexp):
    """Verify that the argument is a proper sexp.

    That is, raise an exception if the argument is not a string or a
    list, or if it contains anything that is not a string or a list at
    any nesting level.
    """
    if isinstance(sexp, list):
        for s in sexp:
            check_sexp(s)
    elif not isinstance(sexp, basestring):
        raise Exception('Not a sexp: {0!r}'.format(sexp))

def parse_sexp(sexp):
    """Convert a string, of the form that would be output by mesa,
    into a sexp represented as nested lists containing strings.
    """
    sexp_token_regexp = re.compile(
        '[a-zA-Z_]+(@[0-9]+)?|[0-9]+(\\.[0-9]+)?|[^ \n]')
    stack = [[]]
    for match in sexp_token_regexp.finditer(sexp):
        token = match.group(0)
        if token == '(':
            stack.append([])
        elif token == ')':
            if len(stack) == 1:
                raise Exception('Unmatched )')
            sexp = stack.pop()
            stack[-1].append(sexp)
        else:
            stack[-1].append(token)
    if len(stack) != 1:
        raise Exception('Unmatched (')
    if len(stack[0]) != 1:
        raise Exception('Multiple sexps')
    return stack[0][0]

def sexp_to_string(sexp):
    """Convert a sexp, represented as nested lists containing strings,
    into a single string of the form parseable by mesa.
    """
    if isinstance(sexp, basestring):
        return sexp
    assert isinstance(sexp, list)
    result = ''
    for s in sexp:
        sub_result = sexp_to_string(s)
        if result == '':
            result = sub_result
        elif '\n' not in result and '\n' not in sub_result and \
                len(result) + len(sub_result) + 1 <= 70:
            result += ' ' + sub_result
        else:
            result += '\n' + sub_result
    return '({0})'.format(result.replace('\n', '\n '))

def sort_decls(sexp):
    """Sort all toplevel variable declarations in sexp.

    This is used to work around the fact that
    ir_reader::read_instructions reorders declarations.
    """
    assert isinstance(sexp, list)
    decls = []
    other_code = []
    for s in sexp:
        if isinstance(s, list) and len(s) >= 4 and s[0] == 'declare':
            decls.append(s)
        else:
            other_code.append(s)
    return sorted(decls) + other_code


text:
<?php

namespace Doctrine\Tests\DBAL\Types;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\StringType;
use Doctrine\DBAL\Types\Type;
use Doctrine\Tests\DbalTestCase;
use PHPUnit\Framework\MockObject\MockObject;

class StringTest extends DbalTestCase
{
    /** @var AbstractPlatform|MockObject */
    private $platform;

    /** @var StringType */
    private $type;

    protected function setUp() : void
    {
        $this->platform = $this->createMock(AbstractPlatform::class);
        $this->type     = Type::getType('string');
    }

    public function testReturnsSqlDeclarationFromPlatformVarchar() : void
    {
        $this->platform->expects($this->once())
            ->method('getVarcharTypeDeclarationSQL')
            ->willReturn('TEST_VARCHAR');

        self::assertEquals('TEST_VARCHAR', $this->type->getSqlDeclaration([], $this->platform));
    }

    public function testReturnsDefaultLengthFromPlatformVarchar() : void
    {
        $this->platform->expects($this->once())
            ->method('getVarcharDefaultLength')
            ->willReturn(255);

        self::assertEquals(255, $this->type->getDefaultLength($this->platform));
    }

    public function testConvertToPHPValue() : void
    {
        self::assertIsString($this->type->convertToPHPValue('foo', $this->platform));
        self::assertIsString($this->type->convertToPHPValue('', $this->platform));
    }

    public function testNullConversion() : void
    {
        self::assertNull($this->type->convertToPHPValue(null, $this->platform));
    }

    public function testSQLConversion() : void
    {
        self::assertFalse($this->type->canRequireSQLConversion(), 'String type can never require SQL conversion to work.');
        self::assertEquals('t.foo', $this->type->convertToDatabaseValueSQL('t.foo', $this->platform));
        self::assertEquals('t.foo', $this->type->convertToPHPValueSQL('t.foo', $this->platform));
    }
}


text:
const path = require('path')
const webpack = require('webpack')

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [require.resolve('babel-preset-env')],
            plugins: [
              require.resolve('babel-plugin-transform-object-rest-spread')
            ]
          }
        }
      }
    ]
  },
  devtool: 'cheap-module-eval-source-map',
  resolveLoader: {
    modules: [path.resolve(__dirname, '../node_modules')]
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true
    })
  ]
}


text:
package security.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

import security.constant.Constant;
import security.service.base.AuthTokenGeneratorService;

/**
 * @author abidk
 *
 */
public class AuthenticationSuccessHandlerImpl extends
		SimpleUrlAuthenticationSuccessHandler {

	@Value("${auth.success.url}")
	private String defaultTargetUrl;

	@Autowired
	private AuthTokenGeneratorService authTokenGeneratorService;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {

		final String authToken = authTokenGeneratorService
				.generateToken(authentication);
		response.addHeader(Constant.HEADER_SECURITY_TOKEN, authToken);
		request.getRequestDispatcher(defaultTargetUrl).forward(request,
				response);

	}

}


text:
package fr.pizzeria.ihm;

import fr.pizzeria.model.Client;

@ActConnexion
public class InscrireClientAction extends ActionClient {

	public InscrireClientAction(IhmHelperClient helper) {
		super("S'incrire", helper);
	}

	@Override
	public void execute() {

		// recuperation de la saisie
		System.out.println("Vous voulez vous inscrire");
		System.out.println("Veuillez saisir votre nom");
		String nom = helper.getScanner().next();
		System.out.println("Veuillez saisir votre prénom");
		String prenom = helper.getScanner().next();
		System.out.println("Veuillez saisir vote solde");
		double solde = helper.getScanner().nextDouble();
		System.out.println("Veuillez saisir votre email");
		String email = helper.getScanner().next();
		System.out.println("Veuillez saisir votre mot de passe");
		String password = helper.getScanner().next();
		// creation du nouveau client
		Client nouveauClient = new Client(0, nom, prenom, solde, email, password);
		helper.getStockageClient().save(nouveauClient);

		System.out.println("Client ajouté avec succes" + "\n");

	}

}


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.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.SimplifyLinqExpression;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.CSharp.Analyzers.UnitTests.SimplifyLinqExpression
{
    using VerifyCS = CSharpCodeFixVerifier<
        CSharpSimplifyLinqExpressionDiagnosticAnalyzer,
        CSharpSimplifyLinqExpressionCodeFixProvider>;

    public partial class CSharpSimplifyLinqExpressionTests
    {
        [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)]
        public static async Task TestAllowedMethodTypes(
            [CombinatorialValues(
                "x => x==1",
                "(x) => x==1",
                "x => { return x==1; }",
                "(x) => { return x==1; }")]
            string lambda,
            [CombinatorialValues(
                "First",
                "Last",
                "Single",
                "Any",
                "Count",
                "SingleOrDefault",
                "FirstOrDefault",
                "LastOrDefault")]
            string methodName)
        {
            await new VerifyCS.Test
            {
                TestCode = $@"
using System;
using System.Linq;
using System.Collections.Generic;

class Test
{{
    static void Main()
    {{
        static IEnumerable<int> Data()
        {{
            yield return 1;
            yield return 2;
        }}

        var test = [|Data().Where({lambda}).{methodName}()|];
    }}
}}",
                FixedCode = $@"
using System;
using System.Linq;
using System.Collections.Generic;

class Test
{{
    static void Main()
    {{
        static IEnumerable<int> Data()
        {{
            yield return 1;
            yield return 2;
        }}

        var test = Data().{methodName}({lambda});
    }}
}}"
            }.RunAsync();
        }

        [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)]
        public static async Task TestWhereWithIndexMethodTypes(
            [CombinatorialValues(
                "(x, index) => x==index",
                "(x, index) => { return x==index; }")]
            string lambda,
            [CombinatorialValues(
                "First",
                "Last",
                "Single",
                "Any",
                "Count",
                "SingleOrDefault",
                "FirstOrDefault",
                "LastOrDefault")]
            string methodName)
        {
            var testCode = $@"
using System;
using System.Linq;
using System.Collections.Generic;

class Test
{{
    static void Main()
    {{
        static IEnumerable<int> Data()
        {{
            yield return 1;
            yield return 2;
        }}

        var test = Data().Where({lambda}).{methodName}();
    }}
}}";
            await VerifyCS.VerifyAnalyzerAsync(testCode);
        }

        [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)]
        public async Task TestQueryComprehensionSyntax(
            [CombinatorialValues(
                "x => x==1",
                "x => { return x==1; }")]
            string lambda,
            [CombinatorialValues(
                "First",
                "Last",
                "Single",
                "Any",
                "Count",
                "SingleOrDefault",
                "FirstOrDefault",
                "LastOrDefault")]
            string methodName)
        {
            await new VerifyCS.Test
            {
                TestCode = $@"
using System.Linq;

class Test
{{
    static void M()
    {{
        var test1 = [|(from value in Enumerable.Range(0, 10) select value).Where({lambda}).{methodName}()|];
    }}
}}",
                FixedCode = $@"
using System.Linq;

class Test
{{
    static void M()
    {{
        var test1 = (from value in Enumerable.Range(0, 10) select value).{methodName}({lambda});
    }}
}}"
            }.RunAsync();
        }

        [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)]
        [InlineData("First")]
        [InlineData("Last")]
        [InlineData("Single")]
        [InlineData("Any")]
        [InlineData("Count")]
        [InlineData("SingleOrDefault")]
        [InlineData("FirstOrDefault")]
        [InlineData("LastOrDefault")]
        public async Task TestMultiLineLambda(string methodName)
        {
            await new VerifyCS.Test
            {
                TestCode = $@"
using System;
using System.Linq;
using System.Collections.Generic;

class Test
{{
    static void Main()
    {{
        static IEnumerable<int> Data()
        {{
            yield return 1;
            yield return 2;
        }}

        var test = [|Data().Where(x =>
        {{
            Console.Write(x);
            return x == 1;
        }}).{methodName}()|];
    }}
}}",
                FixedCode = $@"
using System;
using System.Linq;
using System.Collections.Generic;

class Test
{{
    static void Main()
    {{
        static IEnumerable<int> Data()
        {{
            yield return 1;
            yield return 2;
        }}

        var test = Data().{methodName}(x =>
        {{
            Console.Write(x);
            return x == 1;
        }});
    }}
}}"
            }.RunAsync();
        }

        [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)]
        [InlineData("First", "string")]
        [InlineData("Last", "string")]
        [InlineData("Single", "string")]
        [InlineData("Any", "bool")]
        [InlineData("Count", "int")]
        [InlineData("SingleOrDefault", "string")]
        [InlineData("FirstOrDefault", "string")]
        [InlineData("LastOrDefault", "string")]
        public async Task TestOutsideFunctionCallLambda(string methodName, string returnType)
        {
            await new VerifyCS.Test
            {
                TestCode = $@"
using System;
using System.Linq;
using System.Collections.Generic;

class Test
{{
    public static bool FooTest(string input)
    {{
        return true;
    }}

    static IEnumerable<string> test = new List<string> {{ ""hello"", ""world"", ""!"" }};
    {returnType} result = [|test.Where(x => FooTest(x)).{methodName}()|];
}}",
                FixedCode = $@"
using System;
using System.Linq;
using System.Collections.Generic;

class Test
{{
    public static bool FooTest(string input)
    {{
        return true;
    }}

    static IEnumerable<string> test = new List<string> {{ ""hello"", ""world"", ""!"" }};
    {returnType} result = test.{methodName}(x => FooTest(x));
}}"
            }.RunAsync();
        }

        [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)]
        [InlineData("First")]
        [InlineData("Last")]
        [InlineData("Single")]
        [InlineData("Any")]
        [InlineData("Count")]
        [InlineData("SingleOrDefault")]
        [InlineData("FirstOrDefault")]
        [InlineData("LastOrDefault")]
        public async Task TestQueryableIsNotConsidered(string methodName)
        {
            var source = $@"
using System;
using System.Linq;
using System.Collections.Generic;
namespace demo
{{
    class Test
    {{
        void M()
        {{
            List<int> testvar1 = new List<int> {{ 1, 2, 3, 4, 5, 6, 7, 8 }};
            IQueryable<int> testvar2 = testvar1.AsQueryable().Where(x => x % 2 == 0);
            var output = testvar2.Where(x => x == 4).{methodName}();
        }}
    }}
}}";
            await VerifyCS.VerifyAnalyzerAsync(source);
        }

        [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)]
        public async Task TestNestedLambda(
            [CombinatorialValues(
                "First",
                "Last",
                "Single",
                "Any",
                "Count",
                "SingleOrDefault",
                "FirstOrDefault",
                "LastOrDefault")]
            string firstMethod,
            [CombinatorialValues(
                "First",
                "Last",
                "Single",
                "Any",
                "Count",
                "SingleOrDefault",
                "FirstOrDefault",
                "LastOrDefault")]
            string secondMethod)
        {
            var testCode = $@"
using System;
using System.Linq;
using System.Collections.Generic;

class Test
{{
    void M()
    {{
        IEnumerable<string> test = new List<string> {{ ""hello"", ""world"", ""!"" }};
        var test5 = [|test.Where(a => [|a.Where(s => s.Equals(""hello"")).{secondMethod}()|].Equals(""hello"")).{firstMethod}()|];
    }}
}}";
            var fixedCode = $@"
using System;
using System.Linq;
using System.Collections.Generic;

class Test
{{
    void M()
    {{
        IEnumerable<string> test = new List<string> {{ ""hello"", ""world"", ""!"" }};
        var test5 = test.{firstMethod}(a => a.{secondMethod}(s => s.Equals(""hello"")).Equals(""hello""));
    }}
}}";
            await VerifyCS.VerifyCodeFixAsync(
                testCode,
                fixedCode);
        }

        [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)]
        [InlineData("First")]
        [InlineData("Last")]
        [InlineData("Single")]
        [InlineData("Any")]
        [InlineData("Count")]
        [InlineData("SingleOrDefault")]
        [InlineData("FirstOrDefault")]
        [InlineData("LastOrDefault")]
        public async Task TestExplicitEnumerableCall(string methodName)
        {
            await new VerifyCS.Test
            {
                TestCode = $@"
using System;
using System.Linq;
using System.Collections.Generic;
using System.Linq.Expressions;

class Test
{{
    static void Main()
    {{
        IEnumerable<int> test = new List<int> {{ 1, 2, 3, 4, 5}};
        [|Enumerable.Where(test, (x => x == 1)).{methodName}()|];
    }}
}}",
                FixedCode = $@"
using System;
using System.Linq;
using System.Collections.Generic;
using System.Linq.Expressions;

class Test
{{
    static void Main()
    {{
        IEnumerable<int> test = new List<int> {{ 1, 2, 3, 4, 5}};
        Enumerable.{methodName}(test, (x => x == 1));
    }}
}}"
            }.RunAsync();
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)]
        public async Task TestUserDefinedWhere()
        {
            var source = @"
using System;
using System.Linq;
using System.Collections.Generic;
namespace demo
{
    class Test
    {
        public class TestClass4
        {
            private string test;
            public TestClass4() => test = ""hello"";

            public TestClass4 Where(Func<string, bool> input)
            {
                return this;
            }

            public string Single()
            {
                return test;
            }
        }
        static void Main()
        {
            TestClass4 Test1 = new TestClass4();
            TestClass4 test = Test1.Where(y => true);
        }
    }
}";
            await VerifyCS.VerifyAnalyzerAsync(source);
        }

        [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)]
        [InlineData("First")]
        [InlineData("Last")]
        [InlineData("Single")]
        [InlineData("Any")]
        [InlineData("Count")]
        [InlineData("SingleOrDefault")]
        [InlineData("FirstOrDefault")]
        [InlineData("LastOrDefault")]
        public async Task TestArgumentsInSecondCall(string methodName)
        {
            var source = $@"
using System;
using System.Linq;
using System.Collections.Generic;

class Test
{{
    static void M()
    {{
        IEnumerable<string> test1 = new List<string>{{ ""hello"", ""world"", ""!"" }};
        var test2 = test1.Where(x => x == ""!"").{methodName}(x => x.Length == 1);
    }}
}}";
            await VerifyCS.VerifyAnalyzerAsync(source);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)]
        public async Task TestUnsupportedFunction()
        {
            var source = @"
using System;
using System.Linq;
using System.Collections.Generic;
namespace demo
{
    class Test
    {
        static List<int> test1 = new List<int> { 3, 12, 4, 6, 20 };
        int test2 = test1.Where(x => x > 0).Count();
    }
}";
            await VerifyCS.VerifyAnalyzerAsync(source);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)]
        public async Task TestExpressionTreeInput()
        {
            var source = @"
using System;
using System.Linq;
using System.Collections.Generic;
using System.Linq.Expressions;

class Test
{
    void Main()
    {
        string[] places = { ""Beach"", ""Pool"", ""Store"", ""House"",
                   ""Car"", ""Salon"", ""Mall"", ""Mountain""};

        IQueryable<String> queryableData = places.AsQueryable<string>();
        ParameterExpression pe = Expression.Parameter(typeof(string), ""place"");

        Expression left = Expression.Call(pe, typeof(string).GetMethod(""ToLower"", System.Type.EmptyTypes));
        Expression right = Expression.Constant(""coho winery"");
        Expression e1 = Expression.Equal(left, right);

        left = Expression.Property(pe, typeof(string).GetProperty(""Length""));
        right = Expression.Constant(16, typeof(int));
        Expression e2 = Expression.GreaterThan(left, right);

        Expression predicateBody = Expression.OrElse(e1, e2);
        Expression<Func<int, bool>> lambda1 = num => num < 5;

        string result = queryableData.Where(Expression.Lambda<Func<string, bool>>(predicateBody, new ParameterExpression[] { pe })).First();
    }
}";
            await VerifyCS.VerifyAnalyzerAsync(source);
        }
    }
}


text:
#include "common/geometry/point.h"
#include "common/geometry/rectangle.h"

const int QT_NODE_CAPACITY = 4;

class QuadTree
{
	Rectangle boundary;

	vector<Point> points;

	// Children
	QuadTree* northWest;
	QuadTree* northEast;
	QuadTree* southWest;
	QuadTree* southEast;

	// Methods
public:
	QuadTree(const Rectangle& boundary): boundary(boundary), northWest(NULL), northEast(NULL), southWest(NULL), southEast(NULL) {}

	double width() const
	{
		return boundary.xr - boundary.xl;
	}

	bool insert(const Point& p)
	{
		// Ignore objects which do not belong in this quad tree
		if (!boundary.Contains(p))
			return false; // object cannot be added

		// If there is space in this quad tree, add the object here
		if ((int)points.size() < QT_NODE_CAPACITY)
		{
			points.push_back(p);
			return true;
		}

		// Otherwise, we need to subdivide then add the point to whichever node will accept it
		if (northWest == NULL)
			subdivide();

		if (northWest->insert(p)) return true;
		if (northEast->insert(p)) return true;
		if (southWest->insert(p)) return true;
		if (southEast->insert(p)) return true;

		// Otherwise, the point cannot be inserted for some unknown reason (which should never happen)
		return false;
	}

	// create four children which fully divide this quad into four quads of equal area
	void subdivide()
	{
		northWest = new QuadTree(Rectangle(boundary.xl, boundary.midX(), boundary.midY(), boundary.yr));
		northEast = new QuadTree(Rectangle(boundary.midX(), boundary.xr, boundary.midY(), boundary.yr));
		southWest = new QuadTree(Rectangle(boundary.xl, boundary.midX(), boundary.yl, boundary.midY()));
		southEast = new QuadTree(Rectangle(boundary.midX(), boundary.xr, boundary.yl, boundary.midY()));
	}

	vector<Point> queryRange(const Rectangle& range)
	{
		// Prepare an array of results
		vector<Point> pointsInRange;

		// Automatically abort if the range does not collide with this quad
		if (!boundary.Intersects(range))
			return pointsInRange; // empty list

		// Check objects at this quad level
		for (int i = 0; i < (int)points.size(); i++)
		{
			if (range.Contains(points[i]))
				pointsInRange.push_back(points[i]);
		}

		// Terminate here, if there are no children
		if (northWest == NULL)
			return pointsInRange;

		// Otherwise, add the points from the children
		vector<Point> res;

		res = northWest->queryRange(range);
		pointsInRange.insert(pointsInRange.end(), res.begin(), res.end());
		res = northEast->queryRange(range);
		pointsInRange.insert(pointsInRange.end(), res.begin(), res.end());
		res = southWest->queryRange(range);
		pointsInRange.insert(pointsInRange.end(), res.begin(), res.end());
		res = southEast->queryRange(range);
		pointsInRange.insert(pointsInRange.end(), res.begin(), res.end());

		return pointsInRange;
	}

	bool containsInRange(const Rectangle& range)
	{
		// Automatically abort if the range does not collide with this quad
		if (!boundary.Intersects(range))
			return false; // empty list

		// Check objects at this quad level
		for (int i = 0; i < (int)points.size(); i++)
		{
			if (range.Contains(points[i]))
				return true;
		}

		// Terminate here, if there are no children
		if (northWest == NULL)
			return false;

		// Otherwise, add the points from the children
		if (northWest->containsInRange(range)) return true;
		if (northEast->containsInRange(range)) return true;
		if (southWest->containsInRange(range)) return true;
		if (southEast->containsInRange(range)) return true;

		return false;
	}

	bool containsInRange(const Rectangle& range, const Point& self)
	{
		// Automatically abort if the range does not collide with this quad
		if (!boundary.Intersects(range))
			return false; // empty list

		// Check objects at this quad level
		for (int i = 0; i < (int)points.size(); i++)
		{
			if (points[i] != self && range.Contains(points[i]))
				return true;
		}

		// Terminate here, if there are no children
		if (northWest == NULL)
			return false;

		// Otherwise, add the points from the children
		if (northWest->containsInRange(range, self)) return true;
		if (northEast->containsInRange(range, self)) return true;
		if (southWest->containsInRange(range, self)) return true;
		if (southEast->containsInRange(range, self)) return true;

		return false;
	}
};


text:
package io.aos.concurrent.atomic;

import io.aos.concurrent.atomic.BaseTest.Timestamp;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.junit.Test;

public class CreateTest extends Thread {
    static AtomicInteger nCalls;
    static int target = 0;
    static boolean done = false;
    static Object lock = new Object();

    @Test
    public void test() {

        target = 10000;

        doTestCreate();
        doTestPool(8);
        doTestLoop();

        cleanGC();
        Timestamp createTS = new Timestamp(TimeUnit.MICROSECONDS);
        doTestCreate();
        createTS.stop();
        System.out.println("Create thread test took " + createTS);

        cleanGC();
        Timestamp pool8TS = new Timestamp(TimeUnit.MICROSECONDS);
        doTestPool(8);
        pool8TS.stop();
        System.out.println("Pool test (8 threads) took " + pool8TS);

        cleanGC();
        Timestamp poolTS = new Timestamp(TimeUnit.MICROSECONDS);
        doTestPool(1);
        poolTS.stop();
        System.out.println("Pool test (1 thread) took " + poolTS);

        cleanGC();
        Timestamp loopTS = new Timestamp(TimeUnit.MICROSECONDS);
        doTestLoop();
        loopTS.stop();
        System.out.println("Loop test took " + loopTS);

        double d = ((double) (createTS.elapsedTime() - loopTS.elapsedTime()))
                / target;
        System.out.println("Creating a thread took " + d + " " + loopTS.units()
                + " per thread");

        d = ((double) (createTS.elapsedTime() - poolTS.elapsedTime())) / target;
        System.out.println("Using a thread pool (1 thread) saved  " + d + " "
                + loopTS.units() + " per task");

        d = ((double) (createTS.elapsedTime() - pool8TS.elapsedTime()))
                / target;
        System.out.println("Using a thread pool (8 threads) saved  " + d + " "
                + loopTS.units() + " per task");

        d = ((double) (poolTS.elapsedTime() - loopTS.elapsedTime())) / target;
        System.out.println("Thread pool overhead (1 thread) is " + d + " "
                + loopTS.units() + " per task");

        d = ((double) (pool8TS.elapsedTime() - loopTS.elapsedTime())) / target;
        System.out.println("Thread pool overhead (8 threads) is " + d + " "
                + loopTS.units() + " per task");
    }

    static void doTestLoop() {
        nCalls = new AtomicInteger(0);
        done = false;
        for (int i = 0; i < target; i++)
            work();
        synchronized (lock) {
            while (!done)
                try {
                    lock.wait();
                } catch (Exception e) {
                }
        }
    }

    static void doTestCreate() {
        done = false;
        nCalls = new AtomicInteger(0);
        for (int i = 0; i < target; i++) {
            Thread t = new CreateTest();
            t.start();
        }
        synchronized (lock) {
            while (!done)
                try {
                    lock.wait();
                } catch (Exception e) {
                }
        }
    }

    static void doTestPool(int nThreads) {
        done = false;
        nCalls = new AtomicInteger(0);
        ThreadPoolExecutor tpe = new ThreadPoolExecutor(nThreads, nThreads,
                50000L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
        Runnable r = new CreateTest();
        for (int i = 0; i < target; i++) {
            tpe.execute(r);
        }
        tpe.shutdown();
        try {
            tpe.awaitTermination(10000000L, TimeUnit.SECONDS);
        } catch (Exception e) {
        }
    }

    public void run() {
        work();
    }

    public static void work() {
        int n = nCalls.incrementAndGet();
        if (n == target) {
            synchronized (lock) {
                done = true;
                lock.notify();
            }
        }
    }

    public static void cleanGC() {
        System.gc();
        System.runFinalization();
        System.gc();
    }
}


text:
#ifndef THIRD_PARTY_LIBJINGLE_XMPP_XMPP_UTIL_UNITTEST_H_
#define THIRD_PARTY_LIBJINGLE_XMPP_XMPP_UTIL_UNITTEST_H_

#include <sstream>
#include <string>
#include "third_party/libjingle_xmpp/xmpp/xmppengine.h"

namespace jingle_xmpp {

// This class captures callbacks from engine.
class XmppTestHandler : public XmppOutputHandler,  public XmppSessionHandler,
                        public XmppStanzaHandler {
 public:
  explicit XmppTestHandler(XmppEngine* engine) : engine_(engine) {}
  virtual ~XmppTestHandler() {}

  void SetEngine(XmppEngine* engine);

  // Output handler
  virtual void WriteOutput(const char * bytes, size_t len);
  virtual void StartTls(const std::string & cname);
  virtual void CloseConnection();

  // Session handler
  virtual void OnStateChange(int state);

  // Stanza handler
  virtual bool HandleStanza(const XmlElement* stanza);

  std::string OutputActivity();
  std::string SessionActivity();
  std::string StanzaActivity();

 private:
  XmppEngine* engine_;
  std::stringstream output_;
  std::stringstream session_;
  std::stringstream stanza_;
};

}  // namespace jingle_xmpp

inline std::ostream& operator<<(std::ostream& os, const jingle_xmpp::Jid& jid) {
  os << jid.Str();
  return os;
}

#endif  // THIRD_PARTY_LIBJINGLE_XMPP_XMPP_UTIL_UNITTEST_H_


text:
package fr.sii.ogham.html.inliner.impl.regexp;

/**
 * Common constants for inlining of images included through CSS properties (such
 * as background, list-style, ...).
 *
 *
 * @author Aurélien Baudet
 *
 */
public final class CssImageInlinerConstants {
	/**
	 *

	 * The CSS property name to indicate which strategy for inlining to apply if
	 * the default one is not appropriated.
	 *

	 *
	 * For example:
	 *
	 *

	 *
	 * 	background: url(...);
	 * 	--inline-image: base64;
	 *
	 *

	 *
	 * It forces to use base64 inlining for this image.
	 *
	 *
	 *

	 * You can also skip inlining by using "skip" value:
	 *
	 *

	 *
	 * 	background: url(...);
	 * 	--inline-image: skip;
	 *
	 *

	 *
	 *

	 * It is possible to have several images to inline for the same CSS rule.
	 * Therefore, you can indicate an inline mode per image:
	 *
	 *

	 *
	 * .rule {
	 * 		background: url('path/to/top.png'), url('path/to/bottom.gif');
	 * 		list-style-image: url('path/to/list.gif');
	 * 		cursor: url('path/to/cursor.png');
	 * 		--inline-image: top=attach bottom=base64 list=skip;
	 * }
	 *
	 *

	 *
	 * {@code --inline-image} indicates that:
	 *

	 *
Image 'path/to/top.png' should be inlined using {@code attach}
	 * mode

	 *
Image 'path/to/bottom.gif' should be inlined using {@code base64}
	 * mode

	 *
Image 'path/to/list.gif' should not be inlined

	 *

	 *

	 *
	 * As nothing is specified for 'path/to/cursor.png', the default inline mode
	 * is used.
	 *
	 * NOTE: Only the name is provided but you can also target
	 * an image by providing any matching path
	 * ({@code --inline-image: to/top.png=attach} also targets 'top' image).
	 * This can be useful if you have several images with the same name but in
	 * different folders.
	 *
	 * @see InlineModes
	 */
	public static final String INLINE_MODE_PROPERTY = "--inline-image";

	/**
	 * Property to mark an image as already inlined in order to not process it
	 * again
	 */
	public static final String INLINED_URL_FUNC = "--image-inlined-url";

	/**
	 * Interface for defining an inline mode
	 *
	 * @author Aurélien Baudet
	 *
	 */
	public interface InlineMode {
		/**
		 * The inline mode value
		 *
		 * @return inline mode value
		 */
		String mode();

		/**
		 * Indicates if the mode is the same as the current mode.
		 *
		 * @param mode
		 *            the mode to check if same
		 * @return true if same value, false otherwise
		 */
		boolean is(String mode);
	}

	/**
	 * Provide predefined inline modes
	 *
	 * @author Aurélien Baudet
	 *
	 */
	public enum InlineModes implements InlineMode {
		/**
		 * Attach the image to the email and references it in the HTML using a
		 * Content-ID (CID).
		 */
		ATTACH("attach"),
		/**
		 * Encode the image content to a base64 string that is directly used by
		 * image {@code src} attribute
		 */
		BASE64("base64"),
		/**
		 * Do not inline the image
		 */
		SKIP("skip");

		private final String mode;

		InlineModes(String mode) {
			this.mode = mode;
		}

		@Override
		public String mode() {
			return mode;
		}

		@Override
		public boolean is(String mode) {
			return this.mode.equals(mode);
		}
	}

	private CssImageInlinerConstants() {
		super();
	}
}


text:
package net.nemerosa.ontrack.extension.stash;

import net.nemerosa.ontrack.extension.api.UserMenuExtension;
import net.nemerosa.ontrack.extension.support.AbstractExtension;
import net.nemerosa.ontrack.model.security.GlobalFunction;
import net.nemerosa.ontrack.model.security.GlobalSettings;
import net.nemerosa.ontrack.model.support.Action;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Management of Stash configurations available in the user menu.
 */
@Component
public class StashUserMenuExtension extends AbstractExtension implements UserMenuExtension {

    @Autowired
    public StashUserMenuExtension(StashExtensionFeature feature) {
        super(feature);
    }

    @Override
    public Class<? extends GlobalFunction> getGlobalFunction() {
        return GlobalSettings.class;
    }

    @Override
    public Action getAction() {
        return Action.of("stash-configurations", "BitBucket configurations", "configurations");
    }
}


text:
<link rel="import" href="bower_components/polymer/polymer.html">

<link rel="import" href="conman-summary.html">
<link rel="import" href="na-elements.html">
<link rel="import" href="bower_components/app-storage/app-indexeddb-mirror/app-indexeddb-mirror.html">
<link rel="import" href="bower_components/polymerfire/polymerfire.html">

<link rel="import" href="bower_components/app-route/app-route.html">
<link rel="import" href="bower_components/app-route/app-location.html">

<dom-module id="conman-app">
  <template>
    <style include="note-app-shared-styles"></style>
    <app-location route="{{route}}"></app-location>
    <app-route
        route="{{route}}"
        pattern="/:con/:page"
        data="{{data}}"
        tail="{{tail}}"></app-route>

    <conman-toolbar
        signed-in="[[signedIn]]"
        on-sign-out="signOut"></conman-toolbar>
    <na-login
        on-sign-in="signIn"
        signed-in="[[signedIn]]"
        disabled="[[!online]]"></na-login>
    <firebase-auth
        id="auth"
        app-name="con-man"
        provider="google"
        signed-in="{{signedIn}}"
        user="{{user}}"> </firebase-auth>

    <!-- these should be created lazily?? -->
    <firebase-document
        app-name="con-man"
        path="/con/{{data.con}}/summary"
        data="{{remoteSummary}}"></firebase-document>
    <app-indexeddb-mirror
        session="bob"
        key="{{data.con}}/summary"
        data="{{remoteSummary}}"
        persisted-data="{{summary}}"></app-indexeddb-mirror>

    <conman-summary summary="[[summary]]"></conman-summary>
  </template>
  <script>
    Polymer({
      is: 'conman-app',
      behaviors: [Polymer.NoteAppBehavior],
      signIn: function() {
        this.$.auth.signInWithPopup();
      },
    });
  </script>
</dom-module>


text:
FROM unit9/base:latest
MAINTAINER Kamil Cholewiński <kamil.cholewinski@unit9.com>

# Dependencies
RUN apt-get update && \
    apt-get install --yes --no-install-recommends \
            python-all-dev \
            python-pip \
            python-wheel \
            uwsgi-plugin-python \
    && rm -rf /var/cache/apt /var/lib/apt/lists

# Create the space for the app
RUN mkdir /app
WORKDIR /app

# Add "app" user to run uWSGI as
RUN adduser --system --no-create-home --disabled-login --group app


text:
App.FavouritesController = Ember.ArrayController.extend({
    needs: ['flash']
});


text:
namespace net {

SSLClientSocket::SSLClientSocket()
    : was_npn_negotiated_(false),
      was_spdy_negotiated_(false),
      protocol_negotiated_(kProtoUnknown),
      channel_id_sent_(false),
      signed_cert_timestamps_received_(false),
      stapled_ocsp_response_received_(false) {
}

// static
NextProto SSLClientSocket::NextProtoFromString(
    const std::string& proto_string) {
  if (proto_string == "http1.1" || proto_string == "http/1.1") {
    return kProtoHTTP11;
  } else if (proto_string == "spdy/2") {
    return kProtoDeprecatedSPDY2;
  } else if (proto_string == "spdy/3") {
    return kProtoSPDY3;
  } else if (proto_string == "spdy/3.1") {
    return kProtoSPDY31;
  } else if (proto_string == "h2-12") {
    // This is the HTTP/2 draft 12 identifier. For internal
    // consistency, HTTP/2 is named SPDY4 within Chromium.
    return kProtoSPDY4;
  } else if (proto_string == "quic/1+spdy/3") {
    return kProtoQUIC1SPDY3;
  } else {
    return kProtoUnknown;
  }
}

// static
const char* SSLClientSocket::NextProtoToString(NextProto next_proto) {
  switch (next_proto) {
    case kProtoHTTP11:
      return "http/1.1";
    case kProtoDeprecatedSPDY2:
      return "spdy/2";
    case kProtoSPDY3:
      return "spdy/3";
    case kProtoSPDY31:
      return "spdy/3.1";
    case kProtoSPDY4:
      // This is the HTTP/2 draft 12 identifier. For internal
      // consistency, HTTP/2 is named SPDY4 within Chromium.
      return "h2-12";
    case kProtoQUIC1SPDY3:
      return "quic/1+spdy/3";
    case kProtoUnknown:
      break;
  }
  return "unknown";
}

// static
const char* SSLClientSocket::NextProtoStatusToString(
    const SSLClientSocket::NextProtoStatus status) {
  switch (status) {
    case kNextProtoUnsupported:
      return "unsupported";
    case kNextProtoNegotiated:
      return "negotiated";
    case kNextProtoNoOverlap:
      return "no-overlap";
  }
  return NULL;
}

// static
std::string SSLClientSocket::ServerProtosToString(
    const std::string& server_protos) {
  const char* protos = server_protos.c_str();
  size_t protos_len = server_protos.length();
  std::vector<std::string> server_protos_with_commas;
  for (size_t i = 0; i < protos_len; ) {
    const size_t len = protos[i];
    std::string proto_str(&protos[i + 1], len);
    server_protos_with_commas.push_back(proto_str);
    i += len + 1;
  }
  return JoinString(server_protos_with_commas, ',');
}

bool SSLClientSocket::WasNpnNegotiated() const {
  return was_npn_negotiated_;
}

NextProto SSLClientSocket::GetNegotiatedProtocol() const {
  return protocol_negotiated_;
}

bool SSLClientSocket::IgnoreCertError(int error, int load_flags) {
  if (error == OK || load_flags & LOAD_IGNORE_ALL_CERT_ERRORS)
    return true;

  if (error == ERR_CERT_COMMON_NAME_INVALID &&
      (load_flags & LOAD_IGNORE_CERT_COMMON_NAME_INVALID))
    return true;

  if (error == ERR_CERT_DATE_INVALID &&
      (load_flags & LOAD_IGNORE_CERT_DATE_INVALID))
    return true;

  if (error == ERR_CERT_AUTHORITY_INVALID &&
      (load_flags & LOAD_IGNORE_CERT_AUTHORITY_INVALID))
    return true;

  return false;
}

bool SSLClientSocket::set_was_npn_negotiated(bool negotiated) {
  return was_npn_negotiated_ = negotiated;
}

bool SSLClientSocket::was_spdy_negotiated() const {
  return was_spdy_negotiated_;
}

bool SSLClientSocket::set_was_spdy_negotiated(bool negotiated) {
  return was_spdy_negotiated_ = negotiated;
}

void SSLClientSocket::set_protocol_negotiated(NextProto protocol_negotiated) {
  protocol_negotiated_ = protocol_negotiated;
}

bool SSLClientSocket::WasChannelIDSent() const {
  return channel_id_sent_;
}

void SSLClientSocket::set_channel_id_sent(bool channel_id_sent) {
  channel_id_sent_ = channel_id_sent;
}

void SSLClientSocket::set_signed_cert_timestamps_received(
    bool signed_cert_timestamps_received) {
  signed_cert_timestamps_received_ = signed_cert_timestamps_received;
}

void SSLClientSocket::set_stapled_ocsp_response_received(
    bool stapled_ocsp_response_received) {
  stapled_ocsp_response_received_ = stapled_ocsp_response_received;
}

// static
void SSLClientSocket::RecordChannelIDSupport(
    ServerBoundCertService* server_bound_cert_service,
    bool negotiated_channel_id,
    bool channel_id_enabled,
    bool supports_ecc) {
  // Since this enum is used for a histogram, do not change or re-use values.
  enum {
    DISABLED = 0,
    CLIENT_ONLY = 1,
    CLIENT_AND_SERVER = 2,
    CLIENT_NO_ECC = 3,
    CLIENT_BAD_SYSTEM_TIME = 4,
    CLIENT_NO_SERVER_BOUND_CERT_SERVICE = 5,
    DOMAIN_BOUND_CERT_USAGE_MAX
  } supported = DISABLED;
  if (negotiated_channel_id) {
    supported = CLIENT_AND_SERVER;
  } else if (channel_id_enabled) {
    if (!server_bound_cert_service)
      supported = CLIENT_NO_SERVER_BOUND_CERT_SERVICE;
    else if (!supports_ecc)
      supported = CLIENT_NO_ECC;
    else if (!server_bound_cert_service->IsSystemTimeValid())
      supported = CLIENT_BAD_SYSTEM_TIME;
    else
      supported = CLIENT_ONLY;
  }
  UMA_HISTOGRAM_ENUMERATION("DomainBoundCerts.Support", supported,
                            DOMAIN_BOUND_CERT_USAGE_MAX);
}

// static
bool SSLClientSocket::IsChannelIDEnabled(
    const SSLConfig& ssl_config,
    ServerBoundCertService* server_bound_cert_service) {
  if (!ssl_config.channel_id_enabled)
    return false;
  if (!server_bound_cert_service) {
    DVLOG(1) << "NULL server_bound_cert_service_, not enabling channel ID.";
    return false;
  }
  if (!crypto::ECPrivateKey::IsSupported()) {
    DVLOG(1) << "Elliptic Curve not supported, not enabling channel ID.";
    return false;
  }
  if (!server_bound_cert_service->IsSystemTimeValid()) {
    DVLOG(1) << "System time is not within the supported range for certificate "
                "generation, not enabling channel ID.";
    return false;
  }
  return true;
}

}  // namespace net


text:
<?php

namespace Coyote\Http\Controllers\Adm\Forum;

use Boduch\Grid\Source\EloquentSource;
use Coyote\Forum\Reason;
use Coyote\Http\Controllers\Adm\BaseController;
use Coyote\Http\Forms\ForumReasonsForm;
use Coyote\Http\Grids\Adm\Forum\ReasonsGrid;

class ReasonsController extends BaseController
{
    public function __construct()
    {
        parent::__construct();

        $this->breadcrumb->push([
            'Forum' => route('adm.forum.categories'),
            'Powody moderacji' => route('adm.forum.reasons')
        ]);
    }

    /**
     * @return \Illuminate\View\View
     */
    public function index()
    {
        $grid = $this
            ->gridBuilder()
            ->createGrid(ReasonsGrid::class)
            ->setSource(new EloquentSource(new Reason()))
            ->setEnablePagination(false);

        return $this->view('adm.forum.reasons.home')->with('grid', $grid);
    }

    /**
     * @param int|null $id
     * @return \Illuminate\View\View
     */
    public function edit($id = null)
    {
        $reason = Reason::findOrNew($id);
        $this->breadcrumb->push($reason->name ?? 'Dodaj nowy');

        return $this->view('adm.forum.reasons.save')->with('form', $this->getForm($reason));
    }

    /**
     * @param int|null $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function save($id = null)
    {
        $reason = Reason::findOrNew($id);

        $form = $this->getForm($reason);
        $form->validate();

        $reason->fill($form->all())->save();

        return redirect()->route('adm.forum.reasons')->with('success', 'Zmiany zostały zapisane.');
    }

    /**
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function delete($id)
    {
        Reason::destroy($id);

        return redirect()->route('adm.forum.reasons')->with('success', 'Rekord został usunięty.');
    }

    /**
     * @param Reason $reason
     * @return \Coyote\Services\FormBuilder\Form
     */
    private function getForm($reason)
    {
        return $this->createForm(ForumReasonsForm::class, $reason);
    }
}


text:
<?php

/**
 * sfGuardForgotPassword form base class.
 *
 * @method sfGuardForgotPassword getObject() Returns the current form's model object
 *
 * @package    sf_sandbox
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormGeneratedTemplate.php 29553 2010-05-20 14:33:00Z Kris.Wallsmith $
 */
abstract class BasesfGuardForgotPasswordForm extends BaseFormDoctrine
{
  public function setup()
  {
    $this->setWidgets(array(
      'id'         => new sfWidgetFormInputHidden(),
      'user_id'    => new sfWidgetFormDoctrineChoice(array('model' => $this->getRelatedModelName('SfGuardUser'), 'add_empty' => false)),
      'unique_key' => new sfWidgetFormInputText(),
      'expires_at' => new sfWidgetFormDateTime(),
      'created_at' => new sfWidgetFormDateTime(),
      'updated_at' => new sfWidgetFormDateTime(),
    ));

    $this->setValidators(array(
      'id'         => new sfValidatorChoice(array('choices' => array($this->getObject()->get('id')), 'empty_value' => $this->getObject()->get('id'), 'required' => false)),
      'user_id'    => new sfValidatorDoctrineChoice(array('model' => $this->getRelatedModelName('SfGuardUser'))),
      'unique_key' => new sfValidatorString(array('max_length' => 255, 'required' => false)),
      'expires_at' => new sfValidatorDateTime(),
      'created_at' => new sfValidatorDateTime(),
      'updated_at' => new sfValidatorDateTime(),
    ));

    $this->widgetSchema->setNameFormat('sf_guard_forgot_password[%s]');

    $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);

    $this->setupInheritance();

    parent::setup();
  }

  public function getModelName()
  {
    return 'sfGuardForgotPassword';
  }

}


text:
using AutoMapper;
using SpaJumpstart.DataContracts.Dtos;
using SpaJumpstart.Domain.Entities;
using SpaJumpstart.WebServices.AssemblyReferences;
using System;
using System.Linq;

namespace SpaJumpstart.WebServices.Mappings.AutoMappings
{
    public class MappedDefinitions
    {
        public void Init()
        {
            RegisterMappings();
        }

        private void RegisterMappings()
        {
            var entities =
                ReferencedAssemblies.Domain.
                    GetTypes().Where(x => typeof(IEntity).IsAssignableFrom(x)).ToList();

            var dtos =
                ReferencedAssemblies.Dto.
                    GetTypes().Where(x => typeof(IDto).IsAssignableFrom(x)).ToList();

            foreach (var entity in entities)
            {
                if (Mapper.GetAllTypeMaps().FirstOrDefault(m => m.DestinationType == entity || m.SourceType == entity) == null)
                {
                    var matchingDto =
                        dtos.FirstOrDefault(x => x.Name.Replace("Dto", string.Empty).Equals(entity.Name, StringComparison.InvariantCultureIgnoreCase));

                    if (matchingDto != null)
                    {
                        Mapper.CreateMap(entity, matchingDto);
                        Mapper.CreateMap(matchingDto, entity);
                    }
                }
            }

        }
    }
}


text:
layout: project
type: project
image: images/artcompanion.png
title: Art.Companion
date: 2016
labels:
  - mySQL
  - PHP
  - HTML
  - CSS
  - Javascript
summary: Art.Companion is web application I created for artists to keep track of their own artwork, their favorite artists and their artwork, as well as artwork online. It is PHP based and uses PHP, HTML, and Javascript.
---

Here is the [Project Link](https://github.com/gviloria/art.companion)

Art.Companion is web application I created for artists to keep track of their own artwork, their favorite artists,
as well as artwork online. It is PHP based and uses PHP, HTML, and Javascript.

This was made at the end of my FALL 2016 semester. I decided I wanted to use my newly gained knowledge from Software Engineering and Database Management.

If you have any questions regarding the web application, feel free to send me an email!

Here are screenshots of my web application:

## Landing Page

## My Art Gallery Page

## Manage My Art Page

## Add to My Art Page

## Favorite Artists Page

## Manage Favorite Artists Page

## Add Favorite Artist Page

## Favorite Art Page

## Manage Favorite Art Page

## Add Favorite Art Page


text:
.color-myaccount{color:#333}
#block-history table#order-list thead th{color:#FFF;text-align:left;padding:0 10px}
#block-history table#order-list tbody tr td{background-color:#FFF}
#block-history table#order-list td.history_link{text-align:left;white-space:nowrap}
#block-history #block-order-detail{padding-top:10px}
#block-history table.detail_step_by_step th{text-align:left!important}
#block-history #block-order-detail th{padding:0 10px;text-align:left}
#block-history #block-order-detail p{padding-left:0;padding-right:0}
#order-detail-content{clear:both;margin-top:1.5em}
#order-detail-content tbody tr{height:3em}
#order-detail-content tbody tr td{text-align:left}
#order-detail-content table td input.order_qte_input{display:none}
#order-detail-content table td span.order_qte_span{background:none;display:block;width:100%;border:none}
#block-history #block-order-detail h4{padding-bottom:5px}
#block-history #block-order-detail #sendOrderMessage p{padding:0 4px 0 0 !important}
#block-history #block-order-detail textarea{margin:0 auto;padding:10px;width:96%}
#ordermsg textarea{margin:0;padding:0;width:528px}
#block-history table#order-list,#order-detail-content tfoot td,#order-detail-content table td.order_cb input{border:none;background:none}
#order-detail-content tfoot td span{margin-left:15px}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>se.vidstige</groupId>
    <artifactId>jadb</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <url>https://github.com/vidstige/jadb</url>

    <packaging>jar</packaging>

    <licenses>
        <license>
            <name>The Apache License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
        </license>
    </licenses>

    <developers>
        <developer>
            <id>vidstige</id>
            <name>Samuel Carlsson</name>
            <email>samuel.carlsson@gmai.com</email>
            <url>https://github.com/vidstige</url>
        </developer>
    </developers>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.build.timestamp.format>yyyy-MM-dd'T'HH_mm'Z'</maven.build.timestamp.format>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <java.version>1.8</java.version>
        <junit.version>4.12</junit.version>
        <log4j.version>1.2.17</log4j.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <scm>
        <url>scm:git:git@github.com:vidstige/jadb.git</url>
        <connection>scm:git:git@github.com:vidstige/jadb.git</connection>
        <developerConnection>scm:git:git@github.com:vidstige/jadb.git</developerConnection>
        <tag>HEAD</tag>
    </scm>

</project>


text:
layout: post
title: ASP.NET MVC presentations
date: 2009-04-10T07:24:00.001Z
author: Marcus Hammarberg
tags:
  - ASP.NET MVC
modified_time: 2009-04-10T07:24:07.879Z
blogger_id: tag:blogger.com,1999:blog-36533086.post-2218956877799670681
blogger_orig_url: http://www.marcusoft.net/2009/04/aspnet-mvc-presentations.html
---

Found these two great presentations surronding ASP.NET MVC.

- File|New
    -> Company: Creating NerdDinner.com with Microsoft ASP.NET Model View
    Controller (MVC) - really funny too...
- Microsoft ASP.NET Model View Controller (MVC): Ninja on
    Fire Black Belt Tips - a bit slow presentation but some real
    nuggest are to be found

I haven't seen them straight through yet - but they promise a great
deal.


text:
package com.hearthsim.card.classic.minion.rare;

import com.hearthsim.card.minion.Minion;
import com.hearthsim.exception.HSException;
import com.hearthsim.model.PlayerModel;
import com.hearthsim.model.PlayerSide;
import com.hearthsim.util.tree.HearthTreeNode;

public class MasterSwordsmith extends Minion {

    public MasterSwordsmith() {
        super();
    }

    @Override
    public HearthTreeNode endTurn(PlayerSide thisMinionPlayerIndex, HearthTreeNode boardModel) throws HSException {
        PlayerModel currentPlayer = boardModel.data_.modelForSide(PlayerSide.CURRENT_PLAYER);
        int numMinions = currentPlayer.getNumMinions();
        if (thisMinionPlayerIndex == PlayerSide.CURRENT_PLAYER && numMinions > 1) {
            Minion buffTargetMinion = currentPlayer.getCharacter((int) (Math.random() * numMinions) + 1);
            while (buffTargetMinion == this) {
                buffTargetMinion = currentPlayer.getCharacter((int)(Math.random() * numMinions) + 1);
            }
            buffTargetMinion.addAttack((byte)1);
        }
        return super.endTurn(thisMinionPlayerIndex, boardModel);
    }
}