text:
"""
A reference implementation of a simulated annealing sampler.

:obj:`neal.sampler.SimulatedAnnealingSampler`
is a more performant implementation of simulated annealing you can use for
solving problems.
"""
import random
import math

from six import itervalues

from dimod.core.sampler import Sampler
from dimod.sampleset import SampleSet
from dimod.utilities import ising_energy
from dimod.vartypes import Vartype

__all__ = ['SimulatedAnnealingSampler']

class SimulatedAnnealingSampler(Sampler):
    """A simple simulated annealing sampler for testing and debugging code.

    Examples:
        This example solves a two-variable Ising model.

        >>> h = {'a': -0.5, 'b': 1.0}
        >>> J = {('a', 'b'): -1.5}
        >>> sampleset = dimod.SimulatedAnnealingSampler().sample_ising(h, J)

    """
    properties = None

    parameters = None
    """dict: Keyword arguments accepted by the sampling methods.

    Contents are exactly `{'beta_range': [], num_reads': [], 'num_sweeps': []}`
    """

    def __init__(self):
        self.parameters = {'num_reads': [],
                           'beta_range': [],
                           'num_sweeps': []}
        self.properties = {}

    def sample(self, bqm, beta_range=None, num_reads=10, num_sweeps=1000):
        """Sample from low-energy spin states using simulated annealing.

        Args:
            bqm (:obj:`.BinaryQuadraticModel`):
                Binary quadratic model to be sampled from.

            beta_range (tuple, optional): Beginning and end of the beta schedule
                (beta is the inverse temperature) as a 2-tuple. The schedule is applied
                linearly in beta. Default is chosen based on the total bias associated
                with each node.

            num_reads (int, optional, default=10):
                Number of reads. Each sample is the result of a single run of
                the simulated annealing algorithm.

            num_sweeps (int, optional, default=1000):
                Number of sweeps or steps.

        Returns:
            :obj:`.SampleSet`

        Note:
            This is a reference implementation, not optimized for speed
            and therefore not an appropriate sampler for benchmarking.

        """

        # input checking
        # h, J are handled by the @ising decorator
        # beta_range, sweeps are handled by ising_simulated_annealing
        if not isinstance(num_reads, int):
            raise TypeError("'samples' should be a positive integer")
        if num_reads < 1:
            raise ValueError("'samples' should be a positive integer")

        h, J, offset = bqm.to_ising()

        # run the simulated annealing algorithm
        samples = []
        energies = []
        for __ in range(num_reads):
            sample, energy = ising_simulated_annealing(h, J, beta_range, num_sweeps)
            samples.append(sample)
            energies.append(energy)

        response = SampleSet.from_samples(samples, Vartype.SPIN, energies)
        response.change_vartype(bqm.vartype, offset, inplace=True)
        return response

def ising_simulated_annealing(h, J, beta_range=None, num_sweeps=1000):
    """Tries to find the spins that minimize the given Ising problem.

    Args:
        h (dict): A dictionary of the linear biases in the Ising
            problem. Should be of the form {v: bias, ...} for each
            variable v in the Ising problem.
        J (dict): A dictionary of the quadratic biases in the Ising
            problem. Should be a dict of the form {(u, v): bias, ...}
            for each edge (u, v) in the Ising problem. If J[(u, v)] and
            J[(v, u)] exist then the biases are added.
        beta_range (tuple, optional): A 2-tuple defining the
            beginning and end of the beta schedule (beta is the
            inverse temperature). The schedule is applied linearly
            in beta. Default is chosen based on the total bias associated
            with each node.
        num_sweeps (int, optional): The number of sweeps or steps.
            Default is 1000.

    Returns:
        dict: A sample as a dictionary of spins.
        float: The energy of the returned sample.

    Raises:
        TypeError: If the values in `beta_range` are not numeric.
        TypeError: If `num_sweeps` is not an int.
        TypeError: If `beta_range` is not a tuple.
        ValueError: If the values in `beta_range` are not positive.
        ValueError: If `beta_range` is not a 2-tuple.
        ValueError: If `num_sweeps` is not positive.

    https://en.wikipedia.org/wiki/Simulated_annealing

    """

    if beta_range is None:
        beta_init = .1

        sigmas = {v: abs(h[v]) for v in h}
        for u, v in J:
            sigmas[u] += abs(J[(u, v)])
            sigmas[v] += abs(J[(u, v)])

        if sigmas:
            beta_final = 2. * max(itervalues(sigmas))
        else:
            beta_final = 0.0

    else:
        if not isinstance(beta_range, (tuple, list)):
            raise TypeError("'beta_range' should be a tuple of length 2")
        if any(not isinstance(b, (int, float)) for b in beta_range):
            raise TypeError("values in 'beta_range' should be numeric")
        if any(b <= 0 for b in beta_range):
            raise ValueError("beta values in 'beta_range' should be positive")
        if len(beta_range) != 2:
            raise ValueError("'beta_range' should be a tuple of length 2")
        beta_init, beta_final = beta_range
    if not isinstance(num_sweeps, int):
        raise TypeError("'sweeps' should be a positive int")
    if num_sweeps <= 0:
        raise ValueError("'sweeps' should be a positive int")

    # We want the schedule to be linear in beta (inverse temperature)
    betas = [beta_init + i * (beta_final - beta_init) / (num_sweeps - 1.)
             for i in range(num_sweeps)]

    # set up the adjacency matrix. We can rely on every node in J already being in h
    adj = {n: set() for n in h}
    for n0, n1 in J:
        adj[n0].add(n1)
        adj[n1].add(n0)

    # we will use a vertex coloring for the graph and update the nodes by color. A quick
    # greedy coloring will be sufficient.
    __, colors = greedy_coloring(adj)

    # let's make our initial guess (randomly)
    spins = {v: random.choice((-1, 1)) for v in h}

    # there are exactly as many betas as sweeps
    for beta in betas:

        # we want to know the gain in energy for flipping each of the spins.
        # We can calculate all of the linear terms simultaneously
        energy_diff_h = {v: -2 * spins[v] * h[v] for v in h}

        # for each color, do updates
        for color in colors:

            nodes = colors[color]

            # we now want to know the energy change for flipping the spins within
            # the color class
            energy_diff_J = {}
            for v0 in nodes:
                ediff = 0
                for v1 in adj[v0]:
                    if (v0, v1) in J:
                        ediff += spins[v0] * spins[v1] * J[(v0, v1)]
                    if (v1, v0) in J:
                        ediff += spins[v0] * spins[v1] * J[(v1, v0)]

                energy_diff_J[v0] = -2. * ediff

            # now decide whether to flip spins according to the
            # following scheme:
            #   p ~ Uniform(0, 1)
            #   log(p) < -beta * (energy_diff)
            for v in nodes:
                logp = math.log(random.uniform(0, 1))
                if logp < -1. * beta * (energy_diff_h[v] + energy_diff_J[v]):
                    # flip the variable in the spins
                    spins[v] *= -1

    return spins, ising_energy(spins, h, J)

def greedy_coloring(adj):
    """Determines a vertex coloring.

    Args:
        adj (dict): The edge structure of the graph to be colored.
            `adj` should be of the form {node: neighbors, ...} where
            neighbors is a set.

    Returns:
        dict: the coloring {node: color, ...}
        dict: the colors {color: [node, ...], ...}

    Note:
        This is a greedy heuristic: the resulting coloring is not
        necessarily minimal.

    """

    # now let's start coloring
    coloring = {}
    colors = {}
    possible_colors = {n: set(range(len(adj))) for n in adj}
    while possible_colors:

        # get the n with the fewest possible colors
        n = min(possible_colors, key=lambda n: len(possible_colors[n]))

        # assign that node the lowest color it can still have
        color = min(possible_colors[n])
        coloring[n] = color
        if color not in colors:
            colors[color] = {n}
        else:
            colors[color].add(n)

        # also remove color from the possible colors for n's neighbors
        for neighbor in adj[n]:
            if neighbor in possible_colors and color in possible_colors[neighbor]:
                possible_colors[neighbor].remove(color)

        # finally remove n from nodes
        del possible_colors[n]

    return coloring, colors


text:
package net.clc.bt;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

/**
 * A simple configuration screen that displays the user's current Bluetooth
 * information along with buttons for entering the Bluetooth settings menu and
 * for starting a demo app. This is work in progress and only the demo app
 * buttons are currently available.
 */

public class ConfigActivity extends Activity {

    private ConfigActivity self;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        self = this;
        setContentView(R.layout.config);

        Button startServer = (Button) findViewById(R.id.start_hockey_server);
        startServer.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                //Intent serverIntent = new Intent(self, Demo_Multiscreen.class);
                Intent serverIntent = new Intent(self, AirHockey.class);
                serverIntent.putExtra("TYPE", 0);
                startActivity(serverIntent);
            }
        });

        Button startClient = (Button) findViewById(R.id.start_hockey_client);
        startClient.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                //Intent clientIntent = new Intent(self, Demo_Multiscreen.class);
                Intent clientIntent = new Intent(self, AirHockey.class);
                clientIntent.putExtra("TYPE", 1);
                startActivity(clientIntent);
            }
        });

        Button startMultiScreenServer = (Button) findViewById(R.id.start_demo_server);
        startMultiScreenServer.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                //Intent serverIntent = new Intent(self, Demo_Multiscreen.class);
                Intent serverIntent = new Intent(self, Demo_Multiscreen.class);
                serverIntent.putExtra("TYPE", 0);
                startActivity(serverIntent);
            }
        });

        Button startMultiScreenClient = (Button) findViewById(R.id.start_demo_client);
        startMultiScreenClient.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                //Intent clientIntent = new Intent(self, Demo_Multiscreen.class);
                Intent clientIntent = new Intent(self, Demo_Multiscreen.class);
                clientIntent.putExtra("TYPE", 1);
                startActivity(clientIntent);
            }
        });

        Button startVideoServer = (Button) findViewById(R.id.start_video_server);
        startVideoServer.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Intent serverIntent = new Intent(self, MultiScreenVideo.class);
                serverIntent.putExtra("isMaster", true);
                startActivity(serverIntent);
            }
        });

        Button startVideoClient = (Button) findViewById(R.id.start_video_client);
        startVideoClient.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Intent clientIntent = new Intent(self, MultiScreenVideo.class);
                clientIntent.putExtra("isMaster", false);
                startActivity(clientIntent);
            }
        });

        Button gotoWeb = (Button) findViewById(R.id.goto_website);
        gotoWeb.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Intent i = new Intent();
                i.setAction("android.intent.action.VIEW");
                i.addCategory("android.intent.category.BROWSABLE");
                Uri uri = Uri.parse("http://apps-for-android.googlecode.com/svn/trunk/BTClickLinkCompete/docs/index.html");
                i.setData(uri);
                self.startActivity(i);
            }
        });

    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.gigigo.ggglogger;

