text:
from datetime import datetime
from dateutil.tz import tzutc
import json
from klein import Klein
from math import ceil
import os
import re
import treq
from twisted.internet.defer import inlineCallbacks, returnValue
import uuid
from vumi.application import ApplicationWorker
from vumi.components.session import SessionManager
from vumi.config import ConfigDict, ConfigInt, ConfigText
from vumi.message import TransportUserMessage
from vumi.persist.txredis_manager import TxRedisManager
import xml.etree.ElementTree as ET

from vxtwinio.twiml_parser import TwiMLParser

c2s = re.compile('(?!^)([A-Z+])')

def camel_to_snake(string):
    return c2s.sub(r'_\1', string).lower()

def convert_dict_keys(dct):
    res = {}
    for key, value in dct.iteritems():
        if isinstance(value, dict):
            res[camel_to_snake(key)] = convert_dict_keys(value)
        else:
            res[camel_to_snake(key)] = value
    return res

class SessionIDLookup(object):
    def __init__(self, redis_manager, expiry_time, namespace):
        self._redis_manager = redis_manager
        self._namespace = namespace
        self._expiry_time = expiry_time

    def _get_key(self, message_id):
        return "%s:%s" % (self._namespace, message_id)

    def set_id(self, message_id, address):
        return self._redis_manager.setex(
            self._get_key(message_id), self._expiry_time, address)

    def get_address(self, message_id):
        return self._redis_manager.get(self._get_key(message_id))

    def delete_id(self, message_id):
        return self._redis_manager.delete(self._get_key(message_id))

class TwilioAPIConfig(ApplicationWorker.CONFIG_CLASS):
    """Config for the Twilio API worker"""
    web_path = ConfigText(
        "The path the worker should expose the API on",
        required=True, static=True)
    web_port = ConfigInt(
        "The port the worker should open for the API",
        required=True, static=True)
    api_version = ConfigText(
        "The version of the API, used in the api URL",
        default="2010-04-01", static=True)
    redis_manager = ConfigDict("Redis config.", required=True, static=True)
    redis_timeout = ConfigInt(
        "Expiry time in seconds for redis keys",
        default=3600, static=True)
    session_lookup_namespace = ConfigText(
        "The redis namespace to use for storing session ID lookups",
        default="session_id", static=True)
    client_path = ConfigText(
        "The web path that the API worker should send requests to",
        required=True)
    client_method = ConfigText(
        "The HTTP method that the API worker uses when sending requests",
        default='POST')
    status_callback_path = ConfigText(
        "The web path that the API sends a request to when the call ends",
        default=None)
    status_callback_method = ConfigText(
        "The HTTP method to use when sending the callback status",
        default='POST')

class TwilioAPIWorker(ApplicationWorker):
    """Emulates the Twilio API to use vumi as if it was Twilio"""
    CONFIG_CLASS = TwilioAPIConfig

    @inlineCallbacks
    def setup_application(self):
        """Application specific setup"""
        self.app_config = self.get_static_config()
        self.server = TwilioAPIServer(self, self.app_config.api_version)
        path = os.path.join(
            self.app_config.web_path, self.app_config.api_version)
        self.webserver = self.start_web_resources([
            (self.server.app.resource(), path)],
            self.app_config.web_port)
        redis = yield TxRedisManager.from_config(self.app_config.redis_manager)
        self.session_manager = SessionManager(
            redis, self.app_config.redis_timeout)
        self.session_lookup = SessionIDLookup(
            redis, self.app_config.redis_timeout,
            self.app_config.session_lookup_namespace)

    @inlineCallbacks
    def teardown_application(self):
        """Clean-up of setup done in `setup_application`"""
        yield self.webserver.loseConnection()
        yield self.session_manager.stop()

    def _http_request(self, url='', method='GET', data={}):
        return treq.request(method, url, persistent=False, data=data)

    def _request_data_from_session(self, session):
        return {
            'CallSid': session['CallId'],
            'AccountSid': session['AccountSid'],
            'From': session['From'],
            'To': session['To'],
            'CallStatus': session['Status'],
            'ApiVersion': self.app_config.api_version,
            'Direction': session['Direction'],
        }

    @inlineCallbacks
    def _get_twiml_from_client(self, session, data=None):
        if data is None:
            data = self._request_data_from_session(session)
        twiml_raw = yield self._http_request(
            session['Url'], session['Method'], data)
        if twiml_raw.code < 200 or twiml_raw.code >= 300:
            twiml_raw = yield self._http_request(
                session['FallbackUrl'], session['FallbackMethod'], data)
        twiml_raw = yield twiml_raw.content()
        twiml_parser = TwiMLParser(session['Url'])
        returnValue(twiml_parser.parse(twiml_raw))

    @inlineCallbacks
    def _handle_connected_call(
            self, session_id, session, status='in-progress', twiml=None):
        # TODO: Support sending ForwardedFrom parameter
        # TODO: Support sending CallerName parameter
        # TODO: Support sending geographic data parameters
        session['Status'] = status
        self.session_manager.save_session(session_id, session)
        if twiml is None:
            twiml = yield self._get_twiml_from_client(session)
        for verb in twiml:
            if verb.name == "Play":
                # TODO: Support loop and digit attributes
                yield self._send_message(verb.nouns[0], session)
            elif verb.name == "Hangup":
                yield self._send_message(
                    None, session, TransportUserMessage.SESSION_CLOSE)
                yield self.session_manager.clear_session(session_id)
                break
            elif verb.name == "Gather":
                # TODO: Support timeout and numDigits attributes
                msgs = []
                for subverb in verb.nouns:
                    # TODO: Support Say and Pause subverbs
                    if subverb.name == "Play":
                        msgs.append({'speech_url': subverb.nouns[0]})
                session['Gather_Action'] = verb.attributes['action']
                session['Gather_Method'] = verb.attributes['method']
                yield self.session_manager.save_session(session_id, session)
                if len(msgs) == 0:
                    msgs.append({'speech_url': None})
                msgs[-1]['wait_for'] = verb.attributes['finishOnKey']
                for msg in msgs:
                    yield self._send_message(
                        msg['speech_url'], session,
                        wait_for=msg.get('wait_for'))
                break

    def _send_message(self, url, session, session_event=None, wait_for=None):
        helper_metadata = {'voice': {}}
        if url is not None:
            helper_metadata['voice']['speech_url'] = url
        if wait_for is not None:
            helper_metadata['voice']['wait_for'] = wait_for

        return self.send_to(
            session['To'], None,
            from_addr=session['From'],
            session_event=session_event,
            to_addr_type=TransportUserMessage.AT_MSISDN,
            from_addr_type=TransportUserMessage.AT_MSISDN,
            helper_metadata=helper_metadata)

    @inlineCallbacks
    def consume_user_message(self, message):
        # At the moment there is no way to determine whether or not a message
        # is the result of a wait_for or just a single digit, so if the Gather
        # data exists inside the current session data, then we assume that it
        # is the result of a Gather
        # TODO: Fix this
        session = yield self.session_manager.load_session(message['from_addr'])
        if session.get('Gather_Action') and session.get('Gather_Method'):
            data = self._request_data_from_session(session)
            data['Digits'] = message['content']
            twiml = yield self._get_twiml_from_client({
                'Url': session['Gather_Action'],
                'Method': session['Gather_Method'],
                'Fallback_Url': None,
                'Fallback_Method': None, },
                data=data)
            yield self._handle_connected_call(
                message['from_addr'], session, twiml=twiml)

    @inlineCallbacks
    def consume_ack(self, event):
        message_id = event['user_message_id']
        session_id = yield self.session_lookup.get_address(message_id)
        yield self.session_lookup.delete_id(message_id)
        session = yield self.session_manager.load_session(session_id)

        if session['Status'] == 'queued':
            yield self._handle_connected_call(session_id, session)

    @inlineCallbacks
    def consume_nack(self, event):
        message_id = event['user_message_id']
        session_id = yield self.session_lookup.get_address(message_id)
        yield self.session_lookup.delete_id(message_id)
        session = yield self.session_manager.load_session(session_id)

        if session['Status'] == 'queued':
            yield self._handle_connected_call(
                session_id, session, status='failed')

    @inlineCallbacks
    def new_session(self, message):
        yield self.session_lookup.set_id(
            message['message_id'], message['from_addr'])
        config = yield self.get_config(message)
        session = {
            'CallId': self.server._get_sid(),
            'AccountSid': self.server._get_sid(),
            'From': message['from_addr'],
            'To': message['to_addr'],
            'Status': 'in-progress',
            'Direction': 'inbound',
            'Url': config.client_path,
            'Method': config.client_method,
            'StatusCallback': config.status_callback_path,
            'StatusCallbackMethod': config.status_callback_method,
        }
        yield self.session_manager.create_session(
            message['from_addr'], **session)

        twiml = yield self._get_twiml_from_client(session)
        for verb in twiml:
            if verb.name == "Play":
                yield self.reply_to(message, None, helper_metadata={
                    'voice': {
                        'speech_url': verb.nouns[0],
                        }
                    })
            elif verb.name == "Hangup":
                yield self.reply_to(
                    message, None,
                    session_event=TransportUserMessage.SESSION_CLOSE)
                yield self.session_manager.clear_session(message['from_addr'])
                break
            elif verb.name == "Gather":
                # TODO: Support timeout and numDigits attributes
                msgs = []
                for subverb in verb.nouns:
                    # TODO: Support Say and Pause subverbs
                    if subverb.name == "Play":
                        msgs.append({'speech_url': subverb.nouns[0]})
                session['Gather_Action'] = verb.attributes['action']
                session['Gather_Method'] = verb.attributes['method']
                yield self.session_manager.save_session(
                    message['from_addr'], session)
                if len(msgs) == 0:
                    msgs.append({'speech_url': None})
                msgs[-1]['wait_for'] = verb.attributes['finishOnKey']
                for msg in msgs:
                    yield self.reply_to(message, None, helper_metadata={
                        'voice': {
                            'speech_url': msg.get('speech_url'),
                            'wait_for': msg.get('wait_for'),
                        }})
                break

    @inlineCallbacks
    def close_session(self, message):
        # TODO: Implement call duration parameters
        # TODO: Implement recording parameters
        session = yield self.session_manager.load_session(message['from_addr'])
        yield self.session_manager.clear_session(message['from_addr'])
        url = session.get('StatusCallback')

        if url and url != 'None':
            session['Status'] = 'completed'
            data = self._request_data_from_session(session)
            yield self._http_request(
                session['StatusCallback'], session['StatusCallbackMethod'],
                data)

