text:
require 'test_helper'

class TestInternet < MiniTest::Test
  def setup
    Laranja.load('pt-BR')
  end

  def test_email
    email = Laranja::Internet.email

    assert_kind_of String, email
    assert_match /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i, email
  end

  def test_email_with_parameter
    email = Laranja::Internet.email('John Doe')

    assert_kind_of String, email
    assert_match /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i, email
    assert_includes email, 'john'
    assert_includes email, 'doe'
  end

  def test_username
    username = Laranja::Internet.username

    assert_kind_of String, username
    refute_empty username
  end

  def test_username_with_name_parameter
    username = Laranja::Internet.username('John Doe')

    assert_kind_of String, username
    refute_empty username
    assert_includes username, 'john'
    assert_includes username, 'doe'
  end

  def test_username_with_name_and_separator_parameter
    assert_equal 'john-doe', Laranja::Internet.username('John Doe', ['-'])
  end

  def test_password
    password = Laranja::Internet.password

    assert_kind_of String, password
    refute_match /\W/, password
  end

  def test_password_with_min
    assert_operator Laranja::Internet.password(32).size, :>=, 32
  end

  def test_password_with_min_and_max
    assert_equal 64, Laranja::Internet.password(64, 64).size
  end
end


text:
@interface GridBackgroundView ()

@end

@implementation GridBackgroundView