public enum LogLevel {
  //enum int values here are according to android.util.Log Constants
  ASSERT(7),
  DEBUG(3),
  ERROR(6),
  INFO(4),
  VERBOSE(2),
  WARN(5);
  private final int logLevelValue;

  LogLevel(int logLevelValue) {
    this.logLevelValue = logLevelValue;
  }

  public int getLogLevelValue() {
    return logLevelValue;
  }
}


text:
<?php
header('Content-Type: application/javascript');
ob_start("ob_gzhandler");
require_once realpath(dirname(__FILE__) . '/') . '/secret/wp-hashcash.php';

$field_id = hashcash_random_string(rand(6, 18));
$fn_enable_name = hashcash_random_string(rand(6, 18));
?>

addLoadEvent(<?php echo $fn_enable_name;?>);

function createHiddenField() {
    var inp = document.createElement('input');
    inp.setAttribute('type', 'hidden');
    inp.setAttribute('id', '<?php echo $field_id;?>');
    inp.setAttribute('name', 'hashcash_value');
    inp.setAttribute('value', '-1');

    var e = document.getElementById('<?php echo HASHCASH_FORM_ID;?>');

    e.appendChild(inp); //PB ICI
}

function addVerbage(){ //PB la dedans
    var e = getElementsByClass('<?php echo HASHCASH_FORM_CLASS;?>');
    var p = document.createElement('p');
    p.innerHTML = '<?php echo str_replace("'", "\'", hashcash_verbage());?>';
    e[0].appendChild(p);
}

function <?php echo $fn_enable_name;?>(){
    createHiddenField();
    //addVerbage(); //Affiche la phrase protection antispam active.
    loadHashCashKey('<?php
echo $_GET['siteurl'];
?>/app/wp-hashcash-getkey.php', '<?php echo $field_id;?>');
}

function loadHashCashKey(fragment_url, e_id) {
    var xmlhttp=createXMLHttp();
    var element = document.getElementById(e_id);

    xmlhttp.open("GET", fragment_url, true);
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            element.value = eval(xmlhttp.responseText);
        }
    }

    xmlhttp.send(null);
}

function getElementsByClass(searchClass,node,tag) {
    var classElements = new Array();
    if ( node == null )
        node = document;
    if ( tag == null )
        tag = '*';
    var els = node.getElementsByTagName(tag);
    var elsLen = els.length;
    var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
    for (i = 0, j = 0; i < elsLen; i++) {
        if ( pattern.test(els[i].className) ) {
            classElements[j] = els[i];
            j++;
        }
    }
    return classElements;
}

function createXMLHttp() {
    if (typeof XMLHttpRequest != "undefined")
        return new XMLHttpRequest();

    var xhrVersion = [ "MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp","Microsoft.XMLHttp" ];

    for (var i = 0; i < xhrVersion.length; i++) {
    try {
            var xhrObj = new ActiveXObject(xhrVersion[i]);
      return xhrObj;
    } catch (e) { }
  }

  return null;
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
        func();
        oldonload();
    }
  }
}


text:
@interface CWUBCell_ImgCenter_TitleCenter()

@property (nonatomic, strong) UIView *m_back;
@property (nonatomic, strong) UIImageView *m_img_center;
@property (nonatomic, strong) CWUBLabelWithModel *m_lbl_center;

@end

@implementation CWUBCell_ImgCenter_TitleCenter

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier model:(CWUBCell_ImgCenter_TitleCenter_Model*)model{

    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier model:model]) {

        [self fun_commonInitWithModel:model];
    }

    return self;
}

- (id)initWithModel:(CWUBCell_ImgCenter_TitleCenter_Model*)model{

    if (self = [super init]) {
        [self fun_commonInitWithModel:model];
    }

    return self;
}

- (void)fun_commonInitWithModel:(CWUBCell_ImgCenter_TitleCenter_Model*)model{

    self.selectionStyle = UITableViewCellSelectionStyleNone;
    self.m_model = model;
    if (self.m_model.m_bottomLineInfo.m_color) {
        self.m_img_sep.backgroundColor = self.m_model.m_bottomLineInfo.m_color;
    }else{
        self.m_img_sep.backgroundColor = [UIColor clearColor];
    }
    [self func_initWithSubViews];
}

- (void) func_initWithSubViews{

    [self addSubview:self.m_back];
    [self.m_back addSubview:self.m_img_center];
    [self.m_back addSubview:self.m_lbl_center];
    [self addSubview:self.m_img_sep];

    [self func_updateConsrtains];
}

- (void)func_updateConsrtains{
    [_m_back mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.centerY.equalTo(self);
        make.top.equalTo(self).offset(self.m_model.m_title.m_margin_top);
        make.bottom.equalTo(self.m_img_sep).offset(-self.m_model.m_title.m_margin_bottom);
    }];

    [_m_lbl_center mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.m_img_center.mas_right).offset(self.m_model.m_title.m_margin_left);
        make.top.equalTo(self.m_back);
        make.bottom.equalTo(self.m_back);
        make.right.equalTo(self.m_back);
    }];

    [_m_img_center mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.m_back);
        make.centerY.equalTo(self.m_lbl_center);
        make.width.equalTo(@(self.m_model.m_image.m_width));
        make.height.equalTo(@(self.m_model.m_image.m_height));
    }];

    [self.m_img_sep mas_remakeConstraints:^(MASConstraintMaker *make) {

        make.left.equalTo(@(self.m_model.m_bottomLineInfo.m_margin_left));
        make.right.equalTo(@(-self.m_model.m_bottomLineInfo.m_margin_right));
        make.bottom.equalTo(self);
        make.height.equalTo(@(self.m_model.m_bottomLineInfo.m_height));
        make.top.equalTo(self.m_lbl_center.mas_bottom).offset(self.m_model.m_title.m_margin_bottom);

    }];

}

-(CWUBCell_ImgCenter_TitleCenter_Model*) m_model{

    if (!_m_model) {
        _m_model = [CWUBCell_ImgCenter_TitleCenter_Model new];
    }

    return _m_model;
}

- (UIView *)m_back{

    if (!_m_back) {
        _m_back = [UIView new];
    }

    return _m_back;
}

- (CWUBLabelWithModel *)m_lbl_center{

    if (!_m_lbl_center) {
        _m_lbl_center = [[CWUBLabelWithModel alloc] initWithModel:self.m_model.m_title];
        _m_lbl_center.textAlignment = NSTextAlignmentCenter;

        _m_lbl_center.lineBreakMode = NSLineBreakByWordWrapping|NSLineBreakByTruncatingTail;
        _m_lbl_center.numberOfLines = 0;
    }
    return _m_lbl_center;
}

-(UIImageView *)m_img_center{

    if(!_m_img_center){
        _m_img_center = [UIImageView new];
        [_m_img_center setImage:[UIImage imageNamed:self.m_model.m_image.m_imgName]];
        _m_img_center.contentMode = UIViewContentModeScaleAspectFill;
        _m_img_center.clipsToBounds = YES;
        [_m_img_center setClipsToBounds:YES];
    }
    return _m_img_center;
}

- (void) interface_updateWithModel:(CWUBCell_ImgCenter_TitleCenter_Model*)model{

    [super interface_updateWithModel:model];

    self.m_model = model;
    [self.m_lbl_center interface_update:model.m_title];
    [self.m_img_center setImage:[UIImage imageNamed:self.m_model.m_image.m_imgName]];
    if (self.m_model.m_bottomLineInfo.m_color) {
        self.m_img_sep.backgroundColor = self.m_model.m_bottomLineInfo.m_color;
    }else{
        self.m_img_sep.backgroundColor = [UIColor clearColor];
    }
    if (self.m_model.m_bottomLineInfo.m_image && self.m_model.m_bottomLineInfo.m_image.length>0) {
        [self.m_img_sep setImage:[UIImage imageNamed:self.m_model.m_bottomLineInfo.m_image]];
    }
    [self func_updateConsrtains];
}

-(NSString *)interface_get_event_opt_code{
    return self.m_model.m_event_opt_code;
}

#pragma mark - 事件

- (void)awakeFromNib {[super awakeFromNib];}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {[super setSelected:selected animated:animated];}

@end


text:
@interface AKLaunchWebVC ()<UIWebViewDelegate>
@property(nonatomic,strong)UIWebView* webView;
@end

@implementation AKLaunchWebVC