class TwilioAPIUsageException(Exception):
    """Called when in incorrect query is sent to the API"""
    def __init__(self, message, format_='xml'):
        super(TwilioAPIUsageException, self).__init__(message)
        self.format_ = format_

class Response(object):
    """Base Response object used for HTTP responses"""
    name = 'Response'

    def __init__(self, **kw):
        self._data = kw

    @property
    def xml(self):
        response = ET.Element("TwilioResponse")
        root = ET.SubElement(response, self.name)

        def format_xml_rec(dct, root):
            for key, value in dct.iteritems():
                if isinstance(value, dict):
                    sub = ET.SubElement(root, key)
                    format_xml_rec(value, sub)
                else:
                    sub = ET.SubElement(root, key)
                    sub.text = value
            return root

        format_xml_rec(self._data, root)
        return response

    def format_xml(self):
        return ET.tostring(self.xml)

    @property
    def dictionary(self):
        return convert_dict_keys(self._data)

    def format_json(self):
        return json.dumps(self.dictionary)

    @property
    def sid(self):
        return self._data.get("Sid")

class ListResponse(object):
    """Used for responding to API requests with a paginated list"""
    name = 'ListResponse'

    def __init__(self, items):
        """
        :param int pagesize: The number of elements in each returned page
        :param list items: A list of Response items to be returned
        """
        self.items = sorted(items, key=lambda k: k.sid)

    def _get_page_attributes(self, uri, page, pagesize, aftersid):
        pagesize = min(pagesize, 1000)
        numpages = int(ceil(len(self.items) * 1.0 / pagesize)) or 1
        if aftersid is not None:
            start = (
                n for n, i in enumerate(self.items) if i.sid > aftersid).next()
            page = int(start/pagesize)
        else:
            start = page * pagesize
        page_items = self.items[start:start + pagesize]
        base_uri = uri.split('?')[0]
        if len(page_items) < pagesize:
            nextpageuri = None
        else:
            nextpageuri = "%s?Page=%s&PageSize=%s&AfterSid=%s" % (
                base_uri, page + 1, pagesize, page_items[-1].sid)
        if page == 0:
            prevpageuri = None
        else:
            prevpageuri = "%s?Page=%s&PageSize=%s" % (
                base_uri, page-1, pagesize)
        last = numpages - 1

        attributes = {
            'page': page,
            'num_pages': numpages,
            'page_size': pagesize,
            'total': len(self.items),
            'start': start,
            'end': start + len(page_items),
            'uri': uri,
            'first_page_uri': '%s?Page=%s&PageSize=%s' % (
                base_uri, page, pagesize),
            'next_page_uri': nextpageuri,
            'previous_page_uri': prevpageuri,
            'last_page_uri': '%s?Page=%s&PageSize=%s' % (
                base_uri, last, pagesize),
        }

        return (attributes, page_items)

    def _format_attributes_for_xml(self, dic):
        """XML attributes must be strings"""
        ret = {}
        for key, value in dic.iteritems():
            if value is None:
                value = ''
            ret[key.replace('_', '')] = str(value)
        return ret

    def format_xml(self, uri, page=0, pagesize=50, aftersid=None):
        response = ET.Element("TwilioResponse")
        root = ET.SubElement(response, self.name)

        root.attrib, page_items = self._get_page_attributes(
            uri, page, pagesize, aftersid)
        root.attrib = self._format_attributes_for_xml(root.attrib)

        for obj in page_items:
            [item] = obj.xml
            root.append(item)

        return ET.tostring(response)

    def format_json(self, uri, page=0, pagesize=50, aftersid=None):
        attrib, page_items = self._get_page_attributes(
            uri, page, pagesize, aftersid)
        page_items = [item.dictionary for item in page_items]
        attrib[camel_to_snake(self.name)] = page_items
        return json.dumps(attrib)

class Applications(ListResponse):
    """Used for responding with a list of Applications for the Applications
    resource"""
    name = 'Applications'

    def __init__(self, url, applications):
        self.url = url
        super(Applications, self).__init__(applications)

    def format_xml(self):
        return super(Applications, self).format_xml(self.url)

    def format_json(self):
        return super(Applications, self).format_json(self.url)

class Application(Response):
    """A single Application object"""
    name = 'Application'

class Error(Response):
    """Error HTTP response object, returned for incorred API queries"""
    name = 'Error'

    def __init__(self, error_type, error_message):
        super(Error, self).__init__(
            error_type=error_type, error_message=error_message)

    @classmethod
    def from_exception(cls, exception):
        return cls(exception.__class__.__name__, exception.message)

class Version(Response):
    """Version HTTP response object, returned for root resource"""
    name = 'Version'

    def __init__(self, name, uri, **kwargs):
        super(Version, self).__init__(
            Name=name, Uri=uri, SubresourceUris=kwargs)

class Call(Response):
    """Call HTTP response object, returned for the Calls resource"""
    name = 'Call'

class TwilioAPIServer(object):
    app = Klein()

    def __init__(self, vumi_worker, version):
        self.vumi_worker = vumi_worker
        self.version = version

    def _format_response(self, request, response, format_):
        format_ = str(format_.lstrip('.').lower()) or 'xml'
        func = getattr(
            response, 'format_' + format_, None)
        if not func:
            raise TwilioAPIUsageException(
                '%r is not a valid request format' % format_)
        request.setHeader('Content-Type', 'application/%s' % format_)
        return func()

    @app.handle_errors(TwilioAPIUsageException)
    def usage_exception(self, request, failure):
        request.setResponseCode(400)
        return self._format_response(
            request, Error.from_exception(failure.value),
            failure.value.format_)

    @app.route('/', defaults={'format_': ''}, methods=['GET'])
    @app.route('/<string:format_>', methods=['GET'])
    def root(self, request, format_):
        version = Version(
            self.version,
            '/%s%s' % (self.version, format_),
            Accounts='/%s/Accounts%s' % (self.version, format_))
        return self._format_response(request, version, format_)

    @app.route(
        '/Accounts/<string:account_sid>/Applications',
        defaults={'format_': ''}, methods=['GET'])
    @app.route(
        '/Accounts/<string:account_sid>/Applications<string:format_>',
        methods=['GET'])
    def get_applications(self, request, account_sid, format_):
        application = Application(
            # Application sid the same as Account sid to ensure consistency
            # between calls.
            Sid=account_sid,
            DateCreated=self._get_timestamp(),
            DateUpdated=self._get_timestamp(),
            AccountSid=account_sid,
            FriendlyName=self._get_field(request, 'FriendlyName'),
            ApiVersion=self.version,
            VoiceUrl=None,
            VoiceMethod='POST',
            VoiceFallbackUrl=None,
            VoiceFallbackMethod='POST',
            StatusCallback=None,
            StatusCallbackMethod=None,
            VoiceCallerIdLookup=False,
            SmsUrl=None,
            SmsMethod='POST',
            SmsFallbackUrl=None,
            SmsFallbackMethod='POST',
            SmsStatusCallback=None,
            Uri='/Accounts/%s/Applications/%s%s' % (
                account_sid, account_sid, format_))
        applications = Applications(request.uri, [application])
        return self._format_response(request, applications, format_)

    @app.route(
        '/Accounts/<string:account_sid>/Calls',
        defaults={'format_': ''},
        methods=['POST'])
    @app.route(
        '/Accounts/<string:account_sid>/Calls<string:format_>',
        methods=['POST'])
    @inlineCallbacks
    def make_call(self, request, account_sid, format_):
        """Making calls endpoint
        https://www.twilio.com/docs/api/rest/making-calls"""
        # TODO: Support ApplicationSid field
        # TODO: Support SendDigits field
        # TODO: Support IfMachine field
        # TODO: Support Timeout field
        # TODO: Support Record field
        fields = self._validate_make_call_fields(request, format_)
        fields['AccountSid'] = account_sid
        fields['CallId'] = self._get_sid()
        fields['DateCreated'] = self._get_timestamp()
        fields['Uri'] = '/%s/Accounts/%s/Calls/%s' % (
            self.version, account_sid, fields['CallId'])
        fields['Status'] = 'queued'
        fields['Direction'] = 'outbound-api'
        message = yield self.vumi_worker.send_to(
            fields['To'], '',
            from_addr=fields['From'],
            session_event=TransportUserMessage.SESSION_NEW,
            to_addr_type=TransportUserMessage.AT_MSISDN,
            from_addr_type=TransportUserMessage.AT_MSISDN
        )
        yield self.vumi_worker.session_lookup.set_id(
            message['message_id'], message['to_addr'])
        yield self.vumi_worker.session_manager.create_session(
            message['to_addr'], **fields)
        returnValue(self._format_response(request, Call(
            **{
                'Sid': fields['CallId'],
                'DateCreated': fields['DateCreated'],
                'DateUpdated': fields['DateCreated'],
                'ParentCallSid': None,
                'AccountSid': account_sid,
                'To': fields['To'],
                'FormattedTo': fields['To'],
                'From': fields['From'],
                'FormattedFrom': fields['From'],
                'PhoneNumberSid': None,
                'Status': fields['Status'],
                'StartTime': None,
                'EndTime': None,
                'Duration': None,
                'Price': None,
                'Direction': fields['Direction'],
                'AnsweredBy': None,
                'ApiVersion': self.version,
                'ForwardedFrom': None,
                'CallerName': None,
                'Uri': '%s%s' % (fields['Uri'], format_),
                'SubresourceUris': {
                    'Notifications': '%s/Notifications%s' % (
                        fields['Uri'], format_),
                    'Recordings': '%s/Recordings%s' % (fields['Uri'], format_),
                }
            }), format_))

    def _get_sid(self):
        return str(uuid.uuid4()).replace('-', '')

    def _get_timestamp(self):
        return datetime.now(tzutc()).strftime('%a, %d %b %Y %H:%M:%S %z')

    def _get_field(self, request, field, default=None):
        return request.args.get(field, [default])[0]

    def _validate_make_call_required_fields(self, request, format_):
        """Validates the required fields as detailed by
        https://www.twilio.com/docs/api/rest/making-calls#post-parameters-required
        """
        fields = {}
        for field in ['From', 'To', 'Url', 'ApplicationSid']:
            fields[field] = self._get_field(request, field)

        for field in ['From', 'To']:
            if not fields[field]:
                raise TwilioAPIUsageException(
                    'Required field %r not supplied' % field, format_)

        if not (fields['Url'] or fields['ApplicationSid']):
            raise TwilioAPIUsageException(
                "Request must have an 'Url' or an 'ApplicationSid' field",
                format_)

        return fields

    def _validate_make_call_optional_fields(self, request, format_):
        """Validates the required fields as detailed by
        https://www.twilio.com/docs/api/rest/making-calls#post-parameters-optional
        """
        fields = {}
        for field, default in [
                ('Method', 'POST'), ('FallbackMethod', 'POST'),
                ('StatusCallbackMethod', 'POST'), ('Timeout', 60),
                ('Record', False)]:
            fields[field] = self._get_field(request, field, default)
        for field in [
                'FallbackUrl', 'StatusCallback', 'SendDigits', 'IfMachine']:
            fields[field] = self._get_field(request, field)

        if fields['SendDigits']:
            if not all(re.match('[0-9#*w]', c) for c in fields['SendDigits']):
                raise TwilioAPIUsageException(
                    "SendDigits value %r is not valid. May only contain the "
                    "characters (0-9), '#', '*' and 'w'" % (
                        fields['SendDigits']),
                    format_)

        valid_fields_IfMachine = [None, 'Continue', 'Hangup']
        if fields['IfMachine'] not in valid_fields_IfMachine:
            raise TwilioAPIUsageException(
                "IfMachine value must be one of %r" % valid_fields_IfMachine,
                format_)

        return fields

    def _validate_make_call_fields(self, request, format_):
        """Validates the fields sent to the request according to
        https://www.twilio.com/docs/api/rest/making-calls"""
        fields = self._validate_make_call_required_fields(request, format_)
        fields.update(
            self._validate_make_call_optional_fields(request, format_))
        return fields


