text:
from __future__ import unicode_literals

import datetime
import itertools
import json
import logging
import multiprocessing
import os
import pprint
import re
import sys

from pelican.generators import ArticlesGenerator
from pelican.generators import PagesGenerator
from pelican.settings import DEFAULT_CONFIG
from pelican import signals
from pelican.utils import pelican_open

logger = logging.getLogger(__name__)

try:
    from PIL import Image
    from PIL import ImageDraw
    from PIL import ImageEnhance
    from PIL import ImageFont
except ImportError:
    logger.error('PIL/Pillow not found')

try:
    import piexif
except ImportError:
    ispiexif = False
    logger.warning('piexif not found! Cannot use exif manipulation features')
else:
    ispiexif = True
    logger.debug('piexif found.')

def initialized(pelican):

    p = os.path.expanduser('~/Pictures')

    DEFAULT_CONFIG.setdefault('PHOTO_LIBRARY', p)
    DEFAULT_CONFIG.setdefault('PHOTO_GALLERY', (1024, 768, 80))
    DEFAULT_CONFIG.setdefault('PHOTO_ARTICLE', (760, 506, 80))
    DEFAULT_CONFIG.setdefault('PHOTO_THUMB', (192, 144, 60))
    DEFAULT_CONFIG.setdefault('PHOTO_GALLERY_TITLE', '')
    DEFAULT_CONFIG.setdefault('PHOTO_ALPHA_BACKGROUND_COLOR', (255, 255, 255))
    DEFAULT_CONFIG.setdefault('PHOTO_WATERMARK', False)
    DEFAULT_CONFIG.setdefault('PHOTO_WATERMARK_THUMB', False)
    DEFAULT_CONFIG.setdefault('PHOTO_WATERMARK_TEXT', DEFAULT_CONFIG['SITENAME'])
    DEFAULT_CONFIG.setdefault('PHOTO_WATERMARK_TEXT_COLOR', (255, 255, 255))
    DEFAULT_CONFIG.setdefault('PHOTO_WATERMARK_IMG', '')
    DEFAULT_CONFIG.setdefault('PHOTO_WATERMARK_IMG_SIZE', False)
    DEFAULT_CONFIG.setdefault('PHOTO_RESIZE_JOBS', 1)
    DEFAULT_CONFIG.setdefault('PHOTO_EXIF_KEEP', False)
    DEFAULT_CONFIG.setdefault('PHOTO_EXIF_REMOVE_GPS', False)
    DEFAULT_CONFIG.setdefault('PHOTO_EXIF_AUTOROTATE', True)
    DEFAULT_CONFIG.setdefault('PHOTO_EXIF_COPYRIGHT', False)
    DEFAULT_CONFIG.setdefault('PHOTO_EXIF_COPYRIGHT_AUTHOR', DEFAULT_CONFIG['SITENAME'])
    DEFAULT_CONFIG.setdefault('PHOTO_LIGHTBOX_GALLERY_ATTR', 'data-lightbox')
    DEFAULT_CONFIG.setdefault('PHOTO_LIGHTBOX_CAPTION_ATTR', 'data-title')

    DEFAULT_CONFIG['queue_resize'] = {}
    DEFAULT_CONFIG['created_galleries'] = {}
    DEFAULT_CONFIG['plugin_dir'] = os.path.dirname(os.path.realpath(__file__))

    if pelican:
        pelican.settings.setdefault('PHOTO_LIBRARY', p)
        pelican.settings.setdefault('PHOTO_GALLERY', (1024, 768, 80))
        pelican.settings.setdefault('PHOTO_ARTICLE', (760, 506, 80))
        pelican.settings.setdefault('PHOTO_THUMB', (192, 144, 60))
        pelican.settings.setdefault('PHOTO_GALLERY_TITLE', '')
        pelican.settings.setdefault('PHOTO_ALPHA_BACKGROUND_COLOR', (255, 255, 255))
        pelican.settings.setdefault('PHOTO_WATERMARK', False)
        pelican.settings.setdefault('PHOTO_WATERMARK_THUMB', False)
        pelican.settings.setdefault('PHOTO_WATERMARK_TEXT', pelican.settings['SITENAME'])
        pelican.settings.setdefault('PHOTO_WATERMARK_TEXT_COLOR', (255, 255, 255))
        pelican.settings.setdefault('PHOTO_WATERMARK_IMG', '')
        pelican.settings.setdefault('PHOTO_WATERMARK_IMG_SIZE', False)
        pelican.settings.setdefault('PHOTO_RESIZE_JOBS', 1)
        pelican.settings.setdefault('PHOTO_EXIF_KEEP', False)
        pelican.settings.setdefault('PHOTO_EXIF_REMOVE_GPS', False)
        pelican.settings.setdefault('PHOTO_EXIF_AUTOROTATE', True)
        pelican.settings.setdefault('PHOTO_EXIF_COPYRIGHT', False)
        pelican.settings.setdefault('PHOTO_EXIF_COPYRIGHT_AUTHOR', pelican.settings['AUTHOR'])
        pelican.settings.setdefault('PHOTO_LIGHTBOX_GALLERY_ATTR', 'data-lightbox')
        pelican.settings.setdefault('PHOTO_LIGHTBOX_CAPTION_ATTR', 'data-title')

def read_notes(filename, msg=None):
    notes = {}
    try:
        with pelican_open(filename) as text:
            for line in text.splitlines():
                if line.startswith('#'):
                    continue

                m = line.split(':', 1)
                if len(m) > 1:
                    pic = m[0].strip()
                    note = m[1].strip()
                    if pic and note:
                        notes[pic] = note
                else:
                    notes[line] = ''
    except Exception as e:
        if msg:
            logger.warning('{} at file {}'.format(msg, filename))
        logger.debug('read_notes issue: {} at file {}. Debug message:{}'.format(msg, filename, e))
    return notes

def enqueue_resize(orig, resized, spec=(640, 480, 80)):
    if resized not in DEFAULT_CONFIG['queue_resize']:
        DEFAULT_CONFIG['queue_resize'][resized] = (orig, spec)
    elif DEFAULT_CONFIG['queue_resize'][resized] != (orig, spec):
        logger.error('photos: resize conflict for {}, {}-{} is not {}-{}'.format(resized, DEFAULT_CONFIG['queue_resize'][resized][0], DEFAULT_CONFIG['queue_resize'][resized][1], orig, spec))

def isalpha(img):
    return True if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info) else False

def remove_alpha(img, bg_color):
    background = Image.new("RGB", img.size, bg_color)
    background.paste(img, mask=img.split()[3])  # 3 is the alpha channel

    return background

def ReduceOpacity(im, opacity):
    """Reduces Opacity.

    Returns an image with reduced opacity.
    Taken from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362879
    """
    assert opacity >= 0 and opacity <= 1
    if isalpha(im):
        im = im.copy()
    else:
        im = im.convert('RGBA')

    alpha = im.split()[3]
    alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
    im.putalpha(alpha)
    return im

