text:
% demo2_2temporalfilters.m
%
% Tutorial script illustrating maximum likelihood / maximally informative
% dimensions (MID) estimation for LNP model with TWO temporal filters

% initialize paths
initpaths;

datasetnum = 1;  % select: 1 (white noise) or 2 (correlated)
trainfrac = .8; % fraction of data to use for training (remainder is "test data")

% Load data divided into training and test sets
[Stim_tr,sps_tr,Stim_tst,sps_tst,RefreshRate,filts_true] = loadSimDataset(datasetnum,trainfrac);

slen_tr = size(Stim_tr,1);   % length of training stimulus / spike train
slen_tst = size(Stim_tst,1); % length of test stimulus / spike train
nsp_tr = sum(sps_tr);   % number of spikes in training set
nsp_tst = sum(sps_tst); % number of spikes in test set

%% == 2. Compute iSTAC estimator (for comparison sake)

nkt = 30; % number of time bins to use for filter
% This is important: normally would want to vary this to find optimal filter length

% Compute STA and STC
[sta,stc,rawmu,rawcov] = simpleSTC(Stim_tr,sps_tr,nkt);  % compute STA and STC

% Compute iSTAC estimator
nistacFilts = 3; % number of iSTAC filters to compute
fprintf('\nComputing iSTAC estimate\n');
[istacFilts,vals,DD] = compiSTAC(sta(:),stc,rawmu,rawcov,nistacFilts); % find iSTAC filters

% Fit iSTAC model nonlinearity using filters 1 and 2
pp_istac12 = fitNlin_expquad_ML(Stim_tr,sps_tr,istacFilts(:,1:2),RefreshRate); % LNP model struct

% Compute training and test log-likelihood
LListac12_tr = logli_LNP(pp_istac12,Stim_tr,sps_tr); % training log-likelihood
LListac12_tst = logli_LNP(pp_istac12,Stim_tst,sps_tst); % test log-likelihood

% Fit iSTAC model nonlinearity using filters 2 and 3
pp_istac23 = fitNlin_expquad_ML(Stim_tr,sps_tr,istacFilts(:,2:3),RefreshRate); % LNP model struct

% Compute training and test log-likelihood
LListac23_tr = logli_LNP(pp_istac23,Stim_tr,sps_tr); % training log-likelihood
LListac23_tst = logli_LNP(pp_istac23,Stim_tst,sps_tst); % test log-likelihood

% -----  Visualize filters and 2D nonlinearity for both models ---------------------
[xgrd12,ygrd12,nlvals12] = compNlin_2D(pp_istac12.k,pp_istac12.nlfun,Stim_tr); % compute gridded 2D nonlinearity
[xgrd23,ygrd23,nlvals23] = compNlin_2D(pp_istac23.k,pp_istac23.nlfun,Stim_tr); % compute gridded 2D nonlinearity

subplot(241);
tt = -nkt+1:0;
plot(tt,filts_true,'k--',tt,istacFilts(:,1:2),'linewidth',2);
axis tight; title('istac Filters 1 & 2');
xlabel('time before spike (bins)');

subplot(245);
mesh(xgrd12,ygrd12,nlvals12);
zlm = [0 max(nlvals12(:))*1.01];
axis tight; set(gca,'zlim',zlm);
xlabel('filter 1 axis');ylabel('filter 2 axis');
zlabel('spike rate (sps/sec)'); title('2D iSTAC nonlinearity: filts 1 & 2')

subplot(242);
plot(tt,filts_true,'k--',tt,istacFilts(:,2:3),'linewidth',2);
axis tight; title('istac Filters 2 & 3');

subplot(246); mesh(xgrd23,ygrd23,nlvals23);
axis tight; set(gca,'zlim',zlm);
xlabel('filter 2 axis');ylabel('filter 3 axis');
title('2D iSTAC nonlinearity: filts 2 & 3')

%% == 3. Set up temporal basis for stimulus filters (for ML / MID estimators)

pp0 = makeFittingStruct_LNP(istacFilts(:,1),RefreshRate); % initialize param struct

% == Set up temporal basis for representing filters (see demo 1 more detail)  ====
% (try changing these params until basis can accurately represent STA).
ktbasprs.neye = 0; % number of "identity"-like basis vectors
ktbasprs.ncos = 10; % number of raised cosine basis vectors
ktbasprs.kpeaks = [0 nkt/2+4]; % location of 1st and last basis vector bump
ktbasprs.b = 5; % determines how nonlinearly to stretch basis (higher => more linear)
[ktbas, ktbasis] = makeBasis_StimKernel(ktbasprs, nkt); % make basis
filtprs_basis = (ktbas'*ktbas)\(ktbas'*sta);  % filter represented in new basis
sta_basis = ktbas*filtprs_basis;

% Insert filter basis into fitting struct
pp0.k = sta_basis; % insert sta filter
pp0.kt = filtprs_basis; % filter coefficients (in temporal basis)
pp0.ktbas = ktbas; % temporal basis
pp0.ktbasprs = ktbasprs;  % parameters that define the temporal basis

%% == 4. ML/MID 1:  ML estimator for LNP with CBF (cylindrical basis func) nonlinearity

nfilts = 2; % number of filters to recover

% Set parameters for cylindrical basis funcs (CBFs) and initialize fit
fstructCBF.nfuncs = 5; % number of basis functions for nonlinearity
fstructCBF.epprob = [.01, 0.99]; % cumulative probability outside outermost basis function peaks
fstructCBF.nloutfun = @logexp1;  % log(1+exp(x)) % nonlinear stretching function
fstructCBF.nlfuntype = 'cbf';

% Fit the model (iteratively adding one filter at a time)
[ppcbf,negLcbf] = fitLNP_multifiltsCBF_ML(pp0,Stim_tr,sps_tr,nfilts,fstructCBF,istacFilts);

% Compute test log-likelihood
LLcbf_tr = logli_LNP(ppcbf,Stim_tr,sps_tr); % training log-likelihood
LLcbf_tst = logli_LNP(ppcbf,Stim_tst,sps_tst); % test log-likelihood

% Compute gridded nonlinearity (for plotting purposes)
[xcbf,ycbf,nlcbf] = compNlin_2D(ppcbf.k,ppcbf.nlfun,Stim_tr); % compute gridded 2D nonlinearity

% Plot filters and nonlinearity
subplot(243);  % Plot filters
plot(tt,filts_true,'k--',tt,squeeze(ppcbf.k),'linewidth',2);
axis tight; title('ML-cbf filters');
subplot(247); mesh(xcbf,ycbf,nlcbf);
axis tight; set(gca,'zlim',zlm);
xlabel('filter 1 axis');ylabel('filter 2 axis');
zlabel('spike rate (sps/sec)'); title('2D cbf nonlinearity');

%% == 5. ML / MID 2:  ML estimator for LNP with RBF (radial basis func) nonlinearity

% Set parameters for cylindrical basis funcs (CBFs) and initialize fit
fstructRBF.nfuncs = 3; % number of basis functions for nonlinearity
fstructRBF.epprob = [.01, 0.99]; % cumulative probability outside outermost basis function peaks
fstructRBF.nloutfun = @logexp1;  % log(1+exp(x)) % nonlinear stretching function
fstructRBF.nlfuntype = 'rbf';

% Fit the model (iteratively adding one filter at a time)
[pprbf,negLrbf] = fitLNP_multifiltsRBF_ML(pp0,Stim_tr,sps_tr,nfilts,fstructRBF,istacFilts);

% Compute test log-likelihood
LLrbf_tr = logli_LNP(pprbf,Stim_tr,sps_tr); % training log-likelihood
LLrbf_tst = logli_LNP(pprbf,Stim_tst,sps_tst); % test log-likelihood

% Compute gridded nonlinearity (for plotting purposes)
[xrbf,yrbf,nlrbf] = compNlin_2D(pprbf.k,pprbf.nlfun,Stim_tr); % compute gridded 2D nonlinearity

% Plot filters and nonlinearity
subplot(244);  % Plot filters
plot(tt,filts_true,'k--',tt,squeeze(pprbf.k),'linewidth',2);
axis tight; title('ML-rbf filters');
subplot(248); mesh(xrbf,yrbf,nlrbf);
axis tight; set(gca,'zlim',zlm);
xlabel('filter 1 axis');ylabel('filter 2 axis');
zlabel('spike rate (sps/sec)'); title('2D rbf nonlinearity');

%% 6. ==== Compute training and test performance in bits/spike =====

% ==== report R2 error in reconstructing first two filters =====
ktrue = filts_true(:,1:2); % true filters
kmse = sum((ktrue(:)-mean(ktrue(:))).^2); % mse of these two filters around mean
ferr = @(k)(ktrue-k*(k\ktrue)); % error in optimal R2 reconstruction of ktrue
fRsq = @(k)(1-sum(sum(ferr(k).^2))/kmse); % R-squared

Rsqvals = [fRsq(istacFilts(:,1:2)),fRsq(istacFilts(:,2:3)),fRsq(squeeze(ppcbf.k)),fRsq(squeeze(pprbf.k))];

fprintf('\n=========== RESULTS ======================================\n');
fprintf('\nFilter R^2:\n------------\n');
fprintf('istac-12:%.2f  istac-23:%.2f  cbf:%.2f rbf:%.2f\n',Rsqvals);

% ====== Compute log-likelihood / single-spike information ==========

% Compute log-likelihood of constant rate (homogeneous Poisson) model
muspike_tr = nsp_tr/slen_tr;    % mean number of spikes / bin, training set
muspike_tst = nsp_tst/slen_tst; % mean number of spikes / bin, test set
LL0_tr =   nsp_tr*log(muspike_tr) - slen_tr*muspike_tr; % log-likelihood, training data
LL0_tst = nsp_tst*log(muspike_tst) - slen_tst*muspike_tst; % log-likelihood test data

% Functions to compute single-spike informations
f1 = @(x)((x-LL0_tr)/nsp_tr/log(2)); % compute training single-spike info
f2 = @(x)((x-LL0_tst)/nsp_tst/log(2)); % compute test single-spike info
% (Divide by log 2 to get 'bits' instead of 'nats')

SSinfo_tr = [f1(LListac12_tr), f1(LListac23_tr), f1(LLcbf_tr) f1(LLrbf_tr)];
SSinfo_tst = [f2(LListac12_tst),f2(LListac23_tst), f2(LLcbf_tst) f2(LLrbf_tst)];

fprintf('\nSingle-spike information (bits/spike):\n');
fprintf('------------------------------------- \n');
fprintf('Train: istac-12: %.2f  istac-23: %.2f  cbf:%.2f  rbf:%.2f\n', SSinfo_tr);
fprintf('Test:  istac-12: %.2f  istac-23: %.2f  cbf:%.2f  rbf:%.2f\n', SSinfo_tst);


text:
package errdefs

import (
	"context"
	"testing"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	"github.com/pkg/errors"
)

func TestGRPCRoundTrip(t *testing.T) {
	errShouldLeaveAlone := errors.New("unknown to package")

	for _, testcase := range []struct {
		input error
		cause error
		str   string
	}{
		{
			input: ErrAlreadyExists,
			cause: ErrAlreadyExists,
		},
		{
			input: ErrNotFound,
			cause: ErrNotFound,
		},
		{
			input: errors.Wrapf(ErrFailedPrecondition, "test test test"),
			cause: ErrFailedPrecondition,
			str:   "test test test: failed precondition",
		},
		{
			input: status.Errorf(codes.Unavailable, "should be not available"),
			cause: ErrUnavailable,
			str:   "should be not available: unavailable",
		},
		{
			input: errShouldLeaveAlone,
			cause: ErrUnknown,
			str:   errShouldLeaveAlone.Error() + ": " + ErrUnknown.Error(),
		},
		{
			input: context.Canceled,
			cause: context.Canceled,
			str:   "context canceled",
		},
		{
			input: errors.Wrapf(context.Canceled, "this is a test cancel"),
			cause: context.Canceled,
			str:   "this is a test cancel: context canceled",
		},
		{
			input: context.DeadlineExceeded,
			cause: context.DeadlineExceeded,
			str:   "context deadline exceeded",
		},
		{
			input: errors.Wrapf(context.DeadlineExceeded, "this is a test deadline exceeded"),
			cause: context.DeadlineExceeded,
			str:   "this is a test deadline exceeded: context deadline exceeded",
		},
	} {
		t.Run(testcase.input.Error(), func(t *testing.T) {
			t.Logf("input: %v", testcase.input)
			gerr := ToGRPC(testcase.input)
			t.Logf("grpc: %v", gerr)
			ferr := FromGRPC(gerr)
			t.Logf("recovered: %v", ferr)

			if errors.Cause(ferr) != testcase.cause {
				t.Fatalf("unexpected cause: %v != %v", errors.Cause(ferr), testcase.cause)
			}
			if !errors.Is(ferr, testcase.cause) {
				t.Fatalf("unexpected cause: !errors.Is(%v, %v)", ferr, testcase.cause)
			}

			expected := testcase.str
			if expected == "" {
				expected = testcase.cause.Error()
			}
			if ferr.Error() != expected {
				t.Fatalf("unexpected string: %q != %q", ferr.Error(), expected)
			}
		})
	}

}