text:
package fixedXOR

import (
	"bytes"
	"encoding/hex"
	"testing"

	"github.com/eseymour/cryptopals/pkg/crypto/xor"
	b "github.com/eseymour/cryptopals/pkg/util/bytes"
)

// TestFixedXOR only tests the case from the challenge. The package
// github.com/eseymour/cryptopals/pkg/crypto/xor has more extensive tests.
func TestFixedXOR(t *testing.T) {

	src := b.Must(hex.DecodeString("1c0111001f010100061a024b53535009181c"))
	key := b.Must(hex.DecodeString("686974207468652062756c6c277320657965"))
	want := b.Must(hex.DecodeString("746865206b696420646f6e277420706c6179"))
	fails := false

	got := make([]byte, len(src))
	err := xor.EncryptFixedKey(got, src, key)
	failed := err != nil

	switch {
	case failed != fails:
		t.Errorf("xor.EncryptFixedKey(%x, %x, %x) failure: %t, want %t", got, src, key, failed, fails)
	case !failed && !bytes.Equal(got, want):
		t.Errorf("xor.EncryptFixedKey(%x, %x, %x) == %x, want %x", got, src, key, got, want)
	}
}

redpajama_set_name: RedPajamaGithub


text:
from control4.algs.alg_params import string2dict
import h5py
import numpy as np
from tabulate import tabulate

def pad_ends(lis):
    maxlen = max(len(li) for li in lis)
    def pad(li,n):
        li = list(li)
        return li + [li[-1]]*(n-len(li))
    return [pad(li,maxlen) for li in lis]

def load_diagnostic_info(hdf):
    metadata = string2dict(hdf["params"]["metadata"].value)

    rows = []
    i_run = hdf["params"]["seed"].value
    cfg_name = str(metadata["cfg_name"])
    test_name = metadata["test_name"]
    script_name = metadata["script_name"]

    for (stat_name,ts) in hdf["diagnostics"].items():
        rows.append((cfg_name, test_name, script_name, stat_name, i_run, ts.value))
    columns = ["cfg_name","test_name","script_name","stat_name","i_run","timeseries"]
    return rows, columns

def load_hdfs_as_dataframe(h5files):
    from pandas import DataFrame
    allrows = []
    for h5file in h5files:
        try:
            hdf = h5py.File(h5file,'r')
            rows,columns = load_diagnostic_info(hdf)
            allrows.extend(rows)
            hdf.close()
        except (IOError,RuntimeError):
            print "failed to open %s"%h5file
    df = DataFrame(allrows, columns = columns)
    return df

def compute_mean_std_across_runs(df):
    from pandas import DataFrame

    fields = [col_name for (col_name,example) in zip(df.columns,df.irow(0)) if isinstance(example,(str,unicode))]

    newrows = []
    for (_,grp) in df.groupby(fields):
        firstrow = grp.irow(0)
        newrow = firstrow.tolist()[:-1]
        newrow.append(np.mean(pad_ends(grp["timeseries"]),axis=0))
        newrow.append(np.std(pad_ends(grp["timeseries"]),axis=0)/np.sqrt(max(len(grp)-1,1)))
        newrows.append(newrow)

    df = DataFrame(newrows, columns=list(df.columns[:-1])+["timeseries","timeseries_stderr"])
    return df

def disp_dict_as_3d_array(d, key0=None, key1=None, key2=None,use_numeric_keys=False):
    """
    Assume dict keys are tuples
    Take it as a 3d array and print
    """
    set0 = set()
    set1 = set()
    set2 = set()
    for (k0,k1,k2) in d:
        set0.add(k0)
        set1.add(k1)
        set2.add(k2)
    arr = np.zeros((len(set0),len(set1),len(set2)),object)
    keys0 = sorted(set0,key0)
    keys1 = sorted(set1,key1)
    keys2 = sorted(set2,key2)
    for ((k0,k1,k2),v) in d.items():
        arr[keys0.index(k0),keys1.index(k1),keys2.index(k2)] = v
    header_keys = map(str,range(len(keys2))) if use_numeric_keys else keys2
    for (k0,tabledata) in zip(keys0,arr):
        title = "***** %s *****"%k0
        print
        print "*"*len(title)
        print title
        print "*"*len(title)
        print tabulate(  [[str(k1)]+row.tolist() for (k1,row) in zip(keys1,tabledata)]  ,headers=['cfg']+header_keys)
    if use_numeric_keys:
        for (i,k2) in enumerate(keys2):
            print "%i: %s"%(i,k2)

def disp_dict_as_2d_array(d, key0=None, key1=None, key2=None,use_numeric_keys=False): #pylint: disable=W0613
    """
    Assume dict keys are tuples
    Take it as a 3d array and print
    """
    set0 = set()
    set1 = set()
    for (k0,k1) in d:
        set0.add(k0)
        set1.add(k1)
    arr = np.zeros((len(set0),len(set1)),object)
    keys0 = sorted(set0,key0)
    keys1 = sorted(set1,key1)
    for ((k0,k1),v) in d.items():
        arr[keys0.index(k0),keys1.index(k1)] = v
    header_keys = map(str,range(len(keys1))) if use_numeric_keys else keys1
    print tabulate(  [[str(k0)]+row.tolist() for (k0,row) in zip(keys0,arr)]  ,headers=['']+header_keys)
    if use_numeric_keys:
        for (i,k1) in enumerate(keys1):
            print "%i: %s"%(i,k1)


text:
<?php

namespace WaddlingCo\StreamPerk\Bundle\CoreBundle\Command\Integration;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use WaddlingCo\StreamPerk\Bundle\CoreBundle\Entity\IntegrationData;
use WaddlingCo\StreamPerk\Bundle\CoreBundle\Entity\UserSetting;
use WaddlingCo\StreamPerk\Bundle\CoreBundle\Utilities\Integrations\DiscordIntegration;

class DiscordGroupManagementCommand extends ContainerAwareCommand
{
    const STARTING_MSG = 'Starting to update Discord Role assignments';
    const INTEGRATION_NOT_VERIFIED_MSG = 'The integration for Server ID %s has not been verified by a Discord Server Admin.';
    const FINISHED_MSG = 'Finished updating roles';