-(instancetype)initWithLaunchImage:(UIImage*)launchImage launchH5URL:(NSURL*)launchURL{
    self= [super init];
    self.currentLaunchImage=launchImage;
    self.launchURL=launchURL;
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    //WebView
    UIWebView* webV=[[UIWebView alloc]initWithFrame:self.view.bounds];

    webV.delegate=self;

    webV.scrollView.showsVerticalScrollIndicator=NO;

    webV.scrollView.showsHorizontalScrollIndicator=NO;

    self.webView=webV;

    if (!self.currentLaunchImage) {

        self.currentLaunchImage=[UIImage imageNamed:@"LaunchImage"];
    }

    NSAssert(self.currentLaunchImage!=nil,@"请指定启动图片,避免过度UI卡顿");

    UIImageView* bg= [[UIImageView alloc]initWithImage:self.currentLaunchImage];

    bg.frame=self.view.bounds;

    [self.view addSubview:bg];

    NSAssert(self.launchURL!=nil,@"请指定启动H5地址!");

    NSURLRequest* req = [NSURLRequest requestWithURL:self.launchURL];

    [webV loadRequest:req];

}

#pragma mark  - webView Delegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{

    NSString* url = request.URL.absoluteString ;

    if ([url hasSuffix:@"finishLaunch"]){

        NSLog(@"启动H5 加载完毕");
        if(self.launchFinish){
            self.launchFinish();
        }

        return NO;
    }

    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView{
    NSLog(@"启动H5 webViewDidStartLoad");
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    NSLog(@"启动H5 webViewDidFinishLoad");

    [UIView animateWithDuration:0.1 animations:^{

        [self.view addSubview:self.webView];
        [self.view bringSubviewToFront:self.webView];

    }];

}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    NSLog(@"didFailLoadWithError");

}
@end


text:
package org.gradle.sample

import org.junit.runner.RunWith
import org.scalatest.FunSpec
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class PersonSpec extends FunSpec {
  describe("person creation") {
    it("should successfully create a person") {
      def person: Named = new Person(List("bob", "smith"))
      person
    }
  }
}


text:
@implementation DownloadImageManager

@end


text:
casper.notebook_test(function () {
    // test that the kernel is running
    this.then(function () {
        this.test.assert(this.kernel_running(), 'kernel is running');
    });

    // test list
    this.thenEvaluate(function () {
        IPython._kernels = null;
        IPython.notebook.kernel.list(function (data) {
            IPython._kernels = data;
        });
    });
    this.waitFor(function () {
        return this.evaluate(function () {
            return IPython._kernels !== null;
        });
    });
    this.then(function () {
        var num_kernels = this.evaluate(function () {
            return IPython._kernels.length;
        });
        this.test.assertEquals(num_kernels, 1, 'one kernel running');
    });

    // test get_info
    var kernel_info = this.evaluate(function () {
        return {
            name: IPython.notebook.kernel.name,
            id: IPython.notebook.kernel.id
        };
    });
    this.thenEvaluate(function () {
        IPython._kernel_info = null;
        IPython.notebook.kernel.get_info(function (data) {
            IPython._kernel_info = data;
        });
    });
    this.waitFor(function () {
        return this.evaluate(function () {
            return IPython._kernel_info !== null;
        });
    });
    this.then(function () {
        var new_kernel_info = this.evaluate(function () {
            return IPython._kernel_info;
        });
        this.test.assertEquals(kernel_info.name, new_kernel_info.name, 'kernel: name correct');
        this.test.assertEquals(kernel_info.id, new_kernel_info.id, 'kernel: id correct');
    });

    // test interrupt
    this.thenEvaluate(function () {
        IPython._interrupted = false;
        IPython.notebook.kernel.interrupt(function () {
            IPython._interrupted = true;
        });
    });
    this.waitFor(function () {
        return this.evaluate(function () {
            return IPython._interrupted;
        });
    });
    this.then(function () {
        var interrupted = this.evaluate(function () {
            return IPython._interrupted;
        });
        this.test.assert(interrupted, 'kernel was interrupted');
    });

    // test restart
    this.thenEvaluate(function () {
        IPython.notebook.kernel.restart();
    });
    this.waitFor(this.kernel_disconnected);
    this.wait_for_kernel_ready();
    this.then(function () {
        this.test.assert(this.kernel_running(), 'kernel restarted');
    });

    // test reconnect
    this.thenEvaluate(function () {
        IPython.notebook.kernel.stop_channels();
    });
    this.waitFor(this.kernel_disconnected);
    this.thenEvaluate(function () {
        IPython.notebook.kernel.reconnect();
    });
    this.wait_for_kernel_ready();
    this.then(function () {
        this.test.assert(this.kernel_running(), 'kernel reconnected');
    });

    // test kernel_info_request
    this.evaluate(function () {
        IPython.notebook.kernel.kernel_info(
            function(msg){
                IPython._kernel_info_response = msg;
            });
    });
    this.waitFor(
        function () {
            return this.evaluate(function(){
                return IPython._kernel_info_response;
        });
    });
    this.then(function () {
        var kernel_info_response =  this.evaluate(function(){
            return IPython._kernel_info_response;
        });
        this.test.assertTrue( kernel_info_response.msg_type === 'kernel_info_reply', 'Kernel info request return kernel_info_reply');
        this.test.assertTrue( kernel_info_response.content !== undefined, 'Kernel_info_reply is not undefined');
    });

    // test kill
    this.thenEvaluate(function () {
        IPython.notebook.kernel.kill();
    });
    this.waitFor(this.kernel_disconnected);
    this.then(function () {
        this.test.assert(!this.kernel_running(), 'kernel is not running');
    });

    // test start
    var url;
    this.then(function () {
        url = this.evaluate(function () {
            return IPython.notebook.kernel.start();
        });
    });
    this.then(function () {
        this.test.assertEquals(url, "/api/kernels", "start url is correct");
    });
    this.wait_for_kernel_ready();
    this.then(function () {
        this.test.assert(this.kernel_running(), 'kernel is running');
    });

    // test start with parameters
    this.thenEvaluate(function () {
        IPython.notebook.kernel.kill();
    });
    this.waitFor(this.kernel_disconnected);
    this.then(function () {
        url = this.evaluate(function () {
            return IPython.notebook.kernel.start({foo: "bar"});
        });
    });
    this.then(function () {
        this.test.assertEquals(url, "/api/kernels?foo=bar", "start url with params is correct");
    });
    this.wait_for_kernel_ready();
    this.then(function () {
        this.test.assert(this.kernel_running(), 'kernel is running');
    });

    // check for events in kill/start cycle
    this.event_test(
        'kill/start',
        [
            'kernel_killed.Kernel',
            'kernel_created.Kernel',
            'kernel_connected.Kernel',
            'kernel_starting.Kernel',
            'kernel_ready.Kernel'
        ],
        function () {
            this.thenEvaluate(function () {
                IPython.notebook.kernel.kill();
            });
            this.waitFor(this.kernel_disconnected);
            this.thenEvaluate(function () {
                IPython.notebook.kernel.start();
            });
        }
    );
    // wait for any last idle/busy messages to be handled
    this.wait_for_kernel_ready();

    // check for events in disconnect/connect cycle
    this.event_test(
        'reconnect',
        [
            'kernel_reconnecting.Kernel',
            'kernel_connected.Kernel',
        ],
        function () {
            this.thenEvaluate(function () {
                IPython.notebook.kernel.stop_channels();
                IPython.notebook.kernel.reconnect(1);
            });
        }
    );
    // wait for any last idle/busy messages to be handled
    this.wait_for_kernel_ready();

    // check for events in the restart cycle
    this.event_test(
        'restart',
        [
            'kernel_restarting.Kernel',
            'kernel_created.Kernel',
            'kernel_connected.Kernel',
            'kernel_starting.Kernel',
            'kernel_ready.Kernel'
        ],
        function () {
            this.thenEvaluate(function () {
                IPython.notebook.kernel.restart();
            });
        }
    );
    // wait for any last idle/busy messages to be handled
    this.wait_for_kernel_ready();

    // check for events in the interrupt cycle
    this.event_test(
        'interrupt',
        [
            'kernel_interrupting.Kernel',
            'kernel_busy.Kernel',
            'kernel_idle.Kernel'
        ],
        function () {
            this.thenEvaluate(function () {
                IPython.notebook.kernel.interrupt();
            });
        }
    );
    this.wait_for_kernel_ready();

    // check for events after ws close
    this.event_test(
        'ws_closed_ok',
        [
            'kernel_disconnected.Kernel',
            'kernel_reconnecting.Kernel',
            'kernel_connected.Kernel',
            'kernel_busy.Kernel',
            'kernel_idle.Kernel'
        ],
        function () {
            this.thenEvaluate(function () {
                IPython.notebook.kernel._ws_closed("", false);
            });
        }
    );
    // wait for any last idle/busy messages to be handled
    this.wait_for_kernel_ready();

    // check for events after ws close (error)
    this.event_test(
        'ws_closed_error',
        [
            'kernel_disconnected.Kernel',
            'kernel_connection_failed.Kernel',
            'kernel_reconnecting.Kernel',
            'kernel_connected.Kernel',
            'kernel_busy.Kernel',
            'kernel_idle.Kernel'
        ],
        function () {
            this.thenEvaluate(function () {
                IPython.notebook.kernel._ws_closed("", true);
            });
        }
    );
    // wait for any last idle/busy messages to be handled
    this.wait_for_kernel_ready();

    // start the kernel back up
    this.thenEvaluate(function () {
        IPython.notebook.kernel.restart();
    });
    this.waitFor(this.kernel_running);
    this.wait_for_kernel_ready();

    // test handling of autorestarting messages
    this.event_test(
        'autorestarting',
        [
            'kernel_restarting.Kernel',
            'kernel_autorestarting.Kernel',
        ],
        function () {
            this.thenEvaluate(function () {
                var cell = IPython.notebook.get_cell(0);
                cell.set_text('import os\n' + 'os._exit(1)');
                cell.execute();
            });
        }
    );
    this.wait_for_kernel_ready();

    // test handling of failed restart
    this.event_test(
        'failed_restart',
        [
            'kernel_restarting.Kernel',
            'kernel_autorestarting.Kernel',
            'kernel_dead.Kernel'
        ],
        function () {
            this.thenEvaluate(function () {
                var cell = IPython.notebook.get_cell(0);
                cell.set_text("import os\n" +
                              "from IPython.kernel.connect import get_connection_file\n" +
                              "with open(get_connection_file(), 'w') as f:\n" +
                              "    f.write('garbage')\n" +
                              "os._exit(1)");
                cell.execute();
            });
        },

        // need an extra-long timeout, because it needs to try
        // restarting the kernel 5 times!
        20000
    );
});