redpajama_set_name: RedPajamaGithub


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

      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      <title>IL-25 drives remodelling in allergic airways disease induced by house dust mite -- Gregory et al. 68 (1): 82 -- Thorax </title>
      <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
      <meta name="googlebot" content="NOODP" />
      <meta name="HW.ad-path" content="/cgi/content/abstract/68/1/82" />
      <meta content="Open access; Asthma; Inflammation; Pulmonary eosinophilia"
            name="DC.subject" />
      <link rel="shortcut icon" href="/favicon.ico" />
      <link rel="alternate" type="application/rss+xml" title="RSS feed of current issue"
            href="/rss/current.xml" />
      <link rel="alternate" type="application/rss+xml" title="RSS feed of online first"
            href="/rss/ahead.xml" />
      <link rel="alternate" type="application/rss+xml" title="RSS feed of recent issue"
            href="/rss/recent.xml" />
      <link rel="alternate" type="application/rss+xml"
            title="RSS feed of most frequently read articles"
            href="/rss/mfr.xml" />
      <link rel="alternate" type="application/rss+xml"
            title="RSS feed of most frequently cited articles"
            href="/rss/mfc.xml" />
      <link rel="alternate" type="application/rss+xml" title="RSS feed of Thorax podcast"
            href="http://podcasts.bmj.com/thorax/feed/" />
      <meta content="/thoraxjnl/68/1/82.atom" name="HW.identifier" />
      <meta name="DC.Format" content="text/html" />
      <meta name="DC.Language" content="en" />
      <meta content="IL-25 drives remodelling in allergic airways disease induced by house dust mite"
            name="DC.Title" />
      <meta content="10.1136/thoraxjnl-2012-202003" name="DC.Identifier" />
      <meta content="2013-01-01" name="DC.Date" />
      <meta content="BMJ Publishing Group Ltd and British Thoracic Society"
            name="DC.Publisher" />
      <meta content="Lisa G Gregory" name="DC.Contributor" />
      <meta content="Carla P Jones" name="DC.Contributor" />
      <meta content="Simone A Walker" name="DC.Contributor" />
      <meta content="Devika Sawant" name="DC.Contributor" />
      <meta content="Kate H C Gowers" name="DC.Contributor" />
      <meta content="Gaynor A Campbell" name="DC.Contributor" />
      <meta content="Andrew N J McKenzie" name="DC.Contributor" />
      <meta content="Clare M Lloyd" name="DC.Contributor" />
      <meta content="Thorax" name="citation_journal_title" />
      <meta content="Thorax" name="citation_journal_abbrev" />
      <meta content="" name="citation_issn" />
      <meta content="1468-3296" name="citation_issn" />
      <meta name="citation_author" content="Lisa G Gregory" />
      <meta name="citation_author_institution"
            content="1Leukocyte Biology Section, National Heart and Lung Institute, Imperial College London, London, UK" />
      <meta name="citation_author" content="Carla P Jones" />
      <meta name="citation_author_institution"
            content="1Leukocyte Biology Section, National Heart and Lung Institute, Imperial College London, London, UK" />
      <meta name="citation_author" content="Simone A Walker" />
      <meta name="citation_author_institution"
            content="1Leukocyte Biology Section, National Heart and Lung Institute, Imperial College London, London, UK" />
      <meta name="citation_author" content="Devika Sawant" />
      <meta name="citation_author_institution"
            content="1Leukocyte Biology Section, National Heart and Lung Institute, Imperial College London, London, UK" />
      <meta name="citation_author" content="Kate H C Gowers" />
      <meta name="citation_author_institution"
            content="1Leukocyte Biology Section, National Heart and Lung Institute, Imperial College London, London, UK" />
      <meta name="citation_author" content="Gaynor A Campbell" />
      <meta name="citation_author_institution"
            content="1Leukocyte Biology Section, National Heart and Lung Institute, Imperial College London, London, UK" />
      <meta name="citation_author" content="Andrew N J McKenzie" />
      <meta name="citation_author_institution"
            content="2MRC Laboratory of Molecular Biology, Cambridge, UK" />
      <meta name="citation_author" content="Clare M Lloyd" />
      <meta name="citation_author_institution"
            content="1Leukocyte Biology Section, National Heart and Lung Institute, Imperial College London, London, UK" />
      <meta content="IL-25 drives remodelling in allergic airways disease induced by house dust mite"
            name="citation_title" />
      <meta content="01/01/2013" name="citation_date" />
      <meta content="68" name="citation_volume" />
      <meta content="1" name="citation_issue" />
      <meta content="82" name="citation_firstpage" />
      <meta content="90" name="citation_lastpage" />
      <meta content="68/1/82" name="citation_id" />
      <meta content="68/1/82" name="citation_id_from_sass_path" />
      <meta content="thoraxjnl;68/1/82" name="citation_mjid" />
      <meta content="10.1136/thoraxjnl-2012-202003" name="citation_doi" />
      <meta content="http://thorax.bmj.com/content/68/1/82.abstract"
            name="citation_abstract_html_url" />
      <meta content="http://thorax.bmj.com/content/68/1/82.full"
            name="citation_fulltext_html_url" />
      <meta content="http://thorax.bmj.com/content/68/1/82.full.pdf"
            name="citation_pdf_url" />
      <meta content="http://thorax.bmj.com/content/68/1/82" name="citation_public_url" />
      <meta content="23093652" name="citation_pmid" />
      <meta name="citation_access" content="all" />
      <meta name="citation_fulltext_world_readable" content="" />
      <meta name="citation_section" content="Respiratory research" />
      <meta name="robots" content="noarchive" />
      <link href="/content/68/1/76.short" rel="prev" />
      <link href="/content/68/1/91.short" rel="next" />
      <link rel="stylesheet" type="text/css" media="all" href="/shared/css/hw-global.css" />
      <link rel="stylesheet" type="text/css" media="print" href="/shared/css/hw-print.css" />
      <link rel="stylesheet" type="text/css" media="all"
            href="http://journals.bmj.com/site/bmj-global-nav/css/bmj-group-reset.css" />
      <link rel="stylesheet" type="text/css" media="all"
            href="http://journals.bmj.com/site/bmj-global-nav/css/bmj-group-grid.css" />
      <link rel="stylesheet" type="text/css" media="all"
            href="http://journals.bmj.com/site/bmj-global-nav/css/bmj-group-global-nav.css" />
      <link rel="stylesheet" type="text/css" media="all"
            href="http://eso-cdn.resources.bmj.com/repository/css/global.css" />
      <link rel="stylesheet" type="text/css" media="all"
            href="/publisher/css/hw-publisher-global.css" />
      <link rel="stylesheet" type="text/css" media="all"
            href="http://journals.bmj.com/site/shared/import.css" />
      <link rel="stylesheet" type="text/css" media="all"
            href="http://journals.bmj.com/site/shared/bmj_import.css" />
      <link rel="stylesheet" type="text/css" media="all"
            href="/shared/css/hw-page-content.css" />
      <link rel="stylesheet" type="text/css" media="all"
            href="/shared/css/jquery.fancybox-1.3.4.css" />
      <link rel="stylesheet" type="text/css" media="all"
            href="/publisher/css/hw-publisher-page-content.css" />
      <link rel="stylesheet" type="text/css" media="all"
            href="http://journals.bmj.com/site/shared/bmj_override.css" />
      <link rel="stylesheet" type="text/css" media="all" href="/site/css/local_styles.css" />

                           Menu

                                 Search BMJ Group

                                 <form method="get" enctype="application/x-www-form-urlencoded" class="search"
                                       id="global-header-search"
                                       action="http://group-search.bmj.com">
                                    <fieldset>Search BMJ Group<input type="text" class="text" id="groupSearchGadget" accesskey="/" name="query"
                                              title="Search"
                                              value="Search BMJ Group" /><input type="hidden" name="startRecord" value="1" /><input type="hidden" name="maximumRecords" value="10" /><input type="hidden" name="prod" value="all" /> <input type="submit" class="button" value="Submit" />
                                    </fieldset>
                                 </form>

                                 Journals

                                 Jobs

                                 Education

                                 Decision support

                                 Quality improvement

                                 Community

                                 BMJ

                                    From trainee to consultant, BMJ Group offers doctors around the world tailored information, special events, learning resources
                                    and recruitment services at every step along their career path.

                                    ... by doctors, for doctors, for patients

                                    About BMJ Group

                                    Customer Service

                                    Subscriptions & Sales

                                    Working for BMJ Group

                                    BMJ Group Media Centre

                                    BMJ Group Awards

                                    Advertising & Sponsorship

                                    Rights & Licensing

                                    Affinity & Society Publishing

                                    Online learning

                                       BMJ Learning

                                       High-quality CME / CPD for doctors and other healthcare professionals. BMJ Learning features hundreds of accredited, peer-reviewed
                                       learning modules in text, video, and audio formats. Find out more

                                    Courses and Qualifications

                                       BMJ Masterclasses

                                       BMJ Masterclasses, led by experts, help clinicians to use the latest evidence and recent guidelines in practice and meet their
                                       CPD/CME requirements. Find out more

                                    Exam Preparation

                                       The leading provider of online exam preparation, helping over 167,000 healthcare professionals to pass their exams. Find out more

                                    BMJ Learning

                                    BMJ Portfolio

                                    BMJ Masterclasses

                                    Clinical Leadership Programme

                                    Diabetes Qualifications and Courses

                                    onExamination

                              Decision support and clinical reference

                                    BMJ Evidence Centre

                                    The BMJ Evidence Centre builds evidence into practice, to support improvements in the consistency and quality of health care.

                                    Best Practice

                                    Clinical Evidence

                                    Evidence Updates

                                    Best Health

                                    Action Sets

                                    Informatica Systems

                                    Informatica Systems delivers performance management systems and innovative software solutions to primary care. Learn more

                                       Audit +

                                       Contract +

                                       Health Checks

                                       FrontDesk

                              BMJ Quality

                                    The latest news, research, events, opinion and guidance related to quality and safety in health care.

                                    Attend the BMJ Careers Fair at the Business Design Centre, London. Find out more

                                    BMJ Quality

                                    BMJ Quality and Safety

                                    International Forum on Quality and Safety in Healthcare

                                    BMJ

                                    The flagship general medical journal, published since 1840, updated daily online, weekly in print and on the iPad.

                                    BMJ

                                    BMJ Journals

                                    BMJ Journals division publishes over 40 journals across a broad range of specialties.

                                    BMJ Journals

                                    studentBMJ

                                    An international medical journal written for students by students.

                                    Student BMJ

                              Jobs

                                    BMJ Careers

                                    BMJ Careers makes it easy for you to find the right job with the latest healthcare vacancies, upcoming careers fairs, advice
                                    on choosing the right specialty, pay and working conditions.

                                    18-19 October 2013 at the Business Design Centre in Islington, London. Register here

                                    BMJ Careers

                                    Jobs and vacancies at BMJ Group

                                    BMJ Careers Fair

                              Community

                                    Join the discussions on our community site doc2doc or our social pages

                                    ... by doctors, for doctors, for patients

                                    We are open for entries!

                                    doc2doc

                                    Follow BMJ Group on Twitter

                                    BMJ Group on Facebook

                                    BMJ Group Awards

                        <form id="searchform" name="searchform" action="/search" method="get">
                           <fieldset>Search this site<input value="" type="text" name="fulltext" id="header-qs-input" maxlength="255"
                                     size="20"
                                     class="text" /><input type="hidden" name="submit" value="yes" /><input type="image" class="button" value="go"
                                     src="http://group.bmj.com/bmjpg/images/icon-search.gif" /></fieldset>
                        </form>

 Advanced search

                           An international peer-reviewed journal for health professionals in all aspects of respiratory medicine