    protected function configure()
    {
        $this
            ->setName('streamperk:integration:discord:groups')
            ->setDescription('Automatically assign/unassign users to groups based on StreamPerk groups (and create those groups if they don\'t exist).')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->writeLog($output, self::STARTING_MSG);

        $configurationService = $this->getContainer()->get('madrak_io_extendable_configuration.configuration_service');
        $integrationDataManager = $this->getContainer()->get('streamperk.integration_data_manager');
        $discordIntegration = $this->getContainer()->get('streamperk.core.integration.discord');
        $userSettingManager = $this->getContainer()->get('streamperk.user_setting_manager');
        $userGroupManager = $this->getContainer()->get('streamperk.user_group_manager');

        foreach ($configurationService->get('core.discord.site_owners') AS $discordSiteOwner) {
            if (empty($discordSiteOwner['server_id']) === true) {
                continue;
            }

            $integrationData = $integrationDataManager->findOneBy(['service' => 'discord', 'identifier' => 'server_authorization']);
            if (($integrationData instanceOf IntegrationData) === false || isset($integrationData->getData()[$discordSiteOwner['server_id']]) === false || $integrationData->getData()[$discordSiteOwner['server_id']]['verified'] === false) {
                $this->writeLog($output, self::INTEGRATION_NOT_VERIFIED_MSG, [$discordSiteOwner['server_id']]);

                continue;
            }

            $roles = $discordIntegration->getRoles($discordSiteOwner['server_id']);
            $groupRolesMap = [];
            foreach ($userGroupManager->findAll() AS $userGroup) {
                foreach ($roles AS $role) {
                    if ($role['name'] == $userGroup->getName()) {
                        $groupRolesMap[$userGroup->getId()] = $role['id'];

                        continue;
                    }
                }

                if (isset($groupRolesMap[$userGroup->getId()]) === false) {
                    $groupRolesMap[$userGroup->getId()] = $discordIntegration->createRole($discordSiteOwner['server_id'], $userGroup->getName());
                }
            }

            foreach ($discordIntegration->getMembers($discordSiteOwner['server_id']) AS $member) {
                $userSetting = $userSettingManager->findOneBy(['name' => DiscordIntegration::DISCORD_USER_ID_SETTING_NAME, 'value' => $member['id']]);
                if (($userSetting instanceOf UserSetting) === false) {
                    continue;
                }

                $newRoles = [];
                $userGroupUsers = $userSetting->getUser()->getUserGroupUsers();
                foreach ($userGroupUsers AS $userGroupUser) {
                    $groupId = $userGroupUser->getUserGroup()->getId();
                    if (isset($groupRolesMap[$groupId]) === false) {
                        continue;
                    }

                    $newRoles[] = $groupRolesMap[$groupId];
                }

                foreach ($member['roles'] AS $currentRole) {
                    if (in_array($currentRole, $groupRolesMap) === false) {
                        $newRoles[] = $currentRole;
                    }
                }

                sort($member['roles']);
                sort($newRoles);

                if ($member['roles'] === $newRoles) {
                    continue;
                }

                $discordIntegration->adjustUserRoles($discordSiteOwner['server_id'], $member['id'], $newRoles);
            }
        }

        $this->writeLog($output, self::FINISHED_MSG);
    }

    protected function writeLog(OutputInterface $output, $message, array $arguments = [])
    {
        $output->writeln('[' . date('m-d-Y h:i:s') . '] ' . vsprintf($message, $arguments));
    }
}


text:
layout: post
title: Intigold Mines Ltd. - TTAGIT Mobile
categories:
- News-Release
- Intigold
- TTAGIT
tags:
- IDMNF
- IGD.V
- Intigold
- Lori McClenahan
- TSX
- TTAGIT
- Apple
- Mobile
- IOS
status: publish
type: post
published: true
meta:
  _edit_last: '1'
  _awake_dependencies: s:6:"a:0:{}";
  _layout: right_sidebar
  _intro_text: default
  _bitly_trim:
author:
  login: admin
  email: intigold.ltd@gmail.com
  display_name: admin
  first_name: ''
  last_name: ''
---

Trading  Symbol: IGD (TSX Venture Exchange)

April 8, 2015

NEWS RELEASE

Vancouver, BC, April 8, 2015, Intigold Mines Ltd.(IGD - TSX-V) announced today that it has received the following update from TTAGIT Social Networks Inc. ("TTAGIT"). Intigold owns a 51% interest in TTAGIT.

TTAGIT - Mobile

TTAGIT has released the first version in the Apple Store of TTAGIT Mobile. You can find it at TTAGIT on itunes or search for it in the App Store on your IOS device. TTAGIT mobile requires that you have Twitter and a Twitter account installed on your device.

We are proud to announce that we are the first Action Extension using Apple's new language "Swift" in the App Store. We will also be launching TTAGIT out of Beta shortly after our other extensions become accepted in the other stores which we anticipate shouldn't be much longer.

A new mobile first friendly website was built alongside the application that will be launched shortly and has instructions on loading and usage.

The first step is to download the TTAGIT application, then open the application and login with Twitter. Go to settings and under Twitter allow Tweets from TTAGIT. Then go to any website and when you open the Share icon you will see the TTAGIT spray can, press that and you can start tweeting over any URL on your mobile phone relative to that link.

TTAGIT Technology

TTAGIT is a proprietary technology which allows you to comment, talk and respond over any website (URL) using live feed while you are viewing the page without having to leave the page that you are on and go to a different website to view or post comments. This is what gives TTAGIT a competitive advantage.

For information on Intigold and its projects, please visit us at www.intigold.com or call 604-669-4677 or toll free at 1-888-895-5522.

INTIGOLD MINES LTD.

(signed "Lori McClenahan")

Lori McClenahan,

President

Neither the TSX Venture Exchange nor its Regulation Services Provider (as that term is defined in policies of the TSX Venture Exchange) accepts responsibility for the adequacy or accuracy of this release.


text:
package org.eclipse.bpel.common.ui.editmodel;

import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.gef.commands.Command;

/**
 * Default implementation of IEditModelCommand. Clients of EditModel framework
 * can either subclass AbstractEditModelCommand or implement IEditModelCommand
 */
public abstract class AbstractEditModelCommand extends Command implements
		IEditModelCommand {

	protected static Resource[] EMPTY_RESOURCE_ARRAY = new Resource[0];

	/**
	 *
	 */

	public AbstractEditModelCommand() {
		super();
	}

	/**
	 * @param label
	 */
	public AbstractEditModelCommand (String label) {
		super(label);
	}

	/**
	 * @see org.eclipse.bpel.common.ui.editmodel.IEditModelCommand#getResources()
	 */
	public Resource[] getResources() {
		return EMPTY_RESOURCE_ARRAY;
	}

	/**
	 * @see org.eclipse.bpel.common.ui.editmodel.IEditModelCommand#getModifiedResources()
	 */
	public Resource[] getModifiedResources() {
		return getResources();
	}

}


text:
define({
  "tabs_section_Label": "Schede",
  "addTab": "Aggiungi scheda",
  "layerName": "Layer",
  "layerType": "Tipo di analisi",
  "layerLabel": "Etichetta",
  "actions": "Azioni",
  "closest": "Feature più vicina",
  "proximity": "Prossimità",
  "summary": "Riepilogo",
  "select_lbl": "-- Seleziona --",
  "general_setting_Label": "Impostazioni generali",
  "units_text_lbl": "Unità Distanza",
  "miles": "Miglia",
  "kilometers": "Chilometri",
  "feet": "Piede",
  "meters": "Metri",
  "yards": "Iarde",
  "nauticalMiles": "Miglia nautiche",
  "maximum_distance_lbl": "Distanza massima della feature più vicina",
  "buffer_text_lbl": "Etichetta del buffer",
  "buffer_lbl": "Distanza di buffer",
  "buffer_max_lbl": "Distanza massima del buffer",
  "buffer_min_lbl": "Distanza minima del buffer",
  "routing_checkBox": "Abilita itinerario",
  "weather_Label": "Opzioni meteo",
  "weather_checkBox": "Includi informazioni meteo",
  "selectLayers": "Seleziona layer meteo",
  "currentlySelectedLayer": "Layer meteo attualmente selezionati",
  "missingTabLabel": "Manca l'etichetta ad almeno una scheda",
  "missingLayerInWebMap": "Nessun layer operativo trovato.",
  "selectFields": "Seleziona campi",
  "addField": "Aggiungi Campo",
  "sum": "SOMMA",
  "min": "MIN",
  "max": "MAX",
  "avg": "MEDIA",
  "count": "COUNT",
  "area": "AREA",
  "length": "LENGTH",
  "count_checkBox": "Visualizza conteggio feature",
  "area_checkBox": "Visualizza somma dell'area",
  "length_checkBox": "Visualizza somma della lunghezza",
  "max_records": "Raggiunto limite massimo",
  "save_label": "Salva opzioni",
  "save_checkbox": "Abilita salvataggio",
  "csv_label": "Opzioni CSV",
  "csv_checkbox": "Esporta tutti i campi nel layer",
  "display_label": "Opzioni di visualizzazione",
  "display_checkbox": "Visualizza riepilogo delle feature",
  "must_select_template": "Selezionare uno dei modelli di modifica nelle opzioni di salvataggio.",
  "count_label": "Etichetta conteggio",
  "area_label": "Etichetta area",
  "length_label": "Etichetta lunghezza",
  "invalid_string_width": "Il valore è troppo lungo. ",
  "layer_type_not_supported": "Il tipo di layer non è supportato: ",
  "groupedSummary": "Conteggi raggruppati",
  "groupByField": "Raggruppa per campo",
  "labelType": "Aggiungi etichetta",
  "prefix": "Come prefisso",
  "suffix": "Come suffisso",
  "need_group_field": "Utilizzare l'azione Modifica per definire un Gruppo per campo.",
  "fieldTitle": "Campo",
  "typeTitle": "Tipo",
  "actionsTitle": "Azioni"
});


text:
package imageprocess

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// Lesion is a nested struct in imageprocess response
type Lesion struct {
	EcVolume      string   `json:"EcVolume" xml:"EcVolume"`
	Mask          string   `json:"Mask" xml:"Mask"`
	BenignVolume  string   `json:"BenignVolume" xml:"BenignVolume"`
	PdacVol       string   `json:"PdacVol" xml:"PdacVol"`
	EsoVolume     string   `json:"EsoVolume" xml:"EsoVolume"`
	PancVol       string   `json:"PancVol" xml:"PancVol"`
	NonPdacVol    string   `json:"NonPdacVol" xml:"NonPdacVol"`
	Possibilities []string `json:"Possibilities" xml:"Possibilities"`
}