text:
package yalantis.com.sidemenu.sample.ui.teamInfo;

import yalantis.com.sidemenu.sample.ui.base.MvpPresenter;
import yalantis.com.sidemenu.sample.ui.teams_in_league.ITeamsInLeagueMvpView;

/**
 * Created by TheAppExperts on 23/10/2017.
 */

public interface ITeamInfoMvpPresenter <V extends ITeamInfoMvpView> extends MvpPresenter<V> {

    void onViewPrepared(String id);
}


text:
from flask import Blueprint

auth = Blueprint('auth', __name__)

from . import views
from ..main import errors


text:
from __future__ import division, print_function, unicode_literals, absolute_import
import warnings
warnings.simplefilter('default',DeprecationWarning)

import sys
import crowTestUtils as utils

distribution1D = utils.findCrowModule('distribution1D')

geometric_distribution = distribution1D.BasicGeometricDistribution(0.25)

results = {"pass":0,"fail":0}

utils.checkAnswer("geometric cdf(0)",geometric_distribution.cdf(0),0.25,results)
utils.checkAnswer("geometric cdf(1)",geometric_distribution.cdf(1),0.4375,results)
utils.checkAnswer("geometric mean",geometric_distribution.untrMean(),3.0,results)
utils.checkAnswer("geometric stddev",geometric_distribution.untrStdDev(),3.46410161514,results)

utils.checkAnswer("geometric ppf(0.1)",geometric_distribution.inverseCdf(0.1),0.0,results)
utils.checkAnswer("geometric ppf(0.3)",geometric_distribution.inverseCdf(0.3),0.239823326142,results)
utils.checkAnswer("geometric ppf(0.8)",geometric_distribution.inverseCdf(0.8),4.59450194,results)
utils.checkAnswer("geometric ppf(0.9)",geometric_distribution.inverseCdf(0.9),7.00392277965,results)

print(results)

sys.exit(results["fail"])

"""
 <TestInfo>
    <name>crow.test_geometric</name>
    <author>cogljj</author>
    <created>2017-03-24</created>
    <classesTested>crow</classesTested>
    <description>
      This test is a Unit Test for the crow swig classes. It tests that the geometric
      distribution is accessable by Python
    </description>
    <revisions>
      <revision author="alfoa" date="2018-05-15">Adding this test description.</revision>
    </revisions>
 </TestInfo>
"""


text:
package test.subcomponent.hiding.b;

import dagger2.Module;
import dagger2.Provides;

@Module
public class CommonModuleName {
  @Provides int provideString() {
    return 1;
  }
}


text:
var partials = {
  one: '
click the link now
\n',
  child: '
click the child link now
',
  several:
    '
\n' +
    '
click the link now
\n' +
    '
click the link now
\n' +
    '
click the link now
\n' +
   '
\n'
};

var criterias = {
  valid: 'the link',
  invalid: 'the wrong link',
  child: 'the child link'
};

require('../api-el-suffix-base').test('ByPartialLinkText','by-partial-link', partials, criterias);


text:
> A MEAN boilerplate starter template for all your projects - built with <3 of Bower and Gulp

# MEAN Starter Project 1.0

'master' branch

##Quick Start:

1. Clone the repo: `git clone https://github.com/scriptstar/MEANBoilerplate`
1. Change the directory: `cd MEANBoilerplate`
1. Install the global requirements: `npm install -g gulp bower browserify`
1. Install the local requirements: `npm install`
1. Install the Bower components: `bower install`
1. Run locally: `gulp`
1. Create a build: `gulp build`


text:
/*
 * pred.c -- source for predicate detection, manipulation
 *
 * SOFTWARE RIGHTS
 *
 * We reserve no LEGAL rights to the Purdue Compiler Construction Tool
 * Set (PCCTS) -- PCCTS is in the public domain.  An individual or
 * company may do whatever they wish with source code distributed with
 * PCCTS or the code generated by PCCTS, including the incorporation of
 * PCCTS, or its output, into commerical software.
 *
 * We encourage users to develop software with PCCTS.  However, we do ask
 * that credit is given to us for developing PCCTS.  By "credit",
 * we mean that if you incorporate our source code into one of your
 * programs (commercial product, research project, or otherwise) that you
 * acknowledge this fact somewhere in the documentation, research report,
 * etc...  If you like PCCTS and have developed a nice tool with the
 * output, please mention that you developed it using PCCTS.  In
 * addition, we ask that this header remain intact in our source code.
 * As long as these guidelines are kept, we expect to continue enhancing
 * this system and expect to make other tools available as they are
 * completed.
 *
 * ANTLR 1.33
 * Terence Parr
 * Parr Research Corporation
 * with Purdue University and AHPCRC, University of Minnesota
 * 1989-2001
 */

#include <stdio.h>
#include "pcctscfg.h"
#include "set.h"
#include "syn.h"
#include "hash.h"
#include "generic.h"
#include "dlgdef.h"
#include <ctype.h>

#ifdef __USE_PROTOS
static void complete_context_sets(RuleRefNode *, Predicate *);
static void complete_context_trees(RuleRefNode *, Predicate *);
#else
static void complete_context_sets();
static void complete_context_trees();
#endif

char *PRED_AND_LIST = "AND";
char *PRED_OR_LIST = "OR";

/*
 * In C mode, return the largest constant integer found as the
 * sole argument to LATEXT(i).
 *
 * In C++ mode, return the largest constant integer found as the
 * sole argument to LT(i) given that the char before is nonalpha.
 */

int
#ifdef __USE_PROTOS
predicateLookaheadDepth(ActionNode *a)
#else
predicateLookaheadDepth(a)
ActionNode *a;
#endif
{
	int     max_k=0;

    if (a->predEntry != NULL) {
       MR_pred_depth(a->predEntry->pred,&max_k);
       goto PREDENTRY_EXIT;
    }

	if ( GenCC )
	{
		/* scan for LT(i) */
		int k = 0;
		char *p = a->action;
		while ( p!=NULL )
		{
			p = strstr(p, "LT(");
			if ( p!=NULL )
			{
				if ( p>=a->action && !isalpha(*(p-1)) )
				{
					k = atoi(p+strlen("LT("));
					if ( k>max_k ) max_k=k;
				}
				p += strlen("LT(");
			}
		}
	}
	else {
		/* scan for LATEXT(i) */
		int k = 0;
		char *p = a->action;
		while ( p!=NULL )
		{
			p = strstr(p, "LATEXT(");
			if ( p!=NULL )
			{
				p += strlen("LATEXT(");
				k = atoi(p);
				if ( k>max_k ) max_k=k;
			}
		}
	}

	if (max_k==0) {
		max_k = 1;	   /* MR33 Badly designed if didn't set max_k when CLL_k = 1 */
		if (CLL_k > 1) /* MR27 Don't warn if max(k,ck) == 1 */
		{
			if ( !a->frmwarned )
			{
				a->frmwarned = 1;
				warnFL(eMsg1("predicate: %s missing, bad, or with i=0; assuming i=1",
							 GenCC?"LT(i)":"LATEXT(i)"),
					   FileStr[a->file], a->line);
			}
		}
	}

/* MR10 */    if ( max_k > CLL_k) {
/* MR10 */		if ( !a->frmwarned )
/* MR10 */        {
/* MR10 */			a->frmwarned = 1;
/* MR11 */ errFL(eMsgd2("predicate refers to lookahead token %d. Semantic lookahead is limited to max(k,ck)==%d",
/* MR10 */                        max_k,CLL_k),
/* MR10 */                        FileStr[a->file],a->line);
/* MR10 */          if (max_k >= OutputLL_k) {
/* MR10 */            if (!GenCC) {
/* MR10 */              errFL(eMsgd("    the lookahead buffer size in C mode is %d token(s) (including the one just recognized)",
/* MR10 */                        OutputLL_k),
/* MR10 */                        FileStr[a->file],a->line);
/* MR10 */            };
/* MR10 */          };
/* MR10 */        };
/* MR10 */        max_k= CLL_k;
/* MR10 */    };

PREDENTRY_EXIT:
	return max_k;
}

/* Find all predicates in a block of alternatives.  DO NOT find predicates
 * behind the block because that predicate could depend on things set in
 * one of the nonoptional blocks
 */

Predicate *
#ifdef __USE_PROTOS
find_in_aSubBlk( Junction *alt )
#else
find_in_aSubBlk( alt )
Junction *alt;
#endif
{
	Predicate *a, *head=NULL, *tail=NULL, *root=NULL;
	Junction *p = alt;

    if (MRhoisting) {
      return MR_find_in_aSubBlk(alt);
    };
	for (; p!=NULL; p=(Junction *)p->p2)
	{
		/* ignore empty alts */
		if ( p->p1->ntype != nJunction ||
			 ((Junction *)p->p1)->jtype != EndBlk )
		{
			a = find_predicates(p->p1);	/* get preds for this alt */
			if ( a==NULL ) continue;

			/* make an OR list of predicates */
			if ( head==NULL )
			{
				root = new_pred();
				root->expr = PRED_OR_LIST;
				head = tail = a;
				root->down = head;
			}
			else {
				tail->right = a;
				a->left = tail;
				a->up = tail->up;
				tail = a;
			}
		}
	}

	/* if just one pred, remove OR root */
	if ( root!=NULL && root->down->right == NULL )
	{
		Predicate *d = root->down;
		free( (char *) root);
		return d;
	}

	return root;
}