def watermark_photo(image, settings):

    margin = [10, 10]
    opacity = 0.6

    watermark_layer = Image.new("RGBA", image.size, (0, 0, 0, 0))
    draw_watermark = ImageDraw.Draw(watermark_layer)
    text_reducer = 32
    image_reducer = 8
    text_size = [0, 0]
    mark_size = [0, 0]
    text_position = [0, 0]

    if settings['PHOTO_WATERMARK_TEXT']:
        font_name = 'SourceCodePro-Bold.otf'
        default_font = os.path.join(DEFAULT_CONFIG['plugin_dir'], font_name)
        font = ImageFont.FreeTypeFont(default_font, watermark_layer.size[0] // text_reducer)
        text_size = draw_watermark.textsize(settings['PHOTO_WATERMARK_TEXT'], font)
        text_position = [image.size[i] - text_size[i] - margin[i] for i in [0, 1]]
        draw_watermark.text(text_position, settings['PHOTO_WATERMARK_TEXT'], settings['PHOTO_WATERMARK_TEXT_COLOR'], font=font)

    if settings['PHOTO_WATERMARK_IMG']:
        mark_image = Image.open(settings['PHOTO_WATERMARK_IMG'])
        mark_image_size = [watermark_layer.size[0] // image_reducer for size in mark_size]
        mark_image_size = settings['PHOTO_WATERMARK_IMG_SIZE'] if settings['PHOTO_WATERMARK_IMG_SIZE'] else mark_image_size
        mark_image.thumbnail(mark_image_size, Image.ANTIALIAS)
        mark_position = [watermark_layer.size[i] - mark_image.size[i] - margin[i] for i in [0, 1]]
        mark_position = tuple([mark_position[0] - (text_size[0] // 2) + (mark_image_size[0] // 2), mark_position[1] - text_size[1]])

        if not isalpha(mark_image):
            mark_image = mark_image.convert('RGBA')

        watermark_layer.paste(mark_image, mark_position, mark_image)

    watermark_layer = ReduceOpacity(watermark_layer, opacity)
    image.paste(watermark_layer, (0, 0), watermark_layer)

    return image

def rotate_image(img, exif_dict):

    if "exif" in img.info and piexif.ImageIFD.Orientation in exif_dict["0th"]:
        orientation = exif_dict["0th"].pop(piexif.ImageIFD.Orientation)
        if orientation == 2:
            img = img.transpose(Image.FLIP_LEFT_RIGHT)
        elif orientation == 3:
            img = img.rotate(180)
        elif orientation == 4:
            img = img.rotate(180).transpose(Image.FLIP_LEFT_RIGHT)
        elif orientation == 5:
            img = img.rotate(-90).transpose(Image.FLIP_LEFT_RIGHT)
        elif orientation == 6:
            img = img.rotate(-90)
        elif orientation == 7:
            img = img.rotate(90).transpose(Image.FLIP_LEFT_RIGHT)
        elif orientation == 8:
            img = img.rotate(90)

    return (img, exif_dict)

def build_license(license, author):

    year = datetime.datetime.now().year
    license_file = os.path.join(DEFAULT_CONFIG['plugin_dir'], 'licenses.json')

    with open(license_file) as data_file:
        licenses = json.load(data_file)

    if any(license in k for k in licenses):
        return licenses[license]['Text'].format(Author=author, Year=year, URL=licenses[license]['URL'])
    else:
        return 'Copyright {Year} {Author}, All Rights Reserved'.format(Author=author, Year=year)

def manipulate_exif(img, settings):

    try:
        exif = piexif.load(img.info['exif'])
    except Exception:
        logger.debug('EXIF information not found')
        exif = {}

    if settings['PHOTO_EXIF_AUTOROTATE']:
        img, exif = rotate_image(img, exif)

    if settings['PHOTO_EXIF_REMOVE_GPS']:
        exif.pop('GPS')

    if settings['PHOTO_EXIF_COPYRIGHT']:

        # We want to be minimally destructive to any preset exif author or copyright information.
        # If there is copyright or author information prefer that over everything else.
        if not exif['0th'].get(piexif.ImageIFD.Artist):
            exif['0th'][piexif.ImageIFD.Artist] = settings['PHOTO_EXIF_COPYRIGHT_AUTHOR']
            author = settings['PHOTO_EXIF_COPYRIGHT_AUTHOR']

        if not exif['0th'].get(piexif.ImageIFD.Copyright):
            license = build_license(settings['PHOTO_EXIF_COPYRIGHT'], author)
            exif['0th'][piexif.ImageIFD.Copyright] = license

    return (img, piexif.dump(exif))

def resize_worker(orig, resized, spec, settings):

    logger.info('photos: make photo {} -> {}'.format(orig, resized))
    im = Image.open(orig)

    if ispiexif and settings['PHOTO_EXIF_KEEP'] and im.format == 'JPEG':  # Only works with JPEG exif for sure.
        im, exif_copy = manipulate_exif(im, settings)
    else:
        exif_copy = b''

    icc_profile = im.info.get("icc_profile", None)
    im.thumbnail((spec[0], spec[1]), Image.ANTIALIAS)
    directory = os.path.split(resized)[0]

    if isalpha(im):
        im = remove_alpha(im, settings['PHOTO_ALPHA_BACKGROUND_COLOR'])

    if not os.path.exists(directory):
        try:
            os.makedirs(directory)
        except Exception:
            logger.exception('Could not create {}'.format(directory))
    else:
        logger.debug('Directory already exists at {}'.format(os.path.split(resized)[0]))

    if settings['PHOTO_WATERMARK']:
        isthumb = True if spec == settings['PHOTO_THUMB'] else False
        if not isthumb or (isthumb and settings['PHOTO_WATERMARK_THUMB']):
            im = watermark_photo(im, settings)

    im.save(resized, 'JPEG', quality=spec[2], icc_profile=icc_profile, exif=exif_copy)

def resize_photos(generator, writer):
    if generator.settings['PHOTO_RESIZE_JOBS'] == -1:
        debug = True
        generator.settings['PHOTO_RESIZE_JOBS'] = 1
    else:
        debug = False

    pool = multiprocessing.Pool(generator.settings['PHOTO_RESIZE_JOBS'])
    logger.debug('Debug Status: {}'.format(debug))
    for resized, what in DEFAULT_CONFIG['queue_resize'].items():
        resized = os.path.join(generator.output_path, resized)
        orig, spec = what
        if (not os.path.isfile(resized) or os.path.getmtime(orig) > os.path.getmtime(resized)):
            if debug:
                resize_worker(orig, resized, spec, generator.settings)
            else:
                pool.apply_async(resize_worker, (orig, resized, spec, generator.settings))

    pool.close()
    pool.join()

def detect_content(content):

    hrefs = None

    def replacer(m):
        what = m.group('what')
        value = m.group('value')
        tag = m.group('tag')
        output = m.group(0)

        if what in ('photo', 'lightbox'):
            if value.startswith('/'):
                value = value[1:]

            path = os.path.join(
                os.path.expanduser(settings['PHOTO_LIBRARY']),
                value
            )

            if os.path.isfile(path):
                photo_prefix = os.path.splitext(value)[0].lower()

                if what == 'photo':
                    photo_article = photo_prefix + 'a.jpg'
                    enqueue_resize(
                        path,
                        os.path.join('photos', photo_article),
                        settings['PHOTO_ARTICLE']
                    )

                    output = ''.join((
                        '<',
                        m.group('tag'),
                        m.group('attrs_before'),
                        m.group('src'),
                        '=',
                        m.group('quote'),
                        os.path.join(settings['SITEURL'], 'photos', photo_article),
                        m.group('quote'),
                        m.group('attrs_after'),
                    ))

                elif what == 'lightbox' and tag == 'img':
                    photo_gallery = photo_prefix + '.jpg'
                    enqueue_resize(
                        path,
                        os.path.join('photos', photo_gallery),
                        settings['PHOTO_GALLERY']
                    )

                    photo_thumb = photo_prefix + 't.jpg'
                    enqueue_resize(
                        path,
                        os.path.join('photos', photo_thumb),
                        settings['PHOTO_THUMB']
                    )

                    lightbox_attr_list = ['']

                    gallery_name = value.split('/')[0]
                    lightbox_attr_list.append('{}="{}"'.format(
                        settings['PHOTO_LIGHTBOX_GALLERY_ATTR'],
                        gallery_name
                    ))

                    captions = read_notes(
                        os.path.join(os.path.dirname(path), 'captions.txt'),
                        msg = 'photos: No captions for gallery'
                    )
                    caption = captions.get(os.path.basename(path)) if captions else None
                    if caption:
                        lightbox_attr_list.append('{}="{}"'.format(
                            settings['PHOTO_LIGHTBOX_CAPTION_ATTR'],
                            caption
                        ))

                    lightbox_attrs = ' '.join(lightbox_attr_list)

                    output = ''.join((
                        '<img',
                        m.group('attrs_before'),
                        'src=',
                        m.group('quote'),
                        os.path.join(settings['SITEURL'], 'photos', photo_thumb),
                        m.group('quote'),
                        m.group('attrs_after'),
                        ''
                    ))

            else:
                logger.error('photos: No photo %s', path)

        return output

    if hrefs is None:
        regex = r"""
            <\s*
            (?P<tag>[^\s\>]+)  # detect the tag
            (?P<attrs_before>[^\>]*)
            (?P<src>href|src)  # match tag with src and href attr
            \s*=
            (?P<quote>["\'])  # require value to be quoted
            (?P<path>{0}(?P<value>.*?))  # the url value
            (?P=quote)
            (?P<attrs_after>[^\>]*>)
        """.format(
            content.settings['INTRASITE_LINK_REGEX']
        )
        hrefs = re.compile(regex, re.X)

    if content._content and ('{photo}' in content._content or '{lightbox}' in content._content):
        settings = content.settings
        content._content = hrefs.sub(replacer, content._content)

def galleries_string_decompose(gallery_string):
    splitter_regex = re.compile(r'[\s,]*?({photo}|{filename})')
    title_regex = re.compile(r'{(.+)}')
    galleries = map(unicode.strip if sys.version_info.major == 2 else str.strip, filter(None, splitter_regex.split(gallery_string)))
    galleries = [gallery[1:] if gallery.startswith('/') else gallery for gallery in galleries]
    if len(galleries) % 2 == 0 and ' ' not in galleries:
        galleries = zip(zip(['type'] * len(galleries[0::2]), galleries[0::2]), zip(['location'] * len(galleries[0::2]), galleries[1::2]))
        galleries = [dict(gallery) for gallery in galleries]
        for gallery in galleries:
            title = re.search(title_regex, gallery['location'])
            if title:
                gallery['title'] = title.group(1)
                gallery['location'] = re.sub(title_regex, '', gallery['location']).strip()
            else:
                gallery['title'] = DEFAULT_CONFIG['PHOTO_GALLERY_TITLE']
        return galleries
    else:
        logger.error('Unexpected gallery location format! \n{}'.format(pprint.pformat(galleries)))

def process_gallery(generator, content, location):

    content.photo_gallery = []

    galleries = galleries_string_decompose(location)

    for gallery in galleries:

        if gallery['location'] in DEFAULT_CONFIG['created_galleries']:
            content.photo_gallery.append((gallery['location'], DEFAULT_CONFIG['created_galleries'][gallery]))
            continue

        if gallery['type'] == '{photo}':
            dir_gallery = os.path.join(os.path.expanduser(generator.settings['PHOTO_LIBRARY']), gallery['location'])
            rel_gallery = gallery['location']
        elif gallery['type'] == '{filename}':
            base_path = os.path.join(generator.path, content.relative_dir)
            dir_gallery = os.path.join(base_path, gallery['location'])
            rel_gallery = os.path.join(content.relative_dir, gallery['location'])

        if os.path.isdir(dir_gallery):
            logger.info('photos: Gallery detected: {}'.format(rel_gallery))
            dir_photo = os.path.join('photos', rel_gallery.lower())
            dir_thumb = os.path.join('photos', rel_gallery.lower())
            exifs = read_notes(os.path.join(dir_gallery, 'exif.txt'),
                               msg='photos: No EXIF for gallery')
            captions = read_notes(os.path.join(dir_gallery, 'captions.txt'), msg='photos: No captions for gallery')
            blacklist = read_notes(os.path.join(dir_gallery, 'blacklist.txt'), msg='photos: No blacklist for gallery')
            content_gallery = []

            title = gallery['title']
            for pic in sorted(os.listdir(dir_gallery)):
                if pic.startswith('.'):
                    continue
                if pic.endswith('.txt'):
                    continue
                if pic in blacklist:
                    continue
                photo = os.path.splitext(pic)[0].lower() + '.jpg'
                thumb = os.path.splitext(pic)[0].lower() + 't.jpg'
                content_gallery.append((
                    pic,
                    os.path.join(dir_photo, photo),
                    os.path.join(dir_thumb, thumb),
                    exifs.get(pic, ''),
                    captions.get(pic, '')))

                enqueue_resize(
                    os.path.join(dir_gallery, pic),
                    os.path.join(dir_photo, photo),
                    generator.settings['PHOTO_GALLERY'])
                enqueue_resize(
                    os.path.join(dir_gallery, pic),
                    os.path.join(dir_thumb, thumb),
                    generator.settings['PHOTO_THUMB'])

            content.photo_gallery.append((title, content_gallery))
            logger.debug('Gallery Data: '.format(pprint.pformat(content.photo_gallery)))
            DEFAULT_CONFIG['created_galleries']['gallery'] = content_gallery
        else:
            logger.error('photos: Gallery does not exist: {} at {}'.format(gallery['location'], dir_gallery))

def detect_gallery(generator, content):
    if 'gallery' in content.metadata:
        gallery = content.metadata.get('gallery')
        if gallery.startswith('{photo}') or gallery.startswith('{filename}'):
            process_gallery(generator, content, gallery)
        elif gallery:
            logger.error('photos: Gallery tag not recognized: {}'.format(gallery))

def image_clipper(x):
    return x[8:] if x[8] == '/' else x[7:]

def file_clipper(x):
    return x[11:] if x[10] == '/' else x[10:]

def process_image(generator, content, image):

    if image.startswith('{photo}'):
        path = os.path.join(os.path.expanduser(generator.settings['PHOTO_LIBRARY']), image_clipper(image))
        image = image_clipper(image)
    elif image.startswith('{filename}'):
        path = os.path.join(content.relative_dir, file_clipper(image))
        image = file_clipper(image)

    if os.path.isfile(path):
        photo = os.path.splitext(image)[0].lower() + 'a.jpg'
        thumb = os.path.splitext(image)[0].lower() + 't.jpg'
        content.photo_image = (
            os.path.basename(image).lower(),
            os.path.join('photos', photo),
            os.path.join('photos', thumb))
        enqueue_resize(
            path,
            os.path.join('photos', photo),
            generator.settings['PHOTO_ARTICLE'])
        enqueue_resize(
            path,
            os.path.join('photos', thumb),
            generator.settings['PHOTO_THUMB'])
    else:
        logger.error('photo: No photo for {} at {}'.format(content.source_path, path))

def detect_image(generator, content):
    image = content.metadata.get('image', None)
    if image:
        if image.startswith('{photo}') or image.startswith('{filename}'):
            process_image(generator, content, image)
        else:
            logger.error('photos: Image tag not recognized: {}'.format(image))

def detect_images_and_galleries(generators):
    """Runs generator on both pages and articles."""
    for generator in generators:
        if isinstance(generator, ArticlesGenerator):
            for article in itertools.chain(generator.articles, generator.translations, generator.drafts):
                detect_image(generator, article)
                detect_gallery(generator, article)
        elif isinstance(generator, PagesGenerator):
            for page in itertools.chain(generator.pages, generator.translations, generator.hidden_pages):
                detect_image(generator, page)
                detect_gallery(generator, page)

def register():
    """Uses the new style of registration based on GitHub Pelican issue #314."""
    signals.initialized.connect(initialized)
    try:
        signals.content_object_init.connect(detect_content)
        signals.all_generators_finalized.connect(detect_images_and_galleries)
        signals.article_writer_finalized.connect(resize_photos)
    except Exception as e:
        logger.exception('Plugin failed to execute: {}'.format(pprint.pformat(e)))


text:
package org.ops4j.pax.wicket.test.spring;

import org.apache.wicket.util.tester.WicketTester;

/**
 * An injector using the ApplicationContextMock and the PaxWicketSpringBeanComponentInjector in a quite simplified
 * way making working based on them easier.
 *
 * @author nmw
 * @version $Id: $Id
 */
public class SimplifiedPaxWicketInjector {
    private final ApplicationContextMock applicationContext = new ApplicationContextMock();

    /**
     *
registerBeanInjector.

     *
     * @param tester a {@link org.apache.wicket.util.tester.WicketTester} object.
     * @return a {@link org.ops4j.pax.wicket.test.spring.SimplifiedPaxWicketInjector} object.
     */
    public static SimplifiedPaxWicketInjector registerBeanInjector(WicketTester tester) {
        return new SimplifiedPaxWicketInjector(tester);
    }

    private SimplifiedPaxWicketInjector(WicketTester tester) {
        tester.getApplication().getComponentInstantiationListeners().add(
                new PaxWicketSpringBeanComponentInjector(tester.getApplication(), applicationContext));
    }

    /**
     *
registerBean.

     *
     * @param name a {@link java.lang.String} object.
     * @param bean a {@link java.lang.Object} object.
     */
    public void registerBean(String name, Object bean) {
        applicationContext.putBean(name, bean);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.intellij.debugger.actions;

import com.intellij.debugger.SourcePosition;
import com.intellij.debugger.engine.DebugProcessImpl;
import com.intellij.debugger.engine.JVMNameUtil;
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl;
import com.intellij.debugger.engine.events.SuspendContextCommandImpl;
import com.intellij.debugger.impl.DebuggerContextImpl;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.debugger.jdi.MethodBytecodeUtil;
import com.intellij.debugger.ui.impl.watch.DebuggerTreeNodeImpl;
import com.intellij.debugger.ui.impl.watch.NodeDescriptorImpl;
import com.intellij.debugger.ui.tree.ValueDescriptor;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Computable;
import com.intellij.psi.PsiClass;
import com.intellij.util.containers.ContainerUtil;
import com.sun.jdi.*;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.org.objectweb.asm.MethodVisitor;
import org.jetbrains.org.objectweb.asm.Opcodes;

import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

public class JumpToObjectAction extends DebuggerAction{
  private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.actions.JumpToObjectAction");
  @Override
  public void actionPerformed(AnActionEvent e) {
    DebuggerTreeNodeImpl selectedNode = getSelectedNode(e.getDataContext());
    if(selectedNode == null) {
      return;
    }

    final NodeDescriptorImpl descriptor = selectedNode.getDescriptor();
    if(!(descriptor instanceof ValueDescriptor)) {
      return;
    }

    DebuggerContextImpl debuggerContext = getDebuggerContext(e.getDataContext());
    final DebugProcessImpl debugProcess = debuggerContext.getDebugProcess();
    if(debugProcess == null) {
      return;
    }

    debugProcess.getManagerThread().schedule(new NavigateCommand(debuggerContext, (ValueDescriptor)descriptor, debugProcess, e));
  }

  @Override
  public void update(final AnActionEvent e) {
    if(!isFirstStart(e)) {
      return;
    }

    final DebuggerContextImpl debuggerContext = getDebuggerContext(e.getDataContext());
    final DebugProcessImpl debugProcess = debuggerContext.getDebugProcess();
    if(debugProcess == null) {
      e.getPresentation().setVisible(false);
      return;
    }

    DebuggerTreeNodeImpl selectedNode = getSelectedNode(e.getDataContext());
    if(selectedNode == null) {
      e.getPresentation().setVisible(false);
      return;
    }

    final NodeDescriptorImpl descriptor = selectedNode.getDescriptor();
    if (descriptor instanceof ValueDescriptor) {
      debugProcess.getManagerThread().schedule(new EnableCommand(debuggerContext, (ValueDescriptor)descriptor, debugProcess, e));
    }
    else {
      e.getPresentation().setVisible(false);
    }
  }

  private static SourcePosition calcPosition(final ValueDescriptor descriptor, final DebugProcessImpl debugProcess) throws ClassNotLoadedException {
    Type type = descriptor.getType();
    if (type == null) {
      return null;
    }

    try {
      if(type instanceof ArrayType) {
        type = ((ArrayType)type).componentType();
      }
      if(type instanceof ClassType) {
        final ClassType clsType = (ClassType)type;
        Location lambdaLocation = null;
        if (DebuggerUtilsEx.isLambdaClassName(clsType.name())) {
          List<Method> applicableMethods = ContainerUtil.filter(clsType.methods(), m -> m.isPublic() && !m.isBridge());
          if (applicableMethods.size() == 1) {
            AtomicReference<Location> locationRef = new AtomicReference<>();
            MethodBytecodeUtil.visit(clsType, applicableMethods.get(0), new MethodVisitor(Opcodes.API_VERSION) {
              @Override
              public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
                ReferenceType cls = ContainerUtil.getFirstItem(clsType.virtualMachine().classesByName(owner));
                if (cls != null) {
                  Method method = ContainerUtil.getFirstItem(cls.methodsByName(name));
                  if (method != null) {
                    try {
                      Location loc = ContainerUtil.getFirstItem(method.allLineLocations());
                      if (loc != null) {
                        locationRef.set(loc);
                      }
                    }
                    catch (AbsentInformationException e) {
                      LOG.debug(e);
                    }
                  }
                }
              }
            });
            lambdaLocation = locationRef.get();
          }
        }
        final Location location = lambdaLocation != null ? lambdaLocation : ContainerUtil.getFirstItem(clsType.allLineLocations());
        if (location != null) {
          return ApplicationManager.getApplication().runReadAction(new Computable<SourcePosition>() {
            @Override
            public SourcePosition compute() {
              SourcePosition position = debugProcess.getPositionManager().getSourcePosition(location);
              // adjust position for non-anonymous classes
              if (clsType.name().indexOf('$') < 0) {
                final PsiClass classAt = JVMNameUtil.getClassAt(position);
                if (classAt != null) {
                  final SourcePosition classPosition = SourcePosition.createFromElement(classAt);
                  if (classPosition != null) {
                    position = classPosition;
                  }
                }
              }
              return position;
            }
          });
        }
      }
    }
    catch (ClassNotPreparedException | AbsentInformationException e) {
      LOG.debug(e);
    }
    return null;
  }

  public static class NavigateCommand extends SourcePositionCommand {
    public NavigateCommand(final DebuggerContextImpl debuggerContext, final ValueDescriptor descriptor, final DebugProcessImpl debugProcess, final AnActionEvent e) {
      super(debuggerContext, descriptor, debugProcess, e);
    }
    @Override
    protected NavigateCommand createRetryCommand() {
      return new NavigateCommand(myDebuggerContext, myDescriptor, myDebugProcess, myActionEvent);
    }
    @Override
    protected void doAction(final SourcePosition sourcePosition) {
      if (sourcePosition != null) {
        sourcePosition.navigate(true);
      }
    }
  }

  private static class EnableCommand extends SourcePositionCommand {
    public EnableCommand(final DebuggerContextImpl debuggerContext, final ValueDescriptor descriptor, final DebugProcessImpl debugProcess, final AnActionEvent e) {
      super(debuggerContext, descriptor, debugProcess, e);
    }
    @Override
    protected EnableCommand createRetryCommand() {
      return new EnableCommand(myDebuggerContext, myDescriptor, myDebugProcess, myActionEvent);
    }
    @Override
    protected void doAction(final SourcePosition sourcePosition) {
      enableAction(myActionEvent, sourcePosition != null);
    }
  }

  public abstract static class SourcePositionCommand extends SuspendContextCommandImpl {
    protected final DebuggerContextImpl myDebuggerContext;
    protected final ValueDescriptor myDescriptor;
    protected final DebugProcessImpl myDebugProcess;
    protected final AnActionEvent myActionEvent;

    public SourcePositionCommand(final DebuggerContextImpl debuggerContext,
                                 final ValueDescriptor descriptor,
                                 final DebugProcessImpl debugProcess,
                                 final AnActionEvent actionEvent) {
      super(debuggerContext.getSuspendContext());
      myDebuggerContext = debuggerContext;
      myDescriptor = descriptor;
      myDebugProcess = debugProcess;
      myActionEvent = actionEvent;
    }

    @Override
    public final void contextAction() throws Exception {
      try {
        doAction(calcPosition(myDescriptor, myDebugProcess));
      }
      catch (ClassNotLoadedException ex) {
        final String className = ex.className();
        if (loadClass(className) != null) {
          myDebugProcess.getManagerThread().schedule(createRetryCommand());
        }
      }
    }

    protected abstract SourcePositionCommand createRetryCommand();

    protected abstract void doAction(@Nullable SourcePosition sourcePosition);

    private ReferenceType loadClass(final String className) {
      final EvaluationContextImpl eContext = myDebuggerContext.createEvaluationContext();
      try {
        return myDebugProcess.loadClass(eContext, className, eContext.getClassLoader());
      }
      catch(Throwable ignored) {
      }
      return null;
    }
  }

}


text:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;

namespace FileHelpersAnalyzer
{
    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    public class UseGenericEngineAnalyzer : DiagnosticAnalyzer, IFileHelperAnalyzer
    {
        public string Id => DiagnosticId;
        public const string DiagnosticId = "FileHelpersUseGenericEngine";

        public static readonly string Title = "You can use the generic engine";
        public string FixTitle => "Use the generic engine";

        private static readonly string MessageFormat = "You can use the generic engine";
        private static readonly string Description = "It is recommended to use the generic version of the engine";

        private const string Category = "Usage";

        private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId,
            Title,
            MessageFormat,
            Category,
            DiagnosticSeverity.Warning,
            isEnabledByDefault: true,
            description: Description,
            helpLinkUri: "http://www.filehelpers.net/analizer/");

        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);

        public override void Initialize(AnalysisContext context)
        {
            context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.ObjectCreationExpression);
        }

        private void AnalyzeNode(SyntaxNodeAnalysisContext context)
        {
            var node = (ObjectCreationExpressionSyntax)context.Node;

            var engineType = node.Type.ToString();
            if (engineType.StartsWith("FileHelpers."))
                engineType = engineType.Substring("FileHelpers.".Length);

            if (engineType == "FileHelperEngine" ||
                engineType == "FileHelperAsyncEngine"
                )
            {
                if (node.ArgumentList.Arguments.Count > 0 &&
                    node.ArgumentList.Arguments[0].Expression is TypeOfExpressionSyntax)
                {
                    var symbol = context.SemanticModel.GetTypeInfo(node);
                    if (symbol.Type != null &&
                        symbol.Type.ContainingNamespace.Name == "FileHelpers" &&
                        symbol.Type.ContainingAssembly.Name == "FileHelpers")
                    {
                        var diagnostic = Diagnostic.Create(Rule, node.GetLocation());
                        context.ReportDiagnostic(diagnostic);
                    }
                }
            }
        }

    }
}


text:
// Bzip2 library for .net
// By Jaime Olivares
// Location: http://github.com/jaime-olivares/bzip2
// Ported from the Java implementation by Matthew Francis: https://github.com/MateuszBartosiewicz/bzip2

using System;
using System.IO;

namespace Bzip2
{
    /// An InputStream wrapper that decompresses BZip2 data
    /// <remarks>Instances of this class are not threadsafe</remarks>
	public class BZip2InputStream : Stream
	{
        #region Private fields
        // The stream from which compressed BZip2 data is read and decoded
		private Stream inputStream;

		// An InputStream wrapper that provides bit-level reads
		private BZip2BitInputStream bitInputStream;

		// If true, the caller is assumed to have read away the stream's leading "BZ" identifier bytes
		private readonly bool headerless;

		// (@code true} if the end of the compressed stream has been reached, otherwise false
		private bool streamComplete;

		/**
         * The declared block size of the stream (before final run-length decoding). The final block
         * will usually be smaller, but no block in the stream has to be exactly this large, and an
         * encoder could in theory choose to mix blocks of any size up to this value. Its function is
         * therefore as a hint to the decompressor as to how much working space is sufficient to
         * decompress blocks in a given stream
         */
		private uint streamBlockSize;

		// The merged CRC of all blocks decompressed so far
		private uint streamCRC;

		// The decompressor for the current block
		private BZip2BlockDecompressor blockDecompressor;
        #endregion

        #region Public methods
        /// Public constructor
        /// <param name="inputStream">The InputStream to wrap</param>
        /// <param name="headerless">If true, the caller is assumed to have read away the stream's
        /// leading "BZ" identifier bytes</param>
        public BZip2InputStream(Stream inputStream, bool headerless)
        {

            if (inputStream == null)
            {
                throw new ArgumentException("Null input stream");
            }

            this.inputStream = inputStream;
            this.bitInputStream = new BZip2BitInputStream(inputStream);
            this.headerless = headerless;
        }
        #endregion

        #region Implementation of abstract members of Stream
        #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
        public override void Flush()
        {
            throw new NotImplementedException();
        }
        public override long Seek(long offset, SeekOrigin origin)
        {
            throw new NotImplementedException();
        }
        public override void SetLength(long value)
        {
            throw new NotImplementedException();
        }
        public override void Write(byte[] buffer, int offset, int count)
        {
            throw new NotImplementedException();
        }
        public override bool CanRead
        {
            get
            {
                return true;
            }
        }
        public override bool CanSeek
        {
            get
            {
                return false;
            }
        }
        public override bool CanWrite
        {
            get
            {
                return false;
            }
        }
        public override long Length
        {
            get
            {
                throw new NotImplementedException();
            }
        }
        public override long Position
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public override int ReadByte()
        {
			var nextByte = -1;
			if (this.blockDecompressor == null)
				this.InitialiseStream();
			else
				nextByte = this.blockDecompressor.Read();

            if (nextByte != -1)
                return nextByte;

            if (this.InitialiseNextBlock())
                nextByte = this.blockDecompressor.Read();

            return nextByte;
		}

		public override int Read(byte[] destination,  int offset,  int length)
        {
			var bytesRead = -1;
			if (this.blockDecompressor == null)
				this.InitialiseStream();
			else
				bytesRead = this.blockDecompressor.Read(destination, offset, length);

		    if (bytesRead != -1)
                return bytesRead;
		    bytesRead = 0;

		    if (this.InitialiseNextBlock())
		        bytesRead = this.blockDecompressor.Read(destination, offset, length);

		    return bytesRead;
		}

        public override void Close()
        {
            if (this.bitInputStream == null)
                return;

            this.streamComplete = true;
            this.blockDecompressor = null;
            this.bitInputStream = null;

            try {
                this.inputStream.Close();
            } finally {
                this.inputStream = null;
            }
        }
        #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
        #endregion

        #region Private methods
        /// Reads the stream header and checks that the data appears to be a valid BZip2 stream
        /// <exception>if the stream header is not valid</exception>
        private void InitialiseStream()
        {
			/* If the stream has been explicitly closed, throw an exception */
			if (this.bitInputStream == null)
				throw new Exception ("Stream closed");

			/* If we're already at the end of the stream, do nothing */
			if (this.streamComplete)
				return;

			/* Read the stream header */
			try {
				uint marker1 = this.headerless ? 0 : this.bitInputStream.ReadBits(16);
				uint marker2 = this.bitInputStream.ReadBits (8);
				uint blockSize = (this.bitInputStream.ReadBits(8) - '0');

				if ((!this.headerless && (marker1 != BZip2OutputStream.STREAM_START_MARKER_1))
					|| (marker2 != BZip2OutputStream.STREAM_START_MARKER_2)
					|| (blockSize < 1) || (blockSize > 9))
				{
					throw new Exception ("Invalid BZip2 header");
				}

				this.streamBlockSize = blockSize * 100000;
			}
            catch (IOException)
            {
				// If the stream header was not valid, stop trying to read more data
				this.streamComplete = true;
				throw;
			}
        }

        /// Prepares a new block for decompression if any remain in the stream
        /// <remarks>If a previous block has completed, its CRC is checked and merged into the stream CRC.
        /// If the previous block was the final block in the stream, the stream CRC is validated</remarks>
        /// <return>true if a block was successfully initialised, or false if the end of file marker was encountered</return>
        /// <exception>If either the block or stream CRC check failed, if the following data is
        /// not a valid block-header or end-of-file marker, or if the following block could not be decoded</exception>
        private bool InitialiseNextBlock()  {

			/* If we're already at the end of the stream, do nothing */
			if (this.streamComplete)
				return false;

			/* If a block is complete, check the block CRC and integrate it into the stream CRC */
			if (this.blockDecompressor != null) {
				uint blockCRC = this.blockDecompressor.CheckCrc();
				this.streamCRC = ((this.streamCRC << 1) | (this.streamCRC >> 31)) ^ blockCRC;
			}

			/* Read block-header or end-of-stream marker */
			 uint marker1 = this.bitInputStream.ReadBits(24);
			 uint marker2 = this.bitInputStream.ReadBits(24);

			if (marker1 == BZip2BlockCompressor.BLOCK_HEADER_MARKER_1 && marker2 == BZip2BlockCompressor.BLOCK_HEADER_MARKER_2) {
				// Initialise a new block
				try {
					this.blockDecompressor = new BZip2BlockDecompressor(this.bitInputStream, this.streamBlockSize);
				} catch (IOException) {
					// If the block could not be decoded, stop trying to read more data
					this.streamComplete = true;
					throw;
				}
				return true;
			}
		    if (marker1 == BZip2OutputStream.STREAM_END_MARKER_1 && marker2 == BZip2OutputStream.STREAM_END_MARKER_2) {
		        // Read and verify the end-of-stream CRC
		        this.streamComplete = true;
                uint storedCombinedCRC = this.bitInputStream.ReadInteger(); ///.ReadBits(32);

                if (storedCombinedCRC != this.streamCRC)
		            throw new Exception ("BZip2 stream CRC error");

		        return false;
		    }

		    /* If what was read is not a valid block-header or end-of-stream marker, the stream is broken */
			this.streamComplete = true;
			throw new Exception ("BZip2 stream format error");
		}
        #endregion
    }
}


text:
using DragonSpark.Compose;
using DragonSpark.Model.Operations;
using DragonSpark.Model.Results;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Threading;
using System.Threading.Tasks;

namespace DragonSpark.Application.Runtime.Operations;

public sealed class TokenFilterAttribute : ActionFilterAttribute
{
	readonly IMutable<CancellationToken> _store;

	public TokenFilterAttribute() : this(AmbientToken.Default) {}

	public TokenFilterAttribute(IMutable<CancellationToken> store) => _store = store;

	public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
	{
		using (_store.Assigned(context.HttpContext.RequestAborted))
		{
			await base.OnActionExecutionAsync(context, next).ConfigureAwait(false);
		}
	}
}


text:
using System;

namespace YandexLinguistics.NET.Speller
{
	[Flags]
	public enum SpellerOptions
	{
		IgnoreUppercase = 1,
		IgnoreDigits = 2,
		IgnoreUrls = 4,
		FindRepeatWords = 8,
		IgnoreLatin = 16,
		NoSuggest = 32,
		FlagLatin = 128,
		ByWords = 256,
		IgnoreCapitalization = 512
	}
}


text:
console.time("Array initialize");

var data=[100000];
for(var i=0;i<100000;i++) {
    data[i]=new Object();
}

console.timeEnd("Array initialize");


text:
angular.module('ionic.ion.showWhen', ['ionic'])

.directive('showWhen', ['$window', function($window) {
 return {
    restrict: 'A',
    link: function($scope, $element, $attr) {

	  function checkExpose() {
		var mq = $attr.showWhen == 'large' ? '(min-width:768px)' : $attr.showWhen;
		if($window.matchMedia(mq).matches){
			$element.removeClass('ng-hide');
		} else {
			$element.addClass('ng-hide');
		}
	  }

	  function onResize() {
		debouncedCheck();
	  }

	  var debouncedCheck = ionic.debounce(function() {
		$scope.$apply(function(){
		  checkExpose();
		});
	  }, 300, false);

	  checkExpose();

	  ionic.on('resize', onResize, $window);

	  $scope.$on('$destroy', function(){
		ionic.off('resize', onResize, $window);
	  });

	}
  };
}])

.directive('hideWhen', ['$window', function($window) {
 return {
    restrict: 'A',
    link: function($scope, $element, $attr) {

	  function checkExpose() {
		var mq = $attr.hideWhen == 'large' ? '(min-width:768px)' : $attr.hideWhen;
		if($window.matchMedia(mq).matches){
			$element.addClass('ng-hide');
		} else {
			$element.removeClass('ng-hide');
		}
	  }

	  function onResize() {
		debouncedCheck();
	  }

	  var debouncedCheck = ionic.debounce(function() {
		$scope.$apply(function(){
		  checkExpose();
		});
	  }, 300, false);

	  checkExpose();

	  ionic.on('resize', onResize, $window);

	  $scope.$on('$destroy', function(){
		ionic.off('resize', onResize, $window);
	  });

	}
  };
}])

.directive('showWhenState', ['$window','$state','$rootScope', function($window,$state,$rootScope) {
 return {
    restrict: 'A',
    link: function($scope, $element, $attr) {

	function checkExpose(){
		var state = $state.current.name;
		var statesToMatch = $attr.showWhenState.split(" || ");

		if(statesToMatch.indexOf(state) > -1){
			$element.removeClass('ng-hide');
		} else {
			$element.addClass('ng-hide');
		}
	}

	$rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
		checkExpose();
	})

	checkExpose();
	}
  };
}]);


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>React Practice</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="/css/style.css">


text:
package com.springml.salesforce.wave.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import java.io.Serializable;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Field implements Serializable {

    private static final long serialVersionUID = 1739841109381849160L;

    private String name;
    private int length;
    private String label;
    private boolean filterable;
    private boolean nameField;
    private boolean nillable;
    private boolean unique;
    private boolean updateable;
    private boolean custom;
    private boolean createable;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public boolean isFilterable() {
        return filterable;
    }

    public void setFilterable(boolean filterable) {
        this.filterable = filterable;
    }

    public boolean isNameField() {
        return nameField;
    }

    public void setNameField(boolean nameField) {
        this.nameField = nameField;
    }

    public boolean isNillable() {
        return nillable;
    }

    public void setNillable(boolean nillable) {
        this.nillable = nillable;
    }

    public boolean isUnique() {
        return unique;
    }

    public void setUnique(boolean unique) {
        this.unique = unique;
    }

    public boolean isUpdateable() {
        return updateable;
    }

    public void setUpdateable(boolean updateable) {
        this.updateable = updateable;
    }

    public boolean isCustom() {
        return custom;
    }

    public void setCustom(boolean custom) {
        this.custom = custom;
    }

    public boolean isCreateable() {
        return createable;
    }

    public void setCreateable(boolean createable) {
        this.createable = createable;
    }
}


text:
using System;
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Metadata.Models;
using OrchardCore.DisplayManagement.Handlers;

namespace OrchardCore.ContentTypes.Editors
{
    public abstract class ContentTypePartDefinitionDisplayDriver : DisplayDriver<ContentTypePartDefinition, BuildDisplayContext, BuildEditorContext, UpdateTypePartEditorContext>, IContentTypePartDefinitionDisplayDriver
    {
        protected override void BuildPrefix(ContentTypePartDefinition model, string htmlFielPrefix)
        {
            Prefix = $"{model.ContentTypeDefinition.Name}.{model.PartDefinition.Name}";

            if (!String.IsNullOrEmpty(htmlFielPrefix))
            {
                Prefix = htmlFielPrefix + "." + Prefix;
            }

            // Prefix any driver with a unique name
            Prefix += "." + GetType().Name;
        }

        public override bool CanHandleModel(ContentTypePartDefinition model)
        {
            return true;
        }
    }

    /// <summary>
    /// A concrete implementation of <see cref="ContentTypePartDefinitionDisplayDriver{TPart}"/> provides a driver for part definitions
    /// of the type <c>TPart</c>.
    /// </summary>
    public abstract class ContentTypePartDefinitionDisplayDriver<TPart> : ContentTypePartDefinitionDisplayDriver where TPart : ContentPart
    {
        public override bool CanHandleModel(ContentTypePartDefinition model)
        {
            return string.Equals(typeof(TPart).Name, model.PartDefinition.Name);
        }
    }
}


text:
<?php

namespace Drupal\Tests\hal\Functional\tour;

use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
use Drupal\Tests\tour\Functional\Rest\TourResourceTestBase;

/**
 * @group hal
 * @group legacy
 */
class TourHalJsonCookieTest extends TourResourceTestBase {

  use CookieResourceTestTrait;

  /**
   * {@inheritdoc}
   */
  protected static $modules = ['hal'];

  /**
   * {@inheritdoc}
   */
  protected $defaultTheme = 'stark';

  /**
   * {@inheritdoc}
   */
  protected static $format = 'hal_json';

  /**
   * {@inheritdoc}
   */
  protected static $mimeType = 'application/hal+json';

  /**
   * {@inheritdoc}
   */
  protected static $auth = 'cookie';

}


text:
fails:Struct.new keyword_init: true option new class instantiation raises ArgumentError when passed not declared keyword argument
fails:Struct.new raises ArgumentError when there is a duplicate member
fails:Struct.new keyword_init: true option raises when there is a duplicate member


text:
from heapq import *

class MedianFinder(object):

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.small = [] # max heap
        self.large = [] # min heap

    def addNum(self, num):
        """
        :type num: int
        :rtype: void
        """
        heappush(self.small, -heappushpop(self.large, num))
        if len(self.large) < len(self.small):
            heappush(self.large, -heappop(self.small))

    def findMedian(self):
        """
        :rtype: float
        """
        # even: root of large; odd: mean of two roots
        if len(self.large) == len(self.small):
            return (-self.small[0] + self.large[0] ) / 2.0
        else:
            return float(self.large[0])

# Your MedianFinder object will be instantiated and called as such:
# obj = MedianFinder()
# obj.addNum(num)
# param_2 = obj.findMedian()


text:
//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// connection_handle.cpp
//
// Identification: src/network/connection_handle.cpp
//
// Copyright (c) 2015-2017, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <unistd.h>
#include <cstring>

#include "network/connection_dispatcher_task.h"
#include "network/connection_handle.h"
#include "network/peloton_server.h"
#include "network/postgres_protocol_handler.h"
#include "network/protocol_handler_factory.h"

#include "settings/settings_manager.h"

namespace peloton {
namespace network {

/*
 *  Here we are abusing macro expansion to allow for human readable definition
 *  of the finite state machine's transition table. We put these macros in an
 *  anonymous namespace to avoid them confusing people elsewhere.
 *
 *  The macros merely compose a large function. Unless you know what you are
 *  doing, do not modify their definitions.
 *
 *  To use these macros, follow the examples given. Or, here is a syntax chart:
 *
 *  x list ::= x \n (x list) (each item of x separated by new lines)
 *  graph ::= DEF_TRANSITION_GRAPH
 *              state list
 *            END_DEF
 *
 *  state ::= DEFINE_STATE(ConnState)
 *             transition list
 *            END_DEF
 *
 *  transition ::=
 *  ON (Transition) SET_STATE_TO (ConnState) AND_INVOKE (ConnectionHandle
 * method)
 *
 *  Note that all the symbols used must be defined in ConnState, Transition and
 *  ClientSocketWrapper, respectively.
 */
namespace {
// Underneath the hood these macro is defining the static method
// ConnectionHandle::StateMachine::Delta.
// Together they compose a nested switch statement. Running the function on any
// undefined state or transition on said state will throw a runtime error.
#define DEF_TRANSITION_GRAPH                                          \
  ConnectionHandle::StateMachine::transition_result                   \
  ConnectionHandle::StateMachine::Delta_(ConnState c, Transition t) { \
    switch (c) {
#define DEFINE_STATE(s) \
  case ConnState::s: {  \
    switch (t) {
#define END_DEF                                       \
  default:                                            \
    throw std::runtime_error("undefined transition"); \
    }                                                 \
    }
#define ON(t)         \
  case Transition::t: \
    return
#define SET_STATE_TO(s) \
  {                     \
    ConnState::s,
#define AND_INVOKE(m)                         \
  ([](ConnectionHandle &w) { return w.m(); }) \
  }                                           \
  ;
#define AND_WAIT                                        \
  ([](ConnectionHandle &) { return Transition::NONE; }) \
  }                                                     \
  ;
}

// For readability sake, do not run clang-format on this macro block and follow
// the style presented when editing.
DEF_TRANSITION_GRAPH
  DEFINE_STATE(READ)
    ON(WAKEUP) SET_STATE_TO(READ) AND_INVOKE(FillReadBuffer)
    ON(PROCEED) SET_STATE_TO(PROCESS) AND_INVOKE(Process)
    ON(NEED_DATA) SET_STATE_TO(READ) AND_WAIT
    ON(FINISH) SET_STATE_TO(CLOSING) AND_INVOKE(CloseSocket)
  END_DEF

  DEFINE_STATE(PROCESS)
    ON(PROCEED) SET_STATE_TO(WRITE) AND_INVOKE(ProcessWrite)
    ON(NEED_DATA) SET_STATE_TO(READ) AND_INVOKE(FillReadBuffer)
    ON(GET_RESULT) SET_STATE_TO(GET_RESULT) AND_WAIT
    ON(FINISH) SET_STATE_TO(CLOSING) AND_INVOKE(CloseSocket)
  END_DEF

  DEFINE_STATE(WRITE)
    ON(WAKEUP) SET_STATE_TO(WRITE) AND_INVOKE(ProcessWrite)
    ON(NEED_DATA) SET_STATE_TO(PROCESS) AND_INVOKE(Process)
    ON(PROCEED) SET_STATE_TO(PROCESS) AND_INVOKE(Process)
  END_DEF

  DEFINE_STATE(GET_RESULT)
    ON(WAKEUP) SET_STATE_TO(GET_RESULT) AND_INVOKE(GetResult)
    ON(PROCEED) SET_STATE_TO(WRITE) AND_INVOKE(ProcessWrite)
  END_DEF
END_DEF

void ConnectionHandle::StateMachine::Accept(Transition action,
                                            ConnectionHandle &connection) {
  Transition next = action;
  while (next != Transition::NONE) {
    transition_result result = Delta_(current_state_, next);
    current_state_ = result.first;
    try {
      next = result.second(connection);
    } catch (NetworkProcessException &e) {
      LOG_ERROR("%s\n", e.what());
      connection.CloseSocket();
      return;
    }
  }
}

ConnectionHandle::ConnectionHandle(int sock_fd, ConnectionHandlerTask *handler,
                                   std::shared_ptr<Buffer> rbuf,
                                   std::shared_ptr<Buffer> wbuf, bool ssl_able)
    : sock_fd_(sock_fd),
      handler_(handler),
      protocol_handler_(nullptr),
      rbuf_(std::move(rbuf)),
      wbuf_(std::move(wbuf)),
      ssl_able_(ssl_able) {
  SetNonBlocking(sock_fd_);
  SetTCPNoDelay(sock_fd_);

  network_event = handler->RegisterEvent(
      sock_fd_, EV_READ | EV_PERSIST,
      METHOD_AS_CALLBACK(ConnectionHandle, HandleEvent), this);
  workpool_event = handler->RegisterManualEvent(
      METHOD_AS_CALLBACK(ConnectionHandle, HandleEvent), this);

  // TODO(Tianyu): should put the initialization else where.. check correctness
  // first.
  traffic_cop_.SetTaskCallback(
      [](void *arg) {
        struct event *event = static_cast<struct event *>(arg);
        event_active(event, EV_WRITE, 0);
      },
      workpool_event);
}

void ConnectionHandle::UpdateEventFlags(short flags) {
  // TODO(tianyu): The original network code seems to do this as an
  // optimization. I am leaving this out until we get numbers
  // handler->UpdateEvent(network_event, sock_fd_, flags,
  // METHOD_AS_CALLBACK(ConnectionHandle, HandleEvent), this);

  if (flags == curr_event_flag_) return;

  handler_->UnregisterEvent(network_event);
  network_event = handler_->RegisterEvent(
      sock_fd_, flags, METHOD_AS_CALLBACK(ConnectionHandle, HandleEvent), this);

  curr_event_flag_ = flags;
}

WriteState ConnectionHandle::WritePackets() {
  // iterate through all the packets
  for (; next_response_ < protocol_handler_->responses.size();
       next_response_++) {
    auto pkt = protocol_handler_->responses[next_response_].get();
    LOG_TRACE("To send packet with type: %c, len %lu",
              static_cast<char>(pkt->msg_type), pkt->len);
    // write is not ready during write. transit to WRITE
    auto result = BufferWriteBytesHeader(pkt);
    if (result == WriteState::NOT_READY) return result;
    result = BufferWriteBytesContent(pkt);
    if (result == WriteState::NOT_READY) return result;
  }

  // Done writing all packets. clear packets
  protocol_handler_->responses.clear();
  next_response_ = 0;

  if (protocol_handler_->GetFlushFlag()) {
    return FlushWriteBuffer();
  }

  // we have flushed, disable force flush now
  protocol_handler_->SetFlushFlag(false);

  return WriteState::COMPLETE;
}

Transition ConnectionHandle::FillReadBuffer() {
  // This could be changed by SSL_ERROR_WANT_WRITE
  // When we reenter, we need to recover.
  UpdateEventFlags(EV_READ | EV_PERSIST);

  Transition result = Transition::NEED_DATA;
  ssize_t bytes_read = 0;
  bool done = false;

  // reset buffer if all the contents have been read
  if (rbuf_->buf_ptr == rbuf_->buf_size) rbuf_->Reset();

  // buf_ptr shouldn't overflow
  PL_ASSERT(rbuf_->buf_ptr <= rbuf_->buf_size);

  /* Do we have leftover data and are we at the end of the buffer?
   * Move the data to the head of the buffer and clear out all the old data
   * Note: The assumption here is that all the packets/headers till
   *  rbuf_.buf_ptr have been fully processed
   */
  if (rbuf_->buf_ptr < rbuf_->buf_size &&
      rbuf_->buf_size == rbuf_->GetMaxSize()) {
    auto unprocessed_len = rbuf_->buf_size - rbuf_->buf_ptr;
    // Move this data to the head of rbuf_1
    std::memmove(rbuf_->GetPtr(0), rbuf_->GetPtr(rbuf_->buf_ptr),
                 unprocessed_len);
    // update pointers
    rbuf_->buf_ptr = 0;
    rbuf_->buf_size = unprocessed_len;
  }

  // return explicitly
  while (done == false) {
    if (rbuf_->buf_size == rbuf_->GetMaxSize()) {
      // we have filled the whole buffer, exit loop
      done = true;
    } else {
      // try to fill the available space in the buffer
      // if the connection is a SSL connection, we use SSL_read, otherwise
      // we use general read function
      if (conn_SSL_context != nullptr) {
        ERR_clear_error();
        bytes_read = SSL_read(conn_SSL_context, rbuf_->GetPtr(rbuf_->buf_size),
                              rbuf_->GetMaxSize() - rbuf_->buf_size);
        LOG_TRACE("SSL read successfully");
        int err = SSL_get_error(conn_SSL_context, bytes_read);
        unsigned long ecode =
            (err != SSL_ERROR_NONE || bytes_read < 0) ? ERR_get_error() : 0;
        switch (err) {
          case SSL_ERROR_NONE: {
            // If successfully received, update buffer ptr and read status
            // keep reading till no data is available or the buffer becomes full
            rbuf_->buf_size += bytes_read;
            result = Transition::PROCEED;
            break;
          }

          case SSL_ERROR_ZERO_RETURN: {
            done = true;
            result = Transition::FINISH;
            break;
          }
          // The SSL packet is partially loaded to the SSL buffer only,
          // More data is required in order to decode the whole packet.
          case SSL_ERROR_WANT_READ: {
            LOG_TRACE("SSL packet partially loaded to SSL buffer");
            done = true;
            break;
          }
          // It happens when we're trying to rehandshake and we block on a write
          // during the handshake. We need to wait on the socket to be writable
          case SSL_ERROR_WANT_WRITE: {
            LOG_TRACE("Rehandshake during write, block until writable");
            UpdateEventFlags(EV_WRITE | EV_PERSIST);
            return Transition::NEED_DATA;
          }
          case SSL_ERROR_SYSCALL: {
            // if interrupted, try again
            if (errno == EINTR) {
              LOG_INFO("Error SSL Reading: EINTR");
              break;
            }
          }
          default: {
            throw NetworkProcessException(
                "SSL read error: %d, error code: " + std::to_string(err) +
                " error code:" + std::to_string(ecode));
          }
        }
      } else {
        bytes_read = read(sock_fd_, rbuf_->GetPtr(rbuf_->buf_size),
                          rbuf_->GetMaxSize() - rbuf_->buf_size);
        LOG_TRACE("When filling read buffer, read %ld bytes", bytes_read);

        if (bytes_read > 0) {
          // read succeeded, update buffer size
          rbuf_->buf_size += bytes_read;
          result = Transition::PROCEED;
        } else if (bytes_read == 0) {
          return Transition::FINISH;
        } else if (bytes_read < 0) {
          // Nothing in the network pipe now
          if (errno == EAGAIN || errno == EWOULDBLOCK) {
            // return whatever results we have
            done = true;
          } else if (errno == EINTR) {
            // interrupts are ok, try again
            continue;
          } else {
            // some other error occured
            LOG_ERROR("Error writing: %s", strerror(errno));
            throw NetworkProcessException("Error when filling read buffer " +
                                          std::to_string(errno));
          }
        }
      }
    }
  }
  return result;
}

WriteState ConnectionHandle::FlushWriteBuffer() {
  // This could be changed by unfinished write
  // When we reenter, we need to recover it to read
  UpdateEventFlags(EV_READ | EV_PERSIST);

  ssize_t written_bytes = 0;
  // while we still have outstanding bytes to write
  if (conn_SSL_context != nullptr) {
    while (wbuf_->buf_size > 0) {
      LOG_TRACE("SSL_write flush");
      ERR_clear_error();
      written_bytes = SSL_write(
          conn_SSL_context, &wbuf_->buf[wbuf_->buf_flush_ptr], wbuf_->buf_size);
      int err = SSL_get_error(conn_SSL_context, written_bytes);
      unsigned long ecode =
          (err != SSL_ERROR_NONE || written_bytes < 0) ? ERR_get_error() : 0;
      switch (err) {
        case SSL_ERROR_NONE: {
          wbuf_->buf_flush_ptr += written_bytes;
          wbuf_->buf_size -= written_bytes;
          break;
        }
        case SSL_ERROR_WANT_WRITE: {
          // The kernel will flush the network buffer automatically. What we
          // need to do is to call SSL_write() again when the buffer becomes
          // availble to write again(notified by Libevent).
          UpdateEventFlags(EV_WRITE | EV_PERSIST);
          LOG_TRACE("Flush write buffer, want write, not ready");
          return WriteState::NOT_READY;
        }
        case SSL_ERROR_WANT_READ: {
          // It happens when doing rehandshake with client.
          LOG_TRACE("Flush write buffer, want read, not ready");
          return WriteState::NOT_READY;
        }
        case SSL_ERROR_SYSCALL: {
          // If interrupted, try again.
          if (errno == EINTR) {
            LOG_TRACE("Flush write buffer, eintr");
            break;
          }
        }
        default: {
          LOG_ERROR("SSL write error: %d, error code: %lu", err, ecode);
          throw NetworkProcessException("SSL write error");
        }
      }
    }
  } else {
    while (wbuf_->buf_size > 0) {
      written_bytes = 0;
      while (written_bytes <= 0) {
        LOG_TRACE("Normal write flush");
        written_bytes =
            write(sock_fd_, &wbuf_->buf[wbuf_->buf_flush_ptr], wbuf_->buf_size);
        // Write failed
        if (written_bytes < 0) {
          if (errno == EINTR) {
            // interrupts are ok, try again
            written_bytes = 0;
            continue;
            // Write would have blocked if the socket was
            // in blocking mode. Wait till it's readable
          } else if (errno == EAGAIN || errno == EWOULDBLOCK) {
            // Listen for socket being enabled for write
            UpdateEventFlags(EV_WRITE | EV_PERSIST);
            // We should go to CONN_WRITE state
            LOG_TRACE("WRITE NOT READY");
            return WriteState::NOT_READY;
          } else {
            // fatal errors
            LOG_ERROR("Error writing: %s", strerror(errno));
            throw NetworkProcessException("Fatal error during write");
          }
        }

        // weird edge case?
        if (written_bytes == 0 && wbuf_->buf_size != 0) {
          LOG_TRACE("Not all data is written");
          continue;
        }
      }

      // update book keeping
      wbuf_->buf_flush_ptr += written_bytes;
      wbuf_->buf_size -= written_bytes;
    }
  }
  // buffer is empty
  wbuf_->Reset();

  // we are ok
  return WriteState::COMPLETE;
}

std::string ConnectionHandle::WriteBufferToString() {
#ifdef LOG_TRACE_ENABLED
  LOG_TRACE("Write Buffer:");

  for (size_t i = 0; i < wbuf_->buf_size; ++i) {
    LOG_TRACE("%u", wbuf_->buf[i]);
  }
#endif

  return std::string(wbuf_->buf.begin(), wbuf_->buf.end());
}

ProcessResult ConnectionHandle::ProcessInitial() {
  // TODO(Tianyi): this is a direct copy from protocol handler
  // and we could get rid of it later when we have the second
  // protocol handler;

  if (initial_packet_.header_parsed == false) {
    // parse out the header first
    if (ReadStartupPacketHeader(*rbuf_, initial_packet_) == false) {
      // need more data
      return ProcessResult::MORE_DATA_REQUIRED;
    }
  }
  PL_ASSERT(initial_packet_.header_parsed == true);

  if (initial_packet_.is_initialized == false) {
    // packet needs to be initialized with rest of the contents
    // TODO(Tianyi): If other protocols are added, this need to be changed
    if (PostgresProtocolHandler::ReadPacket(*rbuf_, initial_packet_) == false) {
      // need more data
      return ProcessResult::MORE_DATA_REQUIRED;
    }
  }

  if (protocol_handler_ == nullptr) {
    protocol_handler_ = ProtocolHandlerFactory::CreateProtocolHandler(
        ProtocolHandlerType::Postgres, &traffic_cop_);
  }
  // We need to handle startup packet first
  // TODO(Tianyi): If other protocols are added, this need to be changed
  bool result = protocol_handler_->ProcessInitialPackets(
      &initial_packet_, client_, ssl_able_, ssl_handshake_,
      finish_startup_packet_);
  // Clean up the initial_packet after finishing processing.
  initial_packet_.Reset();
  if (result) {
    return ProcessResult::COMPLETE;
  } else {
    return ProcessResult::TERMINATE;
  }
}

// TODO(Tianyi): This function is now dedicated for postgres packet
bool ConnectionHandle::ReadStartupPacketHeader(Buffer &rbuf,
                                               InputPacket &rpkt) {
  size_t initial_read_size = sizeof(int32_t);

  if (!rbuf.IsReadDataAvailable(initial_read_size)) {
    return false;
  }

  // extract packet contents size
  // content lengths should exclude the length
  rpkt.len = rbuf.GetUInt32BigEndian() - sizeof(uint32_t);

  // do we need to use the extended buffer for this packet?
  rpkt.is_extended = (rpkt.len > rbuf.GetMaxSize());

  if (rpkt.is_extended) {
    LOG_DEBUG("Using extended buffer for pkt size:%ld", rpkt.len);
    // reserve space for the extended buffer
    rpkt.ReserveExtendedBuffer();
  }

  // we have processed the data, move buffer pointer
  rbuf.buf_ptr += initial_read_size;
  rpkt.header_parsed = true;
  return true;
}

// Writes a packet's header (type, size) into the write buffer.
// Return false when the socket is not ready for write
WriteState ConnectionHandle::BufferWriteBytesHeader(OutputPacket *pkt) {
  // If we should not write
  if (pkt->skip_header_write) {
    return WriteState::COMPLETE;
  }

  size_t len = pkt->len;
  unsigned char type = static_cast<unsigned char>(pkt->msg_type);
  int len_nb;  // length in network byte order

  // check if we have enough space in the buffer
  if (wbuf_->GetMaxSize() - wbuf_->buf_ptr < 1 + sizeof(int32_t)) {
    // buffer needs to be flushed before adding header
    auto result = FlushWriteBuffer();
    if (result == WriteState::NOT_READY) {
      // Socket is not ready for write
      return result;
    }
  }

  // assuming wbuf is now large enough to fit type and size fields in one go
  if (type != 0) {
    // type shouldn't be ignored
    wbuf_->buf[wbuf_->buf_ptr++] = type;
  }

  // make len include its field size as well
  len_nb = htonl(len + sizeof(int32_t));

  if (finish_startup_packet_) {
    // append the bytes of this integer in network-byte order
    std::copy(reinterpret_cast<uchar *>(&len_nb),
              reinterpret_cast<uchar *>(&len_nb) + 4,
              std::begin(wbuf_->buf) + wbuf_->buf_ptr);
    // move the write buffer pointer and update size of the socket buffer
    wbuf_->buf_ptr += sizeof(int32_t);
  }

  wbuf_->buf_size = wbuf_->buf_ptr;

  // Header is written to socket buf. No need to write it in the future
  pkt->skip_header_write = true;
  return WriteState::COMPLETE;
}

// Writes a packet's content into the write buffer
// Return false when the socket is not ready for write
WriteState ConnectionHandle::BufferWriteBytesContent(OutputPacket *pkt) {
  // the packet content to write
  ByteBuf &pkt_buf = pkt->buf;
  // the length of remaining content to write
  size_t len = pkt->len;
  // window is the size of remaining space in socket's wbuf
  size_t window = 0;

  // fill the contents
  while (len != 0) {
    // calculate the remaining space in wbuf
    window = wbuf_->GetMaxSize() - wbuf_->buf_ptr;
    if (len <= window) {
      // contents fit in the window, range copy "len" bytes
      std::copy(std::begin(pkt_buf) + pkt->write_ptr,
                std::begin(pkt_buf) + pkt->write_ptr + len,
                std::begin(wbuf_->buf) + wbuf_->buf_ptr);

      // Move the cursor and update size of socket buffer
      wbuf_->buf_ptr += len;
      wbuf_->buf_size = wbuf_->buf_ptr;
      LOG_TRACE("Content fit in window. Write content successful");
      return WriteState::COMPLETE;
    } else {
      // contents longer than socket buffer size, fill up the socket buffer
      // with "window" bytes

      std::copy(std::begin(pkt_buf) + pkt->write_ptr,
                std::begin(pkt_buf) + pkt->write_ptr + window,
                std::begin(wbuf_->buf) + wbuf_->buf_ptr);

      // move the packet's cursor
      pkt->write_ptr += window;
      len -= window;
      // Now the wbuf is full
      wbuf_->buf_size = wbuf_->GetMaxSize();

      LOG_TRACE("Content doesn't fit in window. Try flushing");
      auto result = FlushWriteBuffer();
      // flush before write the remaining content
      if (result == WriteState::NOT_READY) {
        // need to retry or close connection
        return result;
      }
    }
  }
  return WriteState::COMPLETE;
}

Transition ConnectionHandle::CloseSocket() {
  LOG_DEBUG("Attempt to close the connection %d", sock_fd_);
  // Remove listening event
  handler_->UnregisterEvent(network_event);
  handler_->UnregisterEvent(workpool_event);

  if (conn_SSL_context != nullptr) {
    int shutdown_ret = 0;
    while (true) {
      ERR_clear_error();
      shutdown_ret = SSL_shutdown(conn_SSL_context);
      int err = SSL_get_error(conn_SSL_context, shutdown_ret);
      if (shutdown_ret == 1) {
        break;
      } else if (shutdown_ret == 0) {
        LOG_TRACE("SSL shutdown is not finished yet");
        continue;
      } else {
        if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) {
          continue;
        } else {
          LOG_ERROR("Error shutting down ssl session, err: %d", err);
          break;
        }
      }
    }
  }
  for (;;) {
    int status = close(sock_fd_);
    if (status < 0) {
      // failed close
      if (errno == EINTR) {
        // interrupted, try closing again
        continue;
      }
    }
    LOG_DEBUG("Already Closed the connection %d", sock_fd_);
    return Transition::NONE;
  }
}

Transition ConnectionHandle::Wait() {
  // TODO(tianyu): Maybe we don't need this state? Also, this name is terrible
  UpdateEventFlags(EV_READ | EV_PERSIST);
  return Transition::PROCEED;
}

Transition ConnectionHandle::Process() {
  // TODO(tianyu): further simplify this logic
  if (!finish_startup_packet_) {
    // Process initial
    if (ssl_handshake_) {
      // start SSL handshake
      conn_SSL_context = SSL_new(PelotonServer::ssl_context);
      SSL_set_session_id_context(conn_SSL_context, nullptr, 0);
      if (SSL_set_fd(conn_SSL_context, sock_fd_) == 0) {
        LOG_ERROR("Failed to set SSL fd");
        PL_ASSERT(false);
      }

      bool handshake_fail = false;
      // TODO(Yuchen): post-connection verification?
      while (!handshake_fail) {
        // clear current thread's error queue before any OpenSSL call
        ERR_clear_error();
        int ssl_accept_ret = SSL_accept(conn_SSL_context);
        if (ssl_accept_ret > 0) {
          break;
        }
        int err = SSL_get_error(conn_SSL_context, ssl_accept_ret);
        int ecode = ERR_get_error();
        char error_string[120];
        ERR_error_string(ecode, error_string);
        switch (err) {
          case SSL_ERROR_SSL: {
            if (ecode < 0) {
              LOG_ERROR("Could not accept SSL connection");
            } else {
              LOG_ERROR(
                  "Could not accept SSL connection: EOF detected, "
                  "ssl_error_ssl, %s",
                  error_string);
            }
            handshake_fail = true;
            break;
          }
          case SSL_ERROR_ZERO_RETURN: {
            LOG_ERROR(
                "Could not accept SSL connection: EOF detected, "
                "ssl_error_zero_return, %s",
                error_string);
            handshake_fail = true;
            break;
          }
          case SSL_ERROR_SYSCALL: {
            if (ecode < 0) {
              LOG_ERROR("Could not accept SSL connection, %s", error_string);
            } else {
              LOG_ERROR(
                  "Could not accept SSL connection: EOF detected, "
                  "ssl_sys_call, %s",
                  error_string);
            }
            handshake_fail = true;
            break;
          }
          case SSL_ERROR_WANT_READ:
          case SSL_ERROR_WANT_WRITE:
            break;
          default: {
            LOG_ERROR("Unrecognized SSL error code: %d", err);
            handshake_fail = true;
          }
        }
      }
      if (!handshake_fail) {
        // handshake succeeds, reset ssl_sent_
        ssl_handshake_ = false;
        finish_startup_packet_ = false;
        return Transition::NEED_DATA;
      } else {
        throw NetworkProcessException("SSL handshake failure");
      }
    }

    switch (ProcessInitial()) {
      case ProcessResult::COMPLETE:
        return Transition::PROCEED;
      case ProcessResult::MORE_DATA_REQUIRED:
        return Transition::NEED_DATA;
      default:  // PROCESSING is impossible to happens in initial packets
        throw NetworkProcessException("Should not reach");
    }
  } else {
    ProcessResult status =
        protocol_handler_->Process(*rbuf_, (size_t)handler_->Id());

    switch (status) {
      case ProcessResult::MORE_DATA_REQUIRED:
        return Transition::NEED_DATA;
      case ProcessResult::COMPLETE:
        return Transition::PROCEED;
      case ProcessResult::PROCESSING:
        EventUtil::EventDel(network_event);
        LOG_TRACE("ProcessResult: queueing");
        return Transition::GET_RESULT;
      case ProcessResult::TERMINATE:
        return Transition::FINISH;
    }
  }
  throw NetworkProcessException("Unexpected process result");
}

Transition ConnectionHandle::ProcessWrite() {
  // TODO(tianyu): Should convert to use Transition in the top level method
  switch (WritePackets()) {
    case WriteState::COMPLETE:
      UpdateEventFlags(EV_READ | EV_PERSIST);
      if (!finish_startup_packet_) return Transition::NEED_DATA;
      return Transition::PROCEED;
    case WriteState::NOT_READY:
      return Transition::NONE;
  }
  throw NetworkProcessException("Unexpected write state");
}

Transition ConnectionHandle::GetResult() {
  // TODO(tianyu) We probably can collapse this state with some other state.
  if (event_add(network_event, nullptr) < 0) {
    LOG_ERROR("Failed to add event");
    PL_ASSERT(false);
  }
  protocol_handler_->GetResult();
  traffic_cop_.SetQueuing(false);
  return Transition::PROCEED;
}
}  // namespace network
}  // namespace peloton


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Basic Usage — Zend Framework 2 2.3.0dev documentation</title>

    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="top" title="Zend Framework 2 2.3.0dev documentation" href="../index.html" />
    <link rel="next" title="Advanced Usage of Zend\Json" href="zend.json.objects.html" />
    <link rel="prev" title="Introduction to Zend\Json" href="zend.json.introduction.html" />

Navigation

          index

          next |

          previous |

Zend Framework 2 2.3.0dev documentation »

Basic Usage¶

Usage of <tt class="docutils literal">Zend\Json</tt> involves using the two public static methods available: <tt class="docutils literal">Zend\Json\Json::encode()</tt> and
<tt class="docutils literal">Zend\Json\Json::decode()</tt>.

1
2
3
4
5

// Retrieve a value:
$phpNative = Zend\Json\Json::decode($encodedValue);

// Encode it to return to the client:
$json = Zend\Json\Json::encode($phpNative);

Pretty-printing JSON¶

Sometimes, it may be hard to explore JSON data generated by <tt class="docutils literal">Zend\Json\Json::encode()</tt>, since it has no spacing or
indentation. In order to make it easier, <tt class="docutils literal">Zend\Json\Json</tt> allows you to pretty-print JSON data in the human-readable
format with <tt class="docutils literal">Zend\Json\Json::prettyPrint()</tt>.

1
2
3
4
5

// Encode it to return to the client:
$json = Zend\Json\Json::encode($phpNative);
if ($debug) {
    echo Zend\Json\Json::prettyPrint($json, array("indent" => " "));
}

Second optional argument of <tt class="docutils literal">Zend\Json\Json::prettyPrint()</tt> is an option array. Option <tt class="docutils literal">indent</tt> allows to set
indentation string - by default it’s a single tab character.

Table Of Contents

Basic Usage

Pretty-printing JSON

Previous topic

Introduction to Zend\Json

Next topic

Advanced Usage of Zend\Json

This Page

        Show Source

Edit Source

            Note: You need to stay logged into your GitHub account to contribute to the documentation.

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          next |

          previous |

Zend Framework 2 2.3.0dev documentation »

        © Copyright 2013, Zend Technologies Ltd..
      Created using Sphinx 1.2b3.

Edit this document

        The source code of this file is hosted on GitHub. Everyone can
        update and fix errors in this document with few clicks -
        no downloads needed.

            Login with your GitHub account.

            Go to

                Basic Usage
             on GitHub.

            Edit file contents using GitHub's text editor in your web browser

            Fill in the Commit message text box at the end of the page telling why
            you did the changes. Press Propose file change button next to it when done.

            On Send a pull request page you don't need to fill in text anymore. Just
            press Send pull request button.

            Your changes are now queued for review under project's Pull requests tab on GitHub.


text:
import * as fs from 'fs-extra';
import * as path from 'path';

/**
 * Ensures that %USERPROFILE%/.windows-build-tools exists
 * and returns the path to it
 *
 * @returns {string} - Path to windows-build-tools working dir
 */
export function getWorkDirectory() {
  const homeDir = process.env.USERPROFILE || require('os').homedir();
  const workDir = path.join(homeDir, '.windows-build-tools');

  try {
    fs.ensureDirSync(workDir);
    return workDir;
  } catch (error) {
    console.log(error);
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.ctrip.framework</groupId>
    <artifactId>netty-example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <inceptionYear>2016</inceptionYear>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <licenses>
        <license>
            <name>The Apache Software License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
            <distribution>repo</distribution>
        </license>
    </licenses>
    <build>
        <finalName>netty-example</finalName>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>2.6</version>
                    <configuration>
                        <encoding>UTF-8</encoding>
                    </configuration>
                </plugin>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                    <configuration>
                        <source>1.7</source>
                        <target>1.7</target>
                    </configuration>
                </plugin>

                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>build-helper-maven-plugin</artifactId>
                    <version>1.7</version>
                    <executions>
                        <execution>
                            <id>add-source</id>
                            <phase>generate-sources</phase>
                            <goals>
                                <goal>add-source</goal>
                            </goals>
                            <configuration>
                                <sources>
                                    <source>${basedir}/src/code_gen/java</source>
                                </sources>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.ctrip.framework</groupId>
            <artifactId>cornerstone-netty</artifactId>
            <version>0.2.0-SNAPSHOT</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-handler</artifactId>
            <version>5.0.0.Alpha1</version>
        </dependency>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-codec-http</artifactId>
            <version>5.0.0.Alpha1</version>
        </dependency>
    </dependencies>
</project>