text:
#region Using Directives
using System;
using PetShop.Business;
#endregion
namespace PetShop.Data
{
	/// <summary>
	/// Defines the common data access methods that can be used by the
	/// ReadOnlyDataSource control to interact with the underlying data store.
	/// </summary>
	/// <typeparam name="Entity">The class of the business object being accessed.</typeparam>
	public interface IEntityViewProvider<Entity> where Entity : new()
	{
		/// <summary>
		/// Gets a page of rows from the DataSource.
		/// </summary>
		/// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param>
		/// <param name="orderBy">Specifies the sort criteria for the rows in the DataSource (Name ASC; BirthDay DESC, Name ASC);</param>
		/// <param name="start">Row number at which to start reading.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">The total number of rows in the data source.</param>
		/// <returns>Returns a typed collection of Entity objects.</returns>
		VList<Entity> Get(String whereClause, String orderBy, int start, int pageLength, out int count);

		/// <summary>
		/// Gets a page of rows from the DataSource.
		/// </summary>
		/// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param>
		/// <param name="orderBy">Specifies the sort criteria for the rows in the DataSource (Name ASC; BirthDay DESC, Name ASC);</param>
		/// <param name="start">Row number at which to start reading.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">The total number of rows in the data source.</param>
		/// <returns>Returns a typed collection of Entity objects.</returns>
		VList<Entity> GetPaged(String whereClause, String orderBy, int start, int pageLength, out int count);

		/// <summary>
		/// Gets all rows from the DataSource.
		/// </summary>
		/// <param name="start">Row number at which to start reading.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">Number of rows in the DataSource.</param>
		/// <returns>Returns a typed collection of Entity objects.</returns>
		VList<Entity> GetAll(int start, int pageLength, out int count);

		/// <summary>
		/// 	Returns rows from the DataSource that meet the parameter conditions.
		/// </summary>
		/// <param name="parameters">A collection of <see cref="SqlFilterParameter"/> objects.</param>
		/// <param name="orderBy">Specifies the sort criteria for the rows in the DataSource (Name ASC; BirthDay DESC, Name ASC);</param>
		/// <param name="start">Row number at which to start reading.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">out. The number of rows that match this query.</param>
		/// <returns>Returns a typed collection of Entity objects.</returns>
		VList<Entity> Find(IFilterParameterCollection parameters, string orderBy, int start, int pageLength, out int count);

	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Overview List (aalto-xml 0.9.10 API)</title>
<meta name="date" content="2015-02-23">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

All Classes

Packages

com.fasterxml.aalto

com.fasterxml.aalto.async

com.fasterxml.aalto.dom

com.fasterxml.aalto.evt

com.fasterxml.aalto.impl

com.fasterxml.aalto.in

com.fasterxml.aalto.io

com.fasterxml.aalto.out

com.fasterxml.aalto.sax

com.fasterxml.aalto.stax

com.fasterxml.aalto.util

test


text:
/*
 * !!!!! DO NOT EDIT THIS FILE !!!!!
 *
 * This file was generated from
 *   suggest/policyimpl/dictionary/structure/v4/content/shortcut_dict_content.h
 */

#ifndef LATINIME_BACKWARD_V402_SHORTCUT_DICT_CONTENT_H
#define LATINIME_BACKWARD_V402_SHORTCUT_DICT_CONTENT_H

#include "third_party/android_prediction/defines.h"
#include "third_party/android_prediction/suggest/policyimpl/dictionary/structure/backward/v402/content/sparse_table_dict_content.h"
#include "third_party/android_prediction/suggest/policyimpl/dictionary/structure/backward/v402/content/terminal_position_lookup_table.h"
#include "third_party/android_prediction/suggest/policyimpl/dictionary/structure/backward/v402/ver4_dict_constants.h"

namespace latinime {
namespace backward {
namespace v402 {

class ShortcutDictContent : public SparseTableDictContent {
 public:
    ShortcutDictContent(const char *const dictPath, const bool isUpdatable)
            : SparseTableDictContent(dictPath,
                      Ver4DictConstants::SHORTCUT_LOOKUP_TABLE_FILE_EXTENSION,
                      Ver4DictConstants::SHORTCUT_CONTENT_TABLE_FILE_EXTENSION,
                      Ver4DictConstants::SHORTCUT_FILE_EXTENSION, isUpdatable,
                      Ver4DictConstants::SHORTCUT_ADDRESS_TABLE_BLOCK_SIZE,
                      Ver4DictConstants::SHORTCUT_ADDRESS_TABLE_DATA_SIZE) {}

    ShortcutDictContent()
            : SparseTableDictContent(Ver4DictConstants::SHORTCUT_ADDRESS_TABLE_BLOCK_SIZE,
                      Ver4DictConstants::SHORTCUT_ADDRESS_TABLE_DATA_SIZE) {}

    void getShortcutEntry(const int maxCodePointCount, int *const outCodePoint,
            int *const outCodePointCount, int *const outProbability, bool *const outhasNext,
            const int shortcutEntryPos) {
        int readingPos = shortcutEntryPos;
        return getShortcutEntryAndAdvancePosition(maxCodePointCount, outCodePoint,
                outCodePointCount, outProbability, outhasNext, &readingPos);
    }

    void getShortcutEntryAndAdvancePosition(const int maxCodePointCount,
            int *const outCodePoint, int *const outCodePointCount, int *const outProbability,
            bool *const outhasNext, int *const shortcutEntryPos) const;

   // Returns head position of shortcut list for a PtNode specified by terminalId.
   int getShortcutListHeadPos(const int terminalId) const;

   bool flushToFile(const char *const dictPath) const;

   bool runGC(const TerminalPositionLookupTable::TerminalIdMap *const terminalIdMap,
           const ShortcutDictContent *const originalShortcutDictContent);

   bool createNewShortcutList(const int terminalId);

   bool copyShortcutList(const int shortcutListPos, const int toPos);

   bool setProbability(const int probability, const int shortcutEntryPos);

   bool writeShortcutEntry(const int *const codePoint, const int codePointCount,
           const int probability, const bool hasNext, const int shortcutEntryPos) {
       int writingPos = shortcutEntryPos;
       return writeShortcutEntryAndAdvancePosition(codePoint, codePointCount, probability,
               hasNext, &writingPos);
   }

   bool writeShortcutEntryAndAdvancePosition(const int *const codePoint,
           const int codePointCount, const int probability, const bool hasNext,
           int *const shortcutEntryPos);

   int findShortcutEntryAndGetPos(const int shortcutListPos,
           const int *const targetCodePointsToFind, const int codePointCount) const;

 private:
    DISALLOW_COPY_AND_ASSIGN(ShortcutDictContent);

    bool copyShortcutListFromDictContent(const int shortcutListPos,
            const ShortcutDictContent *const sourceShortcutDictContent, const int toPos);

    int createAndGetShortcutFlags(const int probability, const bool hasNext) const;
};
} // namespace v402
} // namespace backward
} // namespace latinime
#endif /* LATINIME_BACKWARD_V402_SHORTCUT_DICT_CONTENT_H */


text:
package edu.asu.qstore4s.domain.events.factory;

import edu.asu.qstore4s.domain.events.impl.AppellationEvent;

/**
 * This is the interface class for AppellationEventFactory class
 * which has the following methods:
 * createAppellationEvent()
 * @author Veena Borannagowda
 *
 */
public interface IAppellationEventFactory {

	AppellationEvent createAppellationEvent();

}


text:
(function($P) {
	'use strict';

	$P.Bubble.Search = $P.defineClass(
		$P.Bubble,
		function SearchBubble(config) {
			config = $.extend(config, {
				closeMenu: true,
				groupMenu: true});
			$P.Bubble.call(this, config);
			if (undefined !== config.text) {this.text = config.text;}},
		{
			get text() {return this.content && $(this.content.element).val();},
			set text(value) {
				if (this.content) {
					$(this.content.element).val(value);}
				else {
					this._readyText = value;}},

			onAdded: function(parent) {
				if ($P.BubbleBase.prototype.onAdded.call(this, parent) || this.content) {return;}
				var config = {};
				config = $.extend(config, this.getInteriorDimensions());
				config.x += 8;
				config.y += 8;
				config.w -= 16;
				config.h -= 16;
				config.parent = this;
				config.url = this.url;
				this.content = new $P.Bubble.SearchContent(config);
				/*
				if (this._readyText) {
					this.text = this._readyText;
					delete this._readyText;}
				 */
				 },

			saveKeys: [].concat($P.Bubble.prototype.saveKeys, ['text'])

		});
	$P.Bubble.Note.loader = function(load, id, data) {
		var config = {};
		$P.Bubble.Note.prototype.saveKeys.forEach(function(key) {
			config[key] = load.loadObject(data[key]);});
		var bubble = new $P.Bubble.Note(config);
		load.objects[id] = bubble;

		return bubble;};

})(PATHBUBBLES);


text:
//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <map>

// template <class Key, class T, class Compare = less<Key>,
//           class Allocator = allocator<pair<const Key, T>>>
// class multimap
// {
// public:
//     // types:
//     typedef Key                                      key_type;
//     typedef T                                        mapped_type;
//     typedef pair<const key_type, mapped_type>        value_type;
//     typedef Compare                                  key_compare;
//     typedef Allocator                                allocator_type;
//     typedef typename allocator_type::reference       reference;
//     typedef typename allocator_type::const_reference const_reference;
//     typedef typename allocator_type::pointer         pointer;
//     typedef typename allocator_type::const_pointer   const_pointer;
//     typedef typename allocator_type::size_type       size_type;
//     typedef typename allocator_type::difference_type difference_type;
//     ...
// };

#include <map>
#include <type_traits>
#include "libcxx_tc_common.h"

int tc_libcxx_containers_multimap_types(void)
{
    {
    typedef std::multimap<int, double> C;
    static_assert((std::is_same<C::key_type, int>::value), "");
    static_assert((std::is_same<C::mapped_type, double>::value), "");
    static_assert((std::is_same<C::value_type, std::pair<const int, double> >::value), "");
    static_assert((std::is_same<C::key_compare, std::less<int> >::value), "");
    static_assert((std::is_same<C::allocator_type, std::allocator<std::pair<const int, double> > >::value), "");
    static_assert((std::is_same<C::reference, std::pair<const int, double>&>::value), "");
    static_assert((std::is_same<C::const_reference, const std::pair<const int, double>&>::value), "");
    static_assert((std::is_same<C::pointer, std::pair<const int, double>*>::value), "");
    static_assert((std::is_same<C::const_pointer, const std::pair<const int, double>*>::value), "");
    static_assert((std::is_same<C::size_type, std::size_t>::value), "");
    static_assert((std::is_same<C::difference_type, std::ptrdiff_t>::value), "");
    }
    TC_SUCCESS_RESULT();
    return 0;
}


text:
package elegit;

import javafx.application.Platform;
import javafx.scene.control.CheckBoxTreeItem;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.control.cell.CheckBoxTreeCell;
import javafx.util.Callback;
import org.eclipse.jgit.api.errors.GitAPIException;

import java.io.IOException;
import java.nio.file.Path;
import java.util.*;

/**
 * AllFilesPanelView displays all files in the current repository,
 * whether tracked or otherwise, as well as their status. It does so
 * in a hierarchical manner
 */
public class AllFilesPanelView extends FileStructurePanelView{