Predicate *
#ifdef __USE_PROTOS
find_in_aOptBlk( Junction *alt )
#else
find_in_aOptBlk( alt )
Junction *alt;
#endif
{
	return find_in_aSubBlk( alt );
}

Predicate *
#ifdef __USE_PROTOS
find_in_aLoopBegin( Junction *alt )
#else
find_in_aLoopBegin( alt )
Junction *alt;
#endif
{
	return find_in_aSubBlk( (Junction *) alt->p1 );	/* get preds in alts */
}

Predicate *
#ifdef __USE_PROTOS
find_in_aPlusBlk( Junction *alt )
#else
find_in_aPlusBlk( alt )
Junction *alt;
#endif
{
	require(alt!=NULL&&alt->p2!=NULL, "invalid aPlusBlk");
	return find_in_aSubBlk( alt );
}

/* Look for a predicate;
 *
 * Do not pass anything but Junction nodes; no Actions, Tokens, RuleRefs.
 * This means that a "hoisting distance" of zero is the only distance
 * allowable.  Init actions are ignored.
 *
 * WARNING:
 *		Assumes no (..)? block after predicate for the moment.
 *		Does not check to see if pred is in production that can generate
 *			a sequence contained in the set of ambiguous tuples.
 *
 * Return the predicate found if any.
 */

Predicate *
#ifdef __USE_PROTOS
find_predicates( Node *alt )
#else
find_predicates( alt )
Node *alt;
#endif
{
#ifdef DBG_PRED
	Junction *j;
	RuleRefNode *r;
	TokNode *t;
#endif
	Predicate *pred;

	if ( alt==NULL ) return NULL;

#ifdef DBG_PRED
	switch ( alt->ntype )
	{
		case nJunction :
			j = (Junction *) alt;
			fprintf(stderr, "Junction(in %s)", j->rname);
			switch ( j->jtype )
			{
				case aSubBlk :
					fprintf(stderr,"aSubBlk\n");
					break;
				case aOptBlk :
					fprintf(stderr,"aOptBlk\n");
					break;
				case aLoopBegin :
					fprintf(stderr,"aLoopBeginBlk\n");
					break;
				case aLoopBlk :
					fprintf(stderr,"aLoopBlk\n");
					break;
				case aPlusBlk :
					fprintf(stderr,"aPlusBlk\n");
					break;
				case EndBlk :
					fprintf(stderr,"EndBlk\n");
					break;
				case RuleBlk :
					fprintf(stderr,"RuleBlk\n");
					break;
				case Generic :
					fprintf(stderr,"Generic\n");
					break;
				case EndRule :
					fprintf(stderr,"EndRule\n");
					break;
			}
			break;
		case nRuleRef :
			r = (RuleRefNode *) alt;
			fprintf(stderr, "RuleRef(in %s)\n", r->rname);
			break;
		case nToken :
			t = (TokNode *) alt;
			fprintf(stderr, "TokenNode(in %s)%s\n", t->rname, TokenString(t->token));
			break;
		case nAction :
			fprintf(stderr, "Action\n");
			break;
	}
#endif

	switch ( alt->ntype )
	{
		case nJunction :
		{
			Predicate *a, *b;
			Junction *p = (Junction *) alt;

			/* lock nodes */
			if ( p->jtype==aLoopBlk || p->jtype==RuleBlk ||
				 p->jtype==aPlusBlk || p->jtype==EndRule )
			{
				require(p->pred_lock!=NULL, "rJunc: lock array is NULL");
				if ( p->pred_lock[1] )
				{
					return NULL;
				}
				p->pred_lock[1] = TRUE;
			}

			switch ( p->jtype )
			{
				case aSubBlk :
					a = find_in_aSubBlk(p);
					return a;	/* nothing is visible past this guy */
				case aOptBlk :
					a = find_in_aOptBlk(p);
					return a;
				case aLoopBegin :
					a = find_in_aLoopBegin(p);
					return a;
				case aLoopBlk :
					a = find_in_aSubBlk(p);
					p->pred_lock[1] = FALSE;
					return a;
				case aPlusBlk :
					a = find_in_aPlusBlk(p);
					p->pred_lock[1] = FALSE;
					return a;	/* nothing is visible past this guy */
				case RuleBlk :
					a = find_predicates(p->p1);
					p->pred_lock[1] = FALSE;
					return a;
				case Generic :
					a = find_predicates(p->p1);
					b = find_predicates(p->p2);
					if ( p->pred_lock!=NULL ) p->pred_lock[1] = FALSE;
					if ( a==NULL ) return b;
					if ( b==NULL ) return a;
					/* otherwise OR the two preds together */
					{
					fatal_internal("hit unknown situation during predicate hoisting");
					}
				case EndBlk :
				case EndRule :	/* Find no predicates after a rule ref */
					return NULL;
				default:
					fatal_internal("this cannot be printed\n");
					break;
			}
		}
		case nAction :
		{
			ActionNode *p = (ActionNode *) alt;
            if ( p->noHoist) return NULL;                           /* MR12c */
			if ( p->init_action ) return find_predicates(p->next);
			if ( p->is_predicate )
			{
				Tree *t=NULL;
#ifdef DBG_PRED
				fprintf(stderr, "predicate: <<%s>>?\n", p->action);
#endif
				if ( p->guardpred!=NULL )
				{
					pred = predicate_dup(p->guardpred);
                    MR_guardPred_plainSet(p,pred);                  /* MR12c */
				}
				else
				{
					pred = new_pred();
					pred->k = predicateLookaheadDepth(p);
					pred->source = p;
					pred->expr = p->action;
					if ( HoistPredicateContext && pred->k > 1 )
					{
						/* MR30 No need to use first_item_is_guess_block_extra
						   since we know this is an action, not a (...)* or
						   (...)+ block.
						*/

						if ( first_item_is_guess_block((Junction *)p->next) )
						{
                            warnFL("cannot compute context of predicate in front of (..)? block",
                            FileStr[p->file], p->line);
						}
						else
						{
							ConstrainSearch = 0;
/* MR11 */                  if (p->ampersandPred != NULL) {
/* MR11 */  					TRAV(p,
/* MR11 */							 pred->k,
/* MR11 */  						 &(pred->completionTree), t);
/* MR11 */                  } else {
    							TRAV(p->next,
    								 pred->k,
    								 &(pred->completionTree), t);
                            };
							pred->tcontext = t;
                            MR_check_pred_too_long(pred,pred->completionTree);
#ifdef DBG_PRED
							fprintf(stderr, "LL(%d) context:", pred->k);
							preorder(t);
							fprintf(stderr, "\n");
#endif
						}
					}
					else if ( HoistPredicateContext && pred->k == 1 )
					{
						pred->scontext[1] = empty;
						/* MR30 No need to use first_item_is_guess_block_extra
						   since we know this is an action.
						*/
						if ( first_item_is_guess_block((Junction *)p->next) )
						{
                        warnFL("cannot compute context of predicate in front of (..)? block",
                                             FileStr[p->file], p->line);
						}
						else
						{
							REACH((Junction *)p->next,
								  1,
								  &(pred->completionSet),
								  pred->scontext[1]);
                            MR_check_pred_too_long(pred,pred->completionSet);
#ifdef DBG_PRED
							fprintf(stderr, "LL(1) context:");
							s_fprT(stderr, pred->scontext[1]);
							fprintf(stderr, "\n");
#endif
						}
					}
				}
				{
					Predicate  *d = find_predicates(p->next);
                    Predicate  *root;

/* Warning: Doesn't seem like the up pointers will all be set correctly;
 * TJP: that's ok, we're not using them now.
 */
					if ( d!=NULL )
					{
						root = new_pred();
						root->expr = PRED_AND_LIST;
						root->down = pred;
						pred->right = d;
						pred->up = root;
						d->left = pred;
						d->up = pred->up;
						return root;
					}
				}
				return pred;
			}
			return NULL;
		}
		case nRuleRef :
		{
			Predicate   *a;
			RuleRefNode *p = (RuleRefNode *) alt;
			Junction    *r;
            Junction    *save_MR_RuleBlkWithHalt;

			RuleEntry *q = (RuleEntry *) hash_get(Rname, p->text);
			if ( q == NULL )
			{
				warnFL( eMsg1("rule %s not defined",p->text), FileStr[p->file], p->line );
				return NULL;
			}
			r = RulePtr[q->rulenum];
			if ( r->pred_lock[1] )
			{
				/* infinite left-recursion; ignore 'cause LL sup 1 (k) analysis
				 * must have seen it earlier.
				 */
				return NULL;
			}

            /* MR10 There should only be one halt set at a time.        */
            /* MR10 Life would have been easier with a global variable  */
            /* MR10    (at least for this particular need)              */
            /* MR10 Unset the old one and set the new one, later undo.  */

            require(r->end->halt == FALSE,"should only have one halt at a time");

/* MR10 */  require(MR_RuleBlkWithHalt == NULL ||
/* MR10 */          (MR_RuleBlkWithHalt->jtype == RuleBlk && MR_RuleBlkWithHalt->end->halt == TRUE),
/* MR10 */             "RuleBlkWithHalt->end not RuleBlk or does not have halt set");
/* MR10 */  if (MR_RuleBlkWithHalt != NULL) {
/* MR10 */    MR_RuleBlkWithHalt->end->halt=FALSE;
/* MR10 */  };

/***        fprintf(stderr,"\nSetting halt on junction #%d\n",r->end->seq);     ***/

            require(r->end->halt == FALSE,"rule->end->halt already set");

            save_MR_RuleBlkWithHalt=MR_RuleBlkWithHalt;

/* MR10 */  MR_pointerStackPush(&MR_RuleBlkWithHaltStack,MR_RuleBlkWithHalt);
/* MR10 */  MR_pointerStackPush(&MR_PredRuleRefStack,p);

			r->end->halt = TRUE;
/* MR10 */  MR_RuleBlkWithHalt=r;

			a = find_predicates((Node *)r);

            require(r->end->halt == TRUE,"rule->end->halt not set");
            r->end->halt = FALSE;

/* MR10 */  MR_pointerStackPop(&MR_PredRuleRefStack);
/* MR10 */  MR_RuleBlkWithHalt=(Junction *) MR_pointerStackPop(&MR_RuleBlkWithHaltStack);

            require (MR_RuleBlkWithHalt==save_MR_RuleBlkWithHalt,
                    "RuleBlkWithHaltStack not consistent");

/* MR10 */  require(MR_RuleBlkWithHalt == NULL ||
/* MR10 */          (MR_RuleBlkWithHalt->jtype == RuleBlk && MR_RuleBlkWithHalt->end->halt == FALSE),
/* MR10 */             "RuleBlkWithHalt->end not RuleBlk or has no halt set");
/* MR10 */  if (MR_RuleBlkWithHalt != NULL) {
/* MR10 */    MR_RuleBlkWithHalt->end->halt=TRUE;
/* MR10 */  };

/***        fprintf(stderr,"\nRestoring halt on junction #%d\n",r->end->seq);   ***/

			if ( a==NULL ) return NULL;

			/* attempt to compute the "local" FOLLOW just like in normal lookahead
			 * computation if needed
			 */

			complete_context_sets(p,a);
			complete_context_trees(p,a);

/* MR10 */  MR_cleanup_pred_trees(a);

			return a;
		}
		case nToken :
			break;
	}

	return NULL;
}