Online First

Current issue

Archive

About the journal

                        Submit a paper

                           Subscribe

Help

Online First

Current issue

Archive

                                 Supplements

                                 Topic collections

                                 Images in Thorax

                                 RSS

Home

 > Volume 68, Issue 1

 > Article

                                    <nlm:abbrev-journal-title xmlns:nlm="http://schema.highwire.org/NLM/Journal" abbrev-type="publisher">Thorax</nlm:abbrev-journal-title>

                              2013;68:82-90

                                 doi:10.1136/thoraxjnl-2012-202003

Respiratory research

IL-25 drives remodelling in allergic airways disease induced by house dust mite

Lisa G Gregory1,

Carla P Jones1,

Simone A Walker1,

Devika Sawant1,

Kate H C Gowers1,

Gaynor A Campbell1,

Andrew N J McKenzie2,

Clare M Lloyd1

<address>1Leukocyte Biology Section, National Heart and Lung Institute, Imperial College London, London, UK
                                    </address>

<address>2MRC Laboratory of Molecular Biology, Cambridge, UK
                                    </address>

Correspondence to Professor Clare M Lloyd, National Heart and Lung Institute, Imperial College, South Kensington, London SW7 2AZ, UK; c.lloyd{at}imperial.ac.uk

Received 11 April 2012

Revised 21 August 2012

Accepted 10 September 2012

Published Online First 23 October 2012

Abstract

Background Overexpression of the transforming growth factor β family signalling molecule smad2 in the airway epithelium provokes enhanced
                                    allergen-induced airway remodelling in mice, concomitant with elevated levels of interleukin (IL)-25.

Objective We investigated whether IL-25 plays an active role in driving this airway remodelling.

Methods Anti-IL-25 antibody was given to mice exposed to either inhaled house dust mite (HDM) alone, or in conjunction with an adenoviral
                                    smad2 vector which promotes an enhanced remodelling phenotype.

Results Blocking IL-25 in allergen-exposed mice resulted in a moderate reduction in pulmonary eosinophilia and levels of T helper
                                    type 2 associated cytokines, IL-5 and IL-13. In addition, IL-25 neutralisation abrogated peribronchial collagen deposition,
                                    airway smooth muscle hyperplasia and airway hyperreactivity in control mice exposed to HDM and smad2-overexpressing mice.
                                    IL-25 was shown to act directly on human fibroblasts to induce collagen secretion. Recruitment of endothelial progenitor cells
                                    to the lung and subsequent neovascularisation was also IL-25 dependent, demonstrating a direct role for IL-25 during angiogenesis
                                    in vivo. Moreover, the secretion of innate epithelial derived cytokines IL-33 and thymic stromal lymphopoietin (TSLP) was
                                    completely ablated.

Conclusions In addition to modulating acute inflammation, we now demonstrate a role for IL-25 in orchestrating airway remodelling. IL-25
                                    also drives IL-33 and TSLP production in the lung. These data delineate a wider role for IL-25 in mediating structural changes
                                    to the lung following allergen exposure and implicate IL-25 as a novel therapeutic target for the treatment of airway remodelling
                                    in asthma.

Airway Epithelium

Allergic lung disease

Asthma

Asthma Mechanisms

This is an open-access article distributed under the terms of the Creative Commons Attribution Non-commercial License, which
                                 permits use, distribution, and reproduction in any medium, provided the original work is properly cited, the use is non commercial
                                 and is otherwise in compliance with the license. See: http://creativecommons.org/licenses/by-nc/3.0/ and http://creativecommons.org/licenses/by-nc/3.0/legalcode

CiteULike

Delicious

Digg

Facebook

Google+

Mendeley

Reddit

Technorati

Twitter

What's this?

This Article

Abstract

Full text

PDF

Web Only Data

All Versions of this Article:

thoraxjnl-2012-202003v1

68/1/82 most recent

Services

                                          Email this link to a friend

Alert me when this article is cited

Alert me if a correction is posted

                                          		Article Usage Statistics

Similar articles in this journal

Similar articles in Web of Science

Similar articles in PubMed

Add article to my folders

Download to citation manager

<a class="request-permissions"
                                          href="https://s100.copyright.com/AppDispatchServlet?publisherName=BMJ&publication=thoraxjnl&title=IL-25%20drives%20remodelling%20in%20allergic%20airways%20disease%20induced%20by%20house%20dust%20mite&publicationDate=01%2F01%2F2013&author=Lisa%20G%20Gregory%2C%20Carla%20P%20Jones%2C%20Simone%20A%20Walker%2C%20Devika%20Sawant%2C%20Kate%20H%20C%20Gowers%2C%20Gaynor%20A%20Campbell%2C%20Andrew%20N%20J%20McKenzie%2C%20Clare%20M%20Lloyd&contentID=10.1136%2Fthoraxjnl-2012-202003&volumeNum=68&issueNum=1&startPage=82&endPage=90&copyright=British%20Medical%20Journal%20Publishing%20Group&of=n&oa=y&orderBeanReset=true">Request permissions

                                          Add to portfolio

Citing articles

Load citing article information

Citing articles via Web of Science

Citing articles via Scopus

Citing articles via Google Scholar

Google Scholar

Articles by  Gregory, L. G.

Articles by  Lloyd, C. M.

Search for related content

PubMed

PubMed citation

Articles by  Gregory, L. G.

Articles by  Lloyd, C. M.

Related Content

Open access

Asthma

Inflammation

Pulmonary eosinophilia

Load related web page information

Social bookmarking

CiteULike

Delicious

Digg

Facebook

Google+

Mendeley

Reddit

Technorati

Twitter

What's this?

                                       Current

                                       Podcasts

                                       Online first

                                 Free sample

                                 				This recent issue is free to all users to allow everyone the opportunity to see the full scope and typical content of
                                 Thorax.

                                 View free sample issue >>

                                 				Don't forget to sign up for content alerts so you keep up to date with all the articles as they are published.

Navigate This Article

Top

Abstract

                              Online First
                              : Online First

                              Current issue
                              : Current issue | Mobile site

                              Archive
                              : Supplements | Topic collections | Images in Thorax | RSS

                              About the journal
                              : About the journal | Editorial board | Instructions for authors | Open Access

                                                              Thank you to our reviewers | Most read articles

                              Submit a paper
                              : Online submission site | Instructions for authors |  Open Access | Track your article

                              Subscribe
                              : Subscribe to the journal | Prices | Email alerts

                              Help
                              : Contact us | Feedback form | Reprints | Permissions | Advertising

                           Subscribe here

                           Activate your subscription

                        <form action="/login" method="post">

                               User Name
                              <input id="username" name="username" value="Type username here" type="text"
                                     class="text"
                                     onclick="if(this.value=='Type username here'){this.value=''}" />

                              Password
                              <input id="password" name="code" value="Password" type="password" class="text"
                                     onfocus="if(this.value == 'Password'){this.value=''}" />

                              <input type="image"
                                     src="http://eso-cdn.resources.bmj.com/repository/images/icon-sign-in.gif" />

                              <input id="rememberme" name="rememberme" type="checkbox" value="true" />
                              Remember me.

Forgot your sign in details?
<input value="http://thorax.bmj.com/content/68/1/82" name="uri" type="hidden" /></form>

                              Login via OpenAthens

                              Login via your home organisation

Recommend to your Institution

                                  email alerts

Register to receive email alerts

                                   twitter

                                  face-

                                 book

                                  my folders

                                  Pod-

                                 casts

                                  Library recom-

                                 mend

                              Impact Factor: 8.376

                           				Latest respiratory medicine jobs

                           Latest respiratory medicine jobs

                           Show me all respiratory medicine jobs >>

                  Online ISSN
                  1468-3296

                        Contact us

                        Website terms & conditions

                        Privacy and Cookies

                        Revenue sources

                        Home

                        Top

                           Copyright © 2014  BMJ Publishing Group Ltd & British Thoracic Society. All rights reserved.

                         BMJ


text:
package br.com.objectos.core.logging;

import static org.testng.Assert.assertEquals;

import org.testng.annotations.Test;

public class LevelTest {

  @Test
  public void orderingTest() {
    Level[] values;
    values = Level.values();

    assertEquals(values.length, 5);

    assertEquals(values[0], Level.TRACE);

    assertEquals(values[1], Level.DEBUG);

    assertEquals(values[2], Level.INFO);

    assertEquals(values[3], Level.WARN);

    assertEquals(values[4], Level.ERROR);
  }

}


text:
<?php
/**
 * PHPMinion
 *
 * A suite of tools to facilitate development and debugging.
 *
 * @package     PHPMinion
 * @author      Evan Johnson
 * @created     October 9, 2015
 * @version     0.1
 */

namespace PHPMinion\Utilities\EntityAnalyzer\Models;

/**
 * Interface DataModelInterface
 *
 * All DataTypeModel entities must implement this
 */
interface DataModelInterface
{

    /**
     * Sets a value for the data model
     *
     * @param mixed $value
     */
    public function setValue($value);

}


text:
import flask.ext.restless
import flask.ext.sqlalchemy
import datetime

app = flask.Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = flask.ext.sqlalchemy.SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=False)
    email = db.Column(db.String(120), unique=False)

    def __init__(self, username, email):
        self.username = username
        self.email = email

    def __repr__(self):
        return '<User %r>' % self.username

# db.create_all()
# admin = User('admin', 'admin@example.com')
# guest = User('guest', 'guest@example.com')
# db.session.add(admin)
# db.session.add(guest)
# db.session.commit()

manager = flask.ext.restless.APIManager(app, flask_sqlalchemy_db=db)

manager.create_api(User,
                   methods=['GET', 'POST', 'DELETE', 'PUT'], results_per_page=20)

app.run()


text:
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
using System.Net;
using ITCC.HTTP.SslConfigUtil.Core.Enums;

namespace ITCC.HTTP.SslConfigUtil.Core.Utils
{
    internal class ParseParamsResult
    {
        public ParseBaseParamsStatus Status { get; set; }
        public string Reason { get; set; }
        public string AssemblyGuid { get; set; }
        public IPAddress IpAddress { get; set; }
        public ushort Port { get; set; }
    }
}


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

        <title>test video</title>

            <time itemprop="datePublished" datetime="2014-10-09T12:06:16">9 octobre 2014 à 12:06</time>

            TextNode 1 - The Scala supported IDE is one of the few pain points of developers who want to start using Scala in their Java project. On existing long term project developed by a team its hard to step in and introduce a new language that is not supported by the existing IDE. On way to go about it is to hid the fact that you use Scala from the Java world by using one way dependency injection. Still, if you wish to truly absorb Scala into your existing java environment then you'll soon introduced cross language dependencies.


text:
module RevisingJob

# package code goes here

end # module


text:
import {OrderedSet, Map, MapWithDefault} from "ember-metal/map";

var object, number, string, map;

var varieties = [['Map', Map], ['MapWithDefault', MapWithDefault]], variety;