    private Map<Path, TreeItem<RepoFile>> itemMap;

    public AllFilesPanelView() {
        this.init();
    }

    @Override
    public void init(){
        this.itemMap = new HashMap<>();
        super.init();
    }

    /**
     * @return a factory that generates a custom tree cell that includes a context menu for each
     * item
     */
    @Override
    protected Callback<TreeView<RepoFile>, TreeCell<RepoFile>> getTreeCellFactory() {
        return arg -> new RepoFileTreeCell();
    }

    @Override
    protected TreeItem<RepoFile> getRootTreeItem(DirectoryRepoFile rootDirectory) {
        return new TreeItem<>(rootDirectory);
    }

    /**
     * Builds a nested tree that follows the same file structure as the system, with the
     * base directory of the current repository as the root. Subsequent calls to this method
     * will update the items in place
     * @param repoFiles the files to add to the tree
     * @param root the root of the tree
     */
    @Override
    protected void addTreeItemsToRoot(List<RepoFile> repoFiles, TreeItem<RepoFile> root){
        // To ensure files are added after their parents, sort the given files into lists
        // based on their respective depths in the file structure
        Map<Integer, List<RepoFile>> filesAtDepthMap = new HashMap<>();
        int maxDepth = 0;
        for(RepoFile repoFile : repoFiles){
            int depthInRepo = repoFile.getLevelInRepository();

            if(depthInRepo > maxDepth) maxDepth=depthInRepo;

            if(!filesAtDepthMap.containsKey(depthInRepo)){
                List<RepoFile> list = new LinkedList<>();
                list.add(repoFile);
                filesAtDepthMap.put(depthInRepo, list);
            }else{
                filesAtDepthMap.get(depthInRepo).add(repoFile);
            }
        }

        // Track all currently displayed files to make sure they are still valid
        Set<TreeItem<RepoFile>> itemsToRemove = new HashSet<>();
        itemsToRemove.addAll(itemMap.values());

        // Loop through files at each depth
        for(int i = 0; i < maxDepth + 1; i++) {
            List<RepoFile> filesAtDepth = filesAtDepthMap.get(i);
            if(filesAtDepth != null) {
                for (RepoFile repoFile : filesAtDepth) {
                    Path pathToFile = repoFile.getFilePath();

                    // Check if there is already a record of this file
                    if (itemMap.containsKey(pathToFile)) {
                        TreeItem<RepoFile> oldItem = itemMap.get(pathToFile);

                        if (oldItem.getValue().equals(repoFile)) {
                            // The given file is already present, no additional processing needed
                            itemsToRemove.remove(oldItem);
                        } else {
                            // The file is displayed, but needs its status updated. Replace the old with the new
                            CheckBoxTreeItem<RepoFile> newItem = new CheckBoxTreeItem<>(repoFile, repoFile.diffButton);
                            TreeItem<RepoFile> parent = oldItem.getParent();
                            newItem.setExpanded(oldItem.isExpanded());
                            newItem.getChildren().setAll(oldItem.getChildren());
                            parent.getChildren().set(parent.getChildren().indexOf(oldItem), newItem);
                            itemsToRemove.remove(oldItem);
                            itemMap.put(pathToFile, newItem);
                        }
                    } else {
                        // The given file wasn't present, so need to add it
                        CheckBoxTreeItem<RepoFile> newItem = new CheckBoxTreeItem<>(repoFile, repoFile.diffButton);

                        Path pathToParent = pathToFile.getParent();
                        boolean foundParent = false;
                        // Make sure this new item is properly inserted as a child to its parent
                        while (pathToParent != null && !root.getValue().getFilePath().equals(pathToParent)) {
                            if (itemMap.containsKey(pathToParent)) {
                                TreeItem<RepoFile> parent = itemMap.get(pathToParent);
                                Platform.runLater(() -> parent.getChildren().add(newItem));
                                foundParent = true;
                                break;
                            }
                            pathToParent = pathToParent.getParent();
                        }
                        // If no parent is found, we can assume it belongs to the root
                        if (!foundParent) {
                            root.getChildren().add(newItem);
                        }
                        itemMap.put(pathToFile, newItem);
                        itemsToRemove.remove(newItem);
                    }
                }
            }
        }

        // Remove all elements that shouldn't be displayed
        for (TreeItem<RepoFile> item : itemsToRemove) {
            Platform.runLater(() -> {
                if(item.getParent() != null) item.getParent().getChildren().remove(item);
            });
            itemMap.remove(item.getValue().getFilePath());
        }
    }

    /**
     * @return every file in the repository (included untracked, ignored, etc)
     * @throws GitAPIException
     * @throws IOException
     */
    @Override
    public List<RepoFile> getFilesToDisplay() throws GitAPIException, IOException {
        return sessionModel.getAllRepoFiles();
    }

    /**
     * An overwritten version of TreeCell that adds a context menu to our
     * tree structure
     */
    private class RepoFileTreeCell extends CheckBoxTreeCell<RepoFile> {
        @Override
        public void updateItem(RepoFile item, boolean empty){
            super.updateItem(item, empty);

            setText(getItem() == null ? "" : getItem().toString());

            setOnContextMenuRequested(event -> {
                if(getTreeItem() != null) getTreeItem().getValue().showContextMenu(this, event.getScreenX(), event.getScreenY());
            });
        }
    }
}


text:
package jp.crafterkina.KinaCore.movelib.config;

import com.google.common.collect.Sets;
import jp.crafterkina.KinaCore.asm.transformer.TransformerKinaProp;
import jp.crafterkina.KinaCore.misclib.utils.reflect.InstancedField;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Set;
import java.util.regex.Pattern;

public class ElementProcessor{
    //    public static Set<String> classNames = new HashSet<String>();
    private Set<KinaPropContainer> containers = Sets.newHashSet();

    public void process(Pattern suffix){
        String[] strings = TransformerKinaProp.className.toArray(new String[TransformerKinaProp.className.size()]);
        for(final String className : strings){
            if(suffix.matcher(className).matches()){
                process(className);
            }
        }
    }

    private void process(String className){
        try{
            Class<?> clazz = Class.forName(className);
            fieldProcess(clazz);
        } catch(ClassNotFoundException e){
            throw new AssertionError(e);
        }
    }

    private void fieldProcess(Class<?> clazz){
        for(Field field : clazz.getDeclaredFields()){
            field.setAccessible(true);
            System.out.println(field.toString());
            if(!(Modifier.isStatic(field.getModifiers()))) continue;
            KinaProp prop = field.getAnnotation(KinaProp.class);
            if(prop == null) continue;
            fieldProcess(new InstancedField(field, null), prop);
        }
    }

    private void fieldProcess(InstancedField field, KinaProp prop){
        if(prop.isInstance()){
            instanceProcess(field);
        }else{
            normalFieldProcess(field);
        }
    }

    private void instanceProcess(InstancedField instanceField){
        Object instance = instanceField.get();
        for(Field holdingField : instance.getClass().getDeclaredFields()){
            holdingField.setAccessible(true);
            if(Modifier.isStatic(holdingField.getModifiers())) continue;
            KinaProp prop = holdingField.getAnnotation(KinaProp.class);
            if(prop == null) continue;
            fieldProcess(new InstancedField(holdingField, instanceField), prop);
        }
    }

    private void normalFieldProcess(InstancedField normalField){
        KinaProp fieldTypeProp = normalField.getField().getType().getAnnotation(KinaProp.class);
        KinaProp instanceProp = normalField.getInstance() == null ? null : normalField.getInstance().getField().getAnnotation(KinaProp.class);
        KinaProp fieldProp = normalField.getField().getAnnotation(KinaProp.class);
        KinaPropContainer container = new KinaPropContainer(normalField, fieldTypeProp, instanceProp, fieldProp);
        containers.add(container);
    }