#ifdef __USE_PROTOS
Predicate *MR_find_predicates_and_supp(Node *alt)
#else
Predicate *MR_find_predicates_and_supp(alt)
  Node      *alt;
#endif
{
    Predicate   *p;

    p=find_predicates(alt);
    p=MR_suppressK(alt,p);
    return p;
}

Predicate *
#ifdef __USE_PROTOS
new_pred( void )
#else
new_pred( )
#endif
{
	Predicate *p = (Predicate *) calloc(1,sizeof(Predicate)); /* MR10 */
	require(p!=NULL, "new_pred: cannot alloc predicate");
    p->scontext[0]=empty;
    p->scontext[1]=empty;
    p->completionTree=empty;
    p->completionSet=empty;
    p->plainSet=empty;
	return p;
}

static void
#ifdef __USE_PROTOS
complete_context_sets( RuleRefNode *p, Predicate *a )
#else
complete_context_sets( p, a )
RuleRefNode *p;
Predicate *a;
#endif
{
	set rk2, b;
	int k2;

#ifdef DBG_PRED
	fprintf(stderr, "enter complete_context_sets\n");
#endif
	for (; a!=NULL; a=a->right)
	{
		if ( a->expr == PRED_AND_LIST || a->expr == PRED_OR_LIST )
		{
			complete_context_sets(p,a->down);
			continue;
		}
		rk2 = b = empty;
		while ( !set_nil(a->completionSet) )
		{
			k2 = set_int(a->completionSet);
			set_rm(k2, a->completionSet);

            REACH(p->next, k2, &rk2, b);
			set_orin(&(a->scontext[1]), b);
			set_free(b);
		}

		set_orin(&(a->completionSet), rk2);/* remember what we couldn't do */
		set_free(rk2);
#ifdef DBG_PRED
		fprintf(stderr, "LL(1) context for %s(addr 0x%x) after ruleref:", a->expr, a);
		s_fprT(stderr, a->scontext[1]);
		fprintf(stderr, "\n");
#endif
/*		complete_context_sets(p, a->down);*/
	}
#ifdef DBG_PRED
	fprintf(stderr, "exit complete_context_sets\n");
#endif
}

static void
#ifdef __USE_PROTOS
complete_context_trees( RuleRefNode *p, Predicate *a )
#else
complete_context_trees( p, a )
RuleRefNode *p;
Predicate *a;
#endif
{
	set rk2;
	int k2;
	Tree *u;

#ifdef DBG_PRED
	fprintf(stderr, "enter complete_context_trees\n");
#endif
	for (; a!=NULL; a=a->right)
	{
		if ( a->expr == PRED_AND_LIST || a->expr == PRED_OR_LIST )
		{
			complete_context_trees(p, a->down);
			continue;
		}
		rk2 = empty;

		/* any k left to do? if so, link onto tree */
		while ( !set_nil(a->completionTree) )
		{
			k2 = set_int(a->completionTree);
			set_rm(k2, a->completionTree);
			u = NULL;

            TRAV(p->next, k2, &rk2, u);

			/* any subtrees missing k2 tokens, add u onto end */
			a->tcontext = tlink(a->tcontext, u, k2);
            Tfree(u);   /* MR10 */
		}
		set_orin(&(a->completionTree), rk2);/* remember what we couldn't do */
		set_free(rk2);
#ifdef DBG_PRED
		fprintf(stderr, "LL(i<%d) context after ruleref:", LL_k);
		preorder(a->tcontext);
		fprintf(stderr, "\n");
#endif
/*		complete_context_trees(p, a->down);*/
	}
#ifdef DBG_PRED
	fprintf(stderr, "exit complete_context_trees\n");
#endif
}

/* Walk a list of predicates and return the set of all tokens in scontext[1]'s */
set
#ifdef __USE_PROTOS
covered_set( Predicate *p )
#else
covered_set( p )
Predicate *p;
#endif
{
	set a;

	a = empty;
	for (; p!=NULL; p=p->right)
	{
		if ( p->expr == PRED_AND_LIST || p->expr == PRED_OR_LIST )
		{
			set_orin(&a, covered_set(p->down));
			continue;
		}
		set_orin(&a, p->scontext[1]);
		set_orin(&a, covered_set(p->down));
	}
	return a;
}

/* MR10 predicate_free()
   MR10 Don't free the leaf nodes since they are part of the action node
*/

#ifdef __USE_PROTOS
void predicate_free(Predicate *p)
#else
void predicate_free(p)
  Predicate     *p;
#endif
{
  if (p == NULL) return;
  predicate_free(p->right);
  predicate_free(p->down);
  if (p->cloned ||
      p->source == NULL ||
      p->source->guardpred == NULL ||
      p->expr == PRED_AND_LIST ||
      p->expr == PRED_OR_LIST) {
    set_free(p->scontext[1]);
    set_free(p->completionSet);
    set_free(p->completionTree);
    set_free(p->plainSet);
    Tfree(p->tcontext);
    free( (char *) p);
  } else {
    p->right=NULL;
    p->down=NULL;  /* MR13 *** debug */
  };
}

/* MR10 predicate_dup() */

#ifdef __USE_PROTOS
Predicate * predicate_dup_xxx(Predicate *p,int contextToo)
#else
Predicate * predicate_dup_xxx(p,contextToo)
  Predicate     *p;
  int           contextToo;
#endif
{
  Predicate     *q;

  if (p == NULL) return NULL;
  q=new_pred();
  q->down=predicate_dup(p->down);
  q->right=predicate_dup(p->right);

  /*
     don't replicate expr - it is read-only
     and address comparison is used to look
     for identical predicates.
  */

  q->expr=p->expr;
  q->k=p->k;
  q->source=p->source;
  q->cloned=1;
  q->ampersandStyle=p->ampersandStyle;
  q->inverted=p->inverted;
  q->predEntry=p->predEntry;
  q->plainSet=set_dup(p->plainSet);

  if (contextToo) {
    q->tcontext=tdup(p->tcontext);
    q->scontext[0]=set_dup(p->scontext[0]);
    q->scontext[1]=set_dup(p->scontext[1]);
    q->completionTree=set_dup(p->completionTree);
    q->completionSet=set_dup(p->completionSet);
  };

  /* don't need to dup "redundant" */

  return q;

}

#ifdef __USE_PROTOS
Predicate * predicate_dup_without_context(Predicate *p)
#else
Predicate * predicate_dup_without_context(p)
  Predicate     *p;
#endif
{
  return predicate_dup_xxx(p,0);
}

#ifdef __USE_PROTOS
Predicate * predicate_dup(Predicate *p)
#else
Predicate * predicate_dup(p)
  Predicate     *p;
#endif
{
  return predicate_dup_xxx(p,1);
}


text:
#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{

    QApplication a(argc, argv);
    MainWindow w;
    w.setTitle("OpenGL Hello World!");
    w.resize(640, 480);
    w.show();
    return a.exec();
}


text:
package eta.runtime.storage;

public class DefaultLocalHeap implements LocalHeap {
    private static LocalHeap INSTANCE = new DefaultLocalHeap();

    public static LocalHeap getInstance() {
        return INSTANCE;
    }

    @Override
    public long allocateLocal(int _miniblocks, boolean _direct, boolean _supr) {
        return 0;
    }

    @Override
    public void setActiveBlock(Block block, boolean direct, boolean supr) {}
}


text:
package com.damianmichalak.fixer.view;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.util.Pair;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.damianmichalak.fixer.R;
import com.damianmichalak.fixer.presenter.MainActivityPresenter;
import com.damianmichalak.fixer.presenter.OpenDetailsActivityArguments;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.functions.Action1;

public class UniversalAdapter extends RecyclerView.Adapter<UniversalAdapter.BaseViewHolder> implements Action1<List<BaseAdapterItem>>, HeaderDecoration.StickyHeaderInterface {

    private static final int ITEM_RATING = 0;
    private static final int ITEM_DATE = 1;
    private static final int ITEM_PROGRESS = 2;