function testMap(nameAndFunc) {
  variety = nameAndFunc[0];

  module("Ember." + variety + " (forEach and get are implicitly tested)", {
    setup: function() {
      object = {};
      number = 42;
      string = "foo";

      map = nameAndFunc[1].create();
    }
  });

  var mapHasLength = function(expected, theMap) {
    theMap = theMap || map;

    var length = 0;
    theMap.forEach(function() {
      length++;
    });

    equal(length, expected, "map should contain " + expected + " items");
  };

  var mapHasEntries = function(entries, theMap) {
    theMap = theMap || map;

    for (var i = 0, l = entries.length; i < l; i++) {
      equal(theMap.get(entries[i][0]), entries[i][1]);
      equal(theMap.has(entries[i][0]), true);
    }

    mapHasLength(entries.length, theMap);
  };

  test("add", function() {
    map.set(object, "winning");
    map.set(number, "winning");
    map.set(string, "winning");

    mapHasEntries([
      [ object, "winning" ],
      [ number, "winning" ],
      [ string, "winning" ]
    ]);

    map.set(object, "losing");
    map.set(number, "losing");
    map.set(string, "losing");

    mapHasEntries([
      [ object, "losing" ],
      [ number, "losing" ],
      [ string, "losing" ]
    ]);

    equal(map.has("nope"), false);
    equal(map.has({}), false);
  });

  test("remove", function() {
    map.set(object, "winning");
    map.set(number, "winning");
    map.set(string, "winning");

    map.remove(object);
    map.remove(number);
    map.remove(string);

    // doesn't explode
    map.remove({});

    mapHasEntries([]);
  });

  test("copy and then update", function() {
    map.set(object, "winning");
    map.set(number, "winning");
    map.set(string, "winning");

    var map2 = map.copy();

    map2.set(object, "losing");
    map2.set(number, "losing");
    map2.set(string, "losing");

    mapHasEntries([
      [ object, "winning" ],
      [ number, "winning" ],
      [ string, "winning" ]
    ]);

    mapHasEntries([
      [ object, "losing" ],
      [ number, "losing" ],
      [ string, "losing" ]
    ], map2);
  });

  test("copy and then remove", function() {
    map.set(object, "winning");
    map.set(number, "winning");
    map.set(string, "winning");

    var map2 = map.copy();

    map2.remove(object);
    map2.remove(number);
    map2.remove(string);

    mapHasEntries([
      [ object, "winning" ],
      [ number, "winning" ],
      [ string, "winning" ]
    ]);

    mapHasEntries([ ], map2);
  });

  test("length", function() {
    //Add a key twice
    equal(map.length, 0);
    map.set(string, "a string");
    equal(map.length, 1);
    map.set(string, "the same string");
    equal(map.length, 1);

    //Add another
    map.set(number, "a number");
    equal(map.length, 2);

    //Remove one that doesn't exist
    map.remove('does not exist');
    equal(map.length, 2);

    //Check copy
    var copy = map.copy();
    equal(copy.length, 2);

    //Remove a key twice
    map.remove(number);
    equal(map.length, 1);
    map.remove(number);
    equal(map.length, 1);

    //Remove the last key
    map.remove(string);
    equal(map.length, 0);
    map.remove(string);
    equal(map.length, 0);
  });
}

for (var i = 0;  i < varieties.length;  i++) {
  testMap(varieties[i]);
}

module("MapWithDefault - default values");

test("Retrieving a value that has not been set returns and sets a default value", function() {
  var map = MapWithDefault.create({
    defaultValue: function(key) {
      return [key];
    }
  });

  var value = map.get('ohai');
  deepEqual(value, [ 'ohai' ]);

  strictEqual(value, map.get('ohai'));
});

test("Copying a MapWithDefault copies the default value", function() {
  var map = MapWithDefault.create({
    defaultValue: function(key) {
      return [key];
    }
  });

  map.set('ohai', 1);
  map.get('bai');

  var map2 = map.copy();

  equal(map2.get('ohai'), 1);
  deepEqual(map2.get('bai'), ['bai']);

  map2.set('kthx', 3);

  deepEqual(map.get('kthx'), ['kthx']);
  equal(map2.get('kthx'), 3);

  deepEqual(map2.get('default'), ['default']);

  map2.defaultValue = function(key) {
    return ['tom is on', key];
  };

  deepEqual(map2.get('drugs'), ['tom is on', 'drugs']);
});


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/include/usr/cxxtest/cxxtest_data.H $                      */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2017                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

/** @file   cxxtest_data.H
 *
 */

#ifndef __cxxtest__cxxtest_data_h__
#define __cxxtest__cxxtest_data_h__

namespace CxxTest
{

enum
{
    CXXTEST_FILENAME_SIZE         =    50,
    CXXTEST_FAIL_LIST_SIZE        =    10
};

struct CxxTestFailedEntry
{
    char failTestFile[CXXTEST_FILENAME_SIZE];
    uint64_t failTestData;
};

} // namespace CxxTest

#endif // __cxxtest__cxxtest_data_h__


text:
<?php defined('SYSPATH') or die('No direct script access.');

class Model_Sys_Module extends Model {

	public function menu($directory)
	{
		$_results = DB::select('name', 'path')
			->from('sys_module')
			->where('parent_id', 'IS', NULL)
			->order_by('position', 'ASC')
			->execute();

		$results = array();
		foreach ($_results as $result)
		{
			$result['selected'] = ($result['path'] == $directory) ? 'selected' : '';
			$result['link'] = $result['path'];
			$results[] = $result;
		}

		return $results;

	}

	public function submenu($directory, $controller)
	{
		$_results = DB::select('m2.name', array('m1.path','group'), 'm2.path')
			->from(array('sys_module', 'm2'))
			->join(array('sys_module', 'm1'))
			->on('m1.id', '=', 'm2.parent_id')
			->where('m1.parent_id', 'IS', NULL)
			->order_by('m1.position', 'ASC')
			->order_by('m2.position', 'ASC')
			->execute();

		$results = array();
		foreach ($_results as $result)
		{
			$result['visible'] = ($result['group'] == $directory) ? 'visible' : '';
			$result['selected'] = ($result['group'] == $directory AND $result['path'] == $controller) ? 'selected' : '';
			$result['link'] = $result['group'].'/'.$result['path'].'/index';
			$results[] = $result;
		}

		return $results;
	}

	public function title($directory, $controller)
	{
		return DB::select('m2.name')
			->from(array('sys_module', 'm2'))
			->join(array('sys_module', 'm1'))
			->on('m1.id', '=', 'm2.parent_id')
			->where('m1.parent_id', 'IS', NULL)
			->where('m1.path', '=', $directory)
			->where('m2.path', '=', $controller)
			->execute()
			->get('name', '');
	}

}


text:
'use strict';

let baseUri = './assets';
let menuTemplate, menuData;
let getMenuTemplate = new Promise(function(resolve, reject) {
  $.get(baseUri + '/templates/module_menu_template.html', function(data) {
    menuTemplate = Handlebars.compile(data);
    resolve();
  });
});

let getMenuData = new Promise(function(resolve, reject) {
  $.get(baseUri + '/data/module_menu_data.json', function(data) {
    menuData = data;
    resolve(data);
  });
});

Promise.all([getMenuTemplate, getMenuData])
  .then(renderMenuItems);

function renderMenuItems() {
  for (let key in menuData) {
    let html = menuTemplate(menuData[key]);
    $('#module-menu-container').append(html);
  }
}


text:
import unittest

from shapely.geometry import LineString, Polygon
from shapely.ops import cascaded_union, unary_union
from matplotlib.pyplot import plot, subplot, show, cla, clf, xlim, ylim, title
from camlib import *
from copy import deepcopy

def mkstorage(paths):
    def get_pts(o):
        return [o.coords[0], o.coords[-1]]
    storage = FlatCAMRTreeStorage()
    storage.get_points = get_pts
    for p in paths:
        storage.insert(p)
    return storage

def plotg2(geo, solid_poly=False, color="black", linestyle='solid'):

    try:
        for sub_geo in geo:
            plotg2(sub_geo, solid_poly=solid_poly, color=color, linestyle=linestyle)
    except TypeError:
        if type(geo) == Polygon:
            if solid_poly:
                patch = PolygonPatch(geo,
                                     #facecolor="#BBF268",
                                     facecolor=color,
                                     edgecolor="#006E20",
                                     alpha=0.5,
                                     zorder=2)
                ax = subplot(111)
                ax.add_patch(patch)
            else:
                x, y = geo.exterior.coords.xy
                plot(x, y, color=color, linestyle=linestyle)
                for ints in geo.interiors:
                    x, y = ints.coords.xy
                    plot(x, y, color=color, linestyle=linestyle)

        if type(geo) == LineString or type(geo) == LinearRing:
            x, y = geo.coords.xy
            plot(x, y, color=color, linestyle=linestyle)

        if type(geo) == Point:
            x, y = geo.coords.xy
            plot(x, y, 'o')

class PaintTestCase(unittest.TestCase):
    # def __init__(self):
    #     super(PaintTestCase, self).__init__()
    #     self.boundary = None
    #     self.descr = None

    def plot_summary_A(self, paths, tooldia, result, msg):
        plotg2(self.boundary, solid_poly=True, color="green")
        plotg2(paths, color="red")
        plotg2([r.buffer(tooldia / 2) for r in result], solid_poly=True, color="blue")
        plotg2(result, color="black", linestyle='dashed')
        title(msg)
        xlim(0, 5)
        ylim(0, 5)
        show()

class PaintConnectTest(PaintTestCase):
    """
    Simple rectangular boundary and paths inside.
    """

    def setUp(self):
        self.boundary = Polygon([[0, 0], [0, 5], [5, 5], [5, 0]])

    def test_jump(self):
        print "Test: WALK Expected"
        paths = [
            LineString([[0.5, 2], [2, 4.5]]),
            LineString([[2, 0.5], [4.5, 2]])
        ]
        for p in paths:
            print p

        tooldia = 1.0

        print "--"
        result = Geometry.paint_connect(mkstorage(deepcopy(paths)), self.boundary, tooldia)

        result = list(result.get_objects())
        for r in result:
            print r

        self.assertEqual(len(result), 1)

        # self.plot_summary_A(paths, tooldia, result, "WALK expected.")

    def test_no_jump1(self):
        print "Test: FLY Expected"
        paths = [
            LineString([[0, 2], [2, 5]]),
            LineString([[2, 0], [5, 2]])
        ]
        for p in paths:
            print p

        tooldia = 1.0

        print "--"
        result = Geometry.paint_connect(mkstorage(deepcopy(paths)), self.boundary, tooldia)

        result = list(result.get_objects())
        for r in result:
            print r

        self.assertEqual(len(result), len(paths))

        # self.plot_summary_A(paths, tooldia, result, "FLY Expected")

    def test_no_jump2(self):
        print "Test: FLY Expected"
        paths = [
            LineString([[0.5, 2], [2, 4.5]]),
            LineString([[2, 0.5], [4.5, 2]])
        ]
        for p in paths:
            print p

        tooldia = 1.1

        print "--"
        result = Geometry.paint_connect(mkstorage(deepcopy(paths)), self.boundary, tooldia)

        result = list(result.get_objects())
        for r in result:
            print r

        self.assertEqual(len(result), len(paths))

        # self.plot_summary_A(paths, tooldia, result, "FLY Expected")

class PaintConnectTest2(PaintTestCase):
    """
    Boundary with an internal cutout.
    """

    def setUp(self):
        self.boundary = Polygon([[0, 0], [0, 5], [5, 5], [5, 0]])
        self.boundary = self.boundary.difference(
            Polygon([[2, 1], [3, 1], [3, 4], [2, 4]])
        )

    def test_no_jump3(self):
        print "TEST: No jump expected"
        paths = [
            LineString([[0.5, 1], [1.5, 3]]),
            LineString([[4, 1], [4, 4]])
        ]
        for p in paths:
            print p

        tooldia = 1.0

        print "--"
        result = Geometry.paint_connect(mkstorage(deepcopy(paths)), self.boundary, tooldia)

        result = list(result.get_objects())
        for r in result:
            print r

        self.assertEqual(len(result), len(paths))

        # self.plot_summary_A(paths, tooldia, result, "FLY Expected")