- (instancetype)init {
    if(self = [super init]){
        [self commonInit];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if(self = [super initWithFrame:frame]){
        [self commonInit];
    }
    return self;
}

- (void)awakeFromNib{
    [self commonInit];
}

- (void)commonInit {
    _lineColor = [UIColor grayColor];
    _edgeLine = GBEdgeLineMake(NO, YES, NO, YES);
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextBeginPath(context);
    [self.lineColor setStroke];
//    CGContextMoveToPoint(context, 0, SINGLE_LINE_ADJUST_OFFSET);
//    CGContextAddLineToPoint(context, CGRectGetWidth(rect), SINGLE_LINE_ADJUST_OFFSET);
//    CGContextSetLineWidth(context, SINGLE_LINE_WIDTH);
//    CGContextStrokePath(context);
    CGFloat width = CGRectGetWidth(self.bounds)/self.column;
    CGFloat height = CGRectGetHeight(self.bounds)/self.row;
    for (int i = 1; i<self.column; i++) {
        CGContextMoveToPoint(context, ceil(width*i)+SINGLE_LINE_ADJUST_OFFSET, 0);
        CGContextAddLineToPoint(context, ceil(width*i)+SINGLE_LINE_ADJUST_OFFSET, CGRectGetHeight(self.bounds));
    }
    for (int i = 1; i<self.row; i++) {
        CGContextMoveToPoint(context, 0, ceil(height*i)+SINGLE_LINE_ADJUST_OFFSET);
        CGContextAddLineToPoint(context, CGRectGetWidth(self.bounds), ceil(height*i)+SINGLE_LINE_ADJUST_OFFSET);
    }
    if(self.edgeLine.top){
        CGContextMoveToPoint(context, 0, SINGLE_LINE_ADJUST_OFFSET);
        CGContextAddLineToPoint(context, CGRectGetWidth(rect), SINGLE_LINE_ADJUST_OFFSET);
    }
    if(self.edgeLine.bottom){
        CGContextMoveToPoint(context, 0, CGRectGetHeight(self.bounds)- SINGLE_LINE_ADJUST_OFFSET);
        CGContextAddLineToPoint(context, CGRectGetWidth(rect), CGRectGetHeight(self.bounds)- SINGLE_LINE_ADJUST_OFFSET);
    }
    if(self.edgeLine.left){
        CGContextMoveToPoint(context, SINGLE_LINE_ADJUST_OFFSET, 0);
        CGContextAddLineToPoint(context, SINGLE_LINE_ADJUST_OFFSET, CGRectGetHeight(self.bounds));
    }
    if (self.edgeLine.right){
        CGContextMoveToPoint(context, CGRectGetWidth(self.bounds)-SINGLE_LINE_ADJUST_OFFSET, 0);
        CGContextAddLineToPoint(context, CGRectGetWidth(self.bounds)-SINGLE_LINE_ADJUST_OFFSET, CGRectGetHeight(self.bounds));
    }

    CGContextSetLineWidth(context, SINGLE_LINE_WIDTH);
    CGContextStrokePath(context);

}

#pragma mark set get
- (void)setLineColor:(UIColor *)lineColor{
    if(_lineColor != lineColor){
        _lineColor = lineColor;
        [self setNeedsDisplay];
    }
}
- (void)setRow:(NSInteger)row{
    if(_row!=row){
        _row = row;
        [self setNeedsDisplay];
    }
}
- (void)setColumn:(NSInteger)column{
    if(_column!=column){
        _column = column;
        [self setNeedsDisplay];
    }
}
- (void)setEdgeLine:(GBEdgeLine)edgeLine{
    _edgeLine = edgeLine;
    [self setNeedsDisplay];
}
@end

redpajama_set_name: RedPajamaGithub


text:
"""Test suite for pymongo, bson, and gridfs.
"""

import os
import socket
import sys
from pymongo.common import partition_node

if sys.version_info[:2] == (2, 6):
    import unittest2 as unittest
    from unittest2 import SkipTest
else:
    import unittest
    from unittest import SkipTest
import warnings

from functools import wraps

import pymongo
import pymongo.errors

from bson.py3compat import _unicode
from pymongo import common
from test.version import Version

# hostnames retrieved from isMaster will be of unicode type in Python 2,
# so ensure these hostnames are unicodes, too. It makes tests like
# `test_repr` predictable.
host = _unicode(os.environ.get("DB_IP", 'localhost'))
port = int(os.environ.get("DB_PORT", 27017))
pair = '%s:%d' % (host, port)

host2 = _unicode(os.environ.get("DB_IP2", 'localhost'))
port2 = int(os.environ.get("DB_PORT2", 27018))

host3 = _unicode(os.environ.get("DB_IP3", 'localhost'))
port3 = int(os.environ.get("DB_PORT3", 27019))

db_user = _unicode(os.environ.get("DB_USER", "user"))
db_pwd = _unicode(os.environ.get("DB_PASSWORD", "password"))

class client_knobs(object):
    def __init__(
            self,
            heartbeat_frequency=None,
            kill_cursor_frequency=None):
        self.heartbeat_frequency = heartbeat_frequency
        self.kill_cursor_frequency = kill_cursor_frequency

        self.old_heartbeat_frequency = None
        self.old_kill_cursor_frequency = None

    def enable(self):
        self.old_heartbeat_frequency = common.HEARTBEAT_FREQUENCY
        self.old_kill_cursor_frequency = common.KILL_CURSOR_FREQUENCY

        if self.heartbeat_frequency is not None:
            common.HEARTBEAT_FREQUENCY = self.heartbeat_frequency

        if self.kill_cursor_frequency is not None:
            common.KILL_CURSOR_FREQUENCY = self.kill_cursor_frequency

    def __enter__(self):
        self.enable()

    def disable(self):
        common.HEARTBEAT_FREQUENCY = self.old_heartbeat_frequency
        common.KILL_CURSOR_FREQUENCY = self.old_kill_cursor_frequency

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.disable()

class ClientContext(object):

    def __init__(self):
        """Create a client and grab essential information from the server."""
        self.connected = False
        self.ismaster = {}
        self.w = None
        self.nodes = set()
        self.replica_set_name = None
        self.rs_client = None
        self.cmd_line = None
        self.version = Version(-1)  # Needs to be comparable with Version
        self.auth_enabled = False
        self.test_commands_enabled = False
        self.is_mongos = False
        self.is_rs = False
        self.has_ipv6 = False

        try:
            client = pymongo.MongoClient(host, port,
                                         serverSelectionTimeoutMS=100)
            client.admin.command('ismaster')  # Can we connect?

            # If so, then reset client to defaults.
            self.client = pymongo.MongoClient(host, port)

        except pymongo.errors.ConnectionFailure:
            self.client = None
        else:
            self.connected = True
            self.ismaster = self.client.admin.command('ismaster')
            self.w = len(self.ismaster.get("hosts", [])) or 1
            self.nodes = set([(host, port)])
            self.replica_set_name = self.ismaster.get('setName', '')
            self.rs_client = None
            self.version = Version.from_client(self.client)
            if self.replica_set_name:
                self.is_rs = True
                self.rs_client = pymongo.MongoClient(
                    pair, replicaSet=self.replica_set_name)

                nodes = [partition_node(node)
                         for node in self.ismaster.get('hosts', [])]
                nodes.extend([partition_node(node)
                              for node in self.ismaster.get('passives', [])])
                nodes.extend([partition_node(node)
                              for node in self.ismaster.get('arbiters', [])])
                self.nodes = set(nodes)

            self.rs_or_standalone_client = self.rs_client or self.client

            try:
                self.cmd_line = self.client.admin.command('getCmdLineOpts')
            except pymongo.errors.OperationFailure as e:
                msg = e.details.get('errmsg', '')
                if e.code == 13 or 'unauthorized' in msg or 'login' in msg:
                    # Unauthorized.
                    self.auth_enabled = True
                else:
                    raise
            else:
                self.auth_enabled = self._server_started_with_auth()

            if self.auth_enabled:
                # See if db_user already exists.
                self.user_provided = self._check_user_provided()
                if not self.user_provided:
                    roles = {}
                    if self.version.at_least(2, 5, 3, -1):
                        roles = {'roles': ['root']}
                    self.client.admin.add_user(db_user, db_pwd, **roles)
                    self.client.admin.authenticate(db_user, db_pwd)

                if self.rs_client:
                    self.rs_client.admin.authenticate(db_user, db_pwd)

                # May not have this if OperationFailure was raised earlier.
                self.cmd_line = self.client.admin.command('getCmdLineOpts')

            if 'enableTestCommands=1' in self.cmd_line['argv']:
                self.test_commands_enabled = True
            elif 'parsed' in self.cmd_line:
                params = self.cmd_line['parsed'].get('setParameter', [])
                if 'enableTestCommands=1' in params:
                    self.test_commands_enabled = True

            self.is_mongos = (self.ismaster.get('msg') == 'isdbgrid')
            self.has_ipv6 = self._server_started_with_ipv6()

    def _check_user_provided(self):
        try:
            self.client.admin.authenticate(db_user, db_pwd)
            return True
        except pymongo.errors.OperationFailure as e:
            msg = e.details.get('errmsg', '')
            if e.code == 18 or 'auth fails' in msg:
                # Auth failed.
                return False
            else:
                raise

    def _server_started_with_auth(self):
        # MongoDB >= 2.0
        if 'parsed' in self.cmd_line:
            parsed = self.cmd_line['parsed']
            # MongoDB >= 2.6
            if 'security' in parsed:
                security = parsed['security']
                # >= rc3
                if 'authorization' in security:
                    return security['authorization'] == 'enabled'
                # < rc3
                return (security.get('auth', False) or
                        bool(security.get('keyFile')))
            return parsed.get('auth', False) or bool(parsed.get('keyFile'))
        # Legacy
        argv = self.cmd_line['argv']
        return '--auth' in argv or '--keyFile' in argv

    def _server_started_with_ipv6(self):
        if not socket.has_ipv6:
            return False

        if 'parsed' in self.cmd_line:
            if not self.cmd_line['parsed'].get('net', {}).get('ipv6'):
                return False
        else:
            if '--ipv6' not in self.cmd_line['argv']:
                return False

        # The server was started with --ipv6. Is there an IPv6 route to it?
        try:
            for info in socket.getaddrinfo(host, port):
                if info[0] == socket.AF_INET6:
                    return True
        except socket.error:
            pass

        return False

    def _require(self, condition, msg, func=None):
        def make_wrapper(f):
            @wraps(f)
            def wrap(*args, **kwargs):
                # Always raise SkipTest if we can't connect to MongoDB
                if not self.connected:
                    raise SkipTest("Cannot connect to MongoDB on %s" % pair)
                if condition:
                    return f(*args, **kwargs)
                raise SkipTest(msg)
            return wrap

        if func is None:
            def decorate(f):
                return make_wrapper(f)
            return decorate
        return make_wrapper(func)

    def require_connection(self, func):
        """Run a test only if we can connect to MongoDB."""
        return self._require(self.connected,
                             "Cannot connect to MongoDB on %s" % pair,
                             func=func)

    def require_version_min(self, *ver):
        """Run a test only if the server version is at least ``version``."""
        other_version = Version(*ver)
        return self._require(self.version >= other_version,
                             "Server version must be at least %s"
                             % str(other_version))

    def require_version_max(self, *ver):
        """Run a test only if the server version is at most ``version``."""
        other_version = Version(*ver)
        return self._require(self.version <= other_version,
                             "Server version must be at most %s"
                             % str(other_version))

    def require_auth(self, func):
        """Run a test only if the server is running with auth enabled."""
        return self.check_auth_with_sharding(
            self._require(self.auth_enabled,
                          "Authentication is not enabled on the server",
                          func=func))

    def require_no_auth(self, func):
        """Run a test only if the server is running without auth enabled."""
        return self._require(not self.auth_enabled,
                             "Authentication must not be enabled on the server",
                             func=func)

    def require_replica_set(self, func):
        """Run a test only if the client is connected to a replica set."""
        return self._require(self.is_rs,
                             "Not connected to a replica set",
                             func=func)

    def require_no_replica_set(self, func):
        """Run a test if the client is *not* connected to a replica set."""
        return self._require(
            not self.is_rs,
            "Connected to a replica set, not a standalone mongod",
            func=func)

    def require_ipv6(self, func):
        """Run a test only if the client can connect to a server via IPv6."""
        return self._require(self.has_ipv6,
                             "No IPv6",
                             func=func)

    def require_no_mongos(self, func):
        """Run a test only if the client is not connected to a mongos."""
        return self._require(not self.is_mongos,
                             "Must be connected to a mongod, not a mongos",
                             func=func)

    def require_mongos(self, func):
        """Run a test only if the client is connected to a mongos."""
        return self._require(self.is_mongos,
                             "Must be connected to a mongos",
                             func=func)

    def check_auth_with_sharding(self, func):
        """Skip a test when connected to mongos < 2.0 and running with auth."""
        condition = not (self.auth_enabled and
                         self.is_mongos and self.version < (2,))
        return self._require(condition,
                             "Auth with sharding requires MongoDB >= 2.0.0",
                             func=func)

    def require_test_commands(self, func):
        """Run a test only if the server has test commands enabled."""
        return self._require(self.test_commands_enabled,
                             "Test commands must be enabled",
                             func=func)

# Reusable client context
client_context = ClientContext()

class IntegrationTest(unittest.TestCase):
    """Base class for TestCases that need a connection to MongoDB to pass."""

    @classmethod
    @client_context.require_connection
    def setUpClass(cls):
        cls.client = client_context.rs_or_standalone_client
        cls.db = cls.client.pymongo_test

class MockClientTest(unittest.TestCase):
    """Base class for TestCases that use MockClient.

    This class is *not* an IntegrationTest: if properly written, MockClient
    tests do not require a running server.

    The class temporarily overrides HEARTBEAT_FREQUENCY to speed up tests.
    """

    def setUp(self):
        super(MockClientTest, self).setUp()

        self.client_knobs = client_knobs(
            heartbeat_frequency=0.001)

        self.client_knobs.enable()

    def tearDown(self):
        self.client_knobs.disable()
        super(MockClientTest, self).tearDown()

def setup():
    warnings.resetwarnings()
    warnings.simplefilter("always")

def teardown():
    c = client_context.client
    c.drop_database("pymongo-pooling-tests")
    c.drop_database("pymongo_test")
    c.drop_database("pymongo_test1")
    c.drop_database("pymongo_test2")
    c.drop_database("pymongo_test_mike")
    c.drop_database("pymongo_test_bernie")
    if client_context.auth_enabled and not client_context.user_provided:
        c.admin.remove_user(db_user)

class PymongoTestRunner(unittest.TextTestRunner):
    def run(self, test):
        setup()
        result = super(PymongoTestRunner, self).run(test)
        try:
            teardown()
        finally:
            return result

def test_cases(suite):
    """Iterator over all TestCases within a TestSuite."""
    for suite_or_case in suite._tests:
        if isinstance(suite_or_case, unittest.TestCase):
            # unittest.TestCase
            yield suite_or_case
        else:
            # unittest.TestSuite
            for case in test_cases(suite_or_case):
                yield case


text:
layout: projects
title: 'Highlights: Alleyway Projection'
category: projects
project-team: 'Highlights: Alleyway Projection'
project-photo: Highlights.jpg
project-site: http://www.instructables.com/id/HIGHLIGHTS-Alleyway-Projection/
#project-launched-links:
#- City and County of Denver: http://www.denvergov.org
#- City and County of San Francisco: http://sfgov.org
#project-gallery: [slide1.jpg,slide2.jpg,slide3.jpg]
---

The idea of the project "Highlights: is to really transform dark public spaces (or alleyways) into usable space at night through thoughtful video/mapping projections.

It could also be a very educational approach, i.e. transforming the alley into a native redwood forest and projecting native flora and fauna, or something that is historically or culturally significant to the alley like the mural that we had done.

Overall goal is to revitalize these urban voids for people to walk through at night and feel safe. It's an idea that could be used in any urban environment scale: city, state, country-  as every built-up environment has these dark spaces between buildings. It could be a way to really revitalize an area and introduce people, business, and culture into a space that is perceived negatively.


text:
template <class It>
void
test(It i, It x)
{
    std::reverse_iterator<It> r(i);
    std::reverse_iterator<It> rr = r--;
    assert(r.base() == x);
    assert(rr.base() == i);
}

int main()
{
    const char* s = "123";
    test(bidirectional_iterator<const char*>(s+1), bidirectional_iterator<const char*>(s+2));
    test(random_access_iterator<const char*>(s+1), random_access_iterator<const char*>(s+2));
    test(s+1, s+2);
}


text:
#include <Game/Calibrator/App.h>

USING_NAMESPACE

int main( int argc, char** argv )
{
   return CalibratorApp::create( argc, argv )->run();
}


text:
WebDriverAgent is a [WebDriver server](https://w3c.github.io/webdriver/webdriver-spec.html) implementation for iOS that can be used to remote control iOS devices. It allows you to launch & kill applications, tap & scroll views or confirm view presence on a screen. This makes it a perfect tool for application end-to-end testing or general purpose device automation. It works by linking `XCTest.framework` and calling Apple's API to execute commands directly on a device. WebDriverAgent is developed and used at Facebook for end-to-end testing and is successfully adopted by [Appium](http://appium.io).

## Features
 * Works with device & simulator
 * Implements most of [WebDriver spec](https://w3c.github.io/webdriver/webdriver-spec.html)
 * [USB support](https://github.com/facebook/WebDriverAgent/wiki/USB-support) for devices
 * Inspector [endpoint](http://localhost:8100/inspector) with friendly user interface to inspect current device state
 * Easy development cycle as it can be launched & debugged directly via Xcode
 * Unsupported yet, but works with tvOS & OSX

[![Demo Video](https://j.gifs.com/gJymG9.gif)](https://youtu.be/EatiYGFxBxY)

## Getting Started
To get the project set up just run bootstrap script:
```
./Scripts/bootstrap.sh
```
It will:
* fetch all dependencies with [Carthage](https://github.com/Carthage/Carthage)
* build Inspector bundle using [npm](https://www.npmjs.com)

After it is finished you can simply open `WebDriverAgent.xcodeproj` and start `WebDriverAgentRunner` test
and start sending [requests](https://github.com/facebook/WebDriverAgent/wiki/Queries).

More about how to start WebDriverAgent [here](https://github.com/facebook/WebDriverAgent/wiki/Starting-WebDriverAgent).

## Known Issues
If you are having some issues please checkout [wiki](https://github.com/facebook/WebDriverAgent/wiki/Common-Issues) first.

## For Contributors
If you want to help us out, you are more than welcome to. However please make sure you have followed the guidelines in [CONTRIBUTING](CONTRIBUTING.md).

## License

[`WebDriverAgent` is BSD-licensed](LICENSE). We also provide an additional [patent grant](PATENTS).

Have fun!


text:
/* /\/\/\/\/\/\/\/\/ CLIENT-SPECIFIC STYLES /\/\/\/\/\/\/\/\/ */
#outlook a{padding:0;} /* Force Outlook to provide a "view in browser" message */
.ReadMsgBody{width:100%;} .ExternalClass{width:100%;} /* Force Hotmail to display emails at full width */
.ExternalClass, .ExternalClass p, .ExternalClass span, .ExternalClass font, .ExternalClass td, .ExternalClass div {line-height: 100%;} /* Force Hotmail to display normal line spacing */
body, table, td, p, a, li, blockquote{-webkit-text-size-adjust:100%; -ms-text-size-adjust:100%;} /* Prevent WebKit and Windows mobile changing default text sizes */
table, td{mso-table-lspace:0pt; mso-table-rspace:0pt;} /* Remove spacing between tables in Outlook 2007 and up */
img{-ms-interpolation-mode:bicubic;} /* Allow smoother rendering of resized image in Internet Explorer */

/* /\/\/\/\/\/\/\/\/ RESET STYLES /\/\/\/\/\/\/\/\/ */
body{margin:0; padding:0;}
img{border:0; height:auto; line-height:100%; outline:none; text-decoration:none;}
table{border-collapse:collapse !important;}
body, #bodyTable, #bodyCell{height:100% !important; margin:0; padding:0; width:100% !important;}

/* /\/\/\/\/\/\/\/\/ TEMPLATE STYLES /\/\/\/\/\/\/\/\/ */

/* ========== Page Styles ========== */

#bodyCell{padding:20px;}
#templateContainer{width:600px;}

/**
* @tab Page
* @section background style
* @tip Set the background color and top border for your email. You may want to choose colors that match your company's branding.
* @theme page
*/
body, #bodyTable{
	/*@editable*/ background-color:#fff;
}

/**
* @tab Page
* @section background style
* @tip Set the background color and top border for your email. You may want to choose colors that match your company's branding.
* @theme page
*/
#bodyCell{
	/*@editable*/ border-top:1px solid #BBBBBB;
}

/**
* @tab Page
* @section email border
* @tip Set the border for your email.
*/
#templateContainer{
	/*@editable*/ border:1px solid #BBBBBB;
}

/**
* @tab Page
* @section heading 1
* @tip Set the styling for all first-level headings in your emails. These should be the largest of your headings.
* @style heading 1
*/
h1{
	/*@editable*/ color:#202020 !important;
	display:block;
	/*@editable*/ font-family:Helvetica;
	/*@editable*/ font-size:26px;
	/*@editable*/ font-style:normal;
	/*@editable*/ font-weight:normal;
	/*@editable*/ line-height:100%;
	/*@editable*/ letter-spacing:normal;
	margin-top:0;
	margin-right:0;
	margin-bottom:10px;
	margin-left:0;
	/*@editable*/ text-align:left;
}

/**
* @tab Page
* @section heading 2
* @tip Set the styling for all second-level headings in your emails.
* @style heading 2
*/
h2{
	/*@editable*/ color:#404040 !important;
	display:block;
	/*@editable*/ font-family:Helvetica;
	/*@editable*/ font-size:20px;
	/*@editable*/ font-style:normal;
	/*@editable*/ font-weight:normal;
	/*@editable*/ line-height:100%;
	/*@editable*/ letter-spacing:normal;
	margin-top:0;
	margin-right:0;
	margin-bottom:10px;
	margin-left:0;
	/*@editable*/ text-align:left;
}

/**
* @tab Page
* @section heading 3
* @tip Set the styling for all third-level headings in your emails.
* @style heading 3
*/
h3{
	/*@editable*/ color:#606060 !important;
	display:block;
	/*@editable*/ font-family:Helvetica;
	/*@editable*/ font-size:16px;
	/*@editable*/ font-weight:normal;
	/*@editable*/ line-height:100%;
	/*@editable*/ letter-spacing:normal;
	margin-top:0;
	margin-right:0;
	margin-bottom:10px;
	margin-left:0;
	/*@editable*/ text-align:left;
}

/**
* @tab Page
* @section heading 4
* @tip Set the styling for all fourth-level headings in your emails. These should be the smallest of your headings.
* @style heading 4
*/
h4{
	/*@editable*/ color:#808080 !important;
	display:block;
	/*@editable*/ font-family:Helvetica;
	/*@editable*/ font-size:14px;
	/*@editable*/ font-weight:normal;
	/*@editable*/ line-height:100%;
	/*@editable*/ letter-spacing:normal;
	margin-top:0;
	margin-right:0;
	margin-bottom:10px;
	margin-left:0;
	/*@editable*/ text-align:left;
}

/* ========== Header Styles ========== */

/**
* @tab Header
* @section preheader style
* @tip Set the background color and bottom border for your email's preheader area.
* @theme header
*/
#templatePreheader{
	/*@editable*/ background-color:#fff;
	/*@editable*/ border-bottom:1px solid #CCCCCC;
}

/**
* @tab Header
* @section preheader text
* @tip Set the styling for your email's preheader text. Choose a size and color that is easy to read.
*/
.preheaderContent{
	/*@editable*/ color:#808080;
	/*@editable*/ font-family:Helvetica;
	/*@editable*/ font-size:10px;
	/*@editable*/ line-height:125%;
	/*@editable*/ text-align:left;
}

/**
* @tab Header
* @section preheader link
* @tip Set the styling for your email's preheader links. Choose a color that helps them stand out from your text.
*/
.preheaderContent a:link, .preheaderContent a:visited, /* Yahoo! Mail Override */ .preheaderContent a .yshortcuts /* Yahoo! Mail Override */{
	/*@editable*/ color:#606060;
	/*@editable*/ font-weight:normal;
	/*@editable*/ text-decoration:underline;
}

/**
* @tab Header
* @section header style
* @tip Set the background color and borders for your email's header area.
* @theme header
*/
#templateHeader{
	/*@editable*/ background-color:#fff;
	/*@editable*/ border-top:1px solid #FFFFFF;
	/*@editable*/ border-bottom:1px solid #CCCCCC;
}

/**
* @tab Header
* @section header text
* @tip Set the styling for your email's header text. Choose a size and color that is easy to read.
*/
.headerContent{
	/*@editable*/ color:#505050;
	/*@editable*/ font-family:Helvetica;
	/*@editable*/ font-size:20px;
	/*@editable*/ font-weight:normal;
	/*@editable*/ line-height:100%;
	/*@editable*/ padding: 10px 20px;
	/*@editable*/ text-align:left;
	/*@editable*/ vertical-align:middle;
}

/**
* @tab Header
* @section header link
* @tip Set the styling for your email's header links. Choose a color that helps them stand out from your text.
*/
.headerContent a:link, .headerContent a:visited, /* Yahoo! Mail Override */ .headerContent a .yshortcuts /* Yahoo! Mail Override */{
	/*@editable*/ color:#EB4102;
	/*@editable*/ font-weight:normal;
	/*@editable*/ text-decoration:underline;
}

#headerImage{
	height:auto;
	max-width:600px;
}

/* ========== Body Styles ========== */

/**
* @tab Body
* @section body style
* @tip Set the background color and borders for your email's body area.
*/
#templateBody{
	/*@editable*/ background-color:#fff;
	/*@editable*/ border-top:1px solid #FFFFFF;
	/*@editable*/ border-bottom:1px solid #CCCCCC;
}

/**
* @tab Body
* @section body text
* @tip Set the styling for your email's main content text. Choose a size and color that is easy to read.
* @theme main
*/
.bodyContent{
	/*@editable*/ color:#505050;
	/*@editable*/ font-family:Helvetica;
	/*@editable*/ font-size:14px;
	/*@editable*/ line-height:150%;
	padding-top:20px;
	padding-right:20px;
	padding-bottom:20px;
	padding-left:20px;
	/*@editable*/ text-align:left;
}

/**
* @tab Body
* @section body link
* @tip Set the styling for your email's main content links. Choose a color that helps them stand out from your text.
*/
.bodyContent a:link, .bodyContent a:visited, /* Yahoo! Mail Override */ .bodyContent a .yshortcuts /* Yahoo! Mail Override */{
	/*@editable*/ color:#EB4102;
	/*@editable*/ font-weight:normal;
	/*@editable*/ text-decoration:underline;
}

.bodyContent img{
	display:inline;
	height:auto;
	max-width:560px;
}

.bodyContent a.btn {
	border: 3px solid #00e36c;
	color: #00e36c;
	padding: 1em;
	text-decoration: none;
	text-align: center;
	display:inline-block;
	font-size:1.2em;
}

/* ========== Footer Styles ========== */

/**
* @tab Footer
* @section footer style
* @tip Set the background color and borders for your email's footer area.
* @theme footer
*/
#templateFooter{
	/*@editable*/ background-color:#fff;
	/*@editable*/ border-top:1px solid #FFFFFF;
}

/**
* @tab Footer
* @section footer text
* @tip Set the styling for your email's footer text. Choose a size and color that is easy to read.
* @theme footer
*/
.footerContent{
	/*@editable*/ color:#808080;
	/*@editable*/ font-family:Helvetica;
	/*@editable*/ font-size:10px;
	/*@editable*/ line-height:150%;
	padding-top:20px;
	padding-right:20px;
	padding-bottom:20px;
	padding-left:20px;
	/*@editable*/ text-align:left;
}

/**
* @tab Footer
* @section footer link
* @tip Set the styling for your email's footer links. Choose a color that helps them stand out from your text.
*/
.footerContent a:link, .footerContent a:visited, /* Yahoo! Mail Override */ .footerContent a .yshortcuts, .footerContent a span /* Yahoo! Mail Override */{
	/*@editable*/ color:#606060;
	/*@editable*/ font-weight:normal;
	/*@editable*/ text-decoration:underline;
}

/* /\/\/\/\/\/\/\/\/ MOBILE STYLES /\/\/\/\/\/\/\/\/ */

      @media only screen and (max-width: 480px){
	/* /\/\/\/\/\/\/ CLIENT-SPECIFIC MOBILE STYLES /\/\/\/\/\/\/ */
	body, table, td, p, a, li, blockquote{-webkit-text-size-adjust:none !important;} /* Prevent Webkit platforms from changing default text sizes */
          body{width:100% !important; min-width:100% !important;} /* Prevent iOS Mail from adding padding to the body */

	/* /\/\/\/\/\/\/ MOBILE RESET STYLES /\/\/\/\/\/\/ */
	#bodyCell{padding:10px !important;}

	/* /\/\/\/\/\/\/ MOBILE TEMPLATE STYLES /\/\/\/\/\/\/ */

	/* ======== Page Styles ======== */

	/**
	* @tab Mobile Styles
	* @section template width
	* @tip Make the template fluid for portrait or landscape view adaptability. If a fluid layout doesn't work for you, set the width to 300px instead.
	*/
	#templateContainer{
		max-width:600px !important;
		/*@editable*/ width:100% !important;
	}

	/**
	* @tab Mobile Styles
	* @section heading 1
	* @tip Make the first-level headings larger in size for better readability on small screens.
	*/
	h1{
		/*@editable*/ font-size:24px !important;
		/*@editable*/ line-height:100% !important;
	}

	/**
	* @tab Mobile Styles
	* @section heading 2
	* @tip Make the second-level headings larger in size for better readability on small screens.
	*/
	h2{
		/*@editable*/ font-size:20px !important;
		/*@editable*/ line-height:100% !important;
	}

	/**
	* @tab Mobile Styles
	* @section heading 3
	* @tip Make the third-level headings larger in size for better readability on small screens.
	*/
	h3{
		/*@editable*/ font-size:18px !important;
		/*@editable*/ line-height:100% !important;
	}

	/**
	* @tab Mobile Styles
	* @section heading 4
	* @tip Make the fourth-level headings larger in size for better readability on small screens.
	*/
	h4{
		/*@editable*/ font-size:16px !important;
		/*@editable*/ line-height:100% !important;
	}

	/* ======== Header Styles ======== */

	#templatePreheader{display:none !important;} /* Hide the template preheader to save space */

	/**
	* @tab Mobile Styles
	* @section header image
	* @tip Make the main header image fluid for portrait or landscape view adaptability, and set the image's original width as the max-width. If a fluid setting doesn't work, set the image width to half its original size instead.
	*/
	#headerImage{
		height:auto !important;
		/*@editable*/ max-width:600px !important;
		/*@editable*/ width:100% !important;
	}

	/**
	* @tab Mobile Styles
	* @section header text
	* @tip Make the header content text larger in size for better readability on small screens. We recommend a font size of at least 16px.
	*/
	.headerContent{
		/*@editable*/ font-size:20px !important;
		/*@editable*/ line-height:125% !important;
	}

	/* ======== Body Styles ======== */

	/**
	* @tab Mobile Styles
	* @section body text
	* @tip Make the body content text larger in size for better readability on small screens. We recommend a font size of at least 16px.
	*/
	.bodyContent{
		/*@editable*/ font-size:18px !important;
		/*@editable*/ line-height:125% !important;
	}

	/* ======== Footer Styles ======== */

	/**
	* @tab Mobile Styles
	* @section footer text
	* @tip Make the body content text larger in size for better readability on small screens.
	*/
	.footerContent{
		/*@editable*/ font-size:14px !important;
		/*@editable*/ line-height:115% !important;
	}

	.footerContent a{display:block !important;} /* Place footer social and utility links on their own lines, for easier access */
}


text:
package com.bond.spider.core.dto;

/**
 * 添加题目
 *
 * @author: Administrator  Date: 2016/12/13 0013 Time: 16:04
 */
public class AddCommonQuestionDto {
    private String sessionId;
    private CommonQuestionDto questionDto;

    public String getSessionId() {
        return sessionId;
    }

    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }

    public CommonQuestionDto getQuestionDto() {
        return questionDto;
    }

    public void setQuestionDto(CommonQuestionDto questionDto) {
        this.questionDto = questionDto;
    }
}


text:
package com.bgh.myopeninvoice.common.util;

public enum RateType {
  DAY,
  HOUR,
  TOTAL
}


text:
import Backbone from 'backbone';

export default Backbone.Model.extend({
    defaults: {
        subTotal: 0,
        discount: 0,
        tax: {},
        total: 0,
        hasTax: false
    }
});


text:
#include "mysql.h"
#include <cstdio>
#include <sstream>
#include <fstream>
#include <cstring>
#include <string>
#include <iostream>
#include <vector>
using namespace std;
int main() {
MYSQL *conn;
MYSQL_RES *res,*res_tot_flows,*res_sip,*res_dip,*res_flags,*res_packets,*res_d,*res_scanner;
MYSQL_RES *res_hit1,*res_hit2,*mysqlResult,*res_miss,*res_ch1,*res_ch2,*res_sip2,*res_ht1,*res_ht2,*res_ht22,*re
s_ht3,*res_ht33;
MYSQL_ROW row,mysqlRow,row_tot_flows,row_sip,row_dip,row_flags,row_packets,row_d,row_scanner;
MYSQL_ROW row_hit1,row_hit2,row_miss,row_ch1,row_ch2,row_sip2,row_ht1,row_ht2,row_ht22,row_ht3,row_ht33;
unsigned int num_fields;
MYSQL_RES *res_syn,*res_f,*res_nom,*res_noh;
MYSQL_ROW row_syn,row_f,row_nom,row_noh;
int curr_id=1;
 float hit_likelihood,miss_likelihood,likelihood;
int noh,nom,miss;
std::string sip,hit,misses,flags,packets,dip,sip1,dip1,mq0;
int tot_flows,ch1,ch2;
//code for connecting to local mysql database
const char *server = "localhost";
  const char *user = "root";
   const char *password = "letmein"; /* set me first */
   //unsigned int port=3307;
   const char *database = "TRW_PLAIN";
   conn = mysql_init(NULL);
   /* Connect to database */

 if (!mysql_real_connect(conn, server,
         user, password, database, 0, NULL, 0))
 {
     fprintf(stderr, "%s\n", mysql_error(conn));
 }
 // code for connecting to cryptDB's server and encrypted database
 const char *server = "127.0.0.1";
const char *user = "root";
const char *password = "letmein";
unsigned int port=3307;
//change the database name
const char *database = "TRW_crypt";
conn = mysql_init(NULL);
/* Connect to database */
if (!mysql_real_connect(conn, server,user, password, database, port, NULL, CLIENT_MULTI_STATEMENTS))
 {
 fprintf(stderr, "%s\n", mysql_error(conn));
 }
mysql_query(conn,"drop table if exists ipset;");
mysql_query(conn,"create table ipset(ip varchar(25));");
mysql_query(conn,"insert into ipset values('131.243.18.66');");
mysql_query(conn,"insert into ipset values('131.243.68.51');");
mysql_query(conn,"insert into ipset values('128.3.99.47');");
mysql_query(conn,"insert into ipset values('128.3.96.153');");
mysql_query(conn,"insert into ipset values('128.3.209.164');");
mysql_query(conn,"insert into ipset values('213.147.167.100');");
/*if (mysql_query(conn, "select count(*) from scan;"))
 {
    fprintf(stderr, "%s\n", mysql_error(conn));
}
res_tot_flows=mysql_store_result(conn);
row_tot_flows = mysql_fetch_row(res_tot_flows);
istringstream tot_flows_buff(row_tot_flows[0]);
tot_flows_buff >> tot_flows;
cout<<tot_flows<<endl;
*/
mysql_query(conn,"drop table if exists scan_sip;");
//std::string status="NULL";
if(mysql_query(conn, "create table scan_sip(s_id integer auto_increment primary key,sip varchar(25),dip varchar(
25),flags varchar(10),packets integer,hit integer,misses integer);"))
{
fprintf(stderr, "%s\n", mysql_error(conn));
}

std::string new_conn="insert into scan_sip(sip,dip,flags,packets) select sip,dip,flags,packets from scan group b
y sip,dip;";
//cout<<new_conn<<endl;
mysql_query(conn,new_conn.c_str());
mysqlResult = mysql_store_result(conn); // Get the Result Set
//mysql_query(conn, "alter table scan_sip add(hit integer);");
//mysql_query(conn, "alter table scan_sip add(misses integer);");
//mysql_query(conn, "alter table scan_sip add(status varchar(10));");
//mysql_query(conn, "insert into scan_sip(hit,misses) values(0,0);");
//mysql_query(conn, "insert into scan_sip(status) values('u|');");
//mysql_query(conn, "update scan_sip set hit=0;");
//mysql_query(conn, "update scan_sip set misses=0;");
//mysql_query(conn, "update scan_sip set status='NULL';");
/*if(mysql_query(conn, "select * from scan_sip into outfile '/tmp/sb1.txt' FIELDS TERMINATED BY '|' LINES TERMIN
ATED BY '\n'")) {
        fprintf(stderr, "%s\n", mysql_error(conn));
    }*/
if (mysql_query(conn, "select count(*) from scan_sip;"))
 {
    fprintf(stderr, "%s\n", mysql_error(conn));
}
res_tot_flows=mysql_store_result(conn);
row_tot_flows = mysql_fetch_row(res_tot_flows);
istringstream tot_flows_buff(row_tot_flows[0]);
tot_flows_buff >> tot_flows;
cout<<tot_flows<<endl;

while(curr_id<tot_flows)
{
stringstream ss;
ss << curr_id;
string id_query = ss.str();
cout<<ss.str()<<endl;
/*std::string h1="select count(*) from scan_sip where s_id=ss.str()";
//std::string h2="and flags='s' + " ";
std::string hit1_query= h1 + " " + "and dip in('131.243.18.66','131.243.68.51','128.3.99.47','128.3.96.153',
'128.3.209.164','213.147.167.100');";
*/
/*std::string ht_query="select count(*) from scan_sip s1 inner join ipset i1 where s1.s_id=" +ss.str();
std::string hit1_query=ht_query + " " + "and s1.flags='S' and s1.dip=i1.ip;";
//cout<<hit1_query<<endl;
*/
//std::string h1="select count(*) from scan_sip where s_id=" + ss.str();
std::string h1="select count(*) from scan_sip s1 inner join ipset i1 where s1.s_id=" +ss.str();
std::string hit1_query= h1 + " " + "and s1.flags='S' and s1.dip=i1.ip;";
cout<<hit1_query<<endl;
mysql_query(conn, hit1_query.c_str());
mysql_query(conn, hit1_query.c_str());
res_hit1=mysql_store_result(conn);
row_hit1=mysql_fetch_row(res_hit1);
istringstream buffer1(row_hit1[0]);
int hit1;
buffer1 >> hit1;
cout<<"hit1:"<<hit1<<endl;

std::string hit2_query=h1 + " " + "and s1.flags!='S' and s1.dip!=i1.ip;";
mysql_query(conn, hit2_query.c_str());
//mysql_query(conn, hit1_query.c_str());
cout<<hit2_query<<endl;
res_hit2=mysql_store_result(conn);
row_hit2=mysql_fetch_row(res_hit2);
istringstream buffer2(row_hit2[0]);
int hit2;
buffer2 >> hit2;
std::cout<<"hit2:"<<hit2<<std::endl;
int h = hit1 + hit2;
stringstream hh;
hh << h;
hit = hh.str();
if(h>0)
{
string uph = "update scan_sip set hit=1;";
mysql_query(conn,uph.c_str());
cout<<uph<<endl;
}
if(h==0)
{
string miss_query= h1 + " " + "and s1.flags='S' and s1.dip!=i1.ip;";
cout<<miss_query<<endl;
mysql_query(conn, miss_query.c_str());
res_miss=mysql_store_result(conn);
cout<<miss_query<<endl;
row_miss=mysql_fetch_row(res_miss);
istringstream miss_buff(row_miss[0]);
miss_buff >> miss;
cout<<"miss:"<<miss<<endl;
stringstream ms;
ms << miss;
misses = ms.str();
string up2;
up2="update scan_sip set misses=1;";
cout<<up2<<endl;
mysql_query(conn,up2.c_str());
}
curr_id = curr_id+1;
}
mysql_query(conn,"drop table if exists sc;");
mysql_query(conn,"create table sc(source_ip varchar(25),status varchar(10));");
mysql_query(conn,"select distinct sip from scan_sip where hit>0 or misses>0;");
res_d=mysql_store_result(conn);
string d;
string synq="select count(*) from scan_sip where sip=";
cout<<"distinct sips:"<<endl;
while ((row_d = mysql_fetch_row(res_d))!=NULL)
{
 d=string(row_d[0]);
cout<<d<<endl;
string sq=synq + "'" +d + "'" + " " + "and flags='S';";
mysql_query(conn,sq.c_str());
res_syn=mysql_store_result(conn);
row_syn = mysql_fetch_row(res_syn);
istringstream syn_buff(row_syn[0]);
int syns;
syn_buff >> syns;
cout<<"syns:"<<syns<<endl;
string s_dq="'" +d + "'" + ";";
string sp_fq="select count(*) from scan_sip where sip=" + s_dq;
mysql_query(conn,sp_fq.c_str());
res_f=mysql_store_result(conn);
row_f=mysql_fetch_row(res_f);
istringstream f_buff(row_syn[0]);
int f;
f_buff >> f;
cout<<"sip_flows:"<<f<<endl;
string no_hits="select sum(hit) from scan_sip where sip=" + s_dq;
mysql_query(conn,no_hits.c_str());
res_noh=mysql_store_result(conn);
row_noh=mysql_fetch_row(res_noh);
istringstream h_buff(row_noh[0]);
noh;
h_buff >> noh;
cout<<"noh:"<<noh<<endl;
string no_misses="select sum(misses) from scan_sip where sip=" + s_dq;
mysql_query(conn,no_misses.c_str());
res_nom=mysql_store_result(conn);
row_nom=mysql_fetch_row(res_nom);
istringstream m_buff(row_nom[0]);
nom;
m_buff >> nom;
cout<<"nom:"<<nom<<endl;
int k=0;
if(noh > 0)
{
hit_likelihood=1;
while(k < noh)
{
hit_likelihood = hit_likelihood  *  0.25;
k++;
}
}
cout<<"hit_likelihood:"<<hit_likelihood<<endl;
 int j=0;
if(nom > 0)
{
miss_likelihood=1;
while(j < nom)
{
miss_likelihood = miss_likelihood  *  4;
j++;
}
}
cout<<"miss_likelihood:"<<miss_likelihood<<endl;
if(noh == 0)
{
likelihood =  miss_likelihood;
}
if(nom == 0)
{
likelihood = hit_likelihood;
}

if(noh > 0 && nom > 0)
{
likelihood = hit_likelihood * miss_likelihood;
}
cout<<"likelihood:"<<likelihood<<endl;
if(likelihood > 99 && syns==f)
{
string sc_iq="insert into sc values(";
string sc_q=sc_iq + "'" +d + "'" + "," + "'scanner');";
mysql_query(conn,sc_q.c_str());
}
}
mysql_query(conn,"select source_ip from sc;");
res_scanner=mysql_store_result(conn);
string scanner;
cout<<"LIST OF SCANNER IP's:"<<endl;
while ((row_scanner = mysql_fetch_row(res_scanner))!=NULL)
{
 scanner=string(row_scanner[0]);
 cout<<scanner<<endl;
}
mysql_close(conn);
return 0;
}


text:
'use strict';

const assert = require('./../../assert');
const common = require('./../../common');

let battle;

describe('Wandering Spirit', function () {
	afterEach(() => battle.destroy());

	it('should exchange abilities with an attacker that makes contact', function () {
		battle = common.createBattle();
		battle.setPlayer('p1', {team: [{species: 'Decidueye', ability: 'overgrow', moves: ['shadowsneak']}]});
		battle.setPlayer('p2', {team: [{species: 'Runerigus', ability: 'wanderingspirit', moves: ['sleeptalk']}]});
		battle.makeChoices('move shadowsneak', 'move sleeptalk');
		assert(battle.p1.active[0].hasAbility('wanderingspirit'));
		assert(battle.p2.active[0].hasAbility('overgrow'));
	});

	it('should not activate while Dynamaxed', function () {
		battle = common.createBattle();
		battle.setPlayer('p1', {team: [{species: 'Decidueye', ability: 'overgrow', moves: ['shadowsneak']}]});
		battle.setPlayer('p2', {team: [{species: 'Runerigus', ability: 'wanderingspirit', moves: ['bodypress']}]});
		battle.makeChoices('move shadowsneak', 'move 1 dynamax');
		assert(battle.p1.active[0].hasAbility('overgrow'));
		assert(battle.p2.active[0].hasAbility('wanderingspirit'));
	});

	it('should not swap with Wonder Guard', function () {
		battle = common.createBattle();
		battle.setPlayer('p1', {team: [{species: 'Shedinja', ability: 'wonderguard', moves: ['shadowsneak']}]});
		battle.setPlayer('p2', {team: [{species: 'Runerigus', ability: 'wanderingspirit', moves: ['sleeptalk']}]});
		battle.makeChoices('move shadowsneak', 'move sleeptalk');
		assert(battle.p1.active[0].hasAbility('wonderguard'));
		assert(battle.p2.active[0].hasAbility('wanderingspirit'));
	});
});


text:
/**
 * Created by timfiez on 11/28/16.
 */
import {Component, ViewChild} from '@angular/core';

@Component({
    selector: 'login',
    template: require<any>('./login.component.html'),
    styles: [],
    providers: []
})
export class AppComponent {

    constructor() {
    }

    ngOnInit() {
        console.log('in login');
    }

    ngAfterViewInit() {
    }
}


text:
<?xml version="1.0" ?>
<!DOCTYPE html
  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "DTD/xhtml1-transitional.dtd">

<title>Simple test of source annotations</title>

Foo!


text:
package kafka.admin

import kafka.utils.{Logging, TestUtils}
import kafka.zk.ZooKeeperTestHarness
import org.junit.Assert._
import org.junit.Test

import scala.collection.{Map, Seq}

class AdminRackAwareTest extends RackAwareTest with Logging {

  @Test
  def testGetRackAlternatedBrokerListAndAssignReplicasToBrokers() {
    val rackMap = Map(0 -> "rack1", 1 -> "rack3", 2 -> "rack3", 3 -> "rack2", 4 -> "rack2", 5 -> "rack1")
    val newList = AdminUtils.getRackAlternatedBrokerList(rackMap)
    assertEquals(List(0, 3, 1, 5, 4, 2), newList)
    val anotherList = AdminUtils.getRackAlternatedBrokerList(rackMap - 5)
    assertEquals(List(0, 3, 1, 4, 2), anotherList)
    val assignment = AdminUtils.assignReplicasToBrokers(toBrokerMetadata(rackMap), 7, 3, 0, 0)
    val expected = Map(0 -> List(0, 3, 1),
                       1 -> List(3, 1, 5),
                       2 -> List(1, 5, 4),
                       3 -> List(5, 4, 2),
                       4 -> List(4, 2, 0),
                       5 -> List(2, 0, 3),
                       6 -> List(0, 4, 2))
    assertEquals(expected, assignment)
  }

  @Test
  def testAssignmentWithRackAware() {
    val brokerRackMapping = Map(0 -> "rack1", 1 -> "rack2", 2 -> "rack2", 3 -> "rack3", 4 -> "rack3", 5 -> "rack1")
    val numPartitions = 6
    val replicationFactor = 3
    val assignment = AdminUtils.assignReplicasToBrokers(toBrokerMetadata(brokerRackMapping), numPartitions,
      replicationFactor, 2, 0)
    checkReplicaDistribution(assignment, brokerRackMapping, brokerRackMapping.size, numPartitions,
      replicationFactor)
  }

  @Test
  def testAssignmentWithRackAwareWithRandomStartIndex() {
    val brokerRackMapping = Map(0 -> "rack1", 1 -> "rack2", 2 -> "rack2", 3 -> "rack3", 4 -> "rack3", 5 -> "rack1")
    val numPartitions = 6
    val replicationFactor = 3
    val assignment = AdminUtils.assignReplicasToBrokers(toBrokerMetadata(brokerRackMapping), numPartitions,
      replicationFactor)
    checkReplicaDistribution(assignment, brokerRackMapping, brokerRackMapping.size, numPartitions,
      replicationFactor)
  }

  @Test
  def testAssignmentWithRackAwareWithUnevenReplicas() {
    val brokerRackMapping = Map(0 -> "rack1", 1 -> "rack2", 2 -> "rack2", 3 -> "rack3", 4 -> "rack3", 5 -> "rack1")
    val numPartitions = 13
    val replicationFactor = 3
    val assignment = AdminUtils.assignReplicasToBrokers(toBrokerMetadata(brokerRackMapping), numPartitions,
      replicationFactor, 0, 0)
    checkReplicaDistribution(assignment, brokerRackMapping, brokerRackMapping.size, numPartitions,
      replicationFactor, verifyLeaderDistribution = false, verifyReplicasDistribution = false)
  }

  @Test
  def testAssignmentWithRackAwareWithUnevenRacks() {
    val brokerRackMapping = Map(0 -> "rack1", 1 -> "rack1", 2 -> "rack2", 3 -> "rack3", 4 -> "rack3", 5 -> "rack1")
    val numPartitions = 12
    val replicationFactor = 3
    val assignment = AdminUtils.assignReplicasToBrokers(toBrokerMetadata(brokerRackMapping), numPartitions,
      replicationFactor)
    checkReplicaDistribution(assignment, brokerRackMapping, brokerRackMapping.size, numPartitions,
      replicationFactor, verifyReplicasDistribution = false)
  }

  @Test
  def testAssignmentWith2ReplicasRackAware() {
    val brokerRackMapping = Map(0 -> "rack1", 1 -> "rack2", 2 -> "rack2", 3 -> "rack3", 4 -> "rack3", 5 -> "rack1")
    val numPartitions = 12
    val replicationFactor = 2
    val assignment = AdminUtils.assignReplicasToBrokers(toBrokerMetadata(brokerRackMapping), numPartitions,
      replicationFactor)
    checkReplicaDistribution(assignment, brokerRackMapping, brokerRackMapping.size, numPartitions,
      replicationFactor)
  }

  @Test
  def testRackAwareExpansion() {
    val brokerRackMapping = Map(6 -> "rack1", 7 -> "rack2", 8 -> "rack2", 9 -> "rack3", 10 -> "rack3", 11 -> "rack1")
    val numPartitions = 12
    val replicationFactor = 2
    val assignment = AdminUtils.assignReplicasToBrokers(toBrokerMetadata(brokerRackMapping), numPartitions,
      replicationFactor, startPartitionId = 12)
    checkReplicaDistribution(assignment, brokerRackMapping, brokerRackMapping.size, numPartitions,
      replicationFactor)
  }

  @Test
  def testAssignmentWith2ReplicasRackAwareWith6Partitions() {
    val brokerRackMapping = Map(0 -> "rack1", 1 -> "rack2", 2 -> "rack2", 3 -> "rack3", 4 -> "rack3", 5 -> "rack1")
    val numPartitions = 6
    val replicationFactor = 2
    val assignment = AdminUtils.assignReplicasToBrokers(toBrokerMetadata(brokerRackMapping), numPartitions,
      replicationFactor)
    checkReplicaDistribution(assignment, brokerRackMapping, brokerRackMapping.size, numPartitions,
      replicationFactor)
  }

  @Test
  def testAssignmentWith2ReplicasRackAwareWith6PartitionsAnd3Brokers() {
    val brokerRackMapping = Map(0 -> "rack1", 1 -> "rack2", 4 -> "rack3")
    val numPartitions = 3
    val replicationFactor = 2
    val assignment = AdminUtils.assignReplicasToBrokers(toBrokerMetadata(brokerRackMapping), numPartitions, replicationFactor)
    checkReplicaDistribution(assignment, brokerRackMapping, brokerRackMapping.size, numPartitions, replicationFactor)
  }

  @Test
  def testLargeNumberPartitionsAssignment() {
    val numPartitions = 96
    val replicationFactor = 3
    val brokerRackMapping = Map(0 -> "rack1", 1 -> "rack2", 2 -> "rack2", 3 -> "rack3", 4 -> "rack3", 5 -> "rack1",
      6 -> "rack1", 7 -> "rack2", 8 -> "rack2", 9 -> "rack3", 10 -> "rack1", 11 -> "rack3")
    val assignment = AdminUtils.assignReplicasToBrokers(toBrokerMetadata(brokerRackMapping), numPartitions,
      replicationFactor)
    checkReplicaDistribution(assignment, brokerRackMapping, brokerRackMapping.size, numPartitions,
      replicationFactor)
  }

  @Test
  def testMoreReplicasThanRacks() {
    val numPartitions = 6
    val replicationFactor = 5
    val brokerRackMapping = Map(0 -> "rack1", 1 -> "rack2", 2 -> "rack2", 3 -> "rack3", 4 -> "rack3", 5 -> "rack2")
    val assignment = AdminUtils.assignReplicasToBrokers(toBrokerMetadata(brokerRackMapping), numPartitions, replicationFactor)
    assertEquals(List.fill(assignment.size)(replicationFactor), assignment.values.map(_.size))
    val distribution = getReplicaDistribution(assignment, brokerRackMapping)
    for (partition <- 0 until numPartitions)
      assertEquals(3, distribution.partitionRacks(partition).toSet.size)
  }

  @Test
  def testLessReplicasThanRacks() {
    val numPartitions = 6
    val replicationFactor = 2
    val brokerRackMapping = Map(0 -> "rack1", 1 -> "rack2", 2 -> "rack2", 3 -> "rack3", 4 -> "rack3", 5 -> "rack2")
    val assignment = AdminUtils.assignReplicasToBrokers(toBrokerMetadata(brokerRackMapping), numPartitions,
      replicationFactor)
    assertEquals(List.fill(assignment.size)(replicationFactor), assignment.values.map(_.size))
    val distribution = getReplicaDistribution(assignment, brokerRackMapping)
    for (partition <- 0 to 5)
      assertEquals(2, distribution.partitionRacks(partition).toSet.size)
  }

  @Test
  def testSingleRack() {
    val numPartitions = 6
    val replicationFactor = 3
    val brokerRackMapping = Map(0 -> "rack1", 1 -> "rack1", 2 -> "rack1", 3 -> "rack1", 4 -> "rack1", 5 -> "rack1")
    val assignment = AdminUtils.assignReplicasToBrokers(toBrokerMetadata(brokerRackMapping), numPartitions, replicationFactor)
    assertEquals(List.fill(assignment.size)(replicationFactor), assignment.values.map(_.size))
    val distribution = getReplicaDistribution(assignment, brokerRackMapping)
    for (partition <- 0 until numPartitions)
      assertEquals(1, distribution.partitionRacks(partition).toSet.size)
    for (broker <- brokerRackMapping.keys)
      assertEquals(1, distribution.brokerLeaderCount(broker))
  }

  @Test
  def testSkipBrokerWithReplicaAlreadyAssigned() {
    val rackInfo = Map(0 -> "a", 1 -> "b", 2 -> "c", 3 -> "a", 4 -> "a")
    val brokerList = 0 to 4
    val numPartitions = 6
    val replicationFactor = 4
    val brokerMetadatas = toBrokerMetadata(rackInfo)
    assertEquals(brokerList, brokerMetadatas.map(_.id))
    val assignment = AdminUtils.assignReplicasToBrokers(brokerMetadatas, numPartitions, replicationFactor,
      fixedStartIndex = 2)
    checkReplicaDistribution(assignment, rackInfo, 5, 6, 4,
      verifyRackAware = false, verifyLeaderDistribution = false, verifyReplicasDistribution = false)
  }
}


text:
USING_NS_FT

TEST(TestStringUtils, TestConversion) {
    const std::string a = "Foo";
    const std::wstring wa = L"Foo";

    auto converted = CharUtil::convertString(wa);
    EXPECT_EQ(converted, a);

    auto converted2 = WCharUtil::convertString(a);
    EXPECT_EQ(converted2, wa);
}

TEST(TestStringUtils, TestConversionLong) {
    const std::string a = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur.";
    const std::wstring wa = L"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur.";

    auto converted = CharUtil::convertString(wa);
    EXPECT_EQ(converted, a);

    auto converted2 = WCharUtil::convertString(a);
    EXPECT_EQ(converted2, wa);
}

TEST(TestStringUtils, TestToLowerCase) {
    std::string a = "LfgewfJUsfSnfhgKedfhS";
    std::wstring b = L"LfgewfJUsfSnfhgKedfhS";

    CharUtil::toLowerCase(a);
    WCharUtil::toLowerCase(b);

    EXPECT_EQ(a, "lfgewfjusfsnfhgkedfhs");
    EXPECT_EQ(b, L"lfgewfjusfsnfhgkedfhs");
}

TEST(TestStringUtils, TestReplace) {
    std::string a = "asd\n dkfks grfesasd\nghs djgfjgawjx";
    std::wstring b = L"asd\n dkfks grfesasd\nghs djgfjgawjx";

    CharUtil::replaceAll(a, "asd\n", "foo");
    WCharUtil::replaceAll(b, L"asd\n", L"foo");

    EXPECT_EQ(a, "foo dkfks grfesfooghs djgfjgawjx");
    EXPECT_EQ(b, L"foo dkfks grfesfooghs djgfjgawjx");
}

TEST(TestStringUtils, TestSplit) {
    std::string a = "asda,gusef, sadf,y \n,sdfsd";
    std::wstring b = L"asda,gusef, sadf,y \n,sdfsd";

    auto av = CharUtil::splitString(a, ',');
    auto bv = WCharUtil::splitString(b, ',');

    std::vector<std::string> av_correct = { "asda","gusef"," sadf","y \n","sdfsd" };
    std::vector<std::wstring> bv_correct = { L"asda",L"gusef",L" sadf",L"y \n",L"sdfsd" };

    EXPECT_EQ(av.size(), av_correct.size());
    EXPECT_EQ(bv.size(), bv_correct.size());
    EXPECT_EQ(av.size(), bv.size());

    for (size_t i = 0; i < av.size(); i++) {
        EXPECT_EQ(av[i], av_correct[i]);
        EXPECT_EQ(bv[i], bv_correct[i]);
    }
}


text:
namespace v8 {
    struct JitCodeEvent;
} // namespace v8

namespace rt {

struct RegisterState {
    void* rsp;
    void* rbp;
    void* rip;
};

struct ProfilerCounters {
    uint64_t sampleCount = 0;
    uint64_t idleCount = 0;
    uint64_t jsCount = 0;
    uint64_t gcCount = 0;
    uint64_t compilerCount = 0;
    uint64_t otherCount = 0;
    uint64_t externalCount = 0;
    uint64_t v8idleCount = 0;

    uint64_t startTime = 0;
    uint64_t endTime = 0;

    uint64_t runtime_state_counters[(uint32_t)RuntimeState::LAST] = {0};

    void Print() {
        uint64_t timediff = endTime - startTime;
        uint64_t timediffms = (endTime - startTime) / 1000;
        printf("==== Counters ====\n");

        RT_ASSERT(timediff > 0);
        RT_ASSERT(sampleCount > 0);

        {   double r = idleCount / (double)sampleCount;
            printf(" Idle thread:   %lu (%lu%%, %lu ms)\n", idleCount, (uint64_t)(r * 100), (uint64_t)(timediffms * r));
        }
        {   double r = jsCount / (double)sampleCount;
            printf(" JavaScript:    %lu (%lu%%, %lu ms)\n", jsCount, (uint64_t)(r * 100), (uint64_t)(timediffms * r));
        }
        {   double r = gcCount / (double)sampleCount;
            printf(" GC:            %lu (%lu%%, %lu ms)\n", gcCount, (uint64_t)(r * 100), (uint64_t)(timediffms * r));
        }
        {   double r = compilerCount / (double)sampleCount;
            printf(" Compiler:      %lu (%lu%%, %lu ms)\n", compilerCount, (uint64_t)(r * 100), (uint64_t)(timediffms * r));
        }
        {   double r = otherCount / (double)sampleCount;
            printf(" Other:         %lu (%lu%%, %lu ms)\n", otherCount, (uint64_t)(r * 100), (uint64_t)(timediffms * r));
        }
        {   double r = externalCount / (double)sampleCount;
            printf(" External:      %lu (%lu%%, %lu ms)\n", externalCount, (uint64_t)(r * 100), (uint64_t)(timediffms * r));
        }
        {   double r = v8idleCount / (double)sampleCount;
            printf(" V8 idle:       %lu (%lu%%, %lu ms)\n", v8idleCount, (uint64_t)(r * 100), (uint64_t)(timediffms * r));
        }

        printf(" Total:         %lu\n", sampleCount);
        printf("\n");
        printf(" Time:          %lu ms\n", timediffms);

        printf("\nRuntime states:\n");
        for (uint32_t i = 0; i < (uint32_t)RuntimeState::LAST; ++i) {
            printf("%s: %lu\n", RuntimeStateToString((RuntimeState)i), runtime_state_counters[i]);
        }
    }
};

class Profiler {
public:
    Profiler() {}
    void Enable();
    void Disable();
    void MakeSample(SystemContextIRQ irq_context, const RegisterState& state);
    void OnJitCodeEvent(const v8::JitCodeEvent* event);
private:
    std::atomic<bool> enabled_;
    ProfilerCounters counters_;

    struct CodeEventEntry {
        std::string name;
        const void* code_start;
        size_t code_len;
    };
    typedef std::map<const void*, CodeEventEntry> CodeEntries;
    const CodeEventEntry* FindEventEntry(const void* address);
    CodeEntries code_entries_;
    char* log_;
    char* log_position_;

    void LogWrite(const char* str) {
        RT_ASSERT(str);
        RT_ASSERT(log_position_);
        auto len = strlen(str);
        memcpy(log_position_, str, len);
        log_position_ += len;
    }
};

} // namespace rt