    public Set<KinaPropContainer> getContainers(){
        return containers;
    }
}


text:
namespace {

NtQuerySectionFunction g_nt_query_section_func = NULL;
NtQueryVirtualMemoryFunction g_nt_query_virtual_memory_func = NULL;
NtUnmapViewOfSectionFunction g_nt_unmap_view_of_section_func = NULL;

// TODO(robertshield): Merge with ntdll exports cache.
FARPROC GetNtDllExportByName(const char* export_name) {
  HMODULE ntdll = ::GetModuleHandle(sandbox::kNtdllName);
  return ::GetProcAddress(ntdll, export_name);
}

int DllMatch(const base::string16& module_name) {
  for (int i = 0; blacklist::g_troublesome_dlls[i] != NULL; ++i) {
    if (_wcsicmp(module_name.c_str(), blacklist::g_troublesome_dlls[i]) == 0)
      return i;
  }
  return -1;
}

// TODO(robertshield): Some of the helper functions below overlap somewhat with
// code in sandbox_nt_util.cc. See if they can be unified.

// Native reimplementation of PSAPIs GetMappedFileName.
base::string16 GetBackingModuleFilePath(PVOID address) {
  DCHECK_NT(g_nt_query_virtual_memory_func);

  // We'll start with something close to max_path characters for the name.
  SIZE_T buffer_bytes = MAX_PATH * 2;
  std::vector<BYTE> buffer_data(buffer_bytes);

  for (;;) {
    MEMORY_SECTION_NAME* section_name =
        reinterpret_cast<MEMORY_SECTION_NAME*>(&buffer_data[0]);

    if (!section_name)
      break;

    SIZE_T returned_bytes;
    NTSTATUS ret = g_nt_query_virtual_memory_func(
        NtCurrentProcess, address, MemorySectionName, section_name,
        buffer_bytes, &returned_bytes);

    if (STATUS_BUFFER_OVERFLOW == ret) {
      // Retry the call with the given buffer size.
      buffer_bytes = returned_bytes + 1;
      buffer_data.resize(buffer_bytes);
      section_name = NULL;
      continue;
    }
    if (!NT_SUCCESS(ret))
      break;

    UNICODE_STRING* section_string =
        reinterpret_cast<UNICODE_STRING*>(section_name);
    return base::string16(section_string->Buffer,
                          section_string->Length / sizeof(wchar_t));
  }

  return base::string16();
}

bool IsModuleValidImageSection(HANDLE section,
                               PVOID *base,
                               PLARGE_INTEGER offset,
                               PSIZE_T view_size) {
  DCHECK_NT(g_nt_query_section_func);

  if (!section || !base || !view_size || offset)
    return false;

  SECTION_BASIC_INFORMATION basic_info;
  SIZE_T bytes_returned;
  NTSTATUS ret = g_nt_query_section_func(section, SectionBasicInformation,
                                         &basic_info, sizeof(basic_info),
                                         &bytes_returned);

  if (!NT_SUCCESS(ret) || sizeof(basic_info) != bytes_returned)
    return false;

  if (!(basic_info.Attributes & SEC_IMAGE))
    return false;

  return true;
}

base::string16 ExtractLoadedModuleName(const base::string16& module_path) {
  if (module_path.empty() || module_path[module_path.size() - 1] == L'\\')
    return base::string16();

  size_t sep = module_path.find_last_of(L'\\');
  if (sep == base::string16::npos)
    return module_path;
  else
    return module_path.substr(sep+1);
}

// Fills |out_name| with the image name from the given |pe| image and |flags|
// with additional info about the image.
void SafeGetImageInfo(const base::win::PEImage& pe,
                      std::string* out_name,
                      uint32* flags) {
  out_name->clear();
  out_name->reserve(MAX_PATH);
  *flags = 0;
  __try {
    if (pe.VerifyMagic()) {
      *flags |= sandbox::MODULE_IS_PE_IMAGE;

      PIMAGE_EXPORT_DIRECTORY exports = pe.GetExportDirectory();
      if (exports) {
        const char* image_name = reinterpret_cast<const char*>(
            pe.RVAToAddr(exports->Name));
        size_t i = 0;
        for (; i < MAX_PATH && *image_name; ++i, ++image_name)
          out_name->push_back(*image_name);
      }

      PIMAGE_NT_HEADERS headers = pe.GetNTHeaders();
      if (headers) {
        if (headers->OptionalHeader.AddressOfEntryPoint)
          *flags |= sandbox::MODULE_HAS_ENTRY_POINT;
        if (headers->OptionalHeader.SizeOfCode)
          *flags |= sandbox::MODULE_HAS_CODE;
      }
    }
  } __except((GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ||
              GetExceptionCode() == EXCEPTION_GUARD_PAGE ||
              GetExceptionCode() == EXCEPTION_IN_PAGE_ERROR) ?
             EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
    out_name->clear();
  }
}

base::string16 GetImageInfoFromLoadedModule(HMODULE module, uint32* flags) {
  std::string out_name;
  base::win::PEImage pe(module);
  SafeGetImageInfo(pe, &out_name, flags);
  return base::string16(out_name.begin(), out_name.end());
}

bool IsSameAsCurrentProcess(HANDLE process) {
  return  (NtCurrentProcess == process) ||
          (::GetProcessId(process) == ::GetCurrentProcessId());
}

NTSTATUS BlNtMapViewOfSectionImpl(
    NtMapViewOfSectionFunction orig_MapViewOfSection,
    HANDLE section,
    HANDLE process,
    PVOID *base,
    ULONG_PTR zero_bits,
    SIZE_T commit_size,
    PLARGE_INTEGER offset,
    PSIZE_T view_size,
    SECTION_INHERIT inherit,
    ULONG allocation_type,
    ULONG protect) {
  NTSTATUS ret = orig_MapViewOfSection(section, process, base, zero_bits,
                                       commit_size, offset, view_size, inherit,
                                       allocation_type, protect);

  if (!NT_SUCCESS(ret) || !IsSameAsCurrentProcess(process) ||
      !IsModuleValidImageSection(section, base, offset, view_size)) {
    return ret;
  }

  HMODULE module = reinterpret_cast<HMODULE>(*base);
  if (module) {
    UINT image_flags;

    base::string16 module_name(GetImageInfoFromLoadedModule(
        reinterpret_cast<HMODULE>(*base), &image_flags));
    base::string16 file_name(GetBackingModuleFilePath(*base));

    if (module_name.empty() && (image_flags & sandbox::MODULE_HAS_CODE)) {
      // If the module has no exports we retrieve the module name from the
      // full path of the mapped section.
      module_name = ExtractLoadedModuleName(file_name);
    }

    if (!module_name.empty()) {
      int blocked_index = DllMatch(module_name);
      if (blocked_index != -1) {
        DCHECK_NT(g_nt_unmap_view_of_section_func);
        g_nt_unmap_view_of_section_func(process, *base);
        ret = STATUS_UNSUCCESSFUL;

        blacklist::BlockedDll(blocked_index);
      }
    }
  }

  return ret;
}

}  // namespace

namespace blacklist {

bool InitializeInterceptImports() {
  g_nt_query_section_func =
      reinterpret_cast<NtQuerySectionFunction>(
          GetNtDllExportByName("NtQuerySection"));
  g_nt_query_virtual_memory_func =
      reinterpret_cast<NtQueryVirtualMemoryFunction>(
          GetNtDllExportByName("NtQueryVirtualMemory"));
  g_nt_unmap_view_of_section_func =
      reinterpret_cast<NtUnmapViewOfSectionFunction>(
          GetNtDllExportByName("NtUnmapViewOfSection"));

  return (g_nt_query_section_func && g_nt_query_virtual_memory_func &&
          g_nt_unmap_view_of_section_func);
}

SANDBOX_INTERCEPT NTSTATUS WINAPI BlNtMapViewOfSection(
    NtMapViewOfSectionFunction orig_MapViewOfSection,
    HANDLE section,
    HANDLE process,
    PVOID *base,
    ULONG_PTR zero_bits,
    SIZE_T commit_size,
    PLARGE_INTEGER offset,
    PSIZE_T view_size,
    SECTION_INHERIT inherit,
    ULONG allocation_type,
    ULONG protect) {
  NTSTATUS ret = STATUS_UNSUCCESSFUL;

  __try {
    ret = BlNtMapViewOfSectionImpl(orig_MapViewOfSection, section, process,
                                   base, zero_bits, commit_size, offset,
                                   view_size, inherit, allocation_type,
                                   protect);
  } __except(GenerateCrashDump(GetExceptionInformation())) {
  }

  return ret;
}

#if defined(_WIN64)
NTSTATUS WINAPI BlNtMapViewOfSection64(
    HANDLE section, HANDLE process, PVOID *base, ULONG_PTR zero_bits,
    SIZE_T commit_size, PLARGE_INTEGER offset, PSIZE_T view_size,
    SECTION_INHERIT inherit, ULONG allocation_type, ULONG protect) {
  return BlNtMapViewOfSection(g_nt_map_view_of_section_func, section, process,
                              base, zero_bits, commit_size, offset, view_size,
                              inherit, allocation_type, protect);
}
#endif
}  // namespace blacklist


text:
package org.apache.gobblin.metrics.reporter;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import org.apache.avro.Schema;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.mockito.Mockito;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import org.apache.gobblin.metrics.GobblinTrackingEvent;
import org.apache.gobblin.metrics.MetricContext;
import org.apache.gobblin.metrics.kafka.KafkaAvroEventKeyValueReporter;
import org.apache.gobblin.metrics.kafka.KafkaAvroSchemaRegistry;
import org.apache.gobblin.metrics.kafka.KafkaEventReporter;
import org.apache.gobblin.metrics.kafka.Pusher;
import org.apache.gobblin.metrics.reporter.util.EventUtils;

public class KafkaAvroEventKeyValueReporterTest extends KafkaAvroEventReporterTest {
  private static final int SCHEMA_ID_LENGTH_BYTES = 20;

  private String schemaId;

  @BeforeClass
  public void setUp() throws IOException {
    Schema schema =
        new Schema.Parser().parse(getClass().getClassLoader().getResourceAsStream("GobblinTrackingEvent.avsc"));
    this.schemaId = DigestUtils.sha1Hex(schema.toString().getBytes());
  }

  @Override
  public KafkaEventReporter.Builder<? extends KafkaEventReporter.Builder> getBuilder(MetricContext context,
                                                                                Pusher pusher) {
    KafkaAvroEventKeyValueReporter.Builder<?> builder = KafkaAvroEventKeyValueReporter.Factory.forContext(context);
    return builder.withKafkaPusher(pusher).withKeys(Lists.newArrayList("k1", "k2", "k3"));
  }