class PaintConnectTest3(PaintTestCase):
    """
    Tests with linerings among elements.
    """

    def setUp(self):
        self.boundary = Polygon([[0, 0], [0, 5], [5, 5], [5, 0]])
        print "TEST w/ LinearRings"

    def test_jump2(self):
        print "Test: WALK Expected"
        paths = [
            LineString([[0.5, 2], [2, 4.5]]),
            LineString([[2, 0.5], [4.5, 2]]),
            self.boundary.buffer(-0.5).exterior
        ]
        for p in paths:
            print p

        tooldia = 1.0

        print "--"
        result = Geometry.paint_connect(mkstorage(deepcopy(paths)), self.boundary, tooldia)

        result = list(result.get_objects())
        for r in result:
            print r

        self.assertEqual(len(result), 1)

        # self.plot_summary_A(paths, tooldia, result, "WALK Expected")

if __name__ == '__main__':
    unittest.main()


text:
from test.test_tools import load_tests
import unittest

unittest.main()


text:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/metro_item_view"
    android:layout_width="@dimen/ITEM_H_WIDTH"
    android:layout_height="@dimen/ITEM_H_HEIGHT" >

    <com.tv.ui.metro.view.CenterIconImage
        android:id="@+id/back_ground_imageview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true"
        android:scaleType="center" />

    <com.tv.ui.metro.view.CenterIconImage
        android:id="@+id/front_ground_imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" />

    <com.tv.ui.metro.view.CenterIconImage
        android:id="@+id/sub_ground_imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="20dp"
        android:gravity="center"
        android:orientation="vertical" >

        <com.tv.ui.metro.view.CenterIconImage
            android:id="@+id/icon_imageview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="gone" />

        <TextView
            android:id="@+id/labelTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:singleLine="true"
            android:textColor="#ffffff"
            android:textSize="@dimen/text_size_50"
            android:visibility="gone" />
    </LinearLayout>

    <ImageView
        android:id="@+id/handler_image_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="@dimen/OPERATOR_MARGIN"
        android:layout_marginRight="@dimen/OPERATOR_MARGIN"
        android:src="@drawable/operator_handler"
        android:visibility="gone" />

    <TextView
        android:id="@+id/recommend_textview"
        android:layout_width="match_parent"
        android:layout_height="@dimen/metro_item_recommend_text_height"
        android:layout_alignLeft="@id/back_ground_imageview"
        android:layout_alignParentBottom="true"
        android:background="@drawable/name_mask"
        android:ellipsize="end"
        android:gravity="center_vertical"
        android:padding="@dimen/metro_item_padding"
        android:singleLine="true"
        android:textColor="#ccffffff" />

</merge>


