text:
import sys, os, shlex, shutil, random, subprocess
from collections import defaultdict
from optparse import OptionParser
from multiprocessing import Pool
from Bio import SeqIO

def run_cmd(cmd):
    proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE )
    stdout, stderr = proc.communicate()
    if proc.returncode != 0:
        raise IOError("%s\n%s"%(" ".join(cmd), stderr))
    return stdout, stderr

def countseqs(infile, sformat):
    headchar = '>'
    if sformat == 'fastq':
        headchar = '@'
    sout, serr = run_cmd(['grep', '-c', "^%s"%headchar, infile])
    slen = sout.strip()
    if not slen:
        sys.stderr.write("%s is invalid %s file\n"%(infile, sformat))
        exit(1)
    return int(slen)

def subfasta(infile, outfile, sformat, Smax, Sratio, verb):
    seqnum = 0
    outhdl = open(outfile, 'w')
    if verb: sys.stdout.write("Creating %d sequence fasta subset of %s ... "%(Smax, infile))
    for i, rec in enumerate(SeqIO.parse(infile, sformat)):
        if seqnum >= Smax:
            break
        if Sratio < random.random():
            continue
        outhdl.write(">%s\n%s\n"%(rec.id, rec.seq))
        seqnum += 1
    if verb: sys.stdout.write("Done\n")
    return seqnum

def adapter_map(adap_file):
    amap = {}
    for rec in SeqIO.parse(adap_file, 'fasta'):
        amap[rec.id] = str(rec.seq)
    return amap

def fastq2fasta(in_file, out_file):
    in_hdl  = open(in_file, 'rU')
    out_hdl = open(out_file, 'w')
    seqnum  = SeqIO.convert(in_hdl, 'fastq', out_hdl, 'fasta')
    in_hdl.close()
    out_hdl.close()
    return seqnum

def rankIDs(blat_file):
    adaps = defaultdict(int)
    bhdl  = open(blat_file, 'rU')
    for line in bhdl:
        sid = line.strip().split('\t')[1]
        adaps[sid] += 1
    return sorted(adaps.items(), key=lambda x: x[1], reverse=True)

def trim_fastq(cmd_str):
    cmd = shlex.split(str(cmd_str))
    sout, serr = run_cmd(cmd)
    return sout

def main(args):
    usage  = "usage: %prog [options] -d <adapter DB> -i <input sequence file> -o <output file>"
    parser = OptionParser(usage)
    parser.add_option("-i", "--input", dest="input", default=None, help="Input sequence file.")
    parser.add_option("", "--rev_input", dest="rev_input", default=None, help="Reverse sequence file, paired-end seqs only.")
    parser.add_option("-o", "--output", dest="output", default=None, help="Output file.")
    parser.add_option("", "--rev_output", dest="rev_output", default=None, help="Reverse sequence file output, paired-end seqs only.")
    parser.add_option("-f", "--format", dest="format", default='fasta', help="file format: fasta, fastq [default 'fasta']")
    parser.add_option("", "--screen_only", dest="screen", action="store_true", default=False, help="Only screen for adaptors (output identified) [default off]")
    parser.add_option("", "--trim_only", dest="trim", default=None, help="Only trim adaptors [default off]")
    parser.add_option("-m", "--max_screen", dest="max_screen", default=100000, type="int", help="max number of seqs to screen [default 100000]")
    parser.add_option("-d", "--db_adaptor", dest="db_adaptor", default=None, help="Fasta file DB of adaptors")
    parser.add_option("-t", "--tmp_dir", dest="tmpdir", default="/tmp", help="DIR for intermediate files (must be full path), deleted at end [default '/tmp']")
    parser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False, help="Wordy [default off]")

    (opts, args) = parser.parse_args()
    if not (opts.input and os.path.isfile(opts.input) and opts.output):
        parser.error("Missing input/output files")
    if not (opts.db_adaptor and os.path.isfile(opts.db_adaptor)):
        parser.error("Missing adapter DB")
    in_seqs   = opts.input
    map_adapt = adapter_map(opts.db_adaptor)
    top_adapt = opts.trim

    # skip screen if adaptor inputted
    if not (opts.trim and (opts.trim in map_adapt)):
        if opts.verbose: sys.stdout.write("Adaptor Screening %s\n"%in_seqs)
        # convert fastq / sub-sample
        seqtotal = countseqs(in_seqs, opts.format)
        seqper   = (opts.max_screen * 1.0) / seqtotal
        to_sub   = False
        if opts.max_screen < seqtotal:
            to_sub = True
        if opts.format == 'fastq':
            fastaf = os.path.join(opts.tmpdir, os.path.basename(in_seqs)+'.fna')
            if to_sub:
                seqnum = subfasta(in_seqs, fastaf, opts.format, opts.max_screen, seqper, opts.verbose)
            else:
                if opts.verbose: sys.stdout.write("Converting %s to fasta ... "%in_seqs)
                seqnum = fastq2fasta(in_seqs, fastaf)
            if opts.verbose: sys.stdout.write("Done converting %d sequences\n"%seqnum)
            in_seqs = fastaf
        elif (opts.format == 'fasta') and to_sub:
            subfile = os.path.join(opts.tmpdir, os.path.basename(in_seqs)+'.sub')
            seqnum  = subfasta(in_seqs, subfile, opts.format, opts.max_screen, seqper, opts.verbose)
            in_seqs = subfile
        # run blat
        if opts.verbose: sys.stdout.write("Running blat ... ")
        blatf = os.path.join(opts.tmpdir, os.path.basename(in_seqs)+'.blat')
        sout, serr = run_cmd(['blat', '-t=dna', '-fastMap', '-out=blast8', opts.db_adaptor, in_seqs, blatf])
        idset = rankIDs(blatf)
        if opts.verbose: sys.stdout.write("Done\n")
        # output if only screening
        if opts.screen:
            if len(idset) == 0:
                if opts.verbose: sys.stdout.write("No adapter sequences found\n")
            else:
                ohdl = open(opts.output, 'w')
                for s in idset:
                    ohdl.write("%s\t%d\n"%(s[0], s[1]))
                ohdl.close()
            os.remove(blatf)
            if in_seqs != opts.input:
                os.remove(in_seqs)
            return 0
        # end if no adapters found
        if len(idset) == 0:
            if opts.verbose: sys.stdout.write("No adapter sequences found\n")
            shutil.copyfile(opts.input, opts.output)
            if opts.rev_input and os.path.isfile(opts.rev_input) and opts.rev_output:
                shutil.copyfile(opts.rev_input, opts.rev_output)
        #found it!
        top_adapt = idset[0][0]

    # trim adapters
    cmd_str = "cutadapt -O 10 -f %s -b %s -o %s %s"%(opts.format, map_adapt[top_adapt], opts.output, opts.input)
    # trim in parallel if paired-end
    if opts.rev_input and os.path.isfile(opts.rev_input) and opts.rev_output:
        if top_adapt.startswith('Tru'):
            rev_adapt = 'TruR'
        elif top_adapt.startswith('MBL'):
            rev_adapt = 'MBLR'
        else:
            rev_adapt = top_adapt
        if opts.verbose: sys.stdout.write("Parallel Adaptor Trimming %s (%s) %s (%s) ... "%(opts.input, top_adapt, opts.rev_input, rev_adapt))
        cmd_set = [cmd_str, "cutadapt -O 10 -f %s -b %s -o %s %s"%(opts.format, map_adapt[rev_adapt], opts.rev_output, opts.rev_input)]
        ppool   = Pool(processes=2)
        log_txt = ppool.map(trim_fastq, cmd_set, 1)
    else:
        if opts.verbose: sys.stdout.write("Adaptor Trimming %s (%s) ... "%(opts.input, top_adapt))
        log_txt = [ trim_fastq(cmd_str) ]
    if opts.verbose:
        sys.stdout.write("Done\n")
        for log in log_txt:
            sys.stdout.write(log)

    # cleanup
    os.remove(blatf)
    if in_seqs != opts.input:
        os.remove(in_seqs)
    return 0