    private List<BaseAdapterItem> items = new ArrayList<>();

    @Inject
    LayoutInflater inflater;

    @Inject
    Activity activity;

    @Inject
    UniversalAdapter() {
    }

    @Override
    public UniversalAdapter.BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case ITEM_DATE:
                return new DateViewHolder(inflater.inflate(R.layout.date_item_layout, parent, false));
            case ITEM_RATING:
                return new RatingViewHolder(inflater.inflate(R.layout.rating_item_layout, parent, false));
            case ITEM_PROGRESS:
                return new ProgressViewHolder(inflater.inflate(R.layout.progress_item_layout, parent, false));
            default:
                throw new IllegalStateException("Cannot find view for : " + viewType);
        }
    }

    @Override
    public void onBindViewHolder(UniversalAdapter.BaseViewHolder holder, int position) {
        holder.bind(items.get(position));
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    @Override
    public int getItemViewType(int position) {
        final BaseAdapterItem baseAdapterItem = items.get(position);
        if (baseAdapterItem instanceof MainActivityPresenter.DateAdapterItem) {
            return ITEM_DATE;
        } else if (baseAdapterItem instanceof MainActivityPresenter.RatingAdapterItem) {
            return ITEM_RATING;
        } else if (baseAdapterItem instanceof MainActivityPresenter.ProgressLoadingItem) {
            return ITEM_PROGRESS;
        } else {
            throw new IllegalStateException("Unsupported adapter item: " + baseAdapterItem.getClass().getSimpleName());
        }
    }

    @Override
    public void call(List<BaseAdapterItem> baseAdapterItems) {
        items = baseAdapterItems;
        notifyDataSetChanged();
    }

    @Override
    public int getHeaderPositionForItem(int itemPosition) {
        int headerPosition = 0;
        do {
            if (isHeader(itemPosition)) {
                headerPosition = itemPosition;
                break;
            }
            itemPosition -= 1;
        } while (itemPosition >= 0);

        return headerPosition;
    }

    @Override
    public int getHeaderLayout(int headerPosition) {
        return R.layout.date_item_layout;
    }

    @Override
    public void bindHeaderData(View header, int headerPosition) {
        final BaseAdapterItem item = items.get(headerPosition);
        ((TextView) header.findViewById(R.id.date_item_layout_text))
                .setText(((MainActivityPresenter.DateAdapterItem) item).getDate());
    }

    @Override
    public boolean isHeader(int itemPosition) {
        return items.get(itemPosition).isHeader();
    }

    abstract class BaseViewHolder extends RecyclerView.ViewHolder {

        BaseViewHolder(View itemView) {
            super(itemView);
        }

        abstract void bind(BaseAdapterItem item);
    }

    class DateViewHolder extends UniversalAdapter.BaseViewHolder {

        @BindView(R.id.date_item_layout_text)
        TextView date;

        DateViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        @Override
        public void bind(BaseAdapterItem item) {
            date.setText(((MainActivityPresenter.DateAdapterItem) item).getDate());
        }

    }

    class RatingViewHolder extends UniversalAdapter.BaseViewHolder {

        @BindView(R.id.rating_item_layout_text_value)
        TextView value;
        @BindView(R.id.rating_item_layout_text_currency)
        TextView currency;

        private final View itemView;

        RatingViewHolder(View itemView) {
            super(itemView);
            this.itemView = itemView;
            ButterKnife.bind(this, itemView);
        }

        @Override
        public void bind(BaseAdapterItem item) {
            final MainActivityPresenter.RatingAdapterItem adapterItem = (MainActivityPresenter.RatingAdapterItem) item;
            currency.setText(adapterItem.getName());
            value.setText(String.valueOf(adapterItem.getNumber()));
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final Intent intent = DetailsActivity.newIntent(activity, new OpenDetailsActivityArguments(adapterItem.getName(), String.valueOf(adapterItem.getNumber()), adapterItem.getDate()));
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        final Pair<View, String> pair1 = Pair.<View, String>create(value, value.getTransitionName());
                        final Pair<View, String> pair2 = Pair.<View, String>create(currency, currency.getTransitionName());

                        //noinspection unchecked
                        ActivityCompat.startActivity(activity, intent,
                                ActivityOptionsCompat
                                        .makeSceneTransitionAnimation(activity, pair1, pair2)
                                        .toBundle());
                    } else {
                        activity.startActivity(intent);
                    }
                }
            });
        }

    }

    private class ProgressViewHolder extends UniversalAdapter.BaseViewHolder {

        ProgressViewHolder(View itemView) {
            super(itemView);
        }

        @Override
        public void bind(BaseAdapterItem item) {
            ((MainActivityPresenter.ProgressLoadingItem) item).getLoadMore().onNext(null);
        }

    }

}


text:
package hydrograph.engine.core.flowmanipulation;

import hydrograph.engine.core.core.HydrographJob;
import hydrograph.engine.core.props.OrderedProperties;
import hydrograph.engine.core.schemapropagation.SchemaFieldHandler;
import hydrograph.engine.core.utilities.OrderedPropertiesHelper;
import hydrograph.engine.jaxb.commontypes.TypeBaseComponent;
import hydrograph.engine.jaxb.commontypes.TypeProperties;
import hydrograph.engine.jaxb.main.Graph;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;
import java.util.List;

/**
 * The Class FlowManipulationHandler.
 *
 * @author Bitwise
 *
 */
public class FlowManipulationHandler {

	private static Logger LOG = LoggerFactory.getLogger(FlowManipulationHandler.class);
	private static List<TypeBaseComponent> jaxbComponents;
	private static TypeProperties jaxbJobLevelRuntimeProperties;
	private static String jobName;

	/**
	 * @param flowManipulationContext
	 * @return the HydrographJob
	 */
	public  HydrographJob execute(FlowManipulationContext flowManipulationContext) {

		jaxbComponents = flowManipulationContext.getJaxbMainGraph();
		jaxbJobLevelRuntimeProperties = flowManipulationContext.getJaxbJobLevelRuntimeProperties();
		jobName = flowManipulationContext.getGraphName();
		OrderedProperties properties;
		try {
			properties = OrderedPropertiesHelper.getOrderedProperties("RegisterPlugin.properties");
		} catch (IOException e) {
			throw new RuntimeException("Error reading the properties file: RegisterPlugin.properties" + e);
		}
		for (String pluginName : addPluginFromFile(properties)) {
			jaxbComponents = executePlugin(pluginName, flowManipulationContext);
			flowManipulationContext.setJaxbMainGraph(jaxbComponents);
			flowManipulationContext.setSchemaFieldMap(new SchemaFieldHandler(jaxbComponents));
		}

		return getJaxbObject();
	}

	private List<String> addPluginFromFile(OrderedProperties properties) {
		List<String> registerdPlugins = new LinkedList<String>();
		for (Object key : properties.keySet()) {
			registerdPlugins.add(properties.get(key).toString());
		}
		return registerdPlugins;
	}

	private static HydrographJob getJaxbObject() {
		Graph graph = new Graph();
		graph.getInputsOrOutputsOrStraightPulls().addAll(jaxbComponents);
		graph.setRuntimeProperties(jaxbJobLevelRuntimeProperties);
		graph.setName(jobName);
		return new HydrographJob(graph);
	}

	private static List<TypeBaseComponent> executePlugin(String clazz,
			FlowManipulationContext flowManipulationContext) {
		try {
			Class pluginClass = Class.forName(clazz);
			Constructor constructor = pluginClass.getDeclaredConstructor();
			ManipulatorListener inst = (ManipulatorListener) constructor.newInstance();
			return inst.execute(flowManipulationContext);
		} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
			throw new RuntimeException(e);
		}
	}
}


text:
PASSWORD="123456"
ARG=""
if [ -n "$2" ]; then ARG="\"$2\","; fi

echo "var output=`solc --optimize --combined-json abi,bin,interface $1`;" > /tmp/test.js

var="$(cat <<EOF
var array = Object.keys(output.contracts);
for (var i in array) {
  var contract = eth.contract(JSON.parse(output.contracts[array[i]].abi));
  var bytecode = '0x' + output.contracts[array[i]].bin;
  var txDeploy = {from:eth.accounts[0], data: bytecode, gas: 4700000};
  personal.unlockAccount(eth.accounts[0], "$PASSWORD", 999999);
  personal.unlockAccount(eth.accounts[1], "$PASSWORD", 999999);
  var test = contract.new($ARG txDeploy,
    function (e, contract) {
      if (typeof contract.address !== 'undefined') {
        console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);
    }
  });
}
EOF
)";

echo $var >> /tmp/test.js


text:
class AddPublicFlagToMessages < ActiveRecord::Migration[5.2]
  def change
    within_renalware_schema do
      add_column(
        :messaging_messages,
        :public,
        :boolean,
        null: false,
        default: false,
        comment: "If true, the message will be displayed on a patient's clinical summary and " \
                 "their messages page. If false (ie private), the message can only be viewed " \
                 "by the sender (in their sent messages) and by the recipients. " \
                 "New messages once this migration is run will always have public=true. "\
                 "Historical messages will remain private."
      )
    end
  end
end


text:
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var deleteDuplicates = function(head) {
	if(head === null){
		return null;
	}
	var node = head;
	while(node.next !== null){
		if(node.val === node.next.val){
			node.next = node.next.next;
		}else{
			node = node.next;
		}
	}
	return head;
};


text:
<?php
// src/Acme/DemoBundle/Form/Type/PersoType.php

namespace Bermone\BlogBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class CkeditorType extends AbstractType
{
	public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'attr' => array(
				'class' => 'ckeditor',
			),
        ));
    }

    public function getParent()
    {
        return 'textarea';
    }

    public function getName()
    {
        return 'ckeditor';
    }
}