text:
using System.Data.Common;
using System.Data.SqlClient;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace NakedObjects.Rest.App.Demo {
    public class Program {
        public static void Main(string[] args) {
            DbProviderFactories.RegisterFactory("System.Data.SqlClient", SqlClientFactory.Instance);
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureLogging(logging => {
                    // Clear default logging providers so we just log to log4net
                    logging.ClearProviders();
                })
                .ConfigureWebHostDefaults(webBuilder => {
                    webBuilder.UseStartup<Startup>();
                });
    }
}


text:
///////////////////////////////////////////////////////////
// CWorldThread

#define FREE_UIDS_SIZE	500000	// list of free empty slots in the UIDs list should contain these elements

class CWorldThread
{
	// A regional thread of execution. Hold all the objects in my region
	// as well as those just created here (but may not be here anymore)

public:
	static const char *m_sClassName;

	CWorldThread();
	virtual ~CWorldThread();

protected:
	CGObArray<CObjBase *> m_UIDs;	// all UID's placed on world (CChar/CItem)
	DWORD m_dwUIDIndexLast;			// last UID index allocated

	DWORD *m_dwFreeUIDs;			// list of free UIDs available
	DWORD m_dwFreeOffset;			// offset of the first free element

public:
	CGObList m_ObjNew;				// Object created but not yet placed in the world
	CGObList m_ObjDelete;			// Objects to be deleted

	// Background save (does this belong here?)
	CScript m_FileData;				// global vars
	CScript m_FileWorld;			// objects placed on world
	CScript m_FilePlayers;			// players chars
	CScript m_FileMultis;			// custom multis
	bool m_fSaveParity;				// the sector has been saved relative to the char entering it?

public:
	// Backgound save
	bool IsSaving() const;

	// UID managenent
	#define UID_PLACE_HOLDER	reinterpret_cast<CObjBase *>(DWORD_PTR_MAX)
	CObjBase *FindUID(DWORD dwIndex) const;
	DWORD GetUIDCount() const;
	void FreeUID(DWORD dwIndex);
	DWORD AllocUID(DWORD dwIndex, CObjBase *pObj);

	int FixObjTry(CObjBase *pObj, DWORD uid = 0);
	int FixObj(CObjBase *pObj, DWORD uid = 0);

	void SaveThreadClose();
	void GarbageCollection_UIDs();
	void GarbageCollection_New();

	void CloseAllUIDs();

private:
	CWorldThread(const CWorldThread &copy);
	CWorldThread &operator=(const CWorldThread &other);
};

///////////////////////////////////////////////////////////
// CWorldClock

#ifndef _WIN32
	#ifdef CLOCKS_PER_SEC
		#undef CLOCKS_PER_SEC
	#endif
	#define CLOCKS_PER_SEC	1000	// must be converted from some internal clock
#endif

class CWorldClock
{
public:
	static const char *m_sClassName;

	CWorldClock()
	{
		Init();
	}

private:
	UINT64 m_SystemClock_Prev;		// system time of the last OnTick() (in CLOCKS_PER_SEC)
	CServTime m_TimeClock;			// the current relative tick time (in TICK_PER_SEC)

public:
	void Init();
	void InitTime(UINT64 uTimeBase);
	bool Advance();

	static UINT64 GetSystemClock();		// time in CLOCKS_PER_SEC
	CServTime GetCurrentTime() const	// time in TICK_PER_SEC
	{
		return m_TimeClock;
	}

private:
	CWorldClock(const CWorldClock &copy);
	CWorldClock &operator=(const CWorldClock &other);
};

///////////////////////////////////////////////////////////
// CTimedFunctionHandler

class CTimedFunctionHandler
{
public:
	static const char *m_sClassName;

	CTimedFunctionHandler();

private:
	struct TimedFunction
	{
		int elapsed;
		char funcname[128];
		CGrayUID uid;
	};

	int m_iCurTick;
	bool m_fBeingProcessed;
	std::vector<TimedFunction *> m_timedFunctions[TICK_PER_SEC];
	std::vector<TimedFunction *> m_tFrecycled;
	std::vector<TimedFunction *> m_tFqueuedToBeAdded;

public:
	void OnTick();
	void r_Write(CScript &s);

	int Load(const char *pszName, bool fQuoted, const char *pszVal);
	void Add(CGrayUID uid, int iNumSeconds, LPCTSTR pszFuncName);
	void Erase(CGrayUID uid);
	void Stop(CGrayUID uid, LPCTSTR pszFuncName);
	TRIGRET_TYPE Loop(LPCTSTR pszFuncName, int iLoopsMade, CScriptLineContext StartContext, CScript &s, CTextConsole *pSrc, CScriptTriggerArgs *pArgs, CGString *sResult);
	int IsTimer(CGrayUID uid, LPCTSTR pszFuncName);

private:
	CTimedFunctionHandler(const CTimedFunctionHandler &copy);
	CTimedFunctionHandler &operator=(const CTimedFunctionHandler &other);
};

///////////////////////////////////////////////////////////
// CWorld

enum IMPFLAGS_TYPE	// IMPORT/EXPORT flags
{
	IMPFLAGS_NOTHING	= 0x00,
	IMPFLAGS_ITEMS		= 0x01,
	IMPFLAGS_CHARS		= 0x02,
	IMPFLAGS_SELF		= 0x04,
	IMPFLAGS_RELATIVE	= 0x10,		// relative distance to object (x,y)
	IMPFLAGS_ACCOUNT	= 0x20		// import/export just this account (all chars and everything they're carrying)
};

extern class CWorld : public CScriptObj, public CWorldThread
{
	// Stuff saved in *world.scp

public:
	static const char *m_sClassName;
	static const LPCTSTR sm_szLoadKeys[];
	LPCTSTR GetName() const
	{
		return "World";
	}

	CWorld();
	~CWorld();

private:
	ULONGLONG m_savetimer;					// time it took to finish world save
	int m_iSaveStage;						// current background save stage
	bool m_fSaveNotificationSent;			// notify all clients before start an world save

	CServTime m_timeSector;					// time to start next sector stuff
	CServTime m_timeSave;					// time to start next world save
	CServTime m_timeRespawn;				// time to resurrect dead NPCs on sector
	CServTime m_timeCallUserFunc;			// time to call next user functions

	CSector **m_Sectors;
	size_t m_SectorsQty;
	size_t m_Sector_Pulse;					// slow down some stuff that doesn't need constant processing

	CWorldClock m_Clock;					// current relative time (in TICK_PER_SEC)

public:
	CServTime m_timeStartup;				// time since the server had started

	long m_iSaveCountID;					// current world save numeric ID ("SAVECOUNT")
	long m_iPrevBuild;						// previous server build version ("PREVBUILD")
	long m_iLoadVersion;					// current server build version ("VERSION")

	CGrayUID m_uidLastNewItem;				// last new created item (for script access)
	CGrayUID m_uidLastNewChar;				// last new created char (for script access)
	CGrayUID m_uidNew;						// current obj stored on NEW ref (for script access)
	CGrayUID m_uidObj;						// current obj stored on OBJ ref (for script access)

	CGPtrTypeArray<CItemTypeDef *> m_TileTypes;		// list of terrain typedefs
	CGPtrTypeArray<CItemStone *> m_Stones;			// list of guild/town stones (not saved array)
	CGObList m_Parties;								// list of active parties (CPartyDef)
	CGObList m_GMPages;								// list of GM pages (CGMPage)

	CTimedFunctionHandler m_TimedFunctions;			// list of timed functions to be called ("TIMERF")
	CGPtrTypeArray<CObjBase *> m_ObjStatusUpdates;	// list of objects that doesn't receive OnTickStatusUpdate() ticks (eg: placed inside containers) and need to call it manually

private:
	static void GetBackupName(CGString &sBuffer, LPCTSTR pszBaseDir, TCHAR pszType, int iSaveCount);
	bool LoadFile(LPCTSTR pszFileName);
	bool LoadWorld();

	bool SaveTry(bool fForceImmediate);
	bool SaveStage();
	bool SaveForce();

public:
	void Init();

	CSector *GetSector(int iMap, int iSector);

	// Time
	CServTime GetCurrentTime() const
	{
		return m_Clock.GetCurrentTime();	// time in TICK_PER_SEC
	}
	INT64 GetTimeDiff(CServTime time) const
	{
		// How long till this event (negative = in the past)
		return time.GetTimeDiff(GetCurrentTime());		// time in TICK_PER_SEC
	}

	#define TRAMMEL_SYNODIC_PERIOD		105	// in game world minutes
	#define FELUCCA_SYNODIC_PERIOD		840	// in game world minutes
	#define TRAMMEL_FULL_BRIGHTNESS		2	// light units LIGHT_BRIGHT
	#define FELUCCA_FULL_BRIGHTNESS		6	// light units LIGHT_BRIGHT
	unsigned int GetMoonPhase(bool fMoonIndex = false) const;
	CServTime GetNextNewMoon(bool fMoonIndex) const;

	DWORD GetGameWorldTime(CServTime basetime) const;
	DWORD GetGameWorldTime() const
	{
		// Return game world minutes
		return GetGameWorldTime(GetCurrentTime());
	}

	// CSector world map stuff
	void GetHeightPoint(const CPointMap &pt, CGrayMapBlockState &block, bool fHouseCheck = false);
	void GetHeightPoint2(const CPointMap &pt, CGrayMapBlockState &block, bool fHouseCheck = false);
	signed char GetHeightPoint(const CPointBase &pt, DWORD &dwBlockFlags, bool fHouseCheck = false);
	signed char GetHeightPoint2(const CPointBase &pt, DWORD &dwBlockFlags, bool fHouseCheck = false);

	void GetFixPoint(const CPointMap &pt, CGrayMapBlockState &block);

	CItemTypeDef *GetTerrainItemTypeDef(DWORD dwIndex);
	IT_TYPE GetTerrainItemType(DWORD dwIndex);

	const CGrayMapBlock *GetMapBlock(const CPointMap &pt)
	{
		return pt.GetSector()->GetMapBlock(pt);
	}
	const CUOMapMeter *GetMapMeter(const CPointMap &pt) const
	{
		// Get height of given map coordinates
		const CGrayMapBlock *pMapBlock = pt.GetSector()->GetMapBlock(pt);
		if ( !pMapBlock )
			return NULL;
		return pMapBlock->GetTerrain(UO_BLOCK_OFFSET(pt.m_x), UO_BLOCK_OFFSET(pt.m_y));
	}

	CPointMap FindItemTypeNearby(const CPointMap &pt, IT_TYPE type, int iDist = 0, bool fCheckMulti = false, bool fLimitZ = false);
	bool IsItemTypeNear(const CPointMap &pt, IT_TYPE type, int iDist = 0, bool fCheckMulti = false, bool fLimitZ = false);

	CPointMap FindTypeNear_Top(const CPointMap &pt, IT_TYPE type, int iDist = 0);
	bool IsTypeNear_Top(const CPointMap &pt, IT_TYPE type, int iDist = 0);

	CItem *CheckNaturalResource(const CPointMap &pt, IT_TYPE type, bool fTest = true, CChar *pCharSrc = NULL);

	static bool OpenScriptBackup(CScript &s, LPCTSTR pszBaseDir, LPCTSTR pszBaseName, int iSaveCount);

	void r_Write(CScript &s);
	bool r_WriteVal(LPCTSTR pszKey, CGString &sVal, CTextConsole *pSrc);
	bool r_LoadVal(CScript &s);
	bool r_GetRef(LPCTSTR &pszKey, CScriptObj *&pRef);

	void OnTick();

	void GarbageCollection();
	void Restock();
	void RespawnDeadNPCs();
	void ReloadMultis();

	void Speak(const CObjBaseTemplate *pSrc, LPCTSTR pszText, HUE_TYPE wHue = HUE_TEXT_DEF, TALKMODE_TYPE mode = TALKMODE_SAY, FONT_TYPE font = FONT_BOLD);
	void SpeakUNICODE(const CObjBaseTemplate *pSrc, const NCHAR *pszText, HUE_TYPE wHue, TALKMODE_TYPE mode, FONT_TYPE font, CLanguageID lang);

	void Broadcast(LPCTSTR pszMsg);
	void __cdecl Broadcastf(LPCTSTR pszMsg, ...) __printfargs(2, 3);

	bool Export(LPCTSTR pszFileName, const CChar *pSrc, WORD wModeFlags = IMPFLAGS_ITEMS, int iDist = SHRT_MAX, int dx = 0, int dy = 0);
	bool Import(LPCTSTR pszFileName, const CChar *pSrc, WORD wModeFlags = IMPFLAGS_ITEMS, int iDist = SHRT_MAX, TCHAR *pszArg1 = NULL, TCHAR *pszArg2 = NULL);
	bool Save(bool fForceImmediate);
	void SaveStatics();
	bool LoadAll();
	bool DumpAreas(CTextConsole *pSrc, LPCTSTR pszFileName);
	void Close();

private:
	CWorld(const CWorld &copy);
	CWorld &operator=(const CWorld &other);
} g_World;

///////////////////////////////////////////////////////////
// CWorldSearch

class CWorldSearch
{
	// Create an search area on world to find objects

public:
	static const char *m_sClassName;
	explicit CWorldSearch(const CPointMap &pt, int iDist = 0);

private:
	const CPointMap m_pt;		// base search point (center)
	const int m_iDist;			// max distance to search
	bool m_fAllShow;			// include inert items and disconnected chars

	CObjBase *m_pObj;			// current object
	CObjBase *m_pObjNext;		// next object (in case the current object get deleted)
	bool m_fInertToggle;		// search on inert items

	CSector *m_pSectorBase;		// store the base sector to avoid search this sector twice on loop
	CSector *m_pSector;			// current sector
	CRectMap m_rectSector;		// rectangle containing sectors to search
	int m_iSectorCur;			// current sector index in m_rectSector

private:
	bool GetNextSector();

public:
	CChar * GetChar();
	CItem *GetItem();

	void SetAllShow(bool fAllShow)
	{
		m_fAllShow = fAllShow;
	}
	void RestartSearch()
	{
		// Setting current obj to NULL will restart the search
		m_pObj = NULL;
	}

private:
	CWorldSearch(const CWorldSearch &copy);
	CWorldSearch &operator=(const CWorldSearch &other);
};

inline CServTime CServTime::GetCurrentTime()	// static
{
	return g_World.GetCurrentTime();
}

#endif	// _INC_CWORLD_H


text:
When you run [`pnpm install`](https://pnpm.io/cli/install) in a monorepo, it
will run from the context of the workspace root. That means it will install
dependencies for your entire monorepo across apps and packages.

Even if you are in a subdirectory for a specific project with its own
`package.json`, running `pnpm install` will install dependencies for the entire
workspace.

If you want to install dependencies only for a specific project or a subset of
projects, you can use [the `--filter`
flag](https://pnpm.io/cli/install#--filter-package_selector).


text:
use prelude::v1::*;

use any::Any;
use intrinsics;
use libc::c_void;

pub unsafe fn panic(_data: Box<Any + Send + 'static>) -> ! {
    intrinsics::abort();
}

pub unsafe fn cleanup(_ptr: *mut c_void) -> Box<Any + Send + 'static> {
    intrinsics::abort();
}

#[lang = "eh_personality"]
#[no_mangle]
pub extern fn rust_eh_personality() {}

#[no_mangle]
pub extern fn rust_eh_personality_catch() {}


text:
Template.home.helpers({
	isCheckboxChecked: function(value){
		return Details.get(DETAILS_QUERY.CHECKBOX) ? "checked": "";
	},
	isRadioChecked: function(value){
		return Details.get(DETAILS_QUERY.RADIO) === value ? "checked": "";
	},
	isModalOpened: function () {
		return Actions.get(ACTIONS_QUERY.IS_MODAL_OPEN);
	}
});

Template.home.events({
	'click .open-modal': function (event, template) {
		goActions(ACTIONS_QUERY.IS_MODAL_OPEN, true);
	},
	'click .close-modal': function (event, template) {
		goActions(ACTIONS_QUERY.IS_MODAL_OPEN, null); //or false
	},
	'change #checkbox': function(event, template){
		goDetails(DETAILS_QUERY.CHECKBOX, $(event.currentTarget).is(":checked"));
	},
	'change [name=gender]': function(event, template){
		var v = $(event.currentTarget).val();
		console.log(v)
		goDetails(DETAILS_QUERY.RADIO, v);
	}
});

function goActions(key, value){
	var query = Router.current().params.query;
	var newQueryParam = Actions.whatIfAsQueryParam(key, value);
	query[newQueryParam.name] = newQueryParam.value;
	Router.go('home', null, {query: query});
}

function goDetails(key, value){
	var query = Router.current().params.query;
	var newQueryParam = Details.whatIfAsQueryParam(key, value);
	query[newQueryParam.name] = newQueryParam.value;
	Router.go('home', null, {query: query});
}


text:
<?php

namespace Micro\Acl;

interface AclInterface
{
    public function isAllowed($role = \null, $resource = \null, $privilege = \null);
}


text:
package org.blockartistry.mod.ThermalRecycling;

import org.apache.logging.log4j.Logger;

public final class ModLog {

	private ModLog() {}

	private static Logger logger;

	public static Logger getLogger() {
		return logger;
	}

	public static void setLogger(final Logger log) {
		logger = log;
	}

	public static void info(final String msg, final Object... parms) {
		if (logger != null)
			logger.info(String.format(msg, parms));
	}

	public static void warn(final String msg, final Object... parms) {
		if (logger != null)
			logger.warn(String.format(msg, parms));
	}

	public static void debug(final String msg, final Object... parms) {
		if (logger != null && ModOptions.getEnableDebugLogging()) {
			logger.info(String.format(msg, parms));
		}
	}

	public static void error(final String msg, final Throwable e) {
		if (logger != null)
			logger.error(msg);
		if(e != null)
			e.printStackTrace();
	}

	public static void catching(final Throwable t) {
		if (logger != null) {
			logger.catching(t);
			t.printStackTrace();
		}
	}
}


text:
package image

import (
	"bytes"
	"testing"

	v1 "github.com/google/go-containerregistry/pkg/v1"
	"github.com/google/go-containerregistry/pkg/v1/empty"
	"github.com/moby/buildkit/frontend/dockerfile/instructions"
	"github.com/moby/buildkit/frontend/dockerfile/parser"

	"github.com/GoogleContainerTools/kaniko/pkg/config"
	"github.com/GoogleContainerTools/kaniko/testutil"
)

var (
	dockerfile = `
	FROM gcr.io/distroless/base:latest as base
	COPY . .

	FROM scratch as second
	ENV foopath context/foo
	COPY --from=0 $foopath context/b* /foo/

	FROM base
	ARG file
	COPY --from=second /foo $file`
)

func Test_StandardImage(t *testing.T) {
	stages, err := parse(dockerfile)
	if err != nil {
		t.Error(err)
	}
	original := RetrieveRemoteImage
	defer func() {
		RetrieveRemoteImage = original
	}()
	mock := func(image string, opts config.RegistryOptions, _ string) (v1.Image, error) {
		return nil, nil
	}
	RetrieveRemoteImage = mock
	actual, err := RetrieveSourceImage(config.KanikoStage{
		Stage: stages[0],
	}, &config.KanikoOptions{})
	testutil.CheckErrorAndDeepEqual(t, false, err, nil, actual)
}

func Test_ScratchImage(t *testing.T) {
	stages, err := parse(dockerfile)
	if err != nil {
		t.Error(err)
	}
	actual, err := RetrieveSourceImage(config.KanikoStage{
		Stage: stages[1],
	}, &config.KanikoOptions{})
	expected := empty.Image
	testutil.CheckErrorAndDeepEqual(t, false, err, expected, actual)
}

func Test_TarImage(t *testing.T) {
	stages, err := parse(dockerfile)
	if err != nil {
		t.Error(err)
	}
	original := retrieveTarImage
	defer func() {
		retrieveTarImage = original
	}()
	mock := func(index int) (v1.Image, error) {
		return nil, nil
	}
	retrieveTarImage = mock
	actual, err := RetrieveSourceImage(config.KanikoStage{
		BaseImageStoredLocally: true,
		BaseImageIndex:         0,
		Stage:                  stages[2],
	}, &config.KanikoOptions{})
	testutil.CheckErrorAndDeepEqual(t, false, err, nil, actual)
}

func Test_ScratchImageFromMirror(t *testing.T) {
	stages, err := parse(dockerfile)
	if err != nil {
		t.Error(err)
	}
	actual, err := RetrieveSourceImage(config.KanikoStage{
		Stage: stages[1],
	}, &config.KanikoOptions{
		RegistryOptions: config.RegistryOptions{
			RegistryMirrors: []string{"mirror.gcr.io"},
		},
	})
	expected := empty.Image
	testutil.CheckErrorAndDeepEqual(t, false, err, expected, actual)
}

// parse parses the contents of a Dockerfile and returns a list of commands
func parse(s string) ([]instructions.Stage, error) {
	p, err := parser.Parse(bytes.NewReader([]byte(s)))
	if err != nil {
		return nil, err
	}
	stages, _, err := instructions.Parse(p.AST)
	if err != nil {
		return nil, err
	}
	return stages, err
}


text:
#include <android/bitmap.h>
#include <jni_common/jni_bitmap2mat.h>
#include <jni_common/jni_primitives.h>
#include <jni_common/jni_fileutils.h>
#include <jni_common/jni_utils.h>
#include <detector.h>
#include <jni.h>

using namespace cv;
extern JNI_VisionDetRet* g_pJNI_VisionDetRet;

namespace {

#define JAVA_NULL 0
using DetectorPtr = OpencvHOGDetctor*;

class JNI_PedestrianDet {
 public:
  JNI_PedestrianDet(JNIEnv* env) {
    jclass clazz = env->FindClass(CLASSNAME_PEDESTRIAN_DET);
    mNativeContext = env->GetFieldID(clazz, "mNativeDetContext", "J");
    env->DeleteLocalRef(clazz);
  }

  DetectorPtr getDetectorPtrFromJava(JNIEnv* env, jobject thiz) {
    DetectorPtr const p = (DetectorPtr)env->GetLongField(thiz, mNativeContext);
    return p;
  }

  void setDetectorPtrToJava(JNIEnv* env, jobject thiz, jlong ptr) {
    env->SetLongField(thiz, mNativeContext, ptr);
  }

  jfieldID mNativeContext;
};

// Protect getting/setting and creating/deleting pointer between java/native
std::mutex gLock;

std::shared_ptr<JNI_PedestrianDet> getJNI_PedestrianDet(JNIEnv* env) {
  static std::once_flag sOnceInitflag;
  static std::shared_ptr<JNI_PedestrianDet> sJNI_PedestrianDet;
  std::call_once(sOnceInitflag, [env]() {
    sJNI_PedestrianDet = std::make_shared<JNI_PedestrianDet>(env);
  });
  return sJNI_PedestrianDet;
}

DetectorPtr const getDetectorPtr(JNIEnv* env, jobject thiz) {
  std::lock_guard<std::mutex> lock(gLock);
  return getJNI_PedestrianDet(env)->getDetectorPtrFromJava(env, thiz);
}

// The function to set a pointer to java and delete it if newPtr is empty
void setDetectorPtr(JNIEnv* env, jobject thiz, DetectorPtr newPtr) {
  std::lock_guard<std::mutex> lock(gLock);
  DetectorPtr oldPtr =
      getJNI_PedestrianDet(env)->getDetectorPtrFromJava(env, thiz);
  if (oldPtr != JAVA_NULL) {
    DLOG(INFO) << "setMapManager delete old ptr : " << oldPtr;
    delete oldPtr;
  }

  if (newPtr != JAVA_NULL) {
    DLOG(INFO) << "setMapManager set new ptr : " << newPtr;
  }

  getJNI_PedestrianDet(env)->setDetectorPtrToJava(env, thiz, (jlong)newPtr);
}

}  // end unnamespace

#ifdef __cplusplus
extern "C" {
#endif

// ========================================================
// JNI Mapping Methods
// ========================================================
#define DLIB_JNI_METHOD(METHOD_NAME) \
  Java_com_tzutalin_dlib_PedestrianDet_##METHOD_NAME

jobjectArray getDetRet(JNIEnv* env, DetectorPtr detectorPtr, const int& size) {
  LOG(INFO) << "getDetRet";
  jobjectArray jDetRetArray = JNI_VisionDetRet::createJObjectArray(env, size);
  for (int i = 0; i < size; i++) {
    jobject jDetRet = JNI_VisionDetRet::createJObject(env);
    env->SetObjectArrayElement(jDetRetArray, i, jDetRet);
    cv::Rect rect = detectorPtr->getResult()[i];
    g_pJNI_VisionDetRet->setRect(env, jDetRet, rect.x, rect.y,
                                 rect.x + rect.width, rect.y + rect.height);
    g_pJNI_VisionDetRet->setLabel(env, jDetRet, "Pedestrian");
  }
  return jDetRetArray;
}

JNIEXPORT jobjectArray JNICALL
    DLIB_JNI_METHOD(jniDetect)(JNIEnv* env, jobject thiz, jstring jImgPath) {
  LOG(INFO) << "jniPeopleDet";
  std::string path = jniutils::convertJStrToString(env, jImgPath);
  cv::Mat src_img = cv::imread(path, CV_LOAD_IMAGE_COLOR);
  DetectorPtr detPtr = getDetectorPtr(env, thiz);
  int size = detPtr->det(src_img);
  LOG(INFO) << "jniPeopleDet size: " << size;
  return getDetRet(env, detPtr, size);
}

JNIEXPORT jobjectArray JNICALL
    DLIB_JNI_METHOD(jniBitmapDetect)(JNIEnv* env, jobject thiz,
                                     jobject bitmap) {
  LOG(INFO) << "jniBitmapPeopleDet";
  cv::Mat rgbaMat;
  cv::Mat bgrMat;
  jniutils::ConvertBitmapToRGBAMat(env, bitmap, rgbaMat, true);
  cv::cvtColor(rgbaMat, bgrMat, cv::COLOR_RGBA2BGR);
  DetectorPtr detPtr = getDetectorPtr(env, thiz);
  jint size = detPtr->det(bgrMat);
  LOG(INFO) << "jniBitmapPeopleDet size: " << size;
  return getDetRet(env, detPtr, size);
}

jint JNIEXPORT JNICALL DLIB_JNI_METHOD(jniInit)(JNIEnv* env, jobject thiz) {
  LOG(INFO) << "jniInit";
  DetectorPtr detPtr = new OpencvHOGDetctor();
  setDetectorPtr(env, thiz, detPtr);
  ;
  return JNI_OK;
  return JNI_OK;
}

jint JNIEXPORT JNICALL DLIB_JNI_METHOD(jniDeInit)(JNIEnv* env, jobject thiz) {
  LOG(INFO) << "jniDeInit";
  return JNI_OK;
}

#ifdef __cplusplus
}
#endif


text:
package org.apache.hadoop.hdfs;

import java.io.IOException;
import java.nio.ByteBuffer;
import static org.apache.hadoop.hdfs.util.IOUtilsClient.updateReadStatistics;

/**
 * Wraps different possible read implementations so that callers can be
 * strategy-agnostic.
 */
interface ReaderStrategy {
  /**
   * Read from a block using the blockReader.
   * @param blockReader
   * @return number of bytes read
   * @throws IOException
   */
  int readFromBlock(BlockReader blockReader) throws IOException;

  /**
   * Read from a block using the blockReader with desired length to read.
   * @param blockReader
   * @param length number of bytes desired to read, not ensured
   * @return number of bytes read
   * @throws IOException
   */
  int readFromBlock(BlockReader blockReader, int length) throws IOException;

  /**
   * Read or copy from a src buffer.
   * @param src
   * @return number of bytes copied
   * Note: the position of the src buffer is not changed after the call
   */
  int readFromBuffer(ByteBuffer src);

  /**
   * Read or copy length of data bytes from a src buffer with desired length.
   * @param src
   * @return number of bytes copied
   * Note: the position of the src buffer is not changed after the call
   */
  int readFromBuffer(ByteBuffer src, int length);

  /**
   * @return the target read buffer that reads data into.
   */
  ByteBuffer getReadBuffer();

  /**
   * @return the target length to read.
   */
  int getTargetLength();
}

/**
 * Used to read bytes into a byte array buffer. Note it's not thread-safe
 * and the behavior is not defined if concurrently operated.
 */
class ByteArrayStrategy implements ReaderStrategy {
  private final DFSClient dfsClient;
  private final ReadStatistics readStatistics;
  private final byte[] readBuf;
  private int offset;
  private final int targetLength;

  /**
   * The constructor.
   * @param readBuf target buffer to read into
   * @param offset offset into the buffer
   * @param targetLength target length of data
   * @param readStatistics statistics counter
   */
  public ByteArrayStrategy(byte[] readBuf, int offset, int targetLength,
                           ReadStatistics readStatistics,
                           DFSClient dfsClient) {
    this.readBuf = readBuf;
    this.offset = offset;
    this.targetLength = targetLength;
    this.readStatistics = readStatistics;
    this.dfsClient = dfsClient;
  }

  @Override
  public ByteBuffer getReadBuffer() {
    return ByteBuffer.wrap(readBuf, offset, targetLength);
  }

  @Override
  public int getTargetLength() {
    return targetLength;
  }

  @Override
  public int readFromBlock(BlockReader blockReader) throws IOException {
    return readFromBlock(blockReader, targetLength);
  }

  @Override
  public int readFromBlock(BlockReader blockReader,
                           int length) throws IOException {
    int nRead = blockReader.read(readBuf, offset, length);
    if (nRead > 0) {
      updateReadStatistics(readStatistics, nRead, blockReader);
      dfsClient.updateFileSystemReadStats(blockReader.getNetworkDistance(),
          nRead);
      offset += nRead;
    }
    return nRead;
  }

  @Override
  public int readFromBuffer(ByteBuffer src) {
    return readFromBuffer(src, src.remaining());
  }

  @Override
  public int readFromBuffer(ByteBuffer src, int length) {
    ByteBuffer dup = src.duplicate();
    dup.get(readBuf, offset, length);
    offset += length;
    return length;
  }
}

/**
 * Used to read bytes into a user-supplied ByteBuffer. Note it's not thread-safe
 * and the behavior is not defined if concurrently operated. When read operation
 * is performed, the position of the underlying byte buffer will move forward as
 * stated in ByteBufferReadable#read(ByteBuffer buf) method.
 */
class ByteBufferStrategy implements ReaderStrategy {
  private final DFSClient dfsClient;
  private final ReadStatistics readStatistics;
  private final ByteBuffer readBuf;
  private final int targetLength;

  /**
   * The constructor.
   * @param readBuf target buffer to read into
   * @param readStatistics statistics counter
   */
  ByteBufferStrategy(ByteBuffer readBuf,
                     ReadStatistics readStatistics,
                     DFSClient dfsClient) {
    this.readBuf = readBuf;
    this.targetLength = readBuf.remaining();
    this.readStatistics = readStatistics;
    this.dfsClient = dfsClient;
  }

  @Override
  public ByteBuffer getReadBuffer() {
    return readBuf;
  }

  @Override
  public int readFromBlock(BlockReader blockReader) throws IOException {
    return readFromBlock(blockReader, readBuf.remaining());
  }

  @Override
  public int readFromBlock(BlockReader blockReader,
                           int length) throws IOException {
    ByteBuffer tmpBuf = readBuf.duplicate();
    tmpBuf.limit(tmpBuf.position() + length);
    int nRead = blockReader.read(tmpBuf);
    // Only when data are read, update the position
    if (nRead > 0) {
      readBuf.position(readBuf.position() + nRead);
      updateReadStatistics(readStatistics, nRead, blockReader);
      dfsClient.updateFileSystemReadStats(blockReader.getNetworkDistance(),
          nRead);
    }

    return nRead;
  }

  @Override
  public int getTargetLength() {
    return targetLength;
  }

  @Override
  public int readFromBuffer(ByteBuffer src) {
    return readFromBuffer(src, src.remaining());
  }

  @Override
  public int readFromBuffer(ByteBuffer src, int length) {
    ByteBuffer dup = src.duplicate();
    int newLen = Math.min(readBuf.remaining(), dup.remaining());
    newLen = Math.min(newLen, length);
    dup.limit(dup.position() + newLen);
    readBuf.put(dup);
    return newLen;
  }
}


text:
title:  "Strings and Stories"
date:   2015-02-17 10:18:00
description: Honest and simple interface copy
---

I'm a writer. I work on interfaces for products and websites, and if I do my job right, you won't notice me at all. My identity isn't important. I'm speaking on behalf of the friendly machine that you are trying to work with.

I'm here to help people know what's next, to guide them, and to ask for information in a non-creepy/unintrusive way, so they'll find what they need and have an easier time doing that thing they need done. I work with content that's wrapped in code. I'm a sort of translator. I take database fields and turn them into something meaningful for readers, so they'll enter structured information back into the system.

I don't know what the databases know. I can't see what a specific person puts into the database and I don't want to. But I do know what fields we're prompting for and what kinds of things we're hoping to learn about people using the system. These details include: names, dates, locations, habits, relationships, topics of interest, or payment details.

The systems I work on talk to people with my words. These words and strings show up in forms connected by buttons and links. What is your name? Do you live in California or Texas? What is your credit card number? How did you hear about us? What do you care about? These are all very private bits of information. They are snippets of stories waiting to be strung together or picked apart. And since I can't see the details, I can only write for the abstract. I write the stories I want the interface to tell, working backwards from everyday human-speak to a language the the database can translate.

It's hard to write interesting stories when you don't know the subject or the reader. To make it easier, I often use myself or someone I know to fill in the blanks.
When I think about my trail on my amazon prime membership, I can see the strings tell my own story.

{% highlight javascript linenos %}
{name} searched for {product}.
{name} requested a return for {product} from {vendor}.
{name}, located in {place} might also enjoy {product}
+ {product}.
{name} is reading about {product} | {vendor}.
{name} accessed the site from {server} on {date} and
{time} with an IP address of {ip_address}.
{name} spent {duration} reading about {product}.
{% endhighlight %}


text:
from PyQt5.QtWidgets import QWidget, QScrollArea, QVBoxLayout, QSizePolicy, QFrame, QAbstractScrollArea, QSpacerItem
from PyQt5.QtCore import Qt

# This file is following C++ style as it's used by Qt.

class QDynamicList(QScrollArea):
    def __init__(self):
        super(QDynamicList, self).__init__()
        self.setObjectName("___list___")
        self.setFocusPolicy(Qt.NoFocus)
        self.setFrameShape(QFrame.NoFrame)
        self.setFrameShadow(QFrame.Plain)
        self.setLineWidth(0)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setSizeAdjustPolicy(QAbstractScrollArea.AdjustToContents)
        self.setWidgetResizable(True)
        self.setStyleSheet(f"#___list___, #___internalList___ {{background-color: transparent;}}")

        self.list = QWidget()
        self.list.setObjectName("___internalList___")

        self.layout = QVBoxLayout(self.list)
        self.layout.setSpacing(0)
        self.layout.setObjectName("___verticalLayout___")
        self.layout.setContentsMargins(0, 0, 0, 0)

        self.aligner = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.layout.addItem(self.aligner)

        self.setWidget(self.list)

    def pushFront(self, widget):
        self.layout.insertWidget(0, widget)

    def remove(self, widget):
        self.layout.removeWidget(widget)
        widget.deleteLater()

    def move(self, widget, position):
        self.remove(widget)
        self.layout.insertWidget(position, widget)


text:
/**
 * angular-elastic-builder
 *
 * /src/directives/BuilderDirective.js
 *
 * Angular Directive for injecting a query builder form.
 */

 (function(angular) {
   'use strict';

   angular.module('angular-elastic-builder')
    .directive('elasticBuilder', [
      'elasticQueryService',

      function EB(elasticQueryService) {

        return {
          scope: {
            data: '=elasticBuilder',
          },

          templateUrl: 'angular-elastic-builder/BuilderDirective.html',

          link: function(scope) {
            var data = scope.data;

            scope.filters = [];

            /**
             * Removes either Group or Rule
             */
            scope.removeChild = function(idx) {
              scope.filters.splice(idx, 1);
            };

            /**
             * Adds a Single Rule
             */
            scope.addRule = function() {
              scope.filters.push({});
            };

            /**
             * Adds a Group of Rules
             */
            scope.addGroup = function() {
              scope.filters.push({
                type: 'group',
                subType: 'and',
                rules: [],
              });
            };

            /**
             * Any time "outside forces" change the query, they should tell us so via
             * `data.needsUpdate`
             */
            scope.$watch('data.needsUpdate', function(curr) {
              if (! curr) return;

              scope.filters = elasticQueryService.toFilters(data.query, scope.data.fields);
              scope.data.needsUpdate = false;
            });

            /**
             * Changes on the page update the Query
             */
            scope.$watch('filters', function(curr) {
              if (! curr) return;

              data.query = elasticQueryService.toQuery(scope.filters, scope.data.fields);
            }, true);
          }
        };
      }

    ]);

 })(window.angular);


text:
"""Easy install Tests
"""
import sys
import os, shutil, tempfile, unittest
import site
from StringIO import StringIO
from setuptools.command.easy_install import easy_install, get_script_args, main
from setuptools.command.easy_install import  PthDistributions
from setuptools.command import easy_install as easy_install_pkg
from setuptools.dist import Distribution
from pkg_resources import Distribution as PRDistribution

try:
    import multiprocessing
    import logging
    _LOG = logging.getLogger('test_easy_install')
    logging.basicConfig(level=logging.INFO, stream=sys.stderr)
    _MULTIPROC = True
except ImportError:
    _MULTIPROC = False
    _LOG = None

class FakeDist(object):
    def get_entry_map(self, group):
        if group != 'console_scripts':
            return {}
        return {'name': 'ep'}

    def as_requirement(self):
        return 'spec'

WANTED = """\
#!%s
# EASY-INSTALL-ENTRY-SCRIPT: 'spec','console_scripts','name'
__requires__ = 'spec'
import sys
from pkg_resources import load_entry_point

if __name__ == '__main__':
    sys.exit(
        load_entry_point('spec', 'console_scripts', 'name')()
    )
""" % sys.executable

SETUP_PY = """\
from setuptools import setup

setup(name='foo')
"""

class TestEasyInstallTest(unittest.TestCase):

    def test_install_site_py(self):
        dist = Distribution()
        cmd = easy_install(dist)
        cmd.sitepy_installed = False
        cmd.install_dir = tempfile.mkdtemp()
        try:
            cmd.install_site_py()
            sitepy = os.path.join(cmd.install_dir, 'site.py')
            self.assert_(os.path.exists(sitepy))
        finally:
            shutil.rmtree(cmd.install_dir)

    def test_get_script_args(self):
        dist = FakeDist()

        old_platform = sys.platform
        try:
            name, script = [i for i in get_script_args(dist).next()][0:2]
        finally:
            sys.platform = old_platform

        self.assertEquals(script, WANTED)

    def test_no_setup_cfg(self):
        # makes sure easy_install as a command (main)
        # doesn't use a setup.cfg file that is located
        # in the current working directory
        dir = tempfile.mkdtemp()
        setup_cfg = open(os.path.join(dir, 'setup.cfg'), 'w')
        setup_cfg.write('[easy_install]\nfind_links = http://example.com')
        setup_cfg.close()
        setup_py = open(os.path.join(dir, 'setup.py'), 'w')
        setup_py.write(SETUP_PY)
        setup_py.close()

        from setuptools.dist import Distribution

        def _parse_command_line(self):
            msg = 'Error: a local setup.cfg was used'
            opts = self.command_options
            if 'easy_install' in opts:
                assert 'find_links' not in opts['easy_install'], msg
            return self._old_parse_command_line

        Distribution._old_parse_command_line = Distribution.parse_command_line
        Distribution.parse_command_line = _parse_command_line

        old_wd = os.getcwd()
        try:
            os.chdir(dir)
            main([])
        finally:
            os.chdir(old_wd)
            shutil.rmtree(dir)

    def test_no_find_links(self):
        # new option '--no-find-links', that blocks find-links added at
        # the project level
        dist = Distribution()
        cmd = easy_install(dist)
        cmd.check_pth_processing = lambda : True
        cmd.no_find_links = True
        cmd.find_links = ['link1', 'link2']
        cmd.install_dir = os.path.join(tempfile.mkdtemp(), 'ok')
        cmd.args = ['ok']
        cmd.ensure_finalized()
        self.assertEquals(cmd.package_index.scanned_urls, {})

        # let's try without it (default behavior)
        cmd = easy_install(dist)
        cmd.check_pth_processing = lambda : True
        cmd.find_links = ['link1', 'link2']
        cmd.install_dir = os.path.join(tempfile.mkdtemp(), 'ok')
        cmd.args = ['ok']
        cmd.ensure_finalized()
        keys = cmd.package_index.scanned_urls.keys()
        keys.sort()
        self.assertEquals(keys, ['link1', 'link2'])

class TestPTHFileWriter(unittest.TestCase):
    def test_add_from_cwd_site_sets_dirty(self):
        '''a pth file manager should set dirty
        if a distribution is in site but also the cwd
        '''
        pth = PthDistributions('does-not_exist', [os.getcwd()])
        self.assert_(not pth.dirty)
        pth.add(PRDistribution(os.getcwd()))
        self.assert_(pth.dirty)

    def test_add_from_site_is_ignored(self):
        if os.name != 'nt':
            location = '/test/location/does-not-have-to-exist'
        else:
            location = 'c:\\does_not_exist'
        pth = PthDistributions('does-not_exist', [location, ])
        self.assert_(not pth.dirty)
        pth.add(PRDistribution(location))
        self.assert_(not pth.dirty)

class TestUserInstallTest(unittest.TestCase):

    def setUp(self):
        self.dir = tempfile.mkdtemp()
        setup = os.path.join(self.dir, 'setup.py')
        f = open(setup, 'w')
        f.write(SETUP_PY)
        f.close()
        self.old_cwd = os.getcwd()
        os.chdir(self.dir)
        if sys.version >= "2.6":
            self.old_has_site = easy_install_pkg.HAS_USER_SITE
            self.old_file = easy_install_pkg.__file__
            self.old_base = site.USER_BASE
            site.USER_BASE = tempfile.mkdtemp()
            self.old_site = site.USER_SITE
            site.USER_SITE = tempfile.mkdtemp()
            easy_install_pkg.__file__ = site.USER_SITE

    def tearDown(self):
        os.chdir(self.old_cwd)
        shutil.rmtree(self.dir)
        if sys.version >=  "2.6":
            shutil.rmtree(site.USER_BASE)
            shutil.rmtree(site.USER_SITE)
            site.USER_BASE = self.old_base
            site.USER_SITE = self.old_site
            easy_install_pkg.HAS_USER_SITE = self.old_has_site
            easy_install_pkg.__file__ = self.old_file

    def test_user_install_implied(self):
        easy_install_pkg.HAS_USER_SITE = True # disabled sometimes
        #XXX: replace with something meaningfull
        if sys.version < "2.6":
            return #SKIP
        dist = Distribution()
        dist.script_name = 'setup.py'
        cmd = easy_install(dist)
        cmd.args = ['py']
        cmd.ensure_finalized()
        self.assertTrue(cmd.user, 'user should be implied')

    def test_multiproc_atexit(self):
        if not _MULTIPROC:
            return
        _LOG.info('this should not break')

    def test_user_install_not_implied_without_usersite_enabled(self):
        easy_install_pkg.HAS_USER_SITE = False # usually enabled
        #XXX: replace with something meaningfull
        if sys.version < "2.6":
            return #SKIP
        dist = Distribution()
        dist.script_name = 'setup.py'
        cmd = easy_install(dist)
        cmd.args = ['py']
        cmd.initialize_options()
        self.assertFalse(cmd.user, 'NOT user should be implied')

    def test_local_index(self):
        # make sure the local index is used
        # when easy_install looks for installed
        # packages
        new_location = tempfile.mkdtemp()
        target = tempfile.mkdtemp()
        egg_file = os.path.join(new_location, 'foo-1.0.egg-info')
        f = open(egg_file, 'w')
        try:
            f.write('Name: foo\n')
        except:
            f.close()

        sys.path.append(target)
        old_ppath = os.environ.get('PYTHONPATH')
        os.environ['PYTHONPATH'] = os.path.pathsep.join(sys.path)
        try:
            dist = Distribution()
            dist.script_name = 'setup.py'
            cmd = easy_install(dist)
            cmd.install_dir = target
            cmd.args = ['foo']
            cmd.ensure_finalized()
            cmd.local_index.scan([new_location])
            res = cmd.easy_install('foo')
            self.assertEquals(res.location, new_location)
        finally:
            sys.path.remove(target)
            for basedir in [new_location, target, ]:
                if not os.path.exists(basedir) or not os.path.isdir(basedir):
                    continue
                try:
                    shutil.rmtree(basedir)
                except:
                    pass
            if old_ppath is not None:
                os.environ['PYTHONPATH'] = old_ppath
            else:
                del os.environ['PYTHONPATH']