  private Pair<String, GobblinTrackingEvent> nextKVEvent(Iterator<Pair<String, byte[]>> it, boolean isSchemaIdEnabled) throws IOException {
    Assert.assertTrue(it.hasNext());
    Pair<String, byte[]> event = it.next();
    return isSchemaIdEnabled ? Pair.of(event.getKey(), EventUtils
        .deserializeEventFromAvroSerialization(new GobblinTrackingEvent(), event.getValue(), schemaId)) : Pair.of(event.getKey(),
        EventUtils.deserializeEventFromAvroSerialization(new GobblinTrackingEvent(), event.getValue()));
  }

  private GobblinTrackingEvent getEvent(boolean isMessageKeyed) {
    String namespace = "gobblin.metrics.test";
    String eventName = "testEvent";

    GobblinTrackingEvent event = new GobblinTrackingEvent();
    event.setName(eventName);
    event.setNamespace(namespace);
    Map<String, String> metadata = Maps.newHashMap();
    metadata.put("m1", "v1");
    metadata.put("m2", null);
    if (isMessageKeyed) {
      metadata.put("k1", "v1");
      metadata.put("k2", "v2");
      metadata.put("k3", "v3");
    }

    event.setMetadata(metadata);
    return event;
  }

  @Test
  public void testKafkaEventReporter() throws IOException {
    MetricContext context = MetricContext.builder("context").build();

    MockKafkaKeyValuePusher pusher = new MockKafkaKeyValuePusher();
    KafkaEventReporter kafkaReporter = getBuilder(context, pusher).build("localhost:0000", "topic");

    context.submitEvent(getEvent(false));

    kafkaReporter.report();

    Pair<String, GobblinTrackingEvent> retrievedEvent = nextKVEvent(pusher.messageIterator(), false);
    Assert.assertNull(retrievedEvent.getKey());

    context.submitEvent(getEvent(true));

    kafkaReporter.report();

    retrievedEvent = nextKVEvent(pusher.messageIterator(), false);
    Assert.assertEquals(retrievedEvent.getKey(), "v1v2v3");
  }

  @Test
  public void testKafkaEventReporterWithSchemaRegistry() throws IOException {
    MetricContext context = MetricContext.builder("context").build();
    MockKafkaKeyValuePusher pusher = new MockKafkaKeyValuePusher();

    Schema schema =
        new Schema.Parser().parse(getClass().getClassLoader().getResourceAsStream("GobblinTrackingEvent.avsc"));
    String schemaId = DigestUtils.sha1Hex(schema.toString().getBytes());

    KafkaAvroEventKeyValueReporter.Builder<?> builder = KafkaAvroEventKeyValueReporter.Factory.forContext(context);
    KafkaAvroEventKeyValueReporter kafkaReporter =
        builder.withKafkaPusher(pusher).withKeys(Lists.newArrayList("k1", "k2", "k3"))
            .withSchemaRegistry(Mockito.mock(KafkaAvroSchemaRegistry.class)).withSchemaId(schemaId)
            .build("localhost:0000", "topic");

    context.submitEvent(getEvent(true));

    kafkaReporter.report();

    Pair<String, GobblinTrackingEvent> retrievedEvent = nextKVEvent(pusher.messageIterator(), true);
    Assert.assertEquals(retrievedEvent.getKey(), "v1v2v3");
  }

  @Test (enabled=false)
  public void testTagInjection() throws IOException {
    // This test is not applicable for testing KafkaAvroEventKeyValueReporter
  }
}


text:
//取出传回来的参数error并与yes比较
	function alertMsg(msg, mode) { //mode为空,即只有一个确认按钮,mode为1时有确认和取消两个按钮
        msg = msg || '';
        mode = mode || 0;
        var top = document.body.scrollTop || document.documentElement.scrollTop;
        var isIe = (document.all) ? true : false;
        var isIE6 = isIe && !window.XMLHttpRequest;
        var sTop = document.documentElement.scrollTop || document.body.scrollTop;
        var sLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
        var winSize = function(){
            var xScroll, yScroll, windowWidth, windowHeight, pageWidth, pageHeight;
            // innerHeight获取的是可视窗口的高度,IE不支持此属性
            if (window.innerHeight && window.scrollMaxY) {
                xScroll = document.body.scrollWidth;
                yScroll = window.innerHeight + window.scrollMaxY;
            } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
                xScroll = document.body.scrollWidth;
                yScroll = document.body.scrollHeight;
            } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
                xScroll = document.body.offsetWidth;
                yScroll = document.body.offsetHeight;
            }

            if (self.innerHeight) {    // all except Explorer
                windowWidth = self.innerWidth;
                windowHeight = self.innerHeight;
            } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
                windowWidth = document.documentElement.clientWidth;
                windowHeight = document.documentElement.clientHeight;
            } else if (document.body) { // other Explorers
                windowWidth = document.body.clientWidth;
                windowHeight = document.body.clientHeight;
            }

            // for small pages with total height less then height of the viewport
            if (yScroll < windowHeight) {
                pageHeight = windowHeight;
            } else {
                pageHeight = yScroll;
            }

            // for small pages with total width less then width of the viewport
            if (xScroll < windowWidth) {
                pageWidth = windowWidth;
            } else {
                pageWidth = xScroll;
            }

            return{
                'pageWidth':pageWidth,
                'pageHeight':pageHeight,
                'windowWidth':windowWidth,
                'windowHeight':windowHeight
            }
        }();
        //alert(winSize.pageWidth);
        //遮罩层
        var styleStr = 'top:0;left:0;position:absolute;z-index:10000;background:#666;width:' + winSize.pageWidth + 'px;height:' +  (winSize.pageHeight + 30) + 'px;';
        styleStr += (isIe) ? "filter:alpha(opacity=80);" : "opacity:0.8;"; //遮罩层DIV
        var shadowDiv = document.createElement('div'); //添加阴影DIV
        shadowDiv.style.cssText = styleStr; //添加样式
        shadowDiv.id = "shadowDiv";
        //如果是IE6则创建IFRAME遮罩SELECT
        if (isIE6) {
            var maskIframe = document.createElement('iframe');
            maskIframe.style.cssText = 'width:' + winSize.pageWidth + 'px;height:' + (winSize.pageHeight + 30) + 'px;position:absolute;visibility:inherit;z-index:-1;filter:alpha(opacity=0);';
            maskIframe.frameborder = 0;
            maskIframe.src = "about:blank";
            shadowDiv.appendChild(maskIframe);
        }
        document.body.insertBefore(shadowDiv, document.body.firstChild); //遮罩层加入文档
        //弹出框
        var styleStr1 = 'display:block;position:fixed;_position:absolute;left:' + (winSize.windowWidth / 2 - 200) + 'px;top:' + (winSize.windowHeight / 2 - 150) + 'px;_top:' + (winSize.windowHeight / 2 + top - 150)+ 'px;'; //弹出框的位置
        var alertBox = document.createElement('div');
        alertBox.id = 'alertMsg';
        alertBox.style.cssText = styleStr1;
        //创建弹出框里面的内容P标签
        var alertMsg_info = document.createElement('P');
        alertMsg_info.id = 'alertMsg_info';
        alertMsg_info.innerHTML = msg;
        alertBox.appendChild(alertMsg_info);
        //创建按钮
        var btn1 = document.createElement('a');
        btn1.id = 'alertMsg_btn1';
        btn1.href = 'javas' + 'cript:void(0)';
        btn1.innerHTML = '确定';
        btn1.onclick = function () {
            document.body.removeChild(alertBox);
            document.body.removeChild(shadowDiv);
            return true;
        };
        alertBox.appendChild(btn1);
        if (mode === 1) {
            var btn2 = document.createElement('a');
            btn2.id = 'alertMsg_btn2';
            btn2.href = 'javas' + 'cript:void(0)';
            btn2.innerHTML = '取消';
            btn2.onclick = function () {
                document.body.removeChild(alertBox);
                document.body.removeChild(shadowDiv);
                return false;
            };
            alertBox.appendChild(btn2);
        }
        document.body.appendChild(alertBox);

    }

  var errori ='yzmerr';
  if(errori=='yzmerr'){
	alertMsg("验证码错误",0);
  }else if(errori=='nouser'){
	alertMsg("用户名不存在",0);
  }else if(errori=='passwderr'){
	alertMsg("密码错误",0);
  }


text:
#pragma once

#include <getopt.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>

#include <pad/pad.h>

#include <cap/core/config.h>
#include <cap/ls/ls.h>
#include <cap/cat/cat.h>
#include <cap/make/make.h>

/**
 * structure and type of command
 */
struct CapServCmd;
typedef struct CapServCmd CapServCmd;

/**
 * destruct command
 *
 * @param[in] self pointer to CapServCmd
 */
void
CapServCmd_Del(CapServCmd *self);

/**
 * construct command
 *
 * @param[in] move_config reference to CapConfig
 * @param[in] argc        number of arguments
 * @param[in] move_argv   reference to array of arguments
 *
 * @return success to pointer to CapServCmd
 * @return failed to NULL
 */
CapServCmd *
CapServCmd_New(CapConfig *config, int argc, char **argv);

/**
 * run command
 *
 * @param[in] self pointer to CapServCmd
 *
 * @return success to number of 0
 * @return failed to number of not 0
 */
int
CapServCmd_Run(CapServCmd *self);


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package erp.mfin.data.diot;

/**
 *
 * @author Sergio Flores
 */
public class SDiotAccount {

    public String AccountCode;
    public boolean IsConfigParamAccount;

    /**
     * Create an account for DIOT processing.
     * Contains account number and a flag for accounts set up in configuration of company.
     * @param accountCode
     * @param isConfigParamAccount
     */
    public SDiotAccount(String accountCode, boolean isConfigParamAccount) {
        AccountCode = accountCode;
        IsConfigParamAccount = isConfigParamAccount;
    }
}