if __name__ == "__main__":
    sys.exit(main(sys.argv))


text:
// Copyright 2007-2018 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.AmazonSqsTransport.Configuration.Configuration
{
    using MassTransit.Configuration;
    using Topology;

    public interface IAmazonSqsReceiveEndpointConfiguration :
        IReceiveEndpointConfiguration,
        IAmazonSqsEndpointConfiguration
    {
        IAmazonSqsReceiveEndpointConfigurator Configurator { get; }

        IAmazonSqsBusConfiguration BusConfiguration { get; }

        IAmazonSqsHostControl Host { get; }

        bool BindMessageTopics { get; set; }

        ReceiveSettings Settings { get; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
{{ site.organizersTitle }}

            {% for organizer in site.data.organizers %}

{{ organizer.group }}

                {% for element in organizer.elements %}

                {% endfor %}

            {% endfor %}


text:
import Vue from 'vue';
import MockAdapter from 'axios-mock-adapter';
import axios from '~/lib/utils/axios_utils';
import '~/behaviors/markdown/render_gfm';
import issuableApp from '~/issue_show/components/app.vue';
import eventHub from '~/issue_show/event_hub';
import setTimeoutPromise from 'spec/helpers/set_timeout_promise_helper';
import issueShowData from '../mock_data';

function formatText(text) {
  return text.trim().replace(/\s\s+/g, ' ');
}

const REALTIME_REQUEST_STACK = [issueShowData.initialRequest, issueShowData.secondRequest];

describe('Issuable output', () => {
  let mock;
  let realtimeRequestCount = 0;
  let vm;

  beforeEach(done => {
    setFixtures(`

    `);
    spyOn(eventHub, '$emit');

    const IssuableDescriptionComponent = Vue.extend(issuableApp);

    mock = new MockAdapter(axios);
    mock.onGet('/gitlab-org/gitlab-shell/issues/9/realtime_changes/realtime_changes').reply(() => {
      const res = Promise.resolve([200, REALTIME_REQUEST_STACK[realtimeRequestCount]]);
      realtimeRequestCount += 1;
      return res;
    });

    vm = new IssuableDescriptionComponent({
      propsData: {
        canUpdate: true,
        canDestroy: true,
        endpoint: '/gitlab-org/gitlab-shell/issues/9/realtime_changes',
        updateEndpoint: gl.TEST_HOST,
        issuableRef: '#1',
        initialTitleHtml: '',
        initialTitleText: '',
        initialDescriptionHtml: 'test',
        initialDescriptionText: 'test',
        lockVersion: 1,
        markdownPreviewPath: '/',
        markdownDocsPath: '/',
        projectNamespace: '/',
        projectPath: '/',
      },
    }).$mount();

    setTimeout(done);
  });

  afterEach(() => {
    mock.restore();
    realtimeRequestCount = 0;

    vm.poll.stop();
    vm.$destroy();
  });

  it('should render a title/description/edited and update title/description/edited on update', done => {
    let editedText;
    Vue.nextTick()
      .then(() => {
        editedText = vm.$el.querySelector('.edited-text');
      })
      .then(() => {
        expect(document.querySelector('title').innerText).toContain('this is a title (#1)');
        expect(vm.$el.querySelector('.title').innerHTML).toContain('
this is a title
');
        expect(vm.$el.querySelector('.wiki').innerHTML).toContain('
this is a description!
');
        expect(vm.$el.querySelector('.js-task-list-field').value).toContain(
          'this is a description',
        );

        expect(formatText(editedText.innerText)).toMatch(/Edited[\s\S]+?by Some User/);
        expect(editedText.querySelector('.author-link').href).toMatch(/\/some_user$/);
        expect(editedText.querySelector('time')).toBeTruthy();
        expect(vm.state.lock_version).toEqual(1);
      })
      .then(() => {
        vm.poll.makeRequest();
      })
      .then(() => new Promise(resolve => setTimeout(resolve)))
      .then(() => {
        expect(document.querySelector('title').innerText).toContain('2 (#1)');
        expect(vm.$el.querySelector('.title').innerHTML).toContain('
2
');
        expect(vm.$el.querySelector('.wiki').innerHTML).toContain('
42
');
        expect(vm.$el.querySelector('.js-task-list-field').value).toContain('42');
        expect(vm.$el.querySelector('.edited-text')).toBeTruthy();
        expect(formatText(vm.$el.querySelector('.edited-text').innerText)).toMatch(
          /Edited[\s\S]+?by Other User/,
        );

        expect(editedText.querySelector('.author-link').href).toMatch(/\/other_user$/);
        expect(editedText.querySelector('time')).toBeTruthy();
        expect(vm.state.lock_version).toEqual(2);
      })
      .then(done)
      .catch(done.fail);
  });

  it('shows actions if permissions are correct', done => {
    vm.showForm = true;

    Vue.nextTick(() => {
      expect(vm.$el.querySelector('.btn')).not.toBeNull();

      done();
    });
  });

  it('does not show actions if permissions are incorrect', done => {
    vm.showForm = true;
    vm.canUpdate = false;

    Vue.nextTick(() => {
      expect(vm.$el.querySelector('.btn')).toBeNull();

      done();
    });
  });

  it('does not update formState if form is already open', done => {
    vm.openForm();

    vm.state.titleText = 'testing 123';

    vm.openForm();

    Vue.nextTick(() => {
      expect(vm.store.formState.title).not.toBe('testing 123');

      done();
    });
  });

  describe('updateIssuable', () => {
    it('fetches new data after update', done => {
      spyOn(vm, 'updateStoreState').and.callThrough();
      spyOn(vm.service, 'getData').and.callThrough();
      spyOn(vm.service, 'updateIssuable').and.returnValue(
        Promise.resolve({
          data: { web_url: window.location.pathname },
        }),
      );

      vm.updateIssuable()
        .then(() => {
          expect(vm.updateStoreState).toHaveBeenCalled();
          expect(vm.service.getData).toHaveBeenCalled();
        })
        .then(done)
        .catch(done.fail);
    });

    it('correctly updates issuable data', done => {
      spyOn(vm.service, 'updateIssuable').and.returnValue(
        Promise.resolve({
          data: { web_url: window.location.pathname },
        }),
      );

      vm.updateIssuable()
        .then(() => {
          expect(vm.service.updateIssuable).toHaveBeenCalledWith(vm.formState);
          expect(eventHub.$emit).toHaveBeenCalledWith('close.form');
        })
        .then(done)
        .catch(done.fail);
    });

    it('does not redirect if issue has not moved', done => {
      const visitUrl = spyOnDependency(issuableApp, 'visitUrl');
      spyOn(vm.service, 'updateIssuable').and.returnValue(
        Promise.resolve({
          data: {
            web_url: window.location.pathname,
            confidential: vm.isConfidential,
          },
        }),
      );

      vm.updateIssuable();

      setTimeout(() => {
        expect(visitUrl).not.toHaveBeenCalled();
        done();
      });
    });

    it('redirects if returned web_url has changed', done => {
      const visitUrl = spyOnDependency(issuableApp, 'visitUrl');
      spyOn(vm.service, 'updateIssuable').and.returnValue(
        Promise.resolve({
          data: {
            web_url: '/testing-issue-move',
            confidential: vm.isConfidential,
          },
        }),
      );

      vm.updateIssuable();

      setTimeout(() => {
        expect(visitUrl).toHaveBeenCalledWith('/testing-issue-move');
        done();
      });
    });

    describe('shows dialog when issue has unsaved changed', () => {
      it('confirms on title change', done => {
        vm.showForm = true;
        vm.state.titleText = 'title has changed';
        const e = { returnValue: null };
        vm.handleBeforeUnloadEvent(e);
        Vue.nextTick(() => {
          expect(e.returnValue).not.toBeNull();

          done();
        });
      });

      it('confirms on description change', done => {
        vm.showForm = true;
        vm.state.descriptionText = 'description has changed';
        const e = { returnValue: null };
        vm.handleBeforeUnloadEvent(e);
        Vue.nextTick(() => {
          expect(e.returnValue).not.toBeNull();

          done();
        });
      });

      it('does nothing when nothing has changed', done => {
        const e = { returnValue: null };
        vm.handleBeforeUnloadEvent(e);
        Vue.nextTick(() => {
          expect(e.returnValue).toBeNull();

          done();
        });
      });
    });

    describe('error when updating', () => {
      it('closes form on error', done => {
        spyOn(vm.service, 'updateIssuable').and.callFake(() => Promise.reject());
        vm.updateIssuable();

        setTimeout(() => {
          expect(eventHub.$emit).not.toHaveBeenCalledWith('close.form');
          expect(document.querySelector('.flash-container .flash-text').innerText.trim()).toBe(
            `Error updating issue`,
          );

          done();
        });
      });

      it('returns the correct error message for issuableType', done => {
        spyOn(vm.service, 'updateIssuable').and.callFake(() => Promise.reject());
        vm.issuableType = 'merge request';

        Vue.nextTick(() => {
          vm.updateIssuable();

          setTimeout(() => {
            expect(eventHub.$emit).not.toHaveBeenCalledWith('close.form');
            expect(document.querySelector('.flash-container .flash-text').innerText.trim()).toBe(
              `Error updating merge request`,
            );

            done();
          });
        });
      });

      it('shows error mesage from backend if exists', done => {
        const msg = 'Custom error message from backend';
        spyOn(vm.service, 'updateIssuable').and.callFake(
          // eslint-disable-next-line prefer-promise-reject-errors
          () => Promise.reject({ response: { data: { errors: [msg] } } }),
        );

        vm.updateIssuable();
        setTimeout(() => {
          expect(document.querySelector('.flash-container .flash-text').innerText.trim()).toBe(
            `${vm.defaultErrorMessage}. ${msg}`,
          );

          done();
        });
      });
    });
  });

  it('opens recaptcha modal if update rejected as spam', done => {
    function mockScriptSrc() {
      const recaptchaChild = vm.$children.find(
        // eslint-disable-next-line no-underscore-dangle
        child => child.$options._componentTag === 'recaptcha-modal',
      );

      recaptchaChild.scriptSrc = '//scriptsrc';
    }

    let modal;
    const promise = new Promise(resolve => {
      resolve({
        data: {
          recaptcha_html: '
recaptcha_html
',
        },
      });
    });

    spyOn(vm.service, 'updateIssuable').and.returnValue(promise);

    vm.canUpdate = true;
    vm.showForm = true;

    vm.$nextTick()
      .then(() => mockScriptSrc())
      .then(() => vm.updateIssuable())
      .then(promise)
      .then(() => setTimeoutPromise())
      .then(() => {
        modal = vm.$el.querySelector('.js-recaptcha-modal');

        expect(modal.style.display).not.toEqual('none');
        expect(modal.querySelector('.g-recaptcha').textContent).toEqual('recaptcha_html');
        expect(document.body.querySelector('.js-recaptcha-script').src).toMatch('//scriptsrc');
      })
      .then(() => modal.querySelector('.close').click())
      .then(() => vm.$nextTick())
      .then(() => {
        expect(modal.style.display).toEqual('none');
        expect(document.body.querySelector('.js-recaptcha-script')).toBeNull();
      })
      .then(done)
      .catch(done.fail);
  });

  describe('deleteIssuable', () => {
    it('changes URL when deleted', done => {
      const visitUrl = spyOnDependency(issuableApp, 'visitUrl');
      spyOn(vm.service, 'deleteIssuable').and.returnValue(
        Promise.resolve({
          data: {
            web_url: '/test',
          },
        }),
      );

      vm.deleteIssuable();

      setTimeout(() => {
        expect(visitUrl).toHaveBeenCalledWith('/test');

        done();
      });
    });

    it('stops polling when deleting', done => {
      spyOnDependency(issuableApp, 'visitUrl');
      spyOn(vm.poll, 'stop').and.callThrough();
      spyOn(vm.service, 'deleteIssuable').and.returnValue(
        Promise.resolve({
          data: {
            web_url: '/test',
          },
        }),
      );

      vm.deleteIssuable();

      setTimeout(() => {
        expect(vm.poll.stop).toHaveBeenCalledWith();

        done();
      });
    });

    it('closes form on error', done => {
      spyOn(vm.service, 'deleteIssuable').and.returnValue(Promise.reject());

      vm.deleteIssuable();

      setTimeout(() => {
        expect(eventHub.$emit).not.toHaveBeenCalledWith('close.form');
        expect(document.querySelector('.flash-container .flash-text').innerText.trim()).toBe(
          'Error deleting issue',
        );

        done();
      });
    });
  });

  describe('open form', () => {
    it('shows locked warning if form is open & data is different', done => {
      vm.$nextTick()
        .then(() => {
          vm.openForm();

          vm.poll.makeRequest();
        })
        // Wait for the request
        .then(vm.$nextTick)
        // Wait for the successCallback to update the store state
        .then(vm.$nextTick)
        // Wait for the new state to flow to the Vue components
        .then(vm.$nextTick)
        .then(() => {
          expect(vm.formState.lockedWarningVisible).toEqual(true);
          expect(vm.formState.lock_version).toEqual(1);
          expect(vm.$el.querySelector('.alert')).not.toBeNull();
        })
        .then(done)
        .catch(done.fail);
    });
  });

  describe('show inline edit button', () => {
    it('should not render by default', () => {
      expect(vm.$el.querySelector('.title-container .note-action-button')).toBeDefined();
    });

    it('should render if showInlineEditButton', () => {
      vm.showInlineEditButton = true;

      expect(vm.$el.querySelector('.title-container .note-action-button')).toBeDefined();
    });
  });

  describe('updateStoreState', () => {
    it('should make a request and update the state of the store', done => {
      const data = { foo: 1 };
      spyOn(vm.store, 'updateState');
      spyOn(vm.service, 'getData').and.returnValue(Promise.resolve({ data }));

      vm.updateStoreState()
        .then(() => {
          expect(vm.service.getData).toHaveBeenCalled();
          expect(vm.store.updateState).toHaveBeenCalledWith(data);
        })
        .then(done)
        .catch(done.fail);
    });

    it('should show error message if store update fails', done => {
      spyOn(vm.service, 'getData').and.returnValue(Promise.reject());
      vm.issuableType = 'merge request';

      vm.updateStoreState()
        .then(() => {
          expect(document.querySelector('.flash-container .flash-text').innerText.trim()).toBe(
            `Error updating ${vm.issuableType}`,
          );
        })
        .then(done)
        .catch(done.fail);
    });
  });
});


text:
body {color: red}

a {color: black}


text:
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}

New Label

        {# TODO: form styling #}
        {% crispy form %}

{% endblock content %}


text:
GSV6_SeriallLib module
======================

.. automodule:: GSV6_SeriallLib
    :members:
    :undoc-members:
    :show-inheritance:


text:
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows.Markup;
using BaamStudios.SharpAngie;
using DrWPF.Windows.Data;

namespace BaamStudios.SharpAngieDemo
{
    public class DemoViewModel : ViewModelBase
    {
        private string _field1;

        private string _field2;

        private DemoViewModel _child;

        private ObservableCollection<DemoViewModel> _children;

        private ObservableDictionary<string, DemoViewModel> _indexedChildren;

        public string Field1
        {
            get
            {
                return _field1;
            }
            set
            {
                SetProperty(ref _field1, value);
            }
        }

        public string Field2
        {
            get
            {
                return _field2;
            }
            set
            {
                SetProperty(ref _field2, value);
            }
        }

        public DemoViewModel Child
        {
            get
            {
                return _child;
            }
            set
            {
                SetProperty(ref _child, value);
            }
        }

        public ObservableCollection<DemoViewModel> Children
        {
            get
            {
                return _children;
            }
            set
            {
                SetProperty(ref _children, value);
            }
        }

        public ObservableDictionary<string, DemoViewModel> IndexedChildren
        {
            get
            {
                return _indexedChildren;
            }
            set
            {
                SetProperty(ref _indexedChildren, value);
            }
        }

        public void DoSomething(string param1, string param2)
        {
            Field1 = param1;
            Field2 = param2;
            if (Children == null)
            {
                Children =
                    new ObservableCollection<DemoViewModel>(new List<DemoViewModel> { new DemoViewModel { Field1 = "v3" } });
            }
            else
            {
                Children.Add(new DemoViewModel { Field1 = Children.Count.ToString() });
            }
        }
    }
}


text:
import os
import cgi
import cgitb
try:
    from configparser import SafeConfigParser
except ImportError:
    from ConfigParser import SafeConfigParser

cgitb.enable()

from GrabzIt import GrabzItClient
try:
	from configparser import SafeConfigParser
except ImportError:
	from ConfigParser import SafeConfigParser

form = cgi.FieldStorage()

message = form.getvalue("message")
customId = form.getvalue("customid")
id = form.getvalue("id")
filename = form.getvalue("filename")
format = form.getvalue("format")
targeterror = form.getvalue("targeterror")

parser = SafeConfigParser()
parser.read('config.ini')

#Custom id can be used to store user ids or whatever is needed for the later processing of the
#resulting screenshot

grabzIt = GrabzItClient.GrabzItClient(parser.get('GrabzIt', 'applicationKey'), parser.get('GrabzIt', 'applicationSecret'))
result = grabzIt.GetResult(id)

if result != None:
	#Ensure that the application has the correct rights for this directory.
	fo = open(os.path.dirname(os.path.abspath(__file__)) + os.path.sep + "results" + os.sep + filename, "wb")
	fo.write(result)
	fo.close()

print ("Content-type: text/html\n\n")


text:
/
public abstract class AbstractSniffer implements SnifferInterface {
	protected List<PacketListenerInterface> listeners;
	protected List<Integer> types;

	protected AbstractSniffer() {
		listeners = new ArrayList<PacketListenerInterface>();
		types = new ArrayList<Integer>();
	}

	public void addPacketListener(PacketListenerInterface listener) {
		if (!listeners.contains(listener)) {
			listeners.add(listener);
		}
	}

	public void removePacketListener(PacketListenerInterface listener) {
		if (listeners.contains(listener)) {
			listeners.remove(listener);
		}
	}

	protected void notifyListeners(AbstractPacketDO packet) {
		for (PacketListenerInterface listener : listeners) {
			listener.packetArrived(packet);
		}
	}
}


text:
package mortgages;

import org.switchyard.component.bean.Service;

@Service(value = IncomeAdjustment.class, name = "IncomeFix")
public class IncomeFixBean implements IncomeAdjustment {

	@Override
	public Applicant adjust(Applicant applicant) {
		double incomeFloor = applicant.getLoanAmount() / 3;
        if (applicant.getIncome() < incomeFloor) {
        	System.out.println("Adjusting income to guarantee approval");
        	applicant.setIncome(incomeFloor + 1);
        }
        return applicant;
	}

}


text:
package org.cagrid.fqp.test.remote.steps.dcql2;

import gov.nih.nci.cagrid.fqp.client.FederatedQueryProcessorClient;
import gov.nih.nci.cagrid.fqp.common.FQPConstants;
import gov.nih.nci.cagrid.fqp.stubs.types.FederatedQueryProcessingFault;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cagrid.data.dcql.DCQLQuery;
import org.cagrid.fqp.execution.QueryExecutionParameters;
import org.cagrid.fqp.execution.TargetDataServiceQueryBehavior;
import org.cagrid.fqp.test.common.UrlReplacer;
import org.cagrid.fqp.test.common.steps.dcql2.BaseDcql2QueryExecutionStep;
import org.oasis.wsrf.faults.BaseFaultType;

public class Dcql2MaxRetriesStep extends BaseDcql2QueryExecutionStep {

    public static final String[] QUERY_URL_PLACEHOLDERS = {
        "DATA_SERVICE_1", "DATA_SERVICE_2"
    };

    private static Log LOG = LogFactory.getLog(Dcql2MaxRetriesStep.class);

    private FederatedQueryProcessorClient fqpClient;
    private String[] serviceUrls;
    private int maxRetries;

    public Dcql2MaxRetriesStep(String queryFilename, String goldFilename,
        FederatedQueryProcessorClient fqpClient, String[] serviceUrls, int maxRetries) {
        super(queryFilename, goldFilename);
        this.fqpClient = fqpClient;
        this.serviceUrls = serviceUrls;
        this.maxRetries = maxRetries;
    }

    public void runStep() throws Throwable {
        // get the query set up
        LOG.debug("Testing with query " + getQueryFilename());
        DCQLQuery query = getCompletedQuery();
        testParameterizedQuery(query);
    }

    private void testParameterizedQuery(DCQLQuery query) {
        // construct parameters
        QueryExecutionParameters params = new QueryExecutionParameters();
        TargetDataServiceQueryBehavior targetBehavior = new TargetDataServiceQueryBehavior();
        targetBehavior.setFailOnFirstError(Boolean.FALSE);
        targetBehavior.setRetries(Integer.valueOf(maxRetries));
        targetBehavior.setTimeoutPerRetry(FQPConstants.DEFAULT_TARGET_QUERY_BEHAVIOR.getTimeoutPerRetry());
        params.setTargetDataServiceQueryBehavior(targetBehavior);
        try {
            fqpClient.queryAsynchronously(query, null, params);
            fail("Query accepted, despite "
                + params.getTargetDataServiceQueryBehavior().getRetries()
                + " retries setting");
        } catch (Exception ex) {
            // query processing exception expected, others not so much
            if (!(ex instanceof BaseFaultType && isFqpException((BaseFaultType) ex))) {
                ex.printStackTrace();
                fail("Unexpected exception type caught: " + ex.getClass().getSimpleName());
            }
        }
    }

    private boolean isFqpException(BaseFaultType fault) {
        if (fault instanceof FederatedQueryProcessingFault) {
            return true;
        }
        for (BaseFaultType cause : fault.getFaultCause()) {
            if (isFqpException(cause)) {
                return true;
            }
        }
        return false;
    }

    private DCQLQuery getCompletedQuery() {
        assertEquals("Unexpected number of service urls", QUERY_URL_PLACEHOLDERS.length, serviceUrls.length);
        LOG.debug("Filling placeholder URLs with real ones");
        DCQLQuery original = deserializeQuery();
        Map<String, String> urlReplacements = new HashMap<String, String>();
        for (int i = 0; i < QUERY_URL_PLACEHOLDERS.length; i++) {
            urlReplacements.put(QUERY_URL_PLACEHOLDERS[i], serviceUrls[i]);
        }
        DCQLQuery replaced = null;
        try {
            replaced = UrlReplacer.replaceUrls(original, urlReplacements);
        } catch (Exception ex) {
            ex.printStackTrace();
            fail("Unable to replace URL placeholders in DCQL 2 query: " + ex.getMessage());
        }
        return replaced;
    }
}


text:
package com.hyperaware.conference.android.dagger;

import java.util.concurrent.Executor;

public class AppExecutors {

    private final Executor computeExecutor;

    public AppExecutors(Executor computeExecutor) {
        this.computeExecutor = computeExecutor;
    }

    public Executor getComputeExecutor() {
        return computeExecutor;
    }

}


text:
package gov.nih.nci.ncicb.cadsr.qa;

import gov.nih.nci.ncicb.cadsr.bulkloader.BulkLoadProcessResult;
import gov.nih.nci.ncicb.cadsr.bulkloader.transformer.TransformerResult;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

public class BL_85_TestCase extends AbstractQATestKase {

	private static String[] XML_IP_FILES = {"/gov/nih/nci/ncicb/cadsr/qa/85_1.xml"};
	private static String dataURL = "/gov/nih/nci/ncicb/cadsr/qa/85.xls";

	public BL_85_TestCase(String name) {
		super(name, XML_IP_FILES, dataURL);
	}

	public void test85_1() {
		BulkLoadProcessResult[] results = blProcessor.process(WORKING_IN_DIR, WORKING_OUT_DIR, true);
		assertNotNull(results);
		assertTrue(results.length == 1);
		for (BulkLoadProcessResult result: results) {
			TransformerResult transformResult = result.getTransformResult();
			assertNotNull(transformResult);
			String fileName = transformResult.getInputParams().getInputFile().getName();

			assertTrue(fileName.equals("85_1.xml"));

			try {
				Connection con = getDataSource().getConnection();
				Statement st = con.createStatement();

				ResultSet rs = st.executeQuery("select * from DESIGNATIONS");
				boolean cmp = compareResultSet(rs, "DESIGNATIONS-1");
				assertTrue(cmp);

				rs = st.executeQuery("select * from REFERENCE_DOCUMENTS");
				cmp = compareResultSet(rs, "REFERENCE_DOCUMENTS-1");
				assertTrue(cmp);
			} catch (Exception e) {
				fail(e.getMessage());
			}
		}
	}

	public void test85_2() {
		try {
			XML_IP_FILES = new String[]{"/gov/nih/nci/ncicb/cadsr/qa/85_2.xml"};
			BL_85_TestCase tc = new BL_85_TestCase("");
			tc.setUp();

			BulkLoadProcessResult[] results = blProcessor.process(WORKING_IN_DIR, WORKING_OUT_DIR, true);

			assertNotNull(results);
			assertTrue(results.length == 1);

			BulkLoadProcessResult result = results[0];
			TransformerResult transformResult = result.getTransformResult();
			assertNotNull(transformResult);
			String fileName = transformResult.getInputParams().getInputFile().getName();

			assertTrue(fileName.equals("85_2.xml"));

			try {
				Connection con = getDataSource().getConnection();
				Statement st = con.createStatement();

				ResultSet rs = st.executeQuery("select * from DESIGNATIONS");
				boolean cmp = compareResultSet(rs, "DESIGNATIONS-2");
				assertTrue(cmp);

				rs = st.executeQuery("select * from REFERENCE_DOCUMENTS");
				cmp = compareResultSet(rs, "REFERENCE_DOCUMENTS-2");
				assertTrue(cmp);
			} catch (Exception e) {
				fail(e.getMessage());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void test85_3() {
		try {
			XML_IP_FILES = new String[]{"/gov/nih/nci/ncicb/cadsr/qa/85_3.xml"};
			BL_85_TestCase tc = new BL_85_TestCase("");
			tc.setUp();

			BulkLoadProcessResult[] results = blProcessor.process(WORKING_IN_DIR, WORKING_OUT_DIR, true);

			assertNotNull(results);
			assertTrue(results.length == 1);

			BulkLoadProcessResult result = results[0];
			TransformerResult transformResult = result.getTransformResult();
			assertNotNull(transformResult);
			String fileName = transformResult.getInputParams().getInputFile().getName();

			assertTrue(fileName.equals("85_3.xml"));

			try {
				Connection con = getDataSource().getConnection();
				Statement st = con.createStatement();

				ResultSet rs = st.executeQuery("select * from DESIGNATIONS");
				boolean cmp = compareResultSet(rs, "DESIGNATIONS-3");
				assertTrue(cmp);

				rs = st.executeQuery("select * from REFERENCE_DOCUMENTS");
				cmp = compareResultSet(rs, "REFERENCE_DOCUMENTS-1");
				assertTrue(cmp);

				rs = st.executeQuery("select * from AC_CSI");
				cmp = compareResultSet(rs, "AC_CSI");
				assertTrue(cmp);
			} catch (Exception e) {
				fail(e.getMessage());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


text:
require 'helper'
require 'json'

describe "Manipulate" do
  before(:each) do
    Dotide.reset!
    @connection = oauth_connection
    @connection.use test_dotide_database
  end

  describe "datastreams:" do
    before(:each) do
      @datastreams = @connection.datastreams
    end

    it 'list datastreams using query params', :vcr do
      get_request = stub_get("/#{test_dotide_database}/datastreams").
          with(:query => { :tags => 'a,b,c' },
               :headers => {
                :authorization => "Bearer #{test_dotide_access_token}"
                }).
          to_return(json_response('datastreams.json'))
      ds = @datastreams.find(tags: ['a', 'b', 'c'])
      expect(ds).to be_kind_of Array
      expect(ds.length).to eq 16
      expect(ds.first).to be_kind_of Dotide::Models::Datastream
      assert_requested get_request
    end

    it 'fetch one datastream', :vcr do
      get_request = stub_get("/#{test_dotide_database}/datastreams/loc-123456").
          with(:headers => {:authorization => "Bearer #{test_dotide_access_token}"}).
          to_return(json_response('datastream.json'))
      ds = @datastreams.find_one('loc-123456')
      expect(ds).to be_kind_of Dotide::Models::Datastream
      assert_requested get_request
    end

    it "create a datastream", :vcr do
      body = {id: 'loc-123456'}
      post_request = stub_post("/#{test_dotide_database}/datastreams").
          with(:headers => {:authorization => "Bearer #{test_dotide_access_token}"},
               :content_type => 'application/json',
               :body => body.to_json
               ).
          to_return(json_response('datastream.json'))
      ds = @datastreams.create(body)
      expect(ds).to be_kind_of Dotide::Models::Datastream
      expect(ds.persist?).to be_true
      assert_requested post_request
    end

    it "build a datastream model" do
      body = {id: 'loc-123456'}
      post_request = stub_post("/#{test_dotide_database}/datastreams").
          with(:headers => {:authorization => "Bearer #{test_dotide_access_token}"},
               :content_type => 'application/json',
               :body => body.to_json
               ).
          to_return(json_response('datastream.json'))
      ds = @datastreams.build(body)
      expect(ds).to be_kind_of Dotide::Models::Datastream
      expect(ds.persist?).to be_false
      ds.save
      expect(ds.persist?).to be_true
      assert_requested post_request
    end

    it "delete a datastream from collection", :vcr do
      delete_request = stub_delete("/#{test_dotide_database}/datastreams/loc-123456").
          with(:headers => {:authorization => "Bearer #{test_dotide_access_token}"})
      @datastreams.destroy_one('loc-123456')
      assert_requested delete_request
    end

    it "delete a datastream in model", :vcr do
      body = {id: 'loc-123456'}
      stub_post("/#{test_dotide_database}/datastreams").
          with(:headers => {:authorization => "Bearer #{test_dotide_access_token}"},
               :content_type => 'application/json',
               :body => body.to_json
               ).
          to_return(json_response('datastream.json'))
      delete_request = stub_delete("/#{test_dotide_database}/datastreams/loc-123456").
          with(:headers => {:authorization => "Bearer #{test_dotide_access_token}"})
      ds = @datastreams.create(body)
      ds.destroy
      assert_requested delete_request
    end
  end

  describe "datapoints:" do
    before(:each) do
      body = {id: 'loc-123456'}
      stub_post("/#{test_dotide_database}/datastreams").
          with(:headers => {:authorization => "Bearer #{test_dotide_access_token}"},
               :content_type => 'application/json',
               :body => body.to_json
               ).
          to_return(json_response('datastream.json'))
      datastreams = @connection.datastreams
      @datastream = datastreams.create(body)
    end

    it "list datapoints using query params", :vcr do
      get_request = stub_get("/#{test_dotide_database}/datastreams/loc-123456/datapoints").
          with(:headers => {:authorization => "Bearer #{test_dotide_access_token}"},
               :query => {:interval => 3600, :summary => 1}
               ).
          to_return(json_response('datapoints_resp.json'))
      dps = @datastream.datapoints.find(interval: 3600, summary: 1)
      expect(dps.id).to be_kind_of String
      expect(dps.options).to be_kind_of Hash
      expect(dps.summary).to be_kind_of Hash
      expect(dps.datapoints).to be_kind_of Array
      expect(dps.datapoints.length).to eq 2
      assert_requested get_request
    end

    it "create a datapoint", :vcr do
      post_request = stub_post("/#{test_dotide_database}/datastreams/loc-123456/datapoints").
          with(headers: {authorization: "Bearer #{test_dotide_access_token}"},
               content_type: 'application/json',
               body: {t: '2014-01-03T00:00:01Z', v: 10}.to_json
               ).
          to_return(headers: {content_type: 'application/json; charset=utf-8'},
                    body: {t: '2014-01-03T00:00:01Z', v: 10}.to_json,
                    status: 201
                    )
      dp = @datastream.datapoints.create(t: '2014-01-03T00:00:01Z', v: 10)
      expect(dp.t).to be_kind_of String
      expect(dp.v).to be_kind_of Integer
      assert_requested post_request
    end

    it "build a datapoint", :vcr do
      post_request = stub_post("/#{test_dotide_database}/datastreams/loc-123456/datapoints").
          with(headers: {authorization: "Bearer #{test_dotide_access_token}"},
               content_type: 'application/json',
               body: {t: '2014-01-03T00:00:01Z', v: 10}.to_json
               ).
          to_return(headers: {content_type: 'application/json; charset=utf-8'},
                    body: {t: '2014-01-03T00:00:01Z', v: 10}.to_json,
                    status: 201
                    )
      dp = @datastream.datapoints.build(t: '2014-01-03T00:00:01Z', v: 10)
      expect(dp).to be_kind_of Dotide::Models::Datapoint
      expect(dp.persist?).to be_false
      dp.save
      expect(dp.persist?).to be_true
      assert_requested post_request
    end

    it "create datapoints", :vcr do
      post_request = stub_post("/#{test_dotide_database}/datastreams/loc-123456/datapoints").
          with(headers: {authorization: "Bearer #{test_dotide_access_token}"},
               content_type: 'application/json',
               body: [{t: '2014-01-03T00:00:01Z', v: 10}, {t: '2014-01-03T00:20:01Z', v: 12}].to_json
               ).
          to_return(headers: {content_type: 'application/json; charset=utf-8'},
                    body: [{t: '2014-01-03T00:00:01Z', v: 10}, {t: '2014-01-03T00:20:01Z', v: 12}].to_json,
                    status: 201
                    )
      dps = @datastream.datapoints.create([{t: '2014-01-03T00:00:01Z', v: 10}, {t: '2014-01-03T00:20:01Z', v: 12}])
      expect(dps).to be_kind_of Array
      expect(dps.length).to eq 2
      assert_requested post_request
    end

    it "delete datapoints according query params", :vcr do
      delete_request = stub_delete("/#{test_dotide_database}/datastreams/loc-123456/datapoints").
          with(headers: {authorization: "Bearer #{test_dotide_access_token}"},
               query: {start: '2014-01-03T00:00:01Z', end: '2014-01-03T00:20:01Z'}
               )
      @datastream.datapoints.destroy_all(start: '2014-01-03T00:00:01Z', end: '2014-01-03T00:20:01Z')
      assert_requested delete_request
    end
  end
end


text:
angular.module('treehouseCourse', [])
  .controller('stageThreeCtrl', function ($scope, People) {
    $scope.people = People.get();

    $scope.newPerson = {};

    $scope.save = function (person) {
      People.save(person);
    }

    $scope.add = function (newPerson) {
      People.add(newPerson);
      $scope.newPerson = {};
    }

    $scope.remove = function (person) {
      People.remove(person);
    }
  })
  .factory('People', function () {
    var people = [];

    return {
      get: function () {
        return people;
      },
      add: function (person) {
        people.push(person);
      },
      remove: function (person) {
        people.splice(people.indexOf(person), 1)
      },
      save: function (person) {

      }
    }
  })


text:
package org.jetbrains.plugins.scala.lang.macros

import com.intellij.openapi.module.Module
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.plugins.scala.SlowTests
import org.jetbrains.plugins.scala.base.ScalaLightPlatformCodeInsightTestCaseAdapter
import org.jetbrains.plugins.scala.base.libraryLoaders.{IvyLibraryLoaderAdapter, ThirdPartyLibraryLoader}
import org.jetbrains.plugins.scala.debugger.{ScalaVersion, Scala_2_12}
import org.jetbrains.plugins.scala.lang.psi.ScalaPsiElement
import org.jetbrains.plugins.scala.lang.psi.api.statements.ScFunctionDefinition
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef.ScObject
import org.jetbrains.plugins.scala.lang.psi.types.result._
import org.jetbrains.plugins.scala.util.TestUtils
import org.junit.Assert._
import org.junit.experimental.categories.Category

@Category(Array(classOf[SlowTests]))
class MonocleLensesTest extends ScalaLightPlatformCodeInsightTestCaseAdapter {

  override implicit val version: ScalaVersion = Scala_2_12

  override protected def additionalLibraries(): Seq[ThirdPartyLibraryLoader] = {
    import MonocleLensesTest._

    Seq(MonocleCoreLoader(), MonocleMacroLoader(), MonocleGeneric())
  }

  protected def folderPath: String = TestUtils.getTestDataPath

  def doTest(text: String, methodName: String, expectedType: String): Unit = {
    val caretPos = text.indexOf("<caret>")
    configureFromFileTextAdapter("dummy.scala", text.replace("<caret>", ""))
    val exp = PsiTreeUtil.findElementOfClassAtOffset(getFileAdapter, caretPos, classOf[ScalaPsiElement], false).asInstanceOf[ScObject]
    exp.allMethods.find(_.name == methodName) match {
      case Some(x) => x.method.asInstanceOf[ScFunctionDefinition].returnType match {
        case Right(t) => assertEquals(s"${t.toString} != $expectedType", expectedType, t.toString)
        case Failure(cause) => fail(cause)
      }
      case None => fail("method not found")
    }
  }

  def testSimple(): Unit = {
    val fileText: String =
      """
        |import monocle.macros.Lenses
        |
        |object Main {
        |  @Lenses
        |  case class Person(name: String, age: Int, address: Address)
        |  @Lenses
        |  case class Address(streetNumber: Int, streetName: String)
        |
        |  object <caret>Person {
        |    import Main.Address._
        |    val john = Person("John", 23, Address(10, "High Street"))
        |    age.get(john)
        |  }
        |}
      """.stripMargin

    doTest(fileText, "age", "monocle.Lens[Main.Person, Int]")
  }

  def testTypeArgs(): Unit = {
    val fileText =
      """
        |import monocle.macros.Lenses
        |import monocle.syntax._
        |
        |object Main {
        |
        |  @Lenses
        |  case class Foo[A,B](q: Map[(A,B),Double], default: Double)
        |  object <caret>Foo {}
        |}
      """.stripMargin

    doTest(fileText, "q", "monocle.Lens[Main.Foo[A, B], Map[(A, B), Double]]")
  }

  def testRecursion(): Unit = {
    //SCL-9420
    val fileText =
      """
        |object Main {
        |import monocle.macros.Lenses
        |import A.B
        |
        |object <caret>A {
        |  type B = String
        |}
        |
        |@Lenses
        |case class A(s : B) {
        |  def blah = s.getBytes
        |}
        |}
      """.stripMargin

    doTest(fileText, "s", "monocle.Lens[Main.A, Main.A.B]")
  }
}

object MonocleLensesTest {

  private abstract class MonocleBaseLoader extends IvyLibraryLoaderAdapter {
    override val version: String = "1.4.0"
    override val vendor: String = "com.github.julien-truffaut"
  }

  private case class MonocleCoreLoader() extends MonocleBaseLoader {
    override val name: String = "monocle-core"
  }

  private case class MonocleMacroLoader() extends MonocleBaseLoader {
    override val name: String = "monocle-macro"
  }

  private case class MonocleGeneric() extends MonocleBaseLoader {
    override val name: String = "monocle-generic"
  }

}


text:
require 'redirects'
require 'invalid_rule'
require 'untestable'

class RewriteRule

  attr_accessor :possibilities, :substitution, :line

  def initialize(line, conditions = [])
    @line = line
    @conds = conditions

    self.parse line

    raise Untestable.new unless @conds.empty?
    raise InvalidRule.new unless valid?
  end

  # Parse an apache RewriteRule and transform it into a Ruby object
  def parse(line)
    match_data = /RewriteRule[ ]+([^ ]+)[ ]+([^ ]+)([ ]+\[([^ ]+)\]\n?)?$/.match(line)

    return if match_data.nil?

    @regex = match_data[1]
    @possibilities = generate_possibilities @regex
    @substitution = match_data[2]
    @substitutions = @possibilities.map do |possibility|
      ::Redirects.substitute @substitution, possibility[:substituted_data]
    end
    @flags = match_data[4].nil? ? nil : match_data[4].split(',')

  end

  def valid?
    !@regex.nil? && !@substitution.nil?
  end

  def redirection?
    !@flags.nil? && @flags.any?{ |flag| /^R/.match(flag) }
  end

  def redirects
    @substitutions.map.with_index do |substitution, i|
      request = ::Redirects.substitute(@possibilities[i][:request_uri])
      response = substitution.nil? ? request : substitution
      {
        :possibility => request,
        :substitution => response,
        :code => redirection_code(@flags)
      }
    end
  end

  def last?
    !@flags.nil? && @flags.include?('L')
  end

  private

  def generate_possibilities regex
    some = []
    base = regex.gsub(/\^|\$/,'')

    capture_regex = /\(([^)^(]+?)\)\??/
    match_data = capture_regex.match(base)
    substituted_data = []
    until match_data.nil?
      matched = match_data[1]
      if /\.\*/.match(matched)
        # Match anything -> Replace by a random string
        matched = matched.gsub('.*', generate_random_string(0, 8))
      elsif /\?$/.match(match_data[0])
        # Maybe regex -> Replace by match or by empty string
        matched = rand(2) == 0 ? matched : ''
      end

      base = base.gsub(match_data[0], matched)
      substituted_data << matched
      match_data = capture_regex.match(base)
    end

    any_regex = /(\.\*)/
    match_data = any_regex.match(base)
    until match_data.nil?
      matched = match_data[1]
      matched = matched.gsub('.*', generate_random_string(0, 8))
      base = base.gsub(match_data[0], matched)
      match_data = any_regex.match(base)
    end

    some << {
      :request_uri => "#{base}",
      :substituted_data => substituted_data
    }
  end

  # Generate a string containing downcase letters, with a random length included
  # between min and max
  def generate_random_string min, max
    (min...rand(max)).map { (97 + rand(26)).chr }.join
  end

  def redirection_code flags
    redirect_regex = /^R=?([0-9]{3})?$/
    redirect_regex.match(flags.detect { |flag| redirect_regex.match(flag) })[1] || '302'
  end
end


text:
   <meta http-equiv="X-UA-Compatible" content="IE=Edge" >
      <meta http-equiv="X-UA-Compatible" content="IE=11" >
      <meta http-equiv="X-UA-Compatible" content="IE=10" >
      <meta http-equiv="X-UA-Compatible" content="IE=9" >
      <meta http-equiv="X-UA-Compatible" content="IE=8" >
      <meta http-equiv="X-UA-Compatible" content="IE=7" >
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel = "stylesheet" type = "text/css" href="main.css"/>
<title>BeffsBrowser Home </title>

  ×
  Home
  Archives
  Support
 Current Release Feature Log
 System Requirements
License Changes as of 1.6.2

  ☰ Home

 BeffsBrowser

"A Simple but Powerful Web Browser." - Written in Vb.net by a High School Student

Download latest version 1.6.2

© 2015-2017 BeffsBrowser

BeffsBrowser is licensed under   The MIT License

  Site Created By: David Nandwa


text:
La tapera invisible
===================

Un sitio random