text:
namespace crashpad {
namespace test {

bool WriteTestModule(const base::FilePath& module_path,
                     const std::string& soname) {
#if defined(ARCH_CPU_64_BITS)
  using Ehdr = Elf64_Ehdr;
  using Phdr = Elf64_Phdr;
  using Shdr = Elf64_Shdr;
  using Dyn = Elf64_Dyn;
  using Sym = Elf64_Sym;
  unsigned char elf_class = ELFCLASS64;
#else
  using Ehdr = Elf32_Ehdr;
  using Phdr = Elf32_Phdr;
  using Shdr = Elf32_Shdr;
  using Dyn = Elf32_Dyn;
  using Sym = Elf32_Sym;
  unsigned char elf_class = ELFCLASS32;
#endif

  struct {
    Ehdr ehdr;
    struct {
      Phdr load1;
      Phdr load2;
      Phdr dynamic;
    } phdr_table;
    struct {
      Dyn hash;
      Dyn strtab;
      Dyn symtab;
      Dyn strsz;
      Dyn syment;
      Dyn soname;
      Dyn null;
    } dynamic_array;
    struct {
      Elf32_Word nbucket;
      Elf32_Word nchain;
      Elf32_Word bucket;
      Elf32_Word chain;
    } hash_table;
    char string_table[32];
    struct {
    } section_header_string_table;
    struct {
      Sym und_symbol;
    } symbol_table;
    struct {
      Shdr null;
      Shdr dynamic;
      Shdr string_table;
      Shdr section_header_string_table;
    } shdr_table;
  } module = {};

  module.ehdr.e_ident[EI_MAG0] = ELFMAG0;
  module.ehdr.e_ident[EI_MAG1] = ELFMAG1;
  module.ehdr.e_ident[EI_MAG2] = ELFMAG2;
  module.ehdr.e_ident[EI_MAG3] = ELFMAG3;

  module.ehdr.e_ident[EI_CLASS] = elf_class;

#if defined(ARCH_CPU_LITTLE_ENDIAN)
  module.ehdr.e_ident[EI_DATA] = ELFDATA2LSB;
#else
  module.ehdr.e_ident[EI_DATA] = ELFDATA2MSB;
#endif  // ARCH_CPU_LITTLE_ENDIAN

  module.ehdr.e_ident[EI_VERSION] = EV_CURRENT;

  module.ehdr.e_type = ET_DYN;

#if defined(ARCH_CPU_X86)
  module.ehdr.e_machine = EM_386;
#elif defined(ARCH_CPU_X86_64)
  module.ehdr.e_machine = EM_X86_64;
#elif defined(ARCH_CPU_ARMEL)
  module.ehdr.e_machine = EM_ARM;
#elif defined(ARCH_CPU_ARM64)
  module.ehdr.e_machine = EM_AARCH64;
#elif defined(ARCH_CPU_MIPSEL) || defined(ARCH_CPU_MIPS64EL)
  module.ehdr.e_machine = EM_MIPS;
#endif

  module.ehdr.e_version = EV_CURRENT;
  module.ehdr.e_ehsize = sizeof(module.ehdr);

  module.ehdr.e_phoff = offsetof(decltype(module), phdr_table);
  module.ehdr.e_phnum = sizeof(module.phdr_table) / sizeof(Phdr);
  module.ehdr.e_phentsize = sizeof(Phdr);

  module.ehdr.e_shoff = offsetof(decltype(module), shdr_table);
  module.ehdr.e_shentsize = sizeof(Shdr);
  module.ehdr.e_shnum = sizeof(module.shdr_table) / sizeof(Shdr);
  module.ehdr.e_shstrndx =
      offsetof(decltype(module.shdr_table), section_header_string_table) /
      sizeof(Shdr);

  const size_t page_size = getpagesize();
  auto align = [page_size](uintptr_t addr) {
    return (addr + page_size - 1) & ~(page_size - 1);
  };
  constexpr size_t segment_size = offsetof(decltype(module), shdr_table);

  // This test module covers cases where:
  // 1. Multiple segments are mapped from file offset 0.
  // 2. Load bias is negative.

  const uintptr_t load2_vaddr = align(std::numeric_limits<uintptr_t>::max() -
                                      align(segment_size) - page_size);
  const uintptr_t load1_vaddr = load2_vaddr - align(segment_size);

  module.phdr_table.load1.p_type = PT_LOAD;
  module.phdr_table.load1.p_offset = 0;
  module.phdr_table.load1.p_vaddr = load1_vaddr;
  module.phdr_table.load1.p_filesz = segment_size;
  module.phdr_table.load1.p_memsz = segment_size;
  module.phdr_table.load1.p_flags = PF_R;
  module.phdr_table.load1.p_align = page_size;

  module.phdr_table.load2.p_type = PT_LOAD;
  module.phdr_table.load2.p_offset = 0;
  module.phdr_table.load2.p_vaddr = load2_vaddr;
  module.phdr_table.load2.p_filesz = segment_size;
  module.phdr_table.load2.p_memsz = segment_size;
  module.phdr_table.load2.p_flags = PF_R | PF_W;
  module.phdr_table.load2.p_align = page_size;

  module.phdr_table.dynamic.p_type = PT_DYNAMIC;
  module.phdr_table.dynamic.p_offset =
      offsetof(decltype(module), dynamic_array);
  module.phdr_table.dynamic.p_vaddr =
      load2_vaddr + module.phdr_table.dynamic.p_offset;
  module.phdr_table.dynamic.p_filesz = sizeof(module.dynamic_array);
  module.phdr_table.dynamic.p_memsz = sizeof(module.dynamic_array);
  module.phdr_table.dynamic.p_flags = PF_R | PF_W;
  module.phdr_table.dynamic.p_align = 8;

  module.dynamic_array.hash.d_tag = DT_HASH;
  module.dynamic_array.hash.d_un.d_ptr =
      load1_vaddr + offsetof(decltype(module), hash_table);
  module.dynamic_array.strtab.d_tag = DT_STRTAB;
  module.dynamic_array.strtab.d_un.d_ptr =
      load1_vaddr + offsetof(decltype(module), string_table);
  module.dynamic_array.symtab.d_tag = DT_SYMTAB;
  module.dynamic_array.symtab.d_un.d_ptr =
      load1_vaddr + offsetof(decltype(module), symbol_table);
  module.dynamic_array.strsz.d_tag = DT_STRSZ;
  module.dynamic_array.strsz.d_un.d_val = sizeof(module.string_table);
  module.dynamic_array.syment.d_tag = DT_SYMENT;
  module.dynamic_array.syment.d_un.d_val = sizeof(Sym);
  constexpr size_t kSonameOffset = 1;
  module.dynamic_array.soname.d_tag = DT_SONAME;
  module.dynamic_array.soname.d_un.d_val = kSonameOffset;

  module.dynamic_array.null.d_tag = DT_NULL;

  module.hash_table.nbucket = 1;
  module.hash_table.nchain = 1;
  module.hash_table.bucket = 0;
  module.hash_table.chain = 0;

  if (sizeof(module.string_table) < soname.size() + 2) {
    ADD_FAILURE() << "string table too small";
    return false;
  }
  module.string_table[0] = '\0';
  memcpy(&module.string_table[kSonameOffset], soname.c_str(), soname.size());

  module.shdr_table.null.sh_type = SHT_NULL;

  module.shdr_table.dynamic.sh_name = 0;
  module.shdr_table.dynamic.sh_type = SHT_DYNAMIC;
  module.shdr_table.dynamic.sh_flags = SHF_WRITE | SHF_ALLOC;
  module.shdr_table.dynamic.sh_addr = module.phdr_table.dynamic.p_vaddr;
  module.shdr_table.dynamic.sh_offset = module.phdr_table.dynamic.p_offset;
  module.shdr_table.dynamic.sh_size = module.phdr_table.dynamic.p_filesz;
  module.shdr_table.dynamic.sh_link =
      offsetof(decltype(module.shdr_table), string_table) / sizeof(Shdr);

  module.shdr_table.string_table.sh_name = 0;
  module.shdr_table.string_table.sh_type = SHT_STRTAB;
  module.shdr_table.string_table.sh_offset =
      offsetof(decltype(module), string_table);
  module.shdr_table.string_table.sh_size = sizeof(module.string_table);

  module.shdr_table.section_header_string_table.sh_name = 0;
  module.shdr_table.section_header_string_table.sh_type = SHT_STRTAB;
  module.shdr_table.section_header_string_table.sh_offset =
      offsetof(decltype(module), section_header_string_table);
  module.shdr_table.section_header_string_table.sh_size =
      sizeof(module.section_header_string_table);

  FileWriter writer;
  if (!writer.Open(module_path,
                   FileWriteMode::kCreateOrFail,
                   FilePermissions::kWorldReadable)) {
    ADD_FAILURE();
    return false;
  }

  if (!writer.Write(&module, sizeof(module))) {
    ADD_FAILURE();
    LoggingRemoveFile(module_path);
    return false;
  }

  return true;
}

ScopedModuleHandle LoadTestModule(const std::string& module_name,
                                  const std::string& module_soname) {
  base::FilePath module_path(
      TestPaths::Executable().DirName().Append(module_name));

  if (!WriteTestModule(module_path, module_soname)) {
    return ScopedModuleHandle(nullptr);
  }
  EXPECT_TRUE(IsRegularFile(module_path));

  ScopedModuleHandle handle(
      dlopen(module_path.value().c_str(), RTLD_LAZY | RTLD_LOCAL));
  EXPECT_TRUE(handle.valid())
      << "dlopen: " << module_path.value() << " " << dlerror();

  EXPECT_TRUE(LoggingRemoveFile(module_path));

  return handle;
}

}  // namespace test
}  // namespace crashpad