text:
"""
    captiveportal
    *************

    This test is a collection of tests to detect the presence of a
    captive portal. Code is taken, in part, from the old ooni-probe,
    which was written by Jacob Appelbaum and Arturo Filastò.

    This module performs multiple tests that match specific vendor captive
    portal tests. This is a basic internet captive portal filter tester written
    for RECon 2011.

    Read the following URLs to understand the captive portal detection process
    for various vendors:

    http://technet.microsoft.com/en-us/library/cc766017%28WS.10%29.aspx
    http://blog.superuser.com/2011/05/16/windows-7-network-awareness/
    http://isc.sans.org/diary.html?storyid=10312&
    http://src.chromium.org/viewvc/chrome?view=rev&revision=74608
    http://code.google.com/p/chromium-os/issues/detail?3281ttp,
    http://crbug.com/52489
    http://crbug.com/71736
    https://bugzilla.mozilla.org/show_bug.cgi?id=562917
    https://bugzilla.mozilla.org/show_bug.cgi?id=603505
    http://lists.w3.org/Archives/Public/ietf-http-wg/2011JanMar/0086.html
    http://tools.ietf.org/html/draft-nottingham-http-portal-02

    :copyright: (c) 2012 Isis Lovecruft
    :license: see LICENSE for more details
"""
import base64
import os
import random
import re
import string
import urllib2
from urlparse import urlparse

from ooni import nettest
from ooni.templates import httpt
from ooni.utils import log

try:
    from dns import resolver
except ImportError:
    print "The dnspython module was not found:"
    print "See https://crate.io/packages/dnspython/"
    resolver = None

__plugoo__ = "captiveportal"
__desc__ = "Captive portal detection test"

optParameters = [['asset', 'a', None, 'Asset file'],
                 ['experiment-url', 'e', 'http://google.com/', 'Experiment URL'],
                 ['user-agent', 'u', random.choice(httpt.useragents),
                  'User agent for HTTP requests']
                ]

class CaptivePortal(nettest.NetTestCase):
    """
    Compares content and status codes of HTTP responses, and attempts
    to determine if content has been altered.
    """

    name = "captivep"
    description = "Captive Portal Test"
    requirements = None

    def http_fetch(self, url, headers={}):
        """
        Parses an HTTP url, fetches it, and returns a urllib2 response
        object.
        """
        url = urlparse(url).geturl()
        request = urllib2.Request(url, None, headers)
        response = urllib2.urlopen(request)
        response_headers = dict(response.headers)
        return response, response_headers

    def http_content_match_fuzzy_opt(self, experimental_url, control_result,
                                     headers=None, fuzzy=False):
        """
        Makes an HTTP request on port 80 for experimental_url, then
        compares the response_content of experimental_url with the
        control_result. Optionally, if the fuzzy parameter is set to
        True, the response_content is compared with a regex of the
        control_result. If the response_content from the
        experimental_url and the control_result match, returns True
        with the HTTP status code and headers; False, status code, and
        headers if otherwise.
        """

        if headers is None:
            default_ua = self.local_options['user-agent']
            headers = {'User-Agent': default_ua}

        response, response_headers = self.http_fetch(experimental_url, headers)
        response_content = response.read()
        response_code = response.code
        if response_content is None:
            log.warn("HTTP connection appears to have failed.")
            return False, False, False

        if fuzzy:
            pattern = re.compile(control_result)
            match = pattern.search(response_content)
            log.msg("Fuzzy HTTP content comparison for experiment URL")
            log.msg("'%s'" % experimental_url)
            if not match:
                log.msg("does not match!")
                return False, response_code, response_headers
            else:
                log.msg("and the expected control result yielded a match.")
                return True, response_code, response_headers
        else:
            if str(response_content) != str(control_result):
                log.msg("HTTP content comparison of experiment URL")
                log.msg("'%s'" % experimental_url)
                log.msg("and the expected control result do not match.")
                return False, response_code, response_headers
            else:
                return True, response_code, response_headers

    def http_status_code_match(self, experiment_code, control_code):
        """
        Compare two HTTP status codes, returns True if they match.
        """
        return int(experiment_code) == int(control_code)

    def http_status_code_no_match(self, experiment_code, control_code):
        """
        Compare two HTTP status codes, returns True if they do not match.
        """
        return int(experiment_code) != int(control_code)

    def dns_resolve(self, hostname, nameserver=None):
        """
        Resolves hostname(s) though nameserver to corresponding
        address(es). hostname may be either a single hostname string,
        or a list of strings. If nameserver is not given, use local
        DNS resolver, and if that fails try using 8.8.8.8.
        """
        if not resolver:
            log.msg("dnspython is not installed.\
                    Cannot perform DNS Resolve test")
            return []
        if isinstance(hostname, str):
            hostname = [hostname]

        if nameserver is not None:
            res = resolver.Resolver(configure=False)
            res.nameservers = [nameserver]
        else:
            res = resolver.Resolver()

        response = []
        answer = None

        for hn in hostname:
            try:
                answer = res.query(hn)
            except resolver.NoNameservers:
                res.nameservers = ['8.8.8.8']
                try:
                    answer = res.query(hn)
                except resolver.NXDOMAIN:
                    log.msg("DNS resolution for %s returned NXDOMAIN" % hn)
                    response.append('NXDOMAIN')
            except resolver.NXDOMAIN:
                log.msg("DNS resolution for %s returned NXDOMAIN" % hn)
                response.append('NXDOMAIN')
            finally:
                if not answer:
                    return response
                for addr in answer:
                    response.append(addr.address)
        return response

    def dns_resolve_match(self, experiment_hostname, control_address):
        """
        Resolve experiment_hostname, and check to see that it returns
        an experiment_address which matches the control_address.  If
        they match, returns True and experiment_address; otherwise
        returns False and experiment_address.
        """
        experiment_address = self.dns_resolve(experiment_hostname)
        if not experiment_address:
            log.debug("dns_resolve() for %s failed" % experiment_hostname)
            return None, experiment_address

        if len(set(experiment_address) & set([control_address])) > 0:
            return True, experiment_address
        else:
            log.msg("DNS comparison of control '%s' does not" % control_address)
            log.msg("match experiment response '%s'" % experiment_address)
            return False, experiment_address

    def get_auth_nameservers(self, hostname):
        """
        Many CPs set a nameserver to be used. Let's query that
        nameserver for the authoritative nameservers of hostname.

        The equivalent of:
        $ dig +short NS ooni.nu
        """
        if not resolver:
            log.msg("dnspython not installed.")
            log.msg("Cannot perform test.")
            return []

        res = resolver.Resolver()
        answer = res.query(hostname, 'NS')
        auth_nameservers = []
        for auth in answer:
            auth_nameservers.append(auth.to_text())
        return auth_nameservers

    def hostname_to_0x20(self, hostname):
        """
        MaKEs yOur HOsTnaME lOoK LiKE THis.

        For more information, see:
        D. Dagon, et. al. "Increased DNS Forgery Resistance
        Through 0x20-Bit Encoding". Proc. CSS, 2008.
        """
        hostname_0x20 = ''
        for char in hostname:
            l33t = random.choice(['caps', 'nocaps'])
            if l33t == 'caps':
                hostname_0x20 += char.capitalize()
            else:
                hostname_0x20 += char.lower()
        return hostname_0x20

    def check_0x20_to_auth_ns(self, hostname, sample_size=None):
        """
        Resolve a 0x20 DNS request for hostname over hostname's
        authoritative nameserver(s), and check to make sure that
        the capitalization in the 0x20 request matches that of the
        response. Also, check the serial numbers of the SOA (Start
        of Authority) records on the authoritative nameservers to
        make sure that they match.

        If sample_size is given, a random sample equal to that number
        of authoritative nameservers will be queried; default is 5.
        """
        log.msg("")
        log.msg("Testing random capitalization of DNS queries...")
        log.msg("Testing that Start of Authority serial numbers match...")

        auth_nameservers = self.get_auth_nameservers(hostname)

        if sample_size is None:
            sample_size = 5
            resolved_auth_ns = random.sample(self.dns_resolve(auth_nameservers),
                                             sample_size)

        querynames = []
        answernames = []
        serials = []

        # Even when gevent monkey patching is on, the requests here
        # are sent without being 0x20'd, so we need to 0x20 them.
        hostname = self.hostname_to_0x20(hostname)

        for auth_ns in resolved_auth_ns:
            res = resolver.Resolver(configure=False)
            res.nameservers = [auth_ns]
            try:
                answer = res.query(hostname, 'SOA')
            except resolver.Timeout:
                continue
            querynames.append(answer.qname.to_text())
            answernames.append(answer.rrset.name.to_text())
            for soa in answer:
                serials.append(str(soa.serial))

        if len(set(querynames).intersection(answernames)) == 1:
            log.msg("Capitalization in DNS queries and responses match.")
            name_match = True
        else:
            log.msg("The random capitalization '%s' used in" % hostname)
            log.msg("DNS queries to that hostname's authoritative")
            log.msg("nameservers does not match the capitalization in")
            log.msg("the response.")
            name_match = False

        if len(set(serials)) == 1:
            log.msg("Start of Authority serial numbers all match.")
            serial_match = True
        else:
            log.msg("Some SOA serial numbers did not match the rest!")
            serial_match = False

        ret = name_match, serial_match, querynames, answernames, serials

        if name_match and serial_match:
            log.msg("Your DNS queries do not appear to be tampered.")
            return ret
        elif name_match or serial_match:
            log.msg("Something is tampering with your DNS queries.")
            return ret
        elif not name_match and not serial_match:
            log.msg("Your DNS queries are definitely being tampered with.")
            return ret

    def get_random_url_safe_string(self, length):
        """
        Returns a random url-safe string of specified length, where
        0 < length <= 256. The returned string will always start with
        an alphabetic character.
        """
        if (length <= 0):
            length = 1
        elif (length > 256):
            length = 256

        random_ascii = base64.urlsafe_b64encode(os.urandom(int(length)))

        while not random_ascii[:1].isalpha():
            random_ascii = base64.urlsafe_b64encode(os.urandom(int(length)))

        three_quarters = int((len(random_ascii)) * (3.0/4.0))
        random_string = random_ascii[:three_quarters]
        return random_string

    def get_random_hostname(self, length=None):
        """
        Returns a random hostname with SLD of specified length. If
        length is unspecified, length=32 is used.

        These *should* all resolve to NXDOMAIN. If they actually
        resolve to a box that isn't part of a captive portal that
        would be rather interesting.
        """
        if length is None:
            length = 32

        random_sld = self.get_random_url_safe_string(length)

        # if it doesn't start with a letter, chuck it.
        while not random_sld[:1].isalpha():
            random_sld = self.get_random_url_safe_string(length)

        tld_list = ['.com', '.net', '.org', '.info', '.test', '.invalid']
        random_tld = urllib2.random.choice(tld_list)
        random_hostname = random_sld + random_tld
        return random_hostname

    def compare_random_hostnames(self, hostname_count=None, hostname_length=None):
        """
        Get hostname_count number of random hostnames with SLD length
        of hostname_length, and then attempt DNS resolution. If no
        arguments are given, default to three hostnames of 32 bytes
        each. These random hostnames *should* resolve to NXDOMAIN,
        except in the case where a user is presented with a captive
        portal and remains unauthenticated, in which case the captive
        portal may return the address of the authentication page.

        If the cardinality of the intersection of the set of resolved
        random hostnames and the single element control set
        (['NXDOMAIN']) are equal to one, then DNS properly resolved.

        Returns true if only NXDOMAINs were returned, otherwise returns
        False with the relative complement of the control set in the
        response set.
        """
        if hostname_count is None:
            hostname_count = 3

        log.msg("Generating random hostnames...")
        log.msg("Resolving DNS for %d random hostnames..." % hostname_count)

        control = ['NXDOMAIN']
        responses = []

        for x in range(hostname_count):
            random_hostname = self.get_random_hostname(hostname_length)
            response_match, response_address = self.dns_resolve_match(random_hostname,
                                                                      control[0])
            for address in response_address:
                if response_match is False:
                    log.msg("Strangely, DNS resolution of the random hostname")
                    log.msg("%s actually points to %s"
                             % (random_hostname, response_address))
                    responses = responses + [address]
                else:
                    responses = responses + [address]

        intersection = set(responses) & set(control)
        relative_complement = set(responses) - set(control)
        r = set(responses)

        if len(intersection) == 1:
            log.msg("All %d random hostnames properly resolved to NXDOMAIN."
                     % hostname_count)
            return True, relative_complement
        elif (len(intersection) == 1) and (len(r) > 1):
            log.msg("Something odd happened. Some random hostnames correctly")
            log.msg("resolved to NXDOMAIN, but several others resolved to")
            log.msg("to the following addresses: %s" % relative_complement)
            return False, relative_complement
        elif (len(intersection) == 0) and (len(r) == 1):
            log.msg("All random hostnames resolved to the IP address ")
            log.msg("'%s', which is indicative of a captive portal." % r)
            return False, relative_complement
        else:
            log.debug("Apparently, pigs are flying on your network, 'cause a")
            log.debug("bunch of hostnames made from 32-byte random strings")
            log.debug("just magically resolved to a bunch of random addresses.")
            log.debug("That is definitely highly improbable. In fact, my napkin")
            log.debug("tells me that the probability of just one of those")
            log.debug("hostnames resolving to an address is 1.68e-59, making")
            log.debug("it nearly twice as unlikely as an MD5 hash collision.")
            log.debug("Either someone is seriously messing with your network,")
            log.debug("or else you are witnessing the impossible. %s" % r)
            return False, relative_complement

    def google_dns_cp_test(self):
        """
        Google Chrome resolves three 10-byte random hostnames.
        """
        subtest = "Google Chrome DNS-based"

        log.msg("")
        log.msg("Running the Google Chrome DNS-based captive portal test...")

        gmatch, google_dns_result = self.compare_random_hostnames(3, 10)

        if gmatch:
            log.msg("Google Chrome DNS-based captive portal test did not")
            log.msg("detect a captive portal.")
            return google_dns_result
        else:
            log.msg("Google Chrome DNS-based captive portal test believes")
            log.msg("you are in a captive portal, or else something very")
            log.msg("odd is happening with your DNS.")
            return google_dns_result

    def ms_dns_cp_test(self):
        """
        Microsoft "phones home" to a server which will always resolve
        to the same address.
        """
        subtest = "Microsoft NCSI DNS-based"

        log.msg("")
        log.msg("Running the Microsoft NCSI DNS-based captive portal")
        log.msg("test...")

        msmatch, ms_dns_result = self.dns_resolve_match("dns.msftncsi.com",
                                                        "131.107.255.255")
        if msmatch:
            log.msg("Microsoft NCSI DNS-based captive portal test did not")
            log.msg("detect a captive portal.")
            return ms_dns_result
        else:
            log.msg("Microsoft NCSI DNS-based captive portal test ")
            log.msg("believes you are in a captive portal.")
            return ms_dns_result

    def run_vendor_dns_tests(self):
        """
        Run the vendor DNS tests.
        """
        report = {}
        report['google_dns_cp'] = self.google_dns_cp_test()
        report['ms_dns_cp'] = self.ms_dns_cp_test()

        return report

    def run_vendor_tests(self, *a, **kw):
        """
        These are several vendor tests used to detect the presence of
        a captive portal. Each test compares HTTP status code and
        content to the control results and has its own User-Agent
        string, in order to emulate the test as it would occur on the
        device it was intended for. Vendor tests are defined in the
        format:
        [exp_url, ctrl_result, ctrl_code, ua, test_name]
        """

        vendor_tests = [['http://www.apple.com/library/test/success.html',
                         'Success',
                         '200',
                         'Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3',
                         'Apple HTTP Captive Portal'],
                        ['http://tools.ietf.org/html/draft-nottingham-http-portal-02',
                         '428 Network Authentication Required',
                         '428',
                         'Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0',
                         'W3 Captive Portal'],
                        ['http://www.msftncsi.com/ncsi.txt',
                         'Microsoft NCSI',
                         '200',
                         'Microsoft NCSI',
                         'MS HTTP Captive Portal',]]

        cm = self.http_content_match_fuzzy_opt
        sm = self.http_status_code_match
        snm = self.http_status_code_no_match

        def compare_content(status_func, fuzzy, experiment_url, control_result,
                            control_code, headers, test_name):
            log.msg("")
            log.msg("Running the %s test..." % test_name)

            content_match, experiment_code, experiment_headers = cm(experiment_url,
                                                                    control_result,
                                                                    headers, fuzzy)
            status_match = status_func(experiment_code, control_code)

            if status_match and content_match:
                log.msg("The %s test was unable to detect" % test_name)
                log.msg("a captive portal.")
                return True
            else:
                log.msg("The %s test shows that your network" % test_name)
                log.msg("is filtered.")
                return False

        result = []
        for vt in vendor_tests:
            report = {}
            report['vt'] = vt

            experiment_url = vt[0]
            control_result = vt[1]
            control_code = vt[2]
            headers = {'User-Agent': vt[3]}
            test_name = vt[4]

            args = (experiment_url, control_result, control_code, headers, test_name)

            if test_name == "MS HTTP Captive Portal":
                report['result'] = compare_content(sm, False, *args)

            elif test_name == "Apple HTTP Captive Portal":
                report['result'] = compare_content(sm, True, *args)

            elif test_name == "W3 Captive Portal":
                report['result'] = compare_content(snm, True, *args)

            else:
                log.warn("Ooni is trying to run an undefined CP vendor test.")
            result.append(report)
        return result

    def control(self, experiment_result, args):
        """
        Compares the content and status code of the HTTP response for
        experiment_url with the control_result and control_code
        respectively. If the status codes match, but the experimental
        content and control_result do not match, fuzzy matching is enabled
        to determine if the control_result is at least included somewhere
        in the experimental content. Returns True if matches are found,
        and False if otherwise.
        """
        # XXX put this back to being parametrized
        #experiment_url = self.local_options['experiment-url']
        experiment_url = 'http://google.com/'
        control_result = 'XX'
        control_code = 200
        ua = self.local_options['user-agent']

        cm = self.http_content_match_fuzzy_opt
        sm = self.http_status_code_match
        snm = self.http_status_code_no_match

        log.msg("Running test for '%s'..." % experiment_url)
        content_match, experiment_code, experiment_headers = cm(experiment_url,
                                                                control_result)
        status_match = sm(experiment_code, control_code)
        if status_match and content_match:
            log.msg("The test for '%s'" % experiment_url)
            log.msg("was unable to detect a captive portal.")

            self.report['result'] = True

        elif status_match and not content_match:
            log.msg("Retrying '%s' with fuzzy match enabled."
                     % experiment_url)
            fuzzy_match, experiment_code, experiment_headers = cm(experiment_url,
                                                                  control_result,
                                                                  fuzzy=True)
            if fuzzy_match:
                self.report['result'] = True
            else:
                log.msg("Found modified content on '%s'," % experiment_url)
                log.msg("which could indicate a captive portal.")

                self.report['result'] = False
        else:
            log.msg("The content comparison test for ")
            log.msg("'%s'" % experiment_url)
            log.msg("shows that your HTTP traffic is filtered.")

            self.report['result'] = False

    def test_captive_portal(self):
        """
        Runs the CaptivePortal(Test).

        CONFIG OPTIONS
        --------------

        If "do_captive_portal_vendor_tests" is set to "true", then vendor
        specific captive portal HTTP-based tests will be run.

        If "do_captive_portal_dns_tests" is set to "true", then vendor
        specific captive portal DNS-based tests will be run.

        If "check_dns_requests" is set to "true", then Ooni-probe will
        attempt to check that your DNS requests are not being tampered with
        by a captive portal.

        If "captive_portal" = "yourfilename.txt", then user-specified tests
        will be run.

        Any combination of the above tests can be run.
        """

        log.msg("")
        log.msg("Running vendor tests...")
        self.report['vendor_tests'] = self.run_vendor_tests()

        log.msg("")
        log.msg("Running vendor DNS-based tests...")
        self.report['vendor_dns_tests'] = self.run_vendor_dns_tests()

        log.msg("")
        log.msg("Checking that DNS requests are not being tampered...")
        self.report['check0x20'] = self.check_0x20_to_auth_ns('ooni.nu')

        log.msg("")
        log.msg("Captive portal test finished!")

        self.control(self.report)


text:
class Profile;
class TemplateURLService;

// Singleton that owns all TemplateURLService and associates them with
// Profiles.
class TemplateURLServiceFactory : public BrowserContextKeyedServiceFactory {
 public:
  static TemplateURLService* GetForProfile(Profile* profile);

  static TemplateURLServiceFactory* GetInstance();

  static scoped_ptr<KeyedService> BuildInstanceFor(
      content::BrowserContext* profile);

 private:
  friend struct base::DefaultSingletonTraits<TemplateURLServiceFactory>;

  TemplateURLServiceFactory();
  ~TemplateURLServiceFactory() override;

  // BrowserContextKeyedServiceFactory:
  KeyedService* BuildServiceInstanceFor(
      content::BrowserContext* profile) const override;
  void RegisterProfilePrefs(
      user_prefs::PrefRegistrySyncable* registry) override;
  content::BrowserContext* GetBrowserContextToUse(
      content::BrowserContext* context) const override;
  bool ServiceIsNULLWhileTesting() const override;
};

#endif  // CHROME_BROWSER_SEARCH_ENGINES_TEMPLATE_URL_SERVICE_FACTORY_H_

redpajama_set_name: RedPajamaGithub


text:
@interface YJSavingImageToAlbumViewController ()
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UIButton *saveButton;
@end

@implementation YJSavingImageToAlbumViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIImage *demoImage = [UIImage imageNamed:@"Octocat.png"];

    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,150,200)];
    self.imageView.backgroundColor = [UIColor lightGrayColor];
    // Make image both aspect fit and align bottom of image view, which is not allowed by setting imageView.contentMode
    self.imageView.yj_contentMode = YJViewContentModeScaleAspectFit | YJViewContentModeBottom;
    self.imageView.image = demoImage;
    [self.view addSubview:self.imageView];

    self.saveButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.saveButton setTitle:@"Tap to save" forState:UIControlStateNormal];
    [self.saveButton sizeToFit];
    [self.view addSubview:self.saveButton];

    // Using block-based APIs for nesting code
    @weakify(self)
    [self.saveButton addActionForControlEvents:UIControlEventTouchUpInside actionHandler:^(UIControl * _Nonnull sender) {

        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Do you want to save the image to photo album ?" cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Save", nil];

        [actionSheet setActionHandler:^(UIActionSheet * _Nonnull actionSheet, NSInteger buttonIndex, NSString * _Nonnull buttonTitle) {
            if (actionSheet.firstOtherButtonIndex == buttonIndex) {

                // Save image to album
                [[YJPhotoLibrary sharedLibrary] saveImage:demoImage metadata:nil success:^{
                    [[[UIAlertView alloc] initWithTitle:@"Well Done" message:@"The image has been saved to the photo album under your app's name." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
                } failure:^(NSError * _Nonnull error) {

                    // If you deny the photo access, saving will be failed.
                    if (YJPhotoLibrary.authorizationStatus != YJPhotoLibraryAuthorizationStatusAuthorized) {
                        // For iOS 8 above, you can jump to setting and get photo access directly.
                        if (iOS_version > 8.0) {

                            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failed" message:@"You do not have photo access. Tap the Setting button and turn on the photo switch if you'd like to save the image to photo album." cancelButtonTitle:@"Cancel" otherButtonTitles:@"Setting", nil];

                            [alert setActionHandler:^(UIAlertView * _Nonnull alertView, NSInteger buttonIndex, NSString * _Nonnull buttonTitle) {
                                if (alertView.firstOtherButtonIndex == buttonIndex) {
                                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                                }
                            }];

                            [alert show];

                        } else {
                            [[[UIAlertView alloc] initWithTitle:@"Failed" message:@"You do not have photo access. Please go to Settings App -> Privacy -> Photo -> turn on the switch of your app if you'd like to save the image to photo album." cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
                        }
                    } else {
                        NSLog(@"Failed to save image with error: %@", error);
                    }
                }];
            }
        }];

        @strongify(self)
        [actionSheet showInView:self.view];

    }];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    CGPoint center = self.view.center;
    center.y -= 100;
    self.imageView.center = center;
    center.y += 200;
    self.saveButton.center = center;
}

- (void)dealloc {
    NSLog(@"%@ dealloc", self.class);
}

@end


text:
PSR 2 Coding Style Guide Example 4.1 (b)

https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md

TODO see https://github.com/gerardroche/sublime-php-grammar/issues/16
--FILE--
<?php
namespace Vendor\Package;

use FooClass;
use BarClass as Bar;
use OtherVendor\OtherPackage\BazClass;

class ClassName extends ParentClass implements
    \ArrayAccess,
    \Countable,
    \Serializable
{
    // constants, properties, methods
}

?>
--EXPECT--
<?php
namespace Vendor\Package;

use FooClass;
use BarClass as Bar;
use OtherVendor\OtherPackage\BazClass;

class ClassName extends ParentClass implements
    \ArrayAccess,
    \Countable,
    \Serializable
{
    // constants, properties, methods
}

?>


text:
"use strict";

const assert = require("assert");
const chip = require("../src/js/8086-emu/chip.8259.asm");

let interrupt = null;
let debug = null;

function init() {
    interrupt.setAPin(0);
    interrupt.handleCW(0b00010011);
    interrupt.tick();
    interrupt.setAPin(1);
    interrupt.handleCW(0b11111000);
    interrupt.tick();
    interrupt.handleCW(0b00000001);
    interrupt.tick();
}

describe("Chip i8259", function () {
    describe("Initialise chip", function () {
        before(function () {
            debug = chip.DebugObject(true);
            interrupt = chip.Chip8259(0, debug);
        });

        beforeEach(function () {
            debug.break();
        });

        after(function () {
            console.log(JSON.stringify(debug.render()));
        });

        it("Setup single chip for x86", function () {
            debug.test("Init x86 single");

            init();

            // DONE!
            assert.strictEqual(interrupt.isInitialised(), 1, "Interrupt chip should now be initialised.");
        });
    });

    describe("Interrupt handling", function () {
        before(function () {
            debug = chip.DebugObject(true);
            interrupt = chip.Chip8259(0, debug);
        });

        beforeEach(function () {
            debug.break();
        });

        after(function () {
            console.log(JSON.stringify(debug.render()));
        });

        it("IRQ0", function () {
            debug.test("IRQ0");

            init();

            interrupt.setIR(0);
            interrupt.tick();
        });

        it("IRQ1", function () {
            debug.test("IRQ1");

            init();

            interrupt.setIR(1);
            interrupt.tick();
        });
    });
});


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Web;
using UDPForwarder.Logging;
using UDPForwarder.Services;
using Thinktecture.IdentityModel.Extensions;

namespace UDPForwarder.Filters
{
    public class LogForwardingHandler : DelegatingHandler
    {
        private readonly LogForwardingService _service;

		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="service"></param>
        public LogForwardingHandler(LogForwardingService service)
		{
			_service = service;
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="innerHandler"></param>
		/// <param name="service"></param>
        public LogForwardingHandler(HttpMessageHandler innerHandler, LogForwardingService service)
			: base(innerHandler)
		{
			_service = service;
		}

        /// <summary>
        /// This message handler catches all http requests. An instance of LoggingInfo is created and various data from the http request is collected.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            // Log the request information
            var stopWatch = new Stopwatch();
            stopWatch.Start();
            var info = CreateLoggingInfoFromRequest(request);

            // Execute the request
            return base.SendAsync(request, cancellationToken).ContinueWith(task =>
            {
                var response = task.Result;
                // Extract the response logging info then persist the information
                stopWatch.Stop();
                info.Elapsed = stopWatch.ElapsedMilliseconds;
                info.ResponseStatusCode = (int)response.StatusCode;
                _service.Log(info);
                return response;
            }, cancellationToken);
        }

        /// <summary>
        /// Creates an instance of LoggingInfo and feeds into it various information extracted from the http request.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private LoggingInfo CreateLoggingInfoFromRequest(HttpRequestMessage request)
        {
            var info = new LoggingInfo
            {
                Start = DateTime.Now,
                HttpMethod = request.Method.Method,
                UriAccessed = request.RequestUri.AbsoluteUri,
                IpAddress = HttpContext.Current != null ? HttpContext.Current.Request.UserHostAddress : "0.0.0.0",
            };

            // Figure out the current user, if any
            var principal = request.GetClaimsPrincipal();
            if (principal != null)
            {
                if (principal.Identity != null)
                {
                    info.UserName = principal.Identity.Name;
                }
            }

            ExtractMessageHeadersIntoLoggingInfo(info, request.Headers.ToList());

            return info;
        }

        private void ExtractMessageHeadersIntoLoggingInfo(LoggingInfo info, List<KeyValuePair<string, IEnumerable<string>>> headers)
        {
            var allHeaders = new StringBuilder();

            headers.ForEach(h =>
            {
                // Convert the header values into one long string from a series of IEnumerable<string> values so it looks for like a HTTP header
                var headerValues = new StringBuilder();

                if (h.Value != null)
                {
                    foreach (var hv in h.Value)
                    {
                        if (headerValues.Length > 0)
                        {
                            headerValues.Append(", ");
                        }
                        headerValues.Append(hv);
                    }
                }

                allHeaders.Append(string.Format("{0}: {1}", h.Key, headerValues.ToString()));
            });

            info.Headers = allHeaders.ToString();
        }

    }
}


text:
package com.zjlp.face.spark;

import static org.elasticsearch.index.query.QueryBuilders.*;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.search.SearchHit;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by root on 9/23/16.
 */
public class EsQuery {
    public static void main(String[] args) throws Exception {
        Settings settings = Settings.settingsBuilder()
                .put("cluster.name", "zjlp-es-cluster")
                .put("client.transport.sniff", true).build();
        // on startup
        TransportClient client = TransportClient.builder().settings(settings)
                .build()
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.175.11"), 9300));
          /*      .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.0.152"), 9300))
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.0.153"), 9300));*/
        long begin = System.currentTimeMillis();
        System.out.println("查询二度人脉");
        String[] loginAccountArray ="2099,1213".split(",");
        int l = loginAccountArray.length;
        System.out.println("数组长度:" + l);

        long begin2 = System.currentTimeMillis();
        SearchResponse response = client.prepareSearch("relation").setTypes("docs")
                //.setQuery(boolQuery().must(termQuery("username", "13000000004")).must(termsQuery("userId",loginAccountArray)))
                .setQuery(boolQuery().must(termQuery("username", "13000000004")).must(termsQuery("userId",loginAccountArray)))
                .setFrom(0).setSize(6000).setExplain(false)
                .execute()
                .actionGet();

        SearchHit[] results = response.getHits().getHits();

        Map<String,Object> source = null;
        for(SearchHit hit : results){
            source = hit.getSource();
            System.out.println(source.get("username") + " "+source.get("userId") + " " + source.get("friendType"));
        }
        System.out.println("cost1:"+(System.currentTimeMillis() - begin2) + "ms");

   /*     System.out.println("查询共同好友");

        List<String> loginAccounts = new ArrayList<String>();
        loginAccounts.add("13030666526");
        loginAccounts.add("13062084630");

        SearchResponse response2 = client.prepareSearch("com_friends").setTypes("docs")
                .setQuery(boolQuery().must(termQuery("username", "13000000002")).must(termsQuery("loginAccount",loginAccounts)))
                .setFrom(0).setSize(6000).setExplain(false)
                .execute()
                .actionGet();
        SearchHit[] results2 = response2.getHits().getHits();
        for(SearchHit hit : results2){
            source = hit.getSource();
            System.out.println(source.get("username") + " " + source.get("loginAccount") + " "+source.get("num"));

        }*/

        System.out.println("cost2:"+(System.currentTimeMillis() - begin) + "ms");

    }
}


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

<title>org.springframework.jdbc.core.simple (Spring Framework 4.3.3.RELEASE API)</title>
<meta name="date" content="2016-09-19">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Spring Framework

Prev Package

Next Package

Frames

No Frames

All Classes

Package org.springframework.jdbc.core.simple

Simplification layer over JdbcTemplate for Java 5 and above.

See: Description

Interface Summary

Interface
Description

SimpleJdbcCallOperations

Interface specifying the API for a Simple JDBC Call implemented by SimpleJdbcCall.

SimpleJdbcInsertOperations

Interface specifying the API for a Simple JDBC Insert implemented by SimpleJdbcInsert.

Class Summary

Class
Description

AbstractJdbcCall

Abstract class to provide base functionality for easy stored procedure calls
 based on configuration options and database metadata.

AbstractJdbcInsert

Abstract class to provide base functionality for easy inserts
 based on configuration options and database metadata.

SimpleJdbcCall

A SimpleJdbcCall is a multi-threaded, reusable object representing a call
 to a stored procedure or a stored function.

SimpleJdbcInsert

A SimpleJdbcInsert is a multi-threaded, reusable object providing easy insert
 capabilities for a table.

Package org.springframework.jdbc.core.simple Description

Simplification layer over JdbcTemplate for Java 5 and above.

SimpleJdbcInsert and SimpleJdbcCall are classes that takes advantage
 of database metadata provided by the JDBC driver to simplify the application code. Much of the
 parameter specification becomes unnecessary since it can be looked up in the metadata.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Spring Framework

Prev Package

Next Package

Frames

No Frames

All Classes


text:
Sacred Texts
Legends & Sagas
Celtic
Index
Previous
Next

p. 51

XXV.

THE ISLE OF PABAIDH.

From Alexander M'Donald, tenant, and others, Barra. July 1859.

THERE came a woman of peace (a fairy) the way of the house of a man in the island of Pabaidh, and she had the hunger of motherhood on her. He gave her food, and that went well with her. She staid that night. When she went away, she said to him, "I am making a desire that none of the people of this island may go in childbed after this." None of these people, and none others that would make their dwelling in the island ever departed in childbed from that time.

(Gaelic omitted)

...

Written by Hector MacLean, from the telling of a man in Barra.

Next: XXVI. Sanntraigh


text:
package ro.nextreports.designer.querybuilder.datatransfer;

import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;
import java.io.Serializable;
//
// Created by IntelliJ IDEA.
// User: mihai.panaitescu
// Date: 27-Apr-2009
// Time: 10:44:10

import ro.nextreports.designer.dbviewer.common.DBProcedure;

//
public class DBProcTransferable implements Transferable, Serializable {

    public static final DataFlavor DATA_FLAVOR = new DataFlavor(DBProcTransferable.class,
            "DBProc Data Flavor");

    private DBProcedure proc;

    public DBProcTransferable(DBProcedure proc) {
        this.proc = proc;
    }

    public Object getTransferData(DataFlavor flavor) {
        if (isDataFlavorSupported(flavor)) {
            return proc;
        }

        return null;
    }

    public DataFlavor[] getTransferDataFlavors() {
        return new DataFlavor[] { DATA_FLAVOR };
    }

    public boolean isDataFlavorSupported(DataFlavor flavor) {
        if (flavor.equals(DATA_FLAVOR)) {
            return true;
        }

        return false;
    }

}


text:
local table = table
local type = type

local M = {}

local LIMIT = 8192

local function chunksize(readbytes, body)
	while true do
		local f,e = body:find("\r\n",1,true)
		if f then
			return tonumber(body:sub(1,f-1),16), body:sub(e+1)
		end
		if #body > 128 then
			-- pervent the attacker send very long stream without \r\n
			return
		end
		body = body .. readbytes()
	end
end

local function readcrln(readbytes, body)
	if #body >= 2 then
		if body:sub(1,2) ~= "\r\n" then
			return
		end
		return body:sub(3)
	else
		body = body .. readbytes(2-#body)
		if body ~= "\r\n" then
			return
		end
		return ""
	end
end

function M.recvheader(readbytes, lines, header)
	if #header >= 2 then
		if header:find "^\r\n" then
			return header:sub(3)
		end
	end
	local result
	local e = header:find("\r\n\r\n", 1, true)
	if e then
		result = header:sub(e+4)
	else
		while true do
			local bytes = readbytes()
			header = header .. bytes
			e = header:find("\r\n\r\n", -#bytes-3, true)
			if e then
				result = header:sub(e+4)
				break
			end
			if header:find "^\r\n" then
				return header:sub(3)
			end
			if #header > LIMIT then
				return
			end
		end
	end
	for v in header:gmatch("(.-)\r\n") do
		if v == "" then
			break
		end
		table.insert(lines, v)
	end
	return result
end

function M.parseheader(lines, from, header)
	local name, value
	for i=from,#lines do
		local line = lines[i]
		if line:byte(1) == 9 then	-- tab, append last line
			if name == nil then
				return
			end
			header[name] = header[name] .. line:sub(2)
		else
			name, value = line:match "^(.-):%s*(.*)"
			if name == nil or value == nil then
				return
			end
			name = name:lower()
			if header[name] then
				local v = header[name]
				if type(v) == "table" then
					table.insert(v, value)
				else
					header[name] = { v , value }
				end
			else
				header[name] = value
			end
		end
	end
	return header
end

function M.recvchunkedbody(readbytes, bodylimit, header, body)
	local result = ""
	local size = 0

	while true do
		local sz
		sz , body = chunksize(readbytes, body)
		if not sz then
			return
		end
		if sz == 0 then
			break
		end
		size = size + sz
		if bodylimit and size > bodylimit then
			return
		end
		if #body >= sz then
			result = result .. body:sub(1,sz)
			body = body:sub(sz+1)
		else
			result = result .. body .. readbytes(sz - #body)
			body = ""
		end
		body = readcrln(readbytes, body)
		if not body then
			return
		end
	end

	local tmpline = {}
	body = M.recvheader(readbytes, tmpline, body)
	if not body then
		return
	end

	header = M.parseheader(tmpline,1,header)

	return result, header
end

local function recvbody(interface, code, header, body)
	local length = header["content-length"]
	if length then
		length = tonumber(length)
	end
	if length then
		if #body >= length then
			body = body:sub(1,length)
		else
			local padding = interface.read(length - #body)
			body = body .. padding
		end
	elseif code == 204 or code == 304 or code < 200 then
		body = ""
		-- See https://stackoverflow.com/questions/15991173/is-the-content-length-header-required-for-a-http-1-0-response
	else
		-- no content-length, read all
		body = body .. interface.readall()
	end
	return body
end

function M.request(interface, method, host, url, recvheader, header, content)
	local read = interface.read
	local write = interface.write
	local header_content = ""
	if header then
		if not header.Host then
			header.Host = host
		end
		for k,v in pairs(header) do
			header_content = string.format("%s%s:%s\r\n", header_content, k, v)
		end
	else
		header_content = string.format("host:%s\r\n",host)
	end

	if content then
		local data = string.format("%s %s HTTP/1.1\r\n%sContent-length:%d\r\n\r\n", method, url, header_content, #content)
		write(data)
		write(content)
	else
		local request_header = string.format("%s %s HTTP/1.1\r\n%sContent-length:0\r\n\r\n", method, url, header_content)
		write(request_header)
	end

	local tmpline = {}
	local body = M.recvheader(read, tmpline, "")
	if not body then
		error("Recv header failed")
	end

	local statusline = tmpline[1]
	local code, info = statusline:match "HTTP/[%d%.]+%s+([%d]+)%s+(.*)$"
	code = assert(tonumber(code))

	local header = M.parseheader(tmpline,2,recvheader or {})
	if not header then
		error("Invalid HTTP response header")
	end
	return code, body, header
end

function M.response(interface, code, body, header)
	local mode = header["transfer-encoding"]
	if mode then
		if mode ~= "identity" and mode ~= "chunked" then
			error ("Unsupport transfer-encoding")
		end
	end

	if mode == "chunked" then
		body, header = M.recvchunkedbody(interface.read, nil, header, body)
		if not body then
			error("Invalid response body")
		end
	else
		-- identity mode
		body = recvbody(interface, code, header, body)
	end

	return body
end

local stream = {}; stream.__index = stream

function stream:close()
	if self._onclose then
		self._onclose(self)
		self._onclose = nil
	end
end

function stream:padding()
	return self._reading(self), self
end

stream.__close = stream.close
stream.__call = stream.padding

local function stream_nobody(stream)
	stream._reading = stream.close
	stream.connected = nil
	return ""
end

local function stream_length(length)
	return function(stream)
		local body = stream._body
		if body == nil then
			local ret, padding = stream._interface.read()
			if not ret then
				-- disconnected
				body = padding
				stream.connected = false
			else
				body = ret
			end
		end
		local n = #body
		if n >= length then
			stream._reading = stream.close
			stream.connected = nil
			return (body:sub(1,length))
		else
			length = length - n
			stream._body = nil
			if not stream.connected then
				stream._reading = stream.close
			end
			return body
		end
	end
end

local function stream_read(stream)
	local ret, padding = stream._interface.read()
	if ret == "" or not ret then
		stream.connected = nil
		stream:close()
		if padding == "" then
			return
		end
		return padding
	end
	return ret
end

local function stream_all(stream)
	local body = stream._body
	stream._body = nil
	stream._reading = stream_read
	return body
end

local function stream_chunked(stream)
	local read = stream._interface.read
	local sz, body = chunksize(read, stream._body)
	if not sz then
		stream.connected = false
		stream:close()
		return
	end

	if sz == 0 then
		-- last chunk
		local tmpline = {}
		body = M.recvheader(read, tmpline, body)
		if not body then
			stream.connected = false
			stream:close()
			return
		end

		M.parseheader(tmpline,1, stream.header)

		stream._reading = stream.close
		stream.connected = nil
		return ""
	end

	local n = #body
	local remain

	if n >= sz then
		remain = body:sub(sz+1)
		body = body:sub(1,sz)
	else
		body = body .. read(sz - n)
		remain = ""
	end
	remain = readcrln(read, remain)
	if not remain then
		stream.connected = false
		stream:close()
		return
	end
	stream._body = remain
	return body
end

function M.response_stream(interface, code, body, header)
	local mode = header["transfer-encoding"]
	if mode then
		if mode ~= "identity" and mode ~= "chunked" then
			error ("Unsupport transfer-encoding")
		end
	end

	local read_func

	if mode == "chunked" then
		read_func = stream_chunked
	else
		-- identity mode
		local length = header["content-length"]
		if length then
			length = tonumber(length)
		end
		if length then
			read_func = stream_length(length)
		elseif code == 204 or code == 304 or code < 200 then
			read_func = stream_nobody
		else
			read_func = stream_all
		end
	end

	-- todo: timeout

	return setmetatable({
		status = code,
		_body = body,
		_interface = interface,
		_reading = read_func,
		header = header,
		connected = true,
	}, stream)
end

return M


text:
"""
Fortran code printer

The FCodePrinter converts single sympy expressions into single Fortran
expressions, using the functions defined in the Fortran 77 standard where
possible. Some useful pointers to Fortran can be found on wikipedia:

http://en.wikipedia.org/wiki/Fortran

Most of the code below is based on the "Professional Programmer\'s Guide to
Fortran77" by Clive G. Page:

http://www.star.le.ac.uk/~cgp/prof77.html

Fortran is a case-insensitive language. This might cause trouble because sympy
is case sensitive. The implementation below does not care and leaves the
responsibility for generating properly cased Fortran code to the user.
"""

from str import StrPrinter
from sympy.printing.precedence import precedence
from sympy.core import S, Add, I
from sympy.core.numbers import NumberSymbol
from sympy.functions import sin, cos, tan, asin, acos, atan, atan2, sinh, \
    cosh, tanh, sqrt, log, exp, abs, sign, conjugate, Piecewise
from sympy.utilities.iterables import postorder_traversal

implicit_functions = set([
    sin, cos, tan, asin, acos, atan, atan2, sinh, cosh, tanh, sqrt, log, exp,
    abs, sign, conjugate
])

class FCodePrinter(StrPrinter):
    """A printer to convert sympy expressions to strings of Fortran code"""
    printmethod = "_fcode"

    _default_settings = {
        'order': None,
        'full_prec': 'auto',
        'assign_to': None,
        'precision': 15,
        'user_functions': {},
        'human': True,
    }

    def doprint(self, expr):
        """Returns Fortran code for expr (as a string)"""
        # find all number symbols
        number_symbols = set([])
        for sub in postorder_traversal(expr):
            if isinstance(sub, NumberSymbol):
                number_symbols.add(sub)
        number_symbols = [(str(ns), ns.evalf(self._settings["precision"]))
                          for ns in sorted(number_symbols)]

        # keep a set of expressions that are not strictly translatable to
        # Fortran.
        self._not_fortran = set([])

        lines = []
        if isinstance(expr, Piecewise):
            # support for top-level Piecewise function
            for i, (e, c) in enumerate(expr.args):
                if i == 0:
                    lines.append("      if (%s) then" % self._print(c))
                elif i == len(expr.args)-1 and c == True:
                    lines.append("      else")
                else:
                    lines.append("      else if (%s) then" % self._print(c))
                if self._settings["assign_to"] is None:
                    lines.append("        %s" % self._print(e))
                else:
                    lines.append("        %s = %s" % (self._settings["assign_to"], self._print(e)))
            lines.append("      end if")
            text = "\n".join(lines)
        else:
            line = StrPrinter.doprint(self, expr)
            if self._settings["assign_to"] is None:
                text = "      %s" % line
            else:
                text = "      %s = %s" % (self._settings["assign_to"], line)

        # format the output
        if self._settings["human"]:
            lines = []
            if len(self._not_fortran) > 0:
                lines.append("C     Not Fortran 77:")
                for expr in sorted(self._not_fortran):
                    lines.append("C     %s" % expr)
            for name, value in number_symbols:
                lines.append("      parameter (%s = %s)" % (name, value))
            lines.extend(text.split("\n"))
            lines = wrap_fortran(lines)
            result = "\n".join(lines)
        else:
            result = number_symbols, self._not_fortran, text

        del self._not_fortran
        return result

    def _print_Add(self, expr):
        # purpose: print complex numbers nicely in Fortran.
        # collect the purely real and purely imaginary parts:
        pure_real = []
        pure_imaginary = []
        mixed = []
        for arg in expr.args:
            if arg.is_real and arg.is_number:
                pure_real.append(arg)
            elif arg.is_imaginary and arg.is_number:
                pure_imaginary.append(arg)
            else:
                mixed.append(arg)
        if len(pure_imaginary) > 0:
            if len(mixed) > 0:
                PREC = precedence(expr)
                term = Add(*mixed)
                t = self._print(term)
                if t.startswith('-'):
                    sign = "-"
                    t = t[1:]
                else:
                    sign = "+"
                if precedence(term) < PREC:
                    t = "(%s)" % t

                return "cmplx(%s,%s) %s %s" % (
                    self._print(Add(*pure_real)),
                    self._print(-I*Add(*pure_imaginary)),
                    sign, t,
                )
            else:
                return "cmplx(%s,%s)" % (
                    self._print(Add(*pure_real)),
                    self._print(-I*Add(*pure_imaginary)),
                )
        else:
            return StrPrinter._print_Add(self, expr)

    def _print_Function(self, expr):
        name = self._settings["user_functions"].get(expr.__class__)
        if name is None:
            if expr.func == conjugate:
                name = "conjg"
            else:
                name = expr.func.__name__
            if expr.func not in implicit_functions:
                self._not_fortran.add(expr)
        return "%s(%s)" % (name, self.stringify(expr.args, ", "))

    _print_Factorial = _print_Function

    def _print_ImaginaryUnit(self, expr):
        # purpose: print complex numbers nicely in Fortran.
        return "cmplx(0,1)"

    def _print_int(self, expr):
        return str(expr)

    def _print_Mul(self, expr):
        # purpose: print complex numbers nicely in Fortran.
        if expr.is_imaginary and expr.is_number:
            return "cmplx(0,%s)" % (
                self._print(-I*expr)
            )
        else:
            return StrPrinter._print_Mul(self, expr)

    def _print_NumberSymbol(self, expr):
        # Standard Fortran has no predefined constants. Write their string
        # representation, and assume parameter statements are defined elsewhere
        # in the code to make this work.
        return str(expr)

    _print_Catalan = _print_NumberSymbol
    _print_EulerGamma = _print_NumberSymbol
    _print_Exp1 = _print_NumberSymbol
    _print_GoldenRatio = _print_NumberSymbol
    _print_Pi = _print_NumberSymbol

    def _print_Pow(self, expr):
        PREC = precedence(expr)
        if expr.exp is S.NegativeOne:
            return '1.0/%s'%(self.parenthesize(expr.base, PREC))
        elif expr.exp == 0.5:
            return 'sqrt(%s)' % self._print(expr.base)
        else:
            return StrPrinter._print_Pow(self, expr)

    def _print_Rational(self, expr):
        p, q = int(expr.p), int(expr.q)
        return '%d.0/%d.0' % (p, q)

    def _print_not_fortran(self, expr):
        self._not_fortran.add(expr)
        return self.emptyPrinter(expr)

    # The following can not be simply translated into Fortran.
    _print_Basic = _print_not_fortran
    _print_ComplexInfinity = _print_not_fortran
    _print_Derivative = _print_not_fortran
    _print_dict = _print_not_fortran
    _print_Dummy = _print_not_fortran
    _print_ExprCondPair = _print_not_fortran
    _print_GeometryEntity = _print_not_fortran
    _print_Infinity = _print_not_fortran
    _print_Integral = _print_not_fortran
    _print_Interval = _print_not_fortran
    _print_Limit = _print_not_fortran
    _print_list = _print_not_fortran
    _print_Matrix = _print_not_fortran
    _print_DeferredVector = _print_not_fortran
    _print_NaN = _print_not_fortran
    _print_NegativeInfinity = _print_not_fortran
    _print_Normal = _print_not_fortran
    _print_Order = _print_not_fortran
    _print_PDF = _print_not_fortran
    _print_RootOf = _print_not_fortran
    _print_RootsOf = _print_not_fortran
    _print_RootSum = _print_not_fortran
    _print_Sample = _print_not_fortran
    _print_SMatrix = _print_not_fortran
    _print_tuple = _print_not_fortran
    _print_Uniform = _print_not_fortran
    _print_Unit = _print_not_fortran
    _print_Wild = _print_not_fortran
    _print_WildFunction = _print_not_fortran

def wrap_fortran(lines):
    """Wrap long Fortran lines

       Argument:
         lines  --  a list of lines (without \\n character)

       A comment line is split at white space. Code lines are split with a more
       complex rule to give nice results.
    """
    # routine to find split point in a code line
    my_alnum = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_")
    my_white = set(" \t()")
    def split_pos_code(line, endpos):
        if len(line) <= endpos:
            return len(line)
        pos = endpos
        split = lambda pos: \
            (line[pos] in my_alnum and line[pos-1] not in my_alnum) or \
            (line[pos] not in my_alnum and line[pos-1] in my_alnum) or \
            (line[pos] in my_white and line[pos-1] not in my_white) or \
            (line[pos] not in my_white and line[pos-1] in my_white)
        while not split(pos):
            pos -= 1
            if pos == 0:
                return endpos
        return pos
    # split line by line and add the splitted lines to result
    result = []
    for line in lines:
        if line.startswith("      "):
            # code line
            pos = split_pos_code(line, 72)
            hunk = line[:pos].rstrip()
            line = line[pos:].lstrip()
            result.append(hunk)
            while len(line) > 0:
                pos = split_pos_code(line, 65)
                hunk = line[:pos].rstrip()
                line = line[pos:].lstrip()
                result.append("     @ %s" % hunk)
        elif line.startswith("C"):
            # comment line
            if len(line) > 72:
                pos = line.rfind(" ", 6, 72)
                if pos == -1:
                    pos = 72
                hunk = line[:pos]
                line = line[pos:].lstrip()
                result.append(hunk)
                while len(line) > 0:
                    pos = line.rfind(" ", 0, 66)
                    if pos == -1:
                        pos = 66
                    hunk = line[:pos]
                    line = line[pos:].lstrip()
                    result.append("C     %s" % hunk)
            else:
                result.append(line)
        else:
            result.append(line)
    return result

def fcode(expr, **settings):
    """Converts an expr to a string of Fortran 77 code

       Arguments:
         expr  --  a sympy expression to be converted

       Optional arguments:
         assign_to  --  When given, the argument is used as the name of the
                        variable to which the Fortran expression is assigned.
                        (This is helpful in case of line-wrapping.)
         precision  --  the precision for numbers such as pi [default=15]
         user_functions  --  A dictionary where keys are FunctionClass instances
                             and values are there string representations.
         human  --  If True, the result is a single string that may contain
                    some parameter statements for the number symbols. If
                    False, the same information is returned in a more
                    programmer-friendly data structure.

       >>> from sympy import fcode, symbols, Rational, pi, sin
       >>> x, tau = symbols(["x", "tau"])
       >>> fcode((2*tau)**Rational(7,2))
       '      8*sqrt(2)*tau**(7.0/2.0)'
       >>> fcode(sin(x), assign_to="s")
       '      s = sin(x)'
       >>> print fcode(pi)
             parameter (pi = 3.14159265358979)
             pi

    """
    # run the printer
    printer = FCodePrinter(settings)
    return printer.doprint(expr)

def print_fcode(expr, **settings):
    """Prints the Fortran representation of the given expression.

       See fcode for the meaning of the optional arguments.
    """
    print fcode(expr, **settings)


text:
/* tslint:disable:max-line-length */
import * as React from 'react';
import SvgIcon from "./SvgIcon";

interface Pallet {
  arrow: string;
  strip: string;
}

class MoveRight extends SvgIcon {
  public displayName: string = 'MoveRight';
  public group(style: any, pallet: Pallet): JSX.Element {
    return (
      <g>
        <path d="M 13 2, L 13 8, L 0 8, L 0 16, L 13 16, L 13 22, L 19 12, L 13 2" stroke="transparent" fill={pallet.arrow} strokeWidth="0" />
        <path d="M 23 0, L 23 24" stroke={pallet.strip} fill="transparent" strokeWidth="3" />
      </g>
    );
  }
  public render() {
    const pallet: Pallet = {
      arrow: this.props.pallet.arrow || this.context.muiTheme.icon.color,
      strip: this.props.pallet.strip || this.context.muiTheme.icon.color,
    };
    const style = {
      ...this.styles,
      ...this.context.muiTheme.icon,
      ...this.props.style,
    };
    return this.svg(this.group(style, pallet), this.props.className, style, this.props.viewBox, this.props.transform);
  }
}

export default MoveRight;


text:
using System;
using System.Collections.Generic;
using xsc = DotNetXmlSwfChart;

namespace testWeb.tests
{
    public class PieOne : ChartTestBase
    {
        #region ChartInclude
        public override xsc.ChartHTML ChartInclude
        {
            get
            {
                xsc.ChartHTML chartHtml = new xsc.ChartHTML();
                chartHtml.height = 300;
                chartHtml.bgColor = "666666";
                chartHtml.flashFile = "charts/charts.swf";
                chartHtml.libraryPath = "charts/charts_library";
                chartHtml.xmlSource = "xmlData.aspx";
                return chartHtml;
            }
        }
        #endregion

        #region Chart
        public override xsc.Chart Chart
        {
            get
            {
                xsc.Chart c = new xsc.Chart();
                c.AddChartType(xsc.XmlSwfChartType.Pie);

                c.Data = SetChartData();
                c.ChartGridH = SetChartGridH();
                c.ChartRectangle = SetChartRectangle();
                c.ChartValue = SetChartValue();

                c.AddDrawText(CreateDrawText());

                c.LegendLabel = SetLegendLabel();
                c.LegendRectangle = SetLegendRectangle();

                c.AddSeriesColor("ddaa41");
                c.AddSeriesColor("88dd11");
                c.AddSeriesColor("4e62dd");
                c.AddSeriesColor("ff8811");
                c.AddSeriesColor("4d4d4d");
                c.AddSeriesColor("5a4b6e");
                c.AddSeriesExplode(20);
                c.AddSeriesExplode(0);
                c.AddSeriesExplode(50);
                return c;
            }
        }
        #endregion

        #region Helpers
        private xsc.ChartData SetChartData()
        {
            xsc.ChartData cd = new xsc.ChartData();
            cd.AddDataPoint("", "2003", 20);
            cd.AddDataPoint("", "2004", 10);
            cd.AddDataPoint("", "2005", 30);
            cd.AddDataPoint("", "2006", 50);
            cd.AddDataPoint("", "2007", 40);
            return cd;
        }

        private xsc.ChartGrid SetChartGridH()
        {
            xsc.ChartGrid cg = new xsc.ChartGrid(xsc.ChartGridType.Horizontal);
            cg.Alpha = 20;
            cg.Color = "000000";
            cg.Thickness = 1;
            cg.GridLineType = xsc.ChartGridLineType.solid;
            return cg;
        }

        private xsc.ChartRectangle SetChartRectangle()
        {
            xsc.ChartRectangle cr = new xsc.ChartRectangle();
            cr.PositiveColor = "ffffff";
            cr.PositiveAlpha = 20;
            cr.NegativeColor = "ff0000";
            cr.NegativeAlpha = 10;
            return cr;
        }

        private xsc.ChartValue SetChartValue()
        {
            xsc.ChartValue cv = new xsc.ChartValue();
            cv.Color = "ffffff";
            cv.Alpha = 90;
            cv.Font = "Arial";
            cv.Bold = true;
            cv.Size = 10;
            cv.Position = "inside";
            cv.Prefix = "";
            cv.Suffix = "";
            cv.Decimals = 0;
            cv.Separator = "";
            cv.AsPercentage = true;
            return cv;
        }

        private xsc.DrawText CreateDrawText()
        {
            xsc.DrawText dt = new xsc.DrawText();
            dt.Color = "000000";
            dt.Alpha = 10;
            dt.Font = "Arial";
            dt.Rotation = 0;
            dt.Bold = true;
            dt.Size = 30;
            dt.X = 0;
            dt.Y = 140;
            dt.Width = 400;
            dt.Height = 150;
            dt.HAlign = xsc.TextHAlign.center;
            dt.VAlign = xsc.TextVAlign.bottom;
            dt.Text = "|||||||||||||||||||||||||||||||||||||||||||||||";
            return dt;
        }

        private xsc.LegendLabel SetLegendLabel()
        {
            xsc.LegendLabel ll = new xsc.LegendLabel();
            ll.Layout = xsc.LegendLabelLayout.horizontal;
            ll.Bullet = xsc.LegendLabelBullet.circle;
            ll.Font = "Arial";
            ll.Bold = true;
            ll.Size = 13;
            ll.Color = "ffffff";
            ll.Alpha = 85;
            return ll;
        }

        private xsc.LegendRectangle SetLegendRectangle()
        {
            xsc.LegendRectangle lr = new xsc.LegendRectangle();
            lr.FillColor = "ffffff";
            lr.FillAlpha = 10;
            lr.LineColor = "000000";
            lr.LineAlpha = 0;
            lr.LineThickness = 0;
            return lr;
        }
        #endregion
    }
}


text:
@implementation NSData (MD5Algorithm)

- (NSString *)md5String
{
    const char *str = [self bytes];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)self.length, result);

    NSMutableString *md5Str = [NSMutableString string];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; ++i) {
        [md5Str appendFormat:@"%02x", result[i]];
    }
    return md5Str;
}

@end

@implementation NSString (MD5Algorithm)

- (NSString *)md5String
{
    NSData * data = [self dataUsingEncoding:NSUTF8StringEncoding];
    return [data md5String];
}

@end


text:
require 'test/unit'
require 'casa/payload'
require 'json-schema'

class TestAbstractPayloadAttributes < Test::Unit::TestCase

  include CASA::Payload

  def test_requirements cls = AbstractPayloadAttributes

    assert_raise JSON::Schema::ValidationError, "Missing required timestamp attribute" do
      cls.new({
        'uri' => 'http://example.com',
        'share' => true,
        'propagate' => true
      }).to_hash
    end

    assert_raise JSON::Schema::ValidationError, "Invalid timestamp attribute" do
      cls.new({
        'timestamp' => 'January 19, 2013',
        'uri' => 'http://example.com',
        'share' => true,
        'propagate' => true
      }).to_hash
    end

    assert_raise JSON::Schema::ValidationError, "Missing required uri attribute" do
      cls.new({
        'timestamp' => '1996-12-19T16:39:57-08:00',
        'share' => true,
        'propagate' => true
      }).to_hash
    end

    assert cls.new({
      'timestamp' => '1996-12-19T16:39:57-08:00',
      'uri' => 'http://example.com',
      'propagate' => true
    }).to_hash.has_key?('share')

    assert cls.new({
      'timestamp' => '1996-12-19T16:39:57-08:00',
      'uri' => 'http://example.com',
      'share' => true
    }).to_hash.has_key?('propagate')

    assert_nothing_raised "All required attributes specified" do
      cls.new({
        'timestamp' => '1996-12-19T16:39:57-08:00',
        'uri' => 'http://example.com',
        'share' => true,
        'propagate' => true
      }).to_hash
    end

  end

end


text:
package capnp

import (
	"encoding/binary"
	"errors"
	"io"
	"math"

	"zombiezen.com/go/capnproto/internal/packed"
)

// A Message is a tree of Cap'n Proto objects, split into one or more
// segments of contiguous memory.  The only required field is Arena.
type Message struct {
	Arena Arena

	// CapTable is the indexed list of the clients referenced in the
	// message.  Capability pointers inside the message will use this table
	// to map pointers to Clients.  The table is usually populated by the
	// RPC system.
	//
	// See https://capnproto.org/encoding.html#capabilities-interfaces for
	// more details on the capability table.
	CapTable []Client

	segs map[SegmentID]*Segment
}

// NewMessage creates a message with a new root and returns the first
// segment.  It is an error to call NewMessage on an arena with data in it.
func NewMessage(arena Arena) (msg *Message, first *Segment, err error) {
	msg = &Message{Arena: arena}
	switch arena.NumSegments() {
	case 0:
		first, err = msg.allocSegment(defaultBufferSize)
		if err != nil {
			return nil, nil, err
		}
	case 1:
		first, err = msg.Segment(0)
		if err != nil {
			return nil, nil, err
		}
		if len(first.data) > 0 {
			return nil, nil, errHasData
		}
		if !hasCapacity(first.data, wordSize) {
			return nil, nil, errSegmentTooSmall
		}
	default:
		return nil, nil, errHasData
	}
	alloc(first, wordSize) // allocate root
	return msg, first, nil
}

// Root returns the pointer to the message's root object.
func (m *Message) Root() (Pointer, error) {
	s, err := m.Segment(0)
	if err != nil {
		return nil, err
	}
	return s.root().At(0)
}

// SetRoot sets the message's root object to p.
func (m *Message) SetRoot(p Pointer) error {
	s, err := m.Segment(0)
	if err != nil {
		return err
	}
	return s.root().Set(0, p)
}

// AddCap appends a capability to the message's capability table and
// returns its ID.
func (m *Message) AddCap(c Client) CapabilityID {
	n := CapabilityID(len(m.CapTable))
	m.CapTable = append(m.CapTable, c)
	return n
}

// NumSegments returns the number of segments in the message.
func (m *Message) NumSegments() int64 {
	return int64(m.Arena.NumSegments())
}

// Segment returns the segment with the given ID.
func (m *Message) Segment(id SegmentID) (*Segment, error) {
	if isInt32Bit() && id > maxInt32 {
		return nil, errSegment32Bit
	}
	if seg := m.segment(id); seg != nil {
		return seg, nil
	}
	if int64(id) >= m.Arena.NumSegments() {
		return nil, errSegmentOutOfBounds
	}
	data, err := m.Arena.Data(id)
	if err != nil {
		return nil, err
	}
	return m.setSegment(id, data), nil
}

func (m *Message) segment(id SegmentID) *Segment {
	if m.segs == nil {
		return nil
	}
	return m.segs[id]
}

func (m *Message) setSegment(id SegmentID, data []byte) *Segment {
	if m.segs == nil {
		m.segs = make(map[SegmentID]*Segment)
	} else if seg := m.segs[id]; seg != nil {
		seg.data = data
		return seg
	}
	seg := &Segment{
		id:   id,
		msg:  m,
		data: data,
	}
	m.segs[id] = seg
	return seg
}

// allocSegment creates or resizes an existing segment such that
// cap(seg.Data) - len(seg.Data) >= sz.
func (m *Message) allocSegment(sz Size) (*Segment, error) {
	id, data, err := m.Arena.Allocate(sz, m.segs)
	if err != nil {
		return nil, err
	}
	if isInt32Bit() && id > maxInt32 {
		return nil, errSegment32Bit
	}
	return m.setSegment(id, data), nil
}

// alloc allocates sz zero-filled bytes.  It prefers using s, but may
// use a different segment in the same message if there's not sufficient
// capacity.
func alloc(s *Segment, sz Size) (*Segment, Address, error) {
	sz = sz.padToWord()
	if sz > Size(math.MaxUint32)-wordSize {
		return nil, 0, errOverlarge
	}

	if !hasCapacity(s.data, sz) {
		var err error
		s, err = s.msg.allocSegment(sz)
		if err != nil {
			return nil, 0, err
		}
	}

	addr := Address(len(s.data))
	end := addr.addSize(sz)
	s.data = s.data[:end]
	for i := addr; i < end; i++ {
		s.data[i] = 0
	}
	return s, addr, nil
}

// An Arena loads and allocates segments for a Message.  Segment IDs
// must be tightly packed in the range [0, NumSegments()).
type Arena interface {
	// NumSegments returns the number of segments in the arena.
	// This must not be larger than 1<<32.
	NumSegments() int64

	// Data loads the data for the segment with the given ID.
	Data(id SegmentID) ([]byte, error)

	// Allocate allocates a byte slice such that cap(data) - len(data) >= minsz.
	// segs is a map of already loaded segments keyed by ID.  The arena may
	// return an existing segment's ID, in which case the arena is responsible
	// for copying the existing data to the returned byte slice.  Allocate must
	// not modify the segments passed into it.
	Allocate(minsz Size, segs map[SegmentID]*Segment) (SegmentID, []byte, error)
}

// Arena parameters.  Must be a multiple of wordSize.
const (
	defaultBufferSize      = 4096
	minSingleSegmentGrowth = 4096
)

type singleSegmentArena []byte

// SingleSegment returns a new arena with an expanding single-segment
// buffer.  b can be used to populate the segment for reading or to
// reserve memory of a specific size.  A SingleSegment arena does not
// return errors unless you attempt to access another segment.
func SingleSegment(b []byte) Arena {
	if cap(b) == 0 {
		b = make([]byte, 0, defaultBufferSize)
	}
	ssa := new(singleSegmentArena)
	*ssa = b
	return ssa
}

func (ssa *singleSegmentArena) NumSegments() int64 {
	return 1
}

func (ssa *singleSegmentArena) Data(id SegmentID) ([]byte, error) {
	if id != 0 {
		return nil, errSegmentOutOfBounds
	}
	return *ssa, nil
}

func (ssa *singleSegmentArena) Allocate(sz Size, segs map[SegmentID]*Segment) (SegmentID, []byte, error) {
	data := []byte(*ssa)
	if segs[0] != nil {
		data = segs[0].data
	}
	if hasCapacity(data, sz) {
		return 0, data, nil
	}
	// TODO(light): ensure len(data)+sz is word-aligned
	if sz < minSingleSegmentGrowth {
		sz = minSingleSegmentGrowth
	} else {
		sz = sz.padToWord()
	}
	buf := make([]byte, len(data), cap(data)+int(sz))
	copy(buf, data)
	*ssa = buf
	return 0, *ssa, nil
}

type multiSegmentArena [][]byte

// MultiSegment returns a new arena that allocates new segments when
// they are full.  b can be used to populate the buffer for reading or
// to reserve memory of a specific size.
func MultiSegment(b [][]byte) Arena {
	msa := new(multiSegmentArena)
	*msa = b
	return msa
}

// demuxArena slices b into a multi-segment arena.
func demuxArena(sizes []Size, data []byte) Arena {
	segs := make([][]byte, len(sizes))
	for i, sz := range sizes {
		segs[i], data = data[:sz:sz], data[sz:]
	}
	return MultiSegment(segs)
}

func (msa *multiSegmentArena) NumSegments() int64 {
	return int64(len(*msa))
}

func (msa *multiSegmentArena) Data(id SegmentID) ([]byte, error) {
	if int64(id) >= int64(len(*msa)) {
		return nil, errSegmentOutOfBounds
	}
	return (*msa)[id], nil
}

func (msa *multiSegmentArena) Allocate(sz Size, segs map[SegmentID]*Segment) (SegmentID, []byte, error) {
	for i, data := range *msa {
		id := SegmentID(i)
		if s := segs[id]; s != nil {
			data = s.data
		}
		if hasCapacity(data, sz) {
			return id, data, nil
		}
	}
	if sz < defaultBufferSize {
		sz = defaultBufferSize
	} else {
		// TODO(light): check >maxInt
		sz = sz.padToWord()
	}
	buf := make([]byte, 0, int(sz))
	id := SegmentID(len(*msa))
	*msa = append(*msa, buf)
	return id, buf, nil
}

// A Decoder represents a framer that deserializes a particular Cap'n
// Proto input stream.
type Decoder struct {
	r io.Reader
}

// NewDecoder creates a new Cap'n Proto framer that reads from r.
func NewDecoder(r io.Reader) *Decoder {
	return &Decoder{r: r}
}

// NewPackedDecoder creates a new Cap'n Proto framer that reads from a
// packed stream r.
func NewPackedDecoder(r io.Reader) *Decoder {
	return NewDecoder(packed.NewReader(r))
}

// Decode reads a message from the decoder stream.
func (d *Decoder) Decode() (*Message, error) {
	var maxSegBuf [msgHeaderSize]byte
	if _, err := io.ReadFull(d.r, maxSegBuf[:]); err != nil {
		return nil, err
	}
	maxSeg := binary.LittleEndian.Uint32(maxSegBuf[:])
	hdrSize := streamHeaderSize(maxSeg)
	hdr := make([]byte, hdrSize)
	copy(hdr, maxSegBuf[:])
	if _, err := io.ReadFull(d.r, hdr[msgHeaderSize:]); err != nil {
		return nil, err
	}
	sizes, _, err := unmarshalStreamHeader(hdr)
	if err != nil {
		return nil, err
	}
	total := totalSize(sizes)
	// TODO(light): size check
	buf := make([]byte, int(total))
	if _, err := io.ReadFull(d.r, buf); err != nil {
		return nil, err
	}
	return &Message{Arena: demuxArena(sizes, buf)}, nil
}

// Unmarshal reads an unpacked serialized stream into a message.  No
// copying is performed, so the objects in the returned message read
// directly from data.
func Unmarshal(data []byte) (*Message, error) {
	if len(data) == 0 {
		return nil, io.EOF
	}
	sizes, data, err := unmarshalStreamHeader(data)
	if err != nil {
		return nil, err
	}
	if tot := totalSize(sizes); tot > uint64(len(data)) {
		return nil, io.ErrUnexpectedEOF
	}
	return &Message{Arena: demuxArena(sizes, data)}, nil
}

// MustUnmarshalRoot reads an unpacked serialized stream and returns its
// root pointer.  If there is any error, it panics.
func MustUnmarshalRoot(data []byte) Pointer {
	msg, err := Unmarshal(data)
	if err != nil {
		panic(err)
	}
	p, err := msg.Root()
	if err != nil {
		panic(err)
	}
	return p
}

// An Encoder represents a framer for serializing a particular Cap'n
// Proto stream.
type Encoder struct {
	w      io.Writer
	hdrbuf []byte

	packed  bool
	packbuf []byte
}

// NewEncoder creates a new Cap'n Proto framer that writes to w.
func NewEncoder(w io.Writer) *Encoder {
	return &Encoder{w: w}
}

// NewPackedEncoder creates a new Cap'n Proto framer that writes to a
// packed stream w.
func NewPackedEncoder(w io.Writer) *Encoder {
	return &Encoder{w: w, packed: true}
}

// Encode writes a message to the encoder stream.
func (e *Encoder) Encode(m *Message) error {
	// TODO(light): Lazily load from arena, don't necessarily need to fit in memory.
	nsegs := m.NumSegments()
	if nsegs == 0 {
		return errMessageEmpty
	}
	sizes, err := m.segmentSizes()
	if err != nil {
		return err
	}
	maxSeg := uint32(nsegs - 1)
	hdrSize := streamHeaderSize(maxSeg)
	if cap(e.hdrbuf) < hdrSize {
		e.hdrbuf = make([]byte, hdrSize)
	} else {
		e.hdrbuf = e.hdrbuf[:hdrSize]
	}
	marshalStreamHeader(e.hdrbuf, sizes)
	if err := e.write(e.hdrbuf); err != nil {
		return err
	}
	for i := int64(0); i < nsegs; i++ {
		s, err := m.Segment(SegmentID(i))
		if err != nil {
			return err
		}
		if err := e.write(s.data); err != nil {
			return err
		}
	}
	return nil
}

func (e *Encoder) write(b []byte) error {
	if e.packed {
		e.packbuf = packed.Pack(e.packbuf[:0], b)
		b = e.packbuf
	}
	_, err := e.w.Write(b)
	return err
}

func (m *Message) segmentSizes() ([]Size, error) {
	nsegs := m.NumSegments()
	sizes := make([]Size, nsegs)
	for i := int64(0); i < nsegs; i++ {
		s, err := m.Segment(SegmentID(i))
		if err != nil {
			return sizes[:i], err
		}
		n := len(s.data)
		if int64(n) > int64(maxSize) {
			return sizes[:i], errOverlarge
		}
		sizes[i] = Size(n)
	}
	return sizes, nil
}

// Marshal concatenates the segments in the message into a single byte
// slice including framing.
func (m *Message) Marshal() ([]byte, error) {
	// Compute buffer size.
	// TODO(light): error out if too many segments
	nsegs := m.NumSegments()
	if nsegs == 0 {
		return nil, errMessageEmpty
	}
	maxSeg := uint32(nsegs - 1)
	hdrSize := streamHeaderSize(maxSeg)
	sizes, err := m.segmentSizes()
	if err != nil {
		return nil, err
	}
	// TODO(light): error out if too large
	total := uint64(hdrSize) + totalSize(sizes)

	// Fill in buffer.
	buf := make([]byte, hdrSize, total)
	marshalStreamHeader(buf, sizes)
	for i := int64(0); i < nsegs; i++ {
		s, err := m.Segment(SegmentID(i))
		if err != nil {
			return nil, err
		}
		buf = append(buf, s.data...)
	}
	return buf, nil
}

// MarshalPacked marshals the message in packed form.
func (m *Message) MarshalPacked() ([]byte, error) {
	data, err := m.Marshal()
	if err != nil {
		return nil, err
	}
	buf := make([]byte, 0, len(data))
	buf = packed.Pack(buf, data)
	return buf, nil
}

// Stream header sizes.
const (
	msgHeaderSize = 4
	segHeaderSize = 4
)

// streamHeaderSize returns the size of the header, given the
// first 32-bit number.
func streamHeaderSize(n uint32) int {
	return (msgHeaderSize + segHeaderSize*(int(n)+1) + 7) &^ 7
}

// marshalStreamHeader marshals the sizes into the byte slice, which
// must be of size streamHeaderSize(len(sizes) - 1).
func marshalStreamHeader(b []byte, sizes []Size) {
	binary.LittleEndian.PutUint32(b, uint32(len(sizes)-1))
	for i, sz := range sizes {
		loc := msgHeaderSize + i*segHeaderSize
		binary.LittleEndian.PutUint32(b[loc:], uint32(sz/Size(wordSize)))
	}
}

// unmarshalStreamHeader parses the header of the stream framing format.
func unmarshalStreamHeader(data []byte) (sizes []Size, tail []byte, err error) {
	if len(data) < streamHeaderSize(0) {
		return nil, nil, io.ErrUnexpectedEOF
	}
	maxSeg := binary.LittleEndian.Uint32(data)
	// TODO(light): check int
	hdrSize := streamHeaderSize(maxSeg)
	if len(data) < hdrSize {
		return nil, nil, io.ErrUnexpectedEOF
	}
	n := int(maxSeg + 1)
	sizes = make([]Size, n)
	for i := 0; i < n; i++ {
		s := binary.LittleEndian.Uint32(data[msgHeaderSize+i*segHeaderSize:])
		sizes[i] = wordSize.times(int32(s))
	}
	return sizes, data[hdrSize:], nil
}

func hasCapacity(b []byte, sz Size) bool {
	return sz <= Size(cap(b)-len(b))
}

func totalSize(s []Size) uint64 {
	var sum uint64
	for _, sz := range s {
		sum += uint64(sz)
	}
	return sum
}

const maxInt32 = 0x7fffffff

// isInt32Bit reports whether the built-in int type is 32 bits.
func isInt32Bit() bool {
	const maxInt = int(^uint(0) >> 1)
	return maxInt == maxInt32
}

var (
	errBufferCall         = errors.New("capnp: can't call on a memory buffer")
	errSegmentOutOfBounds = errors.New("capnp: segment ID out of bounds")
	errSegment32Bit       = errors.New("capnp: segment ID larger than 31 bits")
	errMessageEmpty       = errors.New("capnp: marshalling an empty message")
	errHasData            = errors.New("capnp: NewMessage called on arena with data")
	errTooMuchData        = errors.New("capnp: too much data in stream")
	errSegmentTooSmall    = errors.New("capnp: segment too small")
	errStreamHeader       = errors.New("capnp: invalid stream header")
)


text:
package com.example.android.mysunshine.data;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;

/**
 * Created by Fzu_Xmu_bmw on 2015/4/20.
 * Email£º wmb007@126.com
 * MicroBlog:  http://weibo.com/wangmb007
 * ¡¾Android¡¿Uri¡¢UriMatcher¡¢ContentUrisÏê½â - ÓÒƲ×Ó - ²©¿ÍƵµÀ - CSDN.NET
 * http://blog.csdn.net/feng88724/article/details/6331396
 */

public class WeatherProvider extends ContentProvider {
    // The URI Matcher used by this content provider.
    private static final UriMatcher sUriMatcher = buildUriMatcher();
    private WeatherDbHelper mOpenHelper;

    private static final int WEATHER = 100;
    private static final int WEATHER_WITH_LOCATION = 101;
    private static final int WEATHER_WITH_LOCATION_AND_DATE = 102;
    private static final int LOCATION = 300;
    private static final int LOCATION_ID = 301;

    private static final SQLiteQueryBuilder sWeatherByLocationSettingQueryBuilder;

    static{
        sWeatherByLocationSettingQueryBuilder = new SQLiteQueryBuilder();
        sWeatherByLocationSettingQueryBuilder.setTables(
                WeatherContract.WeatherEntry.TABLE_NAME + " INNER JOIN " +
                        WeatherContract.LocationEntry.TABLE_NAME +
                        " ON " + WeatherContract.WeatherEntry.TABLE_NAME +
                        "." + WeatherContract.WeatherEntry.COLUMN_LOC_KEY +
                        " = " + WeatherContract.LocationEntry.TABLE_NAME +
                        "." + WeatherContract.LocationEntry._ID);
    }

    private static final String sLocationSettingSelection =
            WeatherContract.LocationEntry.TABLE_NAME+
                    "." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? ";
    private static final String sLocationSettingWithStartDateSelection =
            WeatherContract.LocationEntry.TABLE_NAME+
                    "." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? AND " +
                    WeatherContract.WeatherEntry.COLUMN_DATETEXT + " >= ? ";
    private static final String sLocationSettingAndDaySelection =
            WeatherContract.LocationEntry.TABLE_NAME +
                    "." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? AND " +
                    WeatherContract.WeatherEntry.COLUMN_DATETEXT + " = ? ";

    private Cursor getWeatherByLocationSetting(Uri uri, String[] projection, String sortOrder) {
        String locationSetting = WeatherContract.WeatherEntry.getLocationSettingFromUri(uri);
        String startDate = WeatherContract.WeatherEntry.getStartDateFromUri(uri);

        String[] selectionArgs;
        String selection;

        if (startDate == null) {
            selection = sLocationSettingSelection;
            selectionArgs = new String[]{locationSetting};
        } else {
            selectionArgs = new String[]{locationSetting, startDate};
            selection = sLocationSettingWithStartDateSelection;
        }

        return sWeatherByLocationSettingQueryBuilder.query(mOpenHelper.getReadableDatabase(),
                projection,
                selection,
                selectionArgs,
                null,
                null,
                sortOrder
        );
    }

    private Cursor getWeatherByLocationSettingAndDate(
            Uri uri, String[] projection, String sortOrder) {
        String locationSetting = WeatherContract.WeatherEntry.getLocationSettingFromUri(uri);
        String date = WeatherContract.WeatherEntry.getDateFromUri(uri);

        return sWeatherByLocationSettingQueryBuilder.query(mOpenHelper.getReadableDatabase(),
                projection,
                sLocationSettingAndDaySelection,
                new String[]{locationSetting, date},
                null,
                null,
                sortOrder
        );
    }

    private static UriMatcher buildUriMatcher() {
        // I know what you're thinking.  Why create a UriMatcher when you can use regular
        // expressions instead?  Because you're not crazy, that's why.

        // All paths added to the UriMatcher have a corresponding code to return when a match is
        // found.  The code passed into the constructor represents the code to return for the root
        // URI.  It's common to use NO_MATCH as the code for this case.
        final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
        final String authority = WeatherContract.CONTENT_AUTHORITY;

        // For each type of URI you want to add, create a corresponding code.
        matcher.addURI(authority, WeatherContract.PATH_WEATHER, WEATHER);
        matcher.addURI(authority, WeatherContract.PATH_WEATHER + "/*", WEATHER_WITH_LOCATION);
        matcher.addURI(authority, WeatherContract.PATH_WEATHER + "/*/*", WEATHER_WITH_LOCATION_AND_DATE);

        matcher.addURI(authority, WeatherContract.PATH_LOCATION, LOCATION);
        matcher.addURI(authority, WeatherContract.PATH_LOCATION + "/#", LOCATION_ID);

        return matcher;
    }
    @Override
    public boolean onCreate() {
        mOpenHelper = new WeatherDbHelper(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
                        String sortOrder) {
        // Here's the switch statement that, given a URI, will determine what kind of request it is,
        // and query the database accordingly.
        Cursor retCursor;
        switch (sUriMatcher.match(uri)) {
            // "weather/*/*"
            case WEATHER_WITH_LOCATION_AND_DATE:
            {
                retCursor = getWeatherByLocationSettingAndDate(uri, projection, sortOrder);
                break;
            }
            // "weather/*"
            case WEATHER_WITH_LOCATION: {
                retCursor = getWeatherByLocationSetting(uri, projection, sortOrder);
                break;
            }
            // "weather"
            case WEATHER: {
                retCursor = mOpenHelper.getReadableDatabase().query(
                        WeatherContract.WeatherEntry.TABLE_NAME,
                        projection,
                        selection,
                        selectionArgs,
                        null,
                        null,
                        sortOrder
                );
                break;
            }
            // "location/*"
            case LOCATION_ID: {
                retCursor = mOpenHelper.getReadableDatabase().query(
                        WeatherContract.LocationEntry.TABLE_NAME,
                        projection,
                        WeatherContract.LocationEntry._ID + " = '" + ContentUris.parseId(uri) + "'",
                        null,
                        null,
                        null,
                        sortOrder
                );
                break;
            }
            // "location"
            case LOCATION: {
                retCursor = mOpenHelper.getReadableDatabase().query(
                        WeatherContract.LocationEntry.TABLE_NAME,
                        projection,
                        selection,
                        selectionArgs,
                        null,
                        null,
                        sortOrder
                );
                break;
            }

            default:
                throw new UnsupportedOperationException("Unknown uri: " + uri);
        }
        retCursor.setNotificationUri(getContext().getContentResolver(), uri);
        return retCursor;
    }

    @Override
    public String getType(Uri uri) {
        // Use the Uri Matcher to determine what kind of URI this is.
        final int match = sUriMatcher.match(uri);

        switch (match) {
            case WEATHER_WITH_LOCATION_AND_DATE:
                return WeatherContract.WeatherEntry.CONTENT_ITEM_TYPE;
            case WEATHER_WITH_LOCATION:
                return WeatherContract.WeatherEntry.CONTENT_TYPE;
            case WEATHER:
                return WeatherContract.WeatherEntry.CONTENT_TYPE;
            case LOCATION:
                return WeatherContract.LocationEntry.CONTENT_TYPE;
            case LOCATION_ID:
                return WeatherContract.LocationEntry.CONTENT_ITEM_TYPE;

            default:
                throw new UnsupportedOperationException("Unknown uri: " + uri);
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues contentValues) {
        return null;
    }

    @Override
    public int delete(Uri uri, String s, String[] strings) {
        return 0;
    }

    @Override
    public int update(Uri uri, ContentValues contentValues, String s, String[] strings) {
        return 0;
    }
}


text:
package de.uniwue.mk.malletcrf;

import java.util.ArrayList;
import java.util.regex.Pattern;

import cc.mallet.pipe.CharSequence2TokenSequence;
import cc.mallet.pipe.FeatureSequence2FeatureVector;
import cc.mallet.pipe.Input2CharSequence;
import cc.mallet.pipe.Pipe;
import cc.mallet.pipe.SerialPipes;
import cc.mallet.pipe.Target2Label;
import cc.mallet.pipe.TokenSequence2FeatureSequence;
import cc.mallet.pipe.TokenSequenceRemoveStopwords;

public class ClassificationPipeInitializer implements IPipeInitializer {

  public Pipe initializePipe() {
    Pattern tokenPattern = Pattern.compile("[\\p{L}\\p{N}_]+");

    ArrayList<Pipe> pipeList = new ArrayList<Pipe>();

    // It is a Pipe that can read data from various kinds of sources
    // and convert the given input into character sequence.
    pipeList.add(new Input2CharSequence("UTF-8"));

    // It is pipe that tokenizes a character sequence. It expects a character sequence and converts
    // into tokens. For e.g. after passing through Input2CharSequence you have following data.
    pipeList.add(new CharSequence2TokenSequence(tokenPattern));

    // It is the pipe which is used to remove the stop words from the tokens. The program contains a
    // list of stopword(which are basically useless). If tokens contains these stopwords than that
    // tokens are removed from the TokenList.
    pipeList.add(new TokenSequenceRemoveStopwords(true, true));

    // It converts the Token Sequence to FeatureSequence.It indexes the each token.
    pipeList.add(new TokenSequence2FeatureSequence());

    // Convert Object in the target field into the label.
    pipeList.add(new Target2Label());

    // Convert a data field from Feature Sequence to Feature vector. This class does not insist on
    // getting its own Alphabet because it rely on getting from the FeatureSequence input.
    pipeList.add(new FeatureSequence2FeatureVector(false));
    return new SerialPipes(pipeList);
  }

}


text:
class Core;
class Network;
class UnstructuredBuffer;
class NetPacket;

#include "fixed_types.h"
#include "time_types.h"

class ClockSkewManagementObject
{
public:
   enum Scheme
   {
      LAX = 0,
      LAX_BARRIER,
      LAX_P2P,
      NUM_SCHEMES
   };

   static Scheme parseScheme(std::string scheme);
};

void ClockSkewManagementClientNetworkCallback(void* obj, NetPacket packet);

class ClockSkewManagementClient : public ClockSkewManagementObject
{
protected:
   ClockSkewManagementClient() {}

public:
   ~ClockSkewManagementClient() {}
   static ClockSkewManagementClient* create(std::string scheme_str, Core* core);

   virtual void enable() = 0;
   virtual void disable() = 0;
   virtual void synchronize(Time curr_time = Time(0)) = 0;
   virtual void netProcessSyncMsg(const NetPacket& recv_pkt) = 0;
};

class ClockSkewManagementManager : public ClockSkewManagementObject
{
protected:
   ClockSkewManagementManager() {}

public:
   ~ClockSkewManagementManager() {}
   static ClockSkewManagementManager* create(std::string scheme_str);

   virtual void processSyncMsg(Byte* msg) = 0;
};

class ClockSkewManagementServer : public ClockSkewManagementObject
{
protected:
   ClockSkewManagementServer() {}

public:
   ~ClockSkewManagementServer() {}
   static ClockSkewManagementServer* create(std::string scheme_str, Network& network, UnstructuredBuffer& recv_buff);

   virtual void processSyncMsg(core_id_t core_id) = 0;
   virtual void signal() = 0;
};


text:
#ifndef STATE_CHART_INTERNAL_STATE_MACHINE_LOGGER_H_
#define STATE_CHART_INTERNAL_STATE_MACHINE_LOGGER_H_

#include <string>

#include "statechart/platform/types.h"
#include "statechart/state_machine_listener.h"

namespace state_chart {
class Runtime;
namespace model {
class State;
}  // namespace model
}  // namespace state_chart

namespace state_chart {

// Logs state machine changes using VLOG(1).
class StateMachineLogger : public StateMachineListener {
 public:
  StateMachineLogger() = default;
  StateMachineLogger(const StateMachineLogger&) = delete;
  StateMachineLogger& operator=(const StateMachineLogger&) = delete;
  ~StateMachineLogger() override = default;

  void OnStateEntered(const Runtime* runtime,
                      const model::State* state) override;

  void OnStateExited(const Runtime* runtime,
                     const model::State* state) override;

  void OnTransitionFollowed(const Runtime* runtime,
                            const model::Transition* transition) override;

  void OnSendEvent(const Runtime* runtime, const string& event,
                   const string& target, const string& type, const string& id,
                   const string& data) override;
};

}  // namespace state_chart

#endif  // STATE_CHART_INTERNAL_STATE_MACHINE_LOGGER_H_