text:
package cache

import (
	"context"
	"go/ast"
	"go/types"
	"sort"
	"sync"

	"golang.org/x/tools/go/analysis"
	"golang.org/x/tools/go/packages"
	"golang.org/x/tools/internal/lsp/source"
)

// pkg contains the type information needed by the source package.
type pkg struct {
	view *view

	// ID and package path have their own types to avoid being used interchangeably.
	id      packageID
	pkgPath packagePath

	files      []source.ParseGoHandle
	errors     []packages.Error
	imports    map[packagePath]*pkg
	types      *types.Package
	typesInfo  *types.Info
	typesSizes types.Sizes

	// The analysis cache holds analysis information for all the packages in a view.
	// Each graph node (action) is one unit of analysis.
	// Edges express package-to-package (vertical) dependencies,
	// and analysis-to-analysis (horizontal) dependencies.
	mu       sync.Mutex
	analyses map[*analysis.Analyzer]*analysisEntry

	diagMu      sync.Mutex
	diagnostics []source.Diagnostic
}

// packageID is a type that abstracts a package ID.
type packageID string

// packagePath is a type that abstracts a package path.
type packagePath string

type analysisEntry struct {
	done      chan struct{}
	succeeded bool
	*source.Action
}

func (pkg *pkg) GetActionGraph(ctx context.Context, a *analysis.Analyzer) (*source.Action, error) {
	pkg.mu.Lock()
	e, ok := pkg.analyses[a]
	if ok {
		// cache hit
		pkg.mu.Unlock()

		// wait for entry to become ready or the context to be cancelled
		select {
		case <-e.done:
			// If the goroutine we are waiting on was cancelled, we should retry.
			// If errors other than cancelation/timeout become possible, it may
			// no longer be appropriate to always retry here.
			if !e.succeeded {
				return pkg.GetActionGraph(ctx, a)
			}
		case <-ctx.Done():
			return nil, ctx.Err()
		}
	} else {
		// cache miss
		e = &analysisEntry{
			done: make(chan struct{}),
			Action: &source.Action{
				Analyzer: a,
				Pkg:      pkg,
			},
		}
		pkg.analyses[a] = e
		pkg.mu.Unlock()

		defer func() {
			// If we got an error, clear out our defunct cache entry. We don't cache
			// errors since they could depend on our dependencies, which can change.
			// Currently the only possible error is context.Canceled, though, which
			// should also not be cached.
			if !e.succeeded {
				pkg.mu.Lock()
				delete(pkg.analyses, a)
				pkg.mu.Unlock()
			}

			// Always close done so waiters don't get stuck.
			close(e.done)
		}()

		// This goroutine becomes responsible for populating
		// the entry and broadcasting its readiness.

		// Add a dependency on each required analyzers.
		for _, req := range a.Requires {
			act, err := pkg.GetActionGraph(ctx, req)
			if err != nil {
				return nil, err
			}
			e.Deps = append(e.Deps, act)
		}

		// An analysis that consumes/produces facts
		// must run on the package's dependencies too.
		if len(a.FactTypes) > 0 {
			importPaths := make([]string, 0, len(pkg.imports))
			for importPath := range pkg.imports {
				importPaths = append(importPaths, string(importPath))
			}
			sort.Strings(importPaths) // for determinism
			for _, importPath := range importPaths {
				dep, err := pkg.GetImport(ctx, importPath)
				if err != nil {
					return nil, err
				}
				act, err := dep.GetActionGraph(ctx, a)
				if err != nil {
					return nil, err
				}
				e.Deps = append(e.Deps, act)
			}
		}
		e.succeeded = true
	}
	return e.Action, nil
}

func (pkg *pkg) ID() string {
	return string(pkg.id)
}

func (pkg *pkg) PkgPath() string {
	return string(pkg.pkgPath)
}

func (pkg *pkg) GetHandles() []source.ParseGoHandle {
	return pkg.files
}

func (pkg *pkg) GetSyntax(ctx context.Context) []*ast.File {
	var syntax []*ast.File
	for _, ph := range pkg.files {
		file, _ := ph.Cached(ctx)
		if file != nil {
			syntax = append(syntax, file)
		}
	}
	return syntax
}

func (pkg *pkg) GetErrors() []packages.Error {
	return pkg.errors
}

func (pkg *pkg) GetTypes() *types.Package {
	return pkg.types
}

func (pkg *pkg) GetTypesInfo() *types.Info {
	return pkg.typesInfo
}

func (pkg *pkg) GetTypesSizes() types.Sizes {
	return pkg.typesSizes
}

func (pkg *pkg) IsIllTyped() bool {
	return pkg.types == nil && pkg.typesInfo == nil
}

func (pkg *pkg) SetDiagnostics(diags []source.Diagnostic) {
	pkg.diagMu.Lock()
	defer pkg.diagMu.Unlock()
	pkg.diagnostics = diags
}

func (pkg *pkg) GetDiagnostics() []source.Diagnostic {
	pkg.diagMu.Lock()
	defer pkg.diagMu.Unlock()
	return pkg.diagnostics
}


text:
$.fn.frFileUpload = function (option) {
    var $this = $(this);

    var $trigger = $this.find('[data-trigger]');
    var $inputFile = $this.find('input[type="file"]');
    var $uploadTable = $this.find('table[data-file-info]')

    $this['default'] = {
        dismissTime: 3000,
        maxFileSize: 30 * 1024,
        uploadCallback: function(data) {
            return true;
        }
    }

    $this['config'] = $.extend($this['default'], option)

    $inputFile.width($trigger.outerWidth());
    $inputFile.height($trigger.outerHeight());

    $this.fileUploadUIReady({
        autoUpload: false,
        maxChunkSize: 20 * 1024 * 1024,
        namespace: 'fr_file_' + (new Date()).getTime(), // namespace 在同一页面是否必须唯一?
        fileInputFilter: $inputFile,
        dropZone: $trigger,
        uploadTable: $uploadTable,
        downloadTable: $uploadTable,
        acceptFileTypes: $this['config']['acceptFileTypes'],

        buildUploadRow: function (files, index) {
            $uploadTable.html('')

            return $("

" + "" + files[index].name + "	" +
                "

");
        },

        beforeSend: function (event, files, index, xhr, handler, callBack) {
            //test the type of file
            var regexp = $this.config.acceptFileTypes;
            var area = handler.uploadRow.find('.file_upload_progress').html('');

            if (regexp != undefined && !regexp.test(files[index].name)) {
                area.html($this['config']['fileTypeHint']);

                setTimeout(function () {
                    handler.removeNode(handler.uploadRow);
                }, $this['config']['dismissTime']);

                return;
            }

            //test the size of file
            if (files[index].size > $this.config.maxFileSize) {

                area.html('文件必须小于' + ($this.config.maxFileSize >> 10) + 'KB!');

                setTimeout(function () {
                    handler.removeNode(handler.uploadRow);
                }, $this['config']['dismissTime']);

                return;
            }

            callBack();
        },

        buildDownloadRow: function (data) {
            var status = $this['config'].uploadCallback(data);

            if (status == false) {
                return $('
文件上传失败,请重传!
');
            }
        }
    })

    return $this;
}

redpajama_set_name: RedPajamaGithub


text:
Changes in *[arch](#arch)* and *[configs](#configs)* folders are mandantory to support a new board.
Adding static library or expanding driver will be provided later.

## Arch

Changes in *arch* directory for a new board includes chip architecture and BSP for board.
Currently, TizenRT supports only ARM architecture.
But if new board is another architecture, new architecture folder should be added in this path.

### BSP

There are three kinds of folders, core, chip architecture and board.
For example, armv7-r is a core architecture, s5j is a chip architecture and artik053 is a board.

At least, new board folder should be added.

### Kconfig

Modifications on below two Kconfigs show new board configurations on menuconfig.

#### Chip
Modify *os/arch/arm/Kconfig* file.

1. Add new configurations as belows.
```
choice
	prompt "ARM chip selection"

config ARCH_CHIP_<CHIP_NAME>
	bool "XXX"
	select ARCH_HAVE_YYY
endchoice

config ARCH_CHIP
	string
	default "<CHIP_NAME>"       if ARCH_CHIP_<CHIP_NAME>
```

2. Include Kconfig as belows.
```
if ARCH_CHIP_<CHIP_NAME>
source arch/arm/src/<CHIP_NAME>/Kconfig
endif
```

#### Board
Modify *os/arch/Kconfig.board* file.

1. Add new configurations as belows.
```
choice
	prompt "Select target board"

config ARCH_BOARD_<BOARD_NAME>
	bool "XXX Starter Kit"
	depends on ARCH_CHIP_<CHIP_NAME>
	select YYY
endchoice

config ARCH_BOARD
	string
	default "<BOARD_NAME>"           if ARCH_BOARD_<BOARD_NAME>
```

2. Include Kconfig as belows.
```
comment "Board-Specific Options"

if ARCH_BOARD_<BOARD_NAME>
source arch/arm/src/<BOARD_NAME>/Kconfig
endif
```

## Configs

Changes in *configs* folder includes build options and flash operations.

1. Add a new folder with board name.
```
mkdir build/configs/<board-name>
```

2. Add the *script* folder and add the linker script file.
```
mkdir build/configs/<board-name>/scripts
```

3. Add a new folder with representing main program name under \<board-name\> folder.
```
mkdir build/configs/<board-name>/<program-name>
```

4. Put *defconfig* and *Make.defs* inside \<program-name\>.

### defconfig

This is a configurations set of representing folder name.
This is moved to .config at executing configure.sh and used to build TizenRT.

### Make.defs

This is a build options set like setting of including path, ARM build options, linker script name and so on.
There is the DOWNLOAD definition to support "make download xx" command too.


text:
import {Component, ContentChild, ContentChildren, Directive, ElementRef, Input, QueryList, TemplateRef, Type, ViewChild, ViewChildren} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/src/matchers';
import {onlyInIvy} from '@angular/private/testing';

describe('query logic', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComp, QueryComp, SimpleCompA, SimpleCompB, StaticViewQueryComp, TextDirective,
        SubclassStaticViewQueryComp, StaticContentQueryComp, SubclassStaticContentQueryComp,
        QueryCompWithChanges, StaticContentQueryDir, SuperDirectiveQueryTarget, SuperDirective,
        SubComponent
      ]
    });
  });

  describe('view queries', () => {
    it('should return Component instances when Components are labeled and retrieved', () => {
      const template = `

<simple-comp-a #viewQuery></simple-comp-a>

<simple-comp-b #viewQuery></simple-comp-b>

         `;
      const fixture = initWithTemplate(QueryComp, template);
      const comp = fixture.componentInstance;
      expect(comp.viewChild).toBeAnInstanceOf(SimpleCompA);
      expect(comp.viewChildren.first).toBeAnInstanceOf(SimpleCompA);
      expect(comp.viewChildren.last).toBeAnInstanceOf(SimpleCompB);
    });

    it('should return ElementRef when HTML element is labeled and retrieved', () => {
      const template = `

    `;
      const fixture = initWithTemplate(QueryComp, template);
      const comp = fixture.componentInstance;
      expect(comp.viewChild).toBeAnInstanceOf(ElementRef);
      expect(comp.viewChildren.first).toBeAnInstanceOf(ElementRef);
    });

    onlyInIvy('multiple local refs are supported in Ivy')
        .it('should return ElementRefs when HTML elements are labeled and retrieved', () => {
          const template = `

A

B

            `;
          const fixture = initWithTemplate(QueryComp, template);
          const comp = fixture.componentInstance;

          expect(comp.viewChild).toBeAnInstanceOf(ElementRef);
          expect(comp.viewChild.nativeElement).toBe(fixture.debugElement.children[0].nativeElement);

          expect(comp.viewChildren.first).toBeAnInstanceOf(ElementRef);
          expect(comp.viewChildren.last).toBeAnInstanceOf(ElementRef);
          expect(comp.viewChildren.length).toBe(2);
        });

    it('should return TemplateRef when template is labeled and retrieved', () => {
      const template = `
      <ng-template #viewQuery></ng-template>
    `;
      const fixture = initWithTemplate(QueryComp, template);
      const comp = fixture.componentInstance;
      expect(comp.viewChildren.first).toBeAnInstanceOf(TemplateRef);
    });

    onlyInIvy('multiple local refs are supported in Ivy')
        .it('should return TemplateRefs when templates are labeled and retrieved', () => {
          const template = `
              <ng-template #viewQuery></ng-template>
              <ng-template #viewQuery></ng-template>
            `;
          const fixture = initWithTemplate(QueryComp, template);
          const comp = fixture.componentInstance;
          expect(comp.viewChild).toBeAnInstanceOf(TemplateRef);
          expect(comp.viewChild.elementRef.nativeElement)
              .toBe(fixture.debugElement.childNodes[0].nativeNode);

          expect(comp.viewChildren.first).toBeAnInstanceOf(TemplateRef);
          expect(comp.viewChildren.last).toBeAnInstanceOf(TemplateRef);
          expect(comp.viewChildren.length).toBe(2);
        });

    it('should set static view child queries in creation mode (and just in creation mode)', () => {
      const fixture = TestBed.createComponent(StaticViewQueryComp);
      const component = fixture.componentInstance;

      // static ViewChild query should be set in creation mode, before CD runs
      expect(component.textDir).toBeAnInstanceOf(TextDirective);
      expect(component.textDir.text).toEqual('');
      expect(component.setEvents).toEqual(['textDir set']);

      // dynamic ViewChild query should not have been resolved yet
      expect(component.foo).not.toBeDefined();

      const span = fixture.nativeElement.querySelector('span');
      fixture.detectChanges();
      expect(component.textDir.text).toEqual('some text');
      expect(component.foo.nativeElement).toBe(span);
      expect(component.setEvents).toEqual(['textDir set', 'foo set']);
    });

    it('should support static view child queries inherited from superclasses', () => {
      const fixture = TestBed.createComponent(SubclassStaticViewQueryComp);
      const component = fixture.componentInstance;
      const divs = fixture.nativeElement.querySelectorAll('div');
      const spans = fixture.nativeElement.querySelectorAll('span');

      // static ViewChild queries should be set in creation mode, before CD runs
      expect(component.textDir).toBeAnInstanceOf(TextDirective);
      expect(component.textDir.text).toEqual('');
      expect(component.bar.nativeElement).toEqual(divs[1]);

      // dynamic ViewChild queries should not have been resolved yet
      expect(component.foo).not.toBeDefined();
      expect(component.baz).not.toBeDefined();

      fixture.detectChanges();
      expect(component.textDir.text).toEqual('some text');
      expect(component.foo.nativeElement).toBe(spans[0]);
      expect(component.baz.nativeElement).toBe(spans[1]);
    });

    it('should support multiple static view queries (multiple template passes)', () => {
      const template = `
           <static-view-query-comp></static-view-query-comp>
           <static-view-query-comp></static-view-query-comp>
         `;
      TestBed.overrideComponent(AppComp, {set: new Component({template})});
      const fixture = TestBed.createComponent(AppComp);

      const firstComponent = fixture.debugElement.children[0].injector.get(StaticViewQueryComp);
      const secondComponent = fixture.debugElement.children[1].injector.get(StaticViewQueryComp);

      // static ViewChild query should be set in creation mode, before CD runs
      expect(firstComponent.textDir).toBeAnInstanceOf(TextDirective);
      expect(secondComponent.textDir).toBeAnInstanceOf(TextDirective);
      expect(firstComponent.textDir.text).toEqual('');
      expect(secondComponent.textDir.text).toEqual('');
      expect(firstComponent.setEvents).toEqual(['textDir set']);
      expect(secondComponent.setEvents).toEqual(['textDir set']);

      // dynamic ViewChild query should not have been resolved yet
      expect(firstComponent.foo).not.toBeDefined();
      expect(secondComponent.foo).not.toBeDefined();

      const spans = fixture.nativeElement.querySelectorAll('span');
      fixture.detectChanges();
      expect(firstComponent.textDir.text).toEqual('some text');
      expect(secondComponent.textDir.text).toEqual('some text');
      expect(firstComponent.foo.nativeElement).toBe(spans[0]);
      expect(secondComponent.foo.nativeElement).toBe(spans[1]);
      expect(firstComponent.setEvents).toEqual(['textDir set', 'foo set']);
      expect(secondComponent.setEvents).toEqual(['textDir set', 'foo set']);
    });

    it('should allow for view queries to be inherited from a directive', () => {
      const fixture = TestBed.createComponent(SubComponent);
      const comp = fixture.componentInstance;
      fixture.detectChanges();

      expect(comp.headers).toBeTruthy();
      expect(comp.headers.length).toBe(2);
      expect(comp.headers.toArray().every(result => result instanceof SuperDirectiveQueryTarget))
          .toBe(true);
    });

  });

  describe('content queries', () => {
    it('should return Component instance when Component is labeled and retrieved', () => {
      const template = `
           <local-ref-query-component #q>
             <simple-comp-a #contentQuery></simple-comp-a>
           </local-ref-query-component>
         `;
      const fixture = initWithTemplate(AppComp, template);
      const comp = fixture.debugElement.children[0].references['q'];
      expect(comp.contentChild).toBeAnInstanceOf(SimpleCompA);
      expect(comp.contentChildren.first).toBeAnInstanceOf(SimpleCompA);
    });

    onlyInIvy('multiple local refs are supported in Ivy')
        .it('should return Component instances when Components are labeled and retrieved', () => {
          const template = `
                <local-ref-query-component #q>
                  <simple-comp-a #contentQuery></simple-comp-a>
                  <simple-comp-b #contentQuery></simple-comp-b>
                </local-ref-query-component>
              `;
          const fixture = initWithTemplate(AppComp, template);
          const comp = fixture.debugElement.children[0].references['q'];
          expect(comp.contentChild).toBeAnInstanceOf(SimpleCompA);
          expect(comp.contentChildren.first).toBeAnInstanceOf(SimpleCompA);
          expect(comp.contentChildren.last).toBeAnInstanceOf(SimpleCompB);
          expect(comp.contentChildren.length).toBe(2);
        });

    it('should return ElementRef when HTML element is labeled and retrieved', () => {
      const template = `
         <local-ref-query-component #q>

         </local-ref-query-component>
       `;
      const fixture = initWithTemplate(AppComp, template);
      const comp = fixture.debugElement.children[0].references['q'];
      expect(comp.contentChildren.first).toBeAnInstanceOf(ElementRef);
    });

    onlyInIvy('multiple local refs are supported in Ivy')
        .it('should return ElementRefs when HTML elements are labeled and retrieved', () => {
          const template = `
              <local-ref-query-component #q>

              </local-ref-query-component>
            `;
          const fixture = initWithTemplate(AppComp, template);
          const firstChild = fixture.debugElement.children[0];
          const comp = firstChild.references['q'];

          expect(comp.contentChild).toBeAnInstanceOf(ElementRef);
          expect(comp.contentChild.nativeElement).toBe(firstChild.children[0].nativeElement);

          expect(comp.contentChildren.first).toBeAnInstanceOf(ElementRef);
          expect(comp.contentChildren.last).toBeAnInstanceOf(ElementRef);
          expect(comp.contentChildren.length).toBe(2);
        });

    it('should return TemplateRef when template is labeled and retrieved', () => {
      const template = `
       <local-ref-query-component #q>
         <ng-template #contentQuery></ng-template>
       </local-ref-query-component>
     `;
      const fixture = initWithTemplate(AppComp, template);
      const comp = fixture.debugElement.children[0].references['q'];
      expect(comp.contentChildren.first).toBeAnInstanceOf(TemplateRef);
    });

    onlyInIvy('multiple local refs are supported in Ivy')
        .it('should return TemplateRefs when templates are labeled and retrieved', () => {
          const template = `
              <local-ref-query-component #q>
                <ng-template #contentQuery></ng-template>
                <ng-template #contentQuery></ng-template>
              </local-ref-query-component>
            `;
          const fixture = initWithTemplate(AppComp, template);
          const firstChild = fixture.debugElement.children[0];
          const comp = firstChild.references['q'];

          expect(comp.contentChild).toBeAnInstanceOf(TemplateRef);
          expect(comp.contentChild.elementRef.nativeElement)
              .toBe(firstChild.childNodes[0].nativeNode);

          expect(comp.contentChildren.first).toBeAnInstanceOf(TemplateRef);
          expect(comp.contentChildren.last).toBeAnInstanceOf(TemplateRef);
          expect(comp.contentChildren.length).toBe(2);
        });

    it('should set static content child queries in creation mode (and just in creation mode)',
       () => {
         const template = `
              <static-content-query-comp>

              </static-content-query-comp>
            `;
         TestBed.overrideComponent(AppComp, {set: new Component({template})});
         const fixture = TestBed.createComponent(AppComp);
         const component = fixture.debugElement.children[0].injector.get(StaticContentQueryComp);

         // static ContentChild query should be set in creation mode, before CD runs
         expect(component.textDir).toBeAnInstanceOf(TextDirective);
         expect(component.textDir.text).toEqual('');
         expect(component.setEvents).toEqual(['textDir set']);

         // dynamic ContentChild query should not have been resolved yet
         expect(component.foo).not.toBeDefined();

         const span = fixture.nativeElement.querySelector('span');
         (fixture.componentInstance as any).text = 'some text';
         fixture.detectChanges();

         expect(component.textDir.text).toEqual('some text');
         expect(component.foo.nativeElement).toBe(span);
         expect(component.setEvents).toEqual(['textDir set', 'foo set']);
       });

    it('should support static content child queries inherited from superclasses', () => {
      const template = `
              <subclass-static-content-query-comp>

              </subclass-static-content-query-comp>
            `;
      TestBed.overrideComponent(AppComp, {set: new Component({template})});
      const fixture = TestBed.createComponent(AppComp);
      const component =
          fixture.debugElement.children[0].injector.get(SubclassStaticContentQueryComp);
      const divs = fixture.nativeElement.querySelectorAll('div');
      const spans = fixture.nativeElement.querySelectorAll('span');

      // static ContentChild queries should be set in creation mode, before CD runs
      expect(component.textDir).toBeAnInstanceOf(TextDirective);
      expect(component.textDir.text).toEqual('');
      expect(component.bar.nativeElement).toEqual(divs[1]);

      // dynamic ContentChild queries should not have been resolved yet
      expect(component.foo).not.toBeDefined();
      expect(component.baz).not.toBeDefined();

      (fixture.componentInstance as any).text = 'some text';
      fixture.detectChanges();
      expect(component.textDir.text).toEqual('some text');
      expect(component.foo.nativeElement).toBe(spans[0]);
      expect(component.baz.nativeElement).toBe(spans[1]);
    });

    it('should set static content child queries on directives', () => {
      const template = `

            `;
      TestBed.overrideComponent(AppComp, {set: new Component({template})});
      const fixture = TestBed.createComponent(AppComp);
      const component = fixture.debugElement.children[0].injector.get(StaticContentQueryDir);

      // static ContentChild query should be set in creation mode, before CD runs
      expect(component.textDir).toBeAnInstanceOf(TextDirective);
      expect(component.textDir.text).toEqual('');
      expect(component.setEvents).toEqual(['textDir set']);

      // dynamic ContentChild query should not have been resolved yet
      expect(component.foo).not.toBeDefined();

      const span = fixture.nativeElement.querySelector('span');
      (fixture.componentInstance as any).text = 'some text';
      fixture.detectChanges();

      expect(component.textDir.text).toEqual('some text');
      expect(component.foo.nativeElement).toBe(span);
      expect(component.setEvents).toEqual(['textDir set', 'foo set']);
    });

    it('should support multiple content query components (multiple template passes)', () => {
      const template = `
              <static-content-query-comp>

              </static-content-query-comp>
              <static-content-query-comp>

              </static-content-query-comp>
            `;
      TestBed.overrideComponent(AppComp, {set: new Component({template})});
      const fixture = TestBed.createComponent(AppComp);
      const firstComponent = fixture.debugElement.children[0].injector.get(StaticContentQueryComp);
      const secondComponent = fixture.debugElement.children[1].injector.get(StaticContentQueryComp);

      // static ContentChild query should be set in creation mode, before CD runs
      expect(firstComponent.textDir).toBeAnInstanceOf(TextDirective);
      expect(secondComponent.textDir).toBeAnInstanceOf(TextDirective);
      expect(firstComponent.textDir.text).toEqual('');
      expect(secondComponent.textDir.text).toEqual('');
      expect(firstComponent.setEvents).toEqual(['textDir set']);
      expect(secondComponent.setEvents).toEqual(['textDir set']);

      // dynamic ContentChild query should not have been resolved yet
      expect(firstComponent.foo).not.toBeDefined();
      expect(secondComponent.foo).not.toBeDefined();

      const spans = fixture.nativeElement.querySelectorAll('span');
      (fixture.componentInstance as any).text = 'some text';
      fixture.detectChanges();

      expect(firstComponent.textDir.text).toEqual('some text');
      expect(secondComponent.textDir.text).toEqual('some text');

      expect(firstComponent.foo.nativeElement).toBe(spans[0]);
      expect(secondComponent.foo.nativeElement).toBe(spans[1]);

      expect(firstComponent.setEvents).toEqual(['textDir set', 'foo set']);
      expect(secondComponent.setEvents).toEqual(['textDir set', 'foo set']);
    });

  });

  describe('descendants', () => {

    it('should match directives on elements that used to be wrapped by a required parent in HTML parser',
       () => {

         @Directive({selector: '[myDef]'})
         class MyDef {
         }

         @Component({selector: 'my-container', template: ``})
         class MyContainer {
           @ContentChildren(MyDef) myDefs !: QueryList<MyDef>;
         }
         @Component(
             {selector: 'test-cmpt', template: `<my-container><tr myDef></tr></my-container>`})
         class TestCmpt {
         }

         TestBed.configureTestingModule({declarations: [TestCmpt, MyContainer, MyDef]});
         const fixture = TestBed.createComponent(TestCmpt);
         const cmptWithQuery = fixture.debugElement.children[0].injector.get(MyContainer);

         fixture.detectChanges();
         expect(cmptWithQuery.myDefs.length).toBe(1);
       });
  });

  describe('observable interface', () => {

    it('should allow observing changes to query list', () => {
      const fixture = TestBed.createComponent(QueryCompWithChanges);
      let changes = 0;
      fixture.detectChanges();

      fixture.componentInstance.foos.changes.subscribe((value: any) => {
        changes += 1;
        expect(value).toBe(fixture.componentInstance.foos);
      });

      // refresh without setting dirty - no emit
      fixture.detectChanges();
      expect(changes).toBe(0);

      // refresh with setting dirty - emit
      fixture.componentInstance.showing = true;
      fixture.detectChanges();
      expect(changes).toBe(1);
    });

  });

});

function initWithTemplate(compType: Type<any>, template: string) {
  TestBed.overrideComponent(compType, {set: new Component({template})});
  const fixture = TestBed.createComponent(compType);
  fixture.detectChanges();
  return fixture;
}

@Component({selector: 'local-ref-query-component', template: '<ng-content></ng-content>'})
class QueryComp {
  @ViewChild('viewQuery') viewChild !: any;
  @ContentChild('contentQuery') contentChild !: any;

  @ViewChildren('viewQuery') viewChildren !: QueryList<any>;
  @ContentChildren('contentQuery') contentChildren !: QueryList<any>;
}

@Component({selector: 'app-comp', template: ``})
class AppComp {
}

@Component({selector: 'simple-comp-a', template: ''})
class SimpleCompA {
}

@Component({selector: 'simple-comp-b', template: ''})
class SimpleCompB {
}

@Directive({selector: '[text]'})
class TextDirective {
  @Input() text = '';
}

@Component({
  selector: 'static-view-query-comp',
  template: `

  `
})
class StaticViewQueryComp {
  private _textDir !: TextDirective;
  private _foo !: ElementRef;
  setEvents: string[] = [];

  @ViewChild(TextDirective, {static: true})
  get textDir(): TextDirective { return this._textDir; }

  set textDir(value: TextDirective) {
    this.setEvents.push('textDir set');
    this._textDir = value;
  }

  @ViewChild('foo', {static: false})
  get foo(): ElementRef { return this._foo; }

  set foo(value: ElementRef) {
    this.setEvents.push('foo set');
    this._foo = value;
  }

  text = 'some text';
}

@Component({
  selector: 'subclass-static-view-query-comp',
  template: `

  `
})
class SubclassStaticViewQueryComp extends StaticViewQueryComp {
  @ViewChild('bar', {static: true})
  bar !: ElementRef;

  @ViewChild('baz', {static: false})
  baz !: ElementRef;
}

@Component({selector: 'static-content-query-comp', template: `<ng-content></ng-content>`})
class StaticContentQueryComp {
  private _textDir !: TextDirective;
  private _foo !: ElementRef;
  setEvents: string[] = [];

  @ContentChild(TextDirective, {static: true})
  get textDir(): TextDirective { return this._textDir; }

  set textDir(value: TextDirective) {
    this.setEvents.push('textDir set');
    this._textDir = value;
  }

  @ContentChild('foo', {static: false})
  get foo(): ElementRef { return this._foo; }

  set foo(value: ElementRef) {
    this.setEvents.push('foo set');
    this._foo = value;
  }
}

@Directive({selector: '[staticContentQueryDir]'})
class StaticContentQueryDir {
  private _textDir !: TextDirective;
  private _foo !: ElementRef;
  setEvents: string[] = [];

  @ContentChild(TextDirective, {static: true})
  get textDir(): TextDirective { return this._textDir; }

  set textDir(value: TextDirective) {
    this.setEvents.push('textDir set');
    this._textDir = value;
  }

  @ContentChild('foo', {static: false})
  get foo(): ElementRef { return this._foo; }

  set foo(value: ElementRef) {
    this.setEvents.push('foo set');
    this._foo = value;
  }
}

@Component({selector: 'subclass-static-content-query-comp', template: `<ng-content></ng-content>`})
class SubclassStaticContentQueryComp extends StaticContentQueryComp {
  @ContentChild('bar', {static: true})
  bar !: ElementRef;

  @ContentChild('baz', {static: false})
  baz !: ElementRef;
}

@Component({
  selector: 'query-with-changes',
  template: `

  `
})
export class QueryCompWithChanges {
  @ViewChildren('foo') foos !: QueryList<any>;

  showing = false;
}

@Component({selector: 'query-target', template: '<ng-content></ng-content>'})
class SuperDirectiveQueryTarget {
}

@Directive({selector: '[super-directive]'})
class SuperDirective {
  @ViewChildren(SuperDirectiveQueryTarget) headers !: QueryList<SuperDirectiveQueryTarget>;
}

@Component({
  template: `
    <query-target>One</query-target>
    <query-target>Two</query-target>
  `
})
class SubComponent extends SuperDirective {
}


text:
<?php
class ValidatorPercentageTest extends PHPUnit_Framework_TestCase
{
    public function testWith60Percent()
    {
        $percentage = 60;
        $feature = new Enabler\Feature("Music", true, ["Enabler\Filter\Distributed" => [$percentage]]);

        $mockStorage = $this->getMockBuilder('Enabler\Storage\Storable')->getMock();
        $mockStorage->expects($this->any())
            ->method('get')
            ->will($this->returnValue($feature));

        $enabler = new Enabler\Enabler(
            $mockStorage
        );

        $enabler->storage()->create($feature);
        $numEnables = 0;

        for($i = 0; $i <= 10000; $i++) {
            if($enabler->enabled('Music')) {
                $numEnables++;
            }
        }

        $result = (($numEnables-($numEnables)) <= $percentage) ? true : false;

        $this->assertTrue($result);
    }

    public function testWith10Percent()
    {
        $percentage = 10;
        $feature = new Enabler\Feature("Music", true, ["Enabler\Filter\Distributed" => [$percentage]]);

        $mockStorage = $this->getMockBuilder('Enabler\Storage\Storable')->getMock();
        $mockStorage->expects($this->any())
            ->method('get')
            ->will($this->returnValue($feature));

        $enabler = new Enabler\Enabler(
            $mockStorage
        );

        $enabler->storage()->create($feature);
        $numEnables = 0;

        for($i = 0; $i <= 10000; $i++) {
            if($enabler->enabled('Music')) {
                $numEnables++;
            }
        }

        $result = (($numEnables-($numEnables)) <= $percentage) ? true : false;

        $this->assertTrue($result);
    }

    public function testWith35Percent()
    {
        $percentage = 35;
        $feature = new Enabler\Feature("Music", true, ["Enabler\Filter\Distributed" => [$percentage]]);

        $mockStorage = $this->getMockBuilder('Enabler\Storage\Storable')->getMock();
        $mockStorage->expects($this->any())
            ->method('get')
            ->will($this->returnValue($feature));

        $enabler = new Enabler\Enabler(
            $mockStorage
        );

        $enabler->storage()->create($feature);
        $numEnables = 0;

        for($i = 0; $i <= 10000; $i++) {
            if($enabler->enabled('Music')) {
                $numEnables++;
            }
        }

        $result = (($numEnables-($numEnables)) <= $percentage) ? true : false;

        $this->assertTrue($result);
    }

    public function testWith82Percent()
    {
        $percentage = 82;
        $feature = new Enabler\Feature("Music", true, ["Enabler\Filter\Distributed" => [$percentage]]);

        $mockStorage = $this->getMockBuilder('Enabler\Storage\Storable')->getMock();
        $mockStorage->expects($this->any())
            ->method('get')
            ->will($this->returnValue($feature));

        $enabler = new Enabler\Enabler(
            $mockStorage
        );

        $enabler->storage()->create($feature);
        $numEnables = 0;

        for($i = 0; $i <= 10000; $i++) {
            if($enabler->enabled('Music')) {
                $numEnables++;
            }
        }

        $result = (($numEnables-($numEnables)) <= $percentage) ? true : false;

        $this->assertTrue($result);
    }

    public function testWith1Percent()
    {
        $percentage = 1;
        $feature = new Enabler\Feature("Music", true, ["Enabler\Filter\Distributed" => [$percentage]]);

        $mockStorage = $this->getMockBuilder('Enabler\Storage\Storable')->getMock();
        $mockStorage->expects($this->any())
            ->method('get')
            ->will($this->returnValue($feature));

        $enabler = new Enabler\Enabler(
            $mockStorage
        );

        $enabler->storage()->create($feature);
        $numEnables = 0;

        for($i = 0; $i <= 10000; $i++) {
            if($enabler->enabled('Music')) {
                $numEnables++;
            }
        }

        $result = (($numEnables-($numEnables)) <= $percentage) ? true : false;

        $this->assertTrue($result);
    }
}


text:
% main -- LAP Dataset Overview and Geometry (lapdog) main file
%
% Create overview of LAP ops and geometry files for a given data set.
% anders.eriksson@irfu.se 2012-03-29
% frejon@irfu.se 2014-04-28
%For local execution via Matlab, to execute in batch mode, see lapdog.m
%Quick description
%1. The program is designed to be controlled in control.m, with no other user
% input necessary
%2. preamble defines some variables used everywhere in the script
%3.(Unless already done)
%indexgen reads every .LBL file in the archive (50% of all files) as
%specified from the index.dat file in outputs it into a useful "index"
%variable
%4. some post-processing of the index is needed in indexcorr to split files
%exactly at midnight, OBS some files created in temp/ folder,
%5.generates daily geometry files
%6. Seperates all files into macro operation blocks, each block terminated
%by midnight or new macroid
%7. (unless already done)
%process reads all data, and mills it into new, condensed files
%** information of each new file is stored in "tabindex" variable
%8. an_IV analyses sweeps, wave snapshots (spectra), and downsamples data for
%quick-look plots and stores them in files
%** information of each new file is stored in "an_tabindex" variable
%9. createLBL produces .LBL files for each generated file  (PDS archive
%specific file type)
%

'LAPDOG - LAP Data Overview and Geometry'
''
tic

% Define the dataset:
'lapdog: calling control...'
control;

% Set up PDS keywords, constants etc:
'lapdog: calling preamble...'
preamble;

% Load or, if not defined, generate index:
'lapdog: load indices if existing...'

indexversion = '2'; %index updated with a new variable 17Dec 2014
indexfile = sprintf('index/index_%s_v%s.mat',archiveid,indexversion);

if index_cache_enabled & (exist(indexfile) == 2) & exist(derivedpath, 'dir')
    load(indexfile);
else
    'lapdog: calling indexgen...'
    indexgen;
    'lapdog: splitting files at midnight..'
    indexcorr;
    save(indexfile,'index');
end

%--------------------------------------------------
% Debugging code for only keeping a specific date?
%--------------------------------------------------
% i_keep = [];
% for i = 1:length(index)
%     if ~isempty(strfind(index(i).lblfile, '/2014/AUG/D17/'))
%         i_keep(end+1) = i;
%     end
%     if isempty(strfind(index(i).lblfile, '/home/erjo/LAP_ARCHIVE_test/RO-C-RPCLAP-3-1408-CALIB-V0.3/'))
%         ''
%     end
%
%end
%index = index(i_keep);
%-------------------------------------------------

scResetCount=str2double(index(1).sct0str(2));

% Generate daily geometry files:
if(do_geom)
  'lapdog: calling geometry...'
  geometry;
end

% Generate block list file:
'lapdog: calling opsblocks...'
opsblocks;

tabindexfile = sprintf('tabindex/tabindex_%s.mat',archiveid);

if tabindex_cache_enabled & (exist(tabindexfile) == 2)
    load(tabindexfile);
    'lapdog: successfully loaded tabfiles'
else
    'lapdog: calling process...'
    process;

    if exist('tabindex','dir')~=7
        mkdir('tabindex');
    end
    save(tabindexfile,'tabindex');
end

analysis;

'lapdog: generate LBL files....'
createLBL(1,1)    % createLBL(failFastDebugMode, saveCallerWorkspace)

'lapdog: Parmesan -Done!'
toc
% End of main.m


text:
// Copyright 2017-2020 The Verible Authors.
//
// 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.

#include "verilog/analysis/checkers/forbidden_macro_rule.h"

#include <map>
#include <set>
#include <string>

#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "common/analysis/citation.h"
#include "common/analysis/lint_rule_status.h"
#include "common/analysis/matcher/bound_symbol_manager.h"
#include "common/analysis/matcher/matcher.h"
#include "common/text/concrete_syntax_leaf.h"
#include "common/text/symbol.h"
#include "common/text/syntax_tree_context.h"
#include "common/text/token_info.h"
#include "common/util/container_util.h"
#include "verilog/CST/verilog_matchers.h"
#include "verilog/analysis/descriptions.h"
#include "verilog/analysis/lint_rule_registry.h"

namespace verilog {
namespace analysis {

using verible::GetStyleGuideCitation;
using verible::container::FindWithDefault;
using verible::matcher::Matcher;

// Register ForbiddenMacroRule
VERILOG_REGISTER_LINT_RULE(ForbiddenMacroRule);

// TODO(fangism): Generate table of URLs from InvalidMacrosMap().
const LintRuleDescriptor& ForbiddenMacroRule::GetDescriptor() {
  static const LintRuleDescriptor d{
      .name = "forbidden-macro",
      .topic = "uvm-logging",
      .desc = "Checks that no forbidden macro calls are used.",
  };
  return d;
}

// Matches all macro call ids, like `foo.
static const Matcher& MacroCallMatcher() {
  static const Matcher matcher(MacroCallIdLeaf().Bind("name"));
  return matcher;
}

// Set of invalid macros and URLs
const std::map<std::string, std::string>&
ForbiddenMacroRule::InvalidMacrosMap() {
  // TODO(hzeller): don't use GetStyleGuideCitation here, more downstream.
  static const auto* invalid_symbols = new std::map<std::string, std::string>({
      {"`uvm_warning", GetStyleGuideCitation("uvm-logging")},
  });
  return *invalid_symbols;
}

void ForbiddenMacroRule::HandleSymbol(
    const verible::Symbol& symbol, const verible::SyntaxTreeContext& context) {
  verible::matcher::BoundSymbolManager manager;
  if (MacroCallMatcher().Matches(symbol, &manager)) {
    if (const auto* leaf = manager.GetAs<verible::SyntaxTreeLeaf>("name")) {
      const auto& imm = InvalidMacrosMap();
      if (imm.find(std::string(leaf->get().text())) != imm.end()) {
        violations_.insert(
            verible::LintViolation(leaf->get(), FormatReason(*leaf), context));
      }
    }
  }
}

verible::LintRuleStatus ForbiddenMacroRule::Report() const {
  // TODO(b/68104316): restructure LintRuleStatus to not requires a single URL
  // for every LintRuleStatus.
  return verible::LintRuleStatus(violations_, GetDescriptor());
}

/* static */ std::string ForbiddenMacroRule::FormatReason(
    const verible::SyntaxTreeLeaf& leaf) {
  const std::string function_name(leaf.get().text());
  const auto url = FindWithDefault(InvalidMacrosMap(), function_name, "");
  auto message = function_name + " is a forbidden macro";
  if (!url.empty()) {
    message += ", see " + url;
  }
  return message + ".";
}

}  // namespace analysis
}  // namespace verilog


text:
require_dependency 'url_helper'
require_dependency 'file_helper'

module Jobs

  class PullHotlinkedImages < Jobs::Base
    def initialize
      # maximum size of the file in bytes
      @max_size = SiteSetting.max_image_size_kb.kilobytes
    end

    def execute(args)
      return unless SiteSetting.download_remote_images_to_local?

      post_id = args[:post_id]
      raise Discourse::InvalidParameters.new(:post_id) unless post_id.present?

      post = Post.find_by(id: post_id)
      return unless post.present?

      raw = post.raw.dup
      start_raw = raw.dup
      downloaded_urls = {}

      extract_images_from(post.cooked).each do |image|
        src = image['src']
        src = "http:" + src if src.start_with?("//")

        if is_valid_image_url(src)
          hotlinked = nil
          begin
            # have we already downloaded that file?
            unless downloaded_urls.include?(src)
              begin
                hotlinked = FileHelper.download(src, @max_size, "discourse-hotlinked", true)
              rescue Discourse::InvalidParameters
              end
              if hotlinked
                if File.size(hotlinked.path) <= @max_size
                  filename = File.basename(URI.parse(src).path)
                  upload = Upload.create_for(post.user_id, hotlinked, filename, File.size(hotlinked.path), { origin: src })
                  downloaded_urls[src] = upload.url
                else
                  Rails.logger.info("Failed to pull hotlinked image for post: #{post_id}: #{src} - Image is bigger than #{@max_size}")
                end
              else
                Rails.logger.error("There was an error while downloading '#{src}' locally for post: #{post_id}")
              end
            end
            # have we successfully downloaded that file?
            if downloaded_urls[src].present?
              url = downloaded_urls[src]
              escaped_src = Regexp.escape(src)
              # there are 6 ways to insert an image in a post
              # HTML tag -
              raw.gsub!(/src=["']#{escaped_src}["']/i, "src='#{url}'")
              # BBCode tag - [img]http://...[/img]
              raw.gsub!(/\[img\]#{escaped_src}\[\/img\]/i, "[img]#{url}[/img]")
              # Markdown linked image - [![alt](http://...)](http://...)
              raw.gsub!(/\[!\[([^\]]*)\]\(#{escaped_src}\)\]/) { "[]" }
              # Markdown inline - ![alt](http://...)
              raw.gsub!(/!\[([^\]]*)\]\(#{escaped_src}\)/) { "![#{$1}](#{url})" }
              # Markdown reference - [x]: http://
              raw.gsub!(/\[([^\]]+)\]:\s?#{escaped_src}/) { "[#{$1}]: #{url}" }
              # Direct link
              raw.gsub!(/^#{escaped_src}\s?$/, "")
            end
          rescue => e
            Rails.logger.info("Failed to pull hotlinked image: #{src} post:#{post_id}\n" + e.message + "\n" + e.backtrace.join("\n"))
          ensure
            # close & delete the temp file
            hotlinked && hotlinked.close!
          end
        end

      end

      post.reload
      if start_raw == post.raw && raw != post.raw
        changes = { raw: raw, edit_reason: I18n.t("upload.edit_reason") }
        # we never want that job to bump the topic
        options = { bypass_bump: true }
        post.revise(Discourse.system_user, changes, options)
      end
    end

    def extract_images_from(html)
      doc = Nokogiri::HTML::fragment(html)
      doc.css("img[src]") - doc.css(".onebox-result img") - doc.css("img.avatar")
    end

    def is_valid_image_url(src)
      # make sure we actually have a url
      return false unless src.present?
      # we don't want to pull uploaded images
      return false if Discourse.store.has_been_uploaded?(src)
      # we don't want to pull relative images
      return false if src =~ /\A\/[^\/]/i
      # parse the src
      begin
        uri = URI.parse(src)
      rescue URI::InvalidURIError
        return false
      end
      # we don't want to pull images hosted on the CDN (if we use one)
      return false if Discourse.asset_host.present? && URI.parse(Discourse.asset_host).hostname == uri.hostname
      return false if SiteSetting.s3_cdn_url.present? && URI.parse(SiteSetting.s3_cdn_url).hostname == uri.hostname
      # we don't want to pull images hosted on the main domain
      return false if URI.parse(Discourse.base_url_no_prefix).hostname == uri.hostname
      # check the domains blacklist
      SiteSetting.should_download_images?(src)
    end

  end

end


text:
// Copyright (C) 2010 The Android Open Source Project
//
// 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.

package com.google.gerrit.util.cli;

import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.OptionDef;
import org.kohsuke.args4j.spi.OptionHandler;
import org.kohsuke.args4j.spi.Parameters;
import org.kohsuke.args4j.spi.Setter;

/** Typically used with {@code @Option(name="--")} to signal end of options. */
public class EndOfOptionsHandler extends OptionHandler<Boolean> {
  public EndOfOptionsHandler(CmdLineParser parser, OptionDef option,
      Setter<? super Boolean> setter) {
    super(parser, option, setter);
  }

  @Override
  public String getDefaultMetaVariable() {
    return null;
  }

  @Override
  public int parseArguments(Parameters params) throws CmdLineException {
    owner.stopOptionParsing();
    setter.addValue(true);
    return 0;
  }
}


text:
class RedisAdmin::QueuesController < RedisAdmin::BaseController
  def index
  end
end


text:
<!doctype html>
<meta charset=utf-8>


text:
package org.projectfloodlight.openflow.protocol;

import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import java.util.List;
import io.netty.buffer.ByteBuf;

public interface OFPacketQueue extends OFObject {
    long getQueueId();
    OFPort getPort() throws UnsupportedOperationException;
    List<OFQueueProp> getProperties();
    OFVersion getVersion();

    void writeTo(ByteBuf channelBuffer);

    Builder createBuilder();
    public interface Builder  {
        OFPacketQueue build();
        long getQueueId();
        Builder setQueueId(long queueId);
        OFPort getPort() throws UnsupportedOperationException;
        Builder setPort(OFPort port) throws UnsupportedOperationException;
        List<OFQueueProp> getProperties();
        Builder setProperties(List<OFQueueProp> properties);
        OFVersion getVersion();
    }
}


text:
package com.sandwich.annotatedbundle.filereader;

import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

public class URLToURITransformer {

	URI toURI(URL url) throws URISyntaxException {
		return url.toURI();
	}

}


text:
// Copyright 2021 The Bazel Authors. All rights reserved.
//
// 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.
//

package com.google.devtools.build.lib.bazel.bzlmod;

import com.google.auto.value.AutoValue;
import com.google.auto.value.extension.memoized.Memoized;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Interner;
import com.google.devtools.build.lib.concurrent.BlazeInterners;
import com.google.devtools.build.lib.skyframe.SkyFunctions;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec;
import com.google.devtools.build.skyframe.SkyFunctionName;
import com.google.devtools.build.skyframe.SkyKey;
import com.google.devtools.build.skyframe.SkyValue;
import javax.annotation.Nullable;

/** The result of {@link ModuleFileFunction}. */
public abstract class ModuleFileValue implements SkyValue {

  public static final ModuleFileValue.Key KEY_FOR_ROOT_MODULE = key(ModuleKey.ROOT, null);

  /**
   * The module resulting from the module file evaluation. Note that the name and version of this
   * module might not match the one in the requesting {@link SkyKey} in certain circumstances (for
   * example, for the root module, or when non-registry overrides are in play.
   */
  public abstract Module getModule();

  /** The {@link ModuleFileValue} for non-root modules. */
  @AutoValue
  public abstract static class NonRootModuleFileValue extends ModuleFileValue {

    public static NonRootModuleFileValue create(Module module) {
      return new AutoValue_ModuleFileValue_NonRootModuleFileValue(module);
    }
  }

  /**
   * The {@link ModuleFileValue} for the root module, containing additional information about
   * overrides.
   */
  @AutoValue
  public abstract static class RootModuleFileValue extends ModuleFileValue {
    /**
     * The overrides specified by the evaluated module file. The key is the module name and the
     * value is the override itself.
     */
    public abstract ImmutableMap<String, ModuleOverride> getOverrides();

    /**
     * A mapping from a canonical repo name to the name of the module. Only works for modules with
     * non-registry overrides.
     */
    public abstract ImmutableMap<String, String> getNonRegistryOverrideCanonicalRepoNameLookup();

    public static RootModuleFileValue create(
        Module module,
        ImmutableMap<String, ModuleOverride> overrides,
        ImmutableMap<String, String> nonRegistryOverrideCanonicalRepoNameLookup) {
      return new AutoValue_ModuleFileValue_RootModuleFileValue(
          module, overrides, nonRegistryOverrideCanonicalRepoNameLookup);
    }
  }

  public static Key key(ModuleKey moduleKey, @Nullable ModuleOverride override) {
    return Key.create(moduleKey, override);
  }

  /** {@link SkyKey} for {@link ModuleFileValue} computation. */
  @AutoCodec
  @AutoValue
  abstract static class Key implements SkyKey {
    private static final Interner<Key> interner = BlazeInterners.newWeakInterner();

    abstract ModuleKey getModuleKey();

    @Nullable
    abstract ModuleOverride getOverride();

    @AutoCodec.Instantiator
    static Key create(ModuleKey moduleKey, @Nullable ModuleOverride override) {
      return interner.intern(new AutoValue_ModuleFileValue_Key(moduleKey, override));
    }

    @Override
    public SkyFunctionName functionName() {
      return SkyFunctions.MODULE_FILE;
    }

    @Memoized
    @Override
    public abstract int hashCode();
  }
}


text:
using System;
using System.Windows.Input;
using Xamarin.Forms;

namespace Xamarin.CustomControls
{
    public partial class BadgeButton : ContentView
    {
        private bool _hideBadgeIfTextIsZero = true;

        public event EventHandler Clicked;

        public static readonly BindableProperty CommandProperty = BindableProperty.Create(nameof(Command), typeof(ICommand), typeof(BadgeButton));
        public static readonly BindableProperty CommandParameterProperty = BindableProperty.Create(nameof(CommandParameter), typeof(object), typeof(BadgeButton));

        public static readonly BindableProperty ImageSourceProperty = BindableProperty.Create(nameof(ImageSource), typeof(ImageSource), typeof(BadgeButton), default(FileImageSource));
        public static readonly BindableProperty BadgeTextColorProperty = BindableProperty.Create(nameof(BadgeTextColor), typeof(Color), typeof(BadgeButton), Color.White);
        public static readonly BindableProperty BadgeBackgroundColorProperty = BindableProperty.Create(nameof(BadgeBackgroundColor), typeof(Color), typeof(BadgeButton), Color.Red);

        public static readonly BindableProperty BadgeTextProperty = BindableProperty.Create(nameof(BadgeText), typeof(string), typeof(BadgeButton), string.Empty);
        public static readonly BindableProperty BadgeFontSizeProperty = BindableProperty.Create(nameof(BadgeFontSize), typeof(double), typeof(BadgeButton), Device.GetNamedSize(NamedSize.Default, typeof(BadgeButton)));

        public ICommand Command
        {
            get { return (ICommand)GetValue(CommandProperty); }
            set { SetValue(CommandProperty, value); }
        }

        public object CommandParameter
        {
            get { return GetValue(CommandParameterProperty); }
            set { SetValue(CommandParameterProperty, value); }
        }

        public Color BadgeTextColor
        {
            get { return (Color)GetValue(BadgeTextColorProperty); }
            set { SetValue(BadgeTextColorProperty, value); }
        }

        public Color BadgeBackgroundColor
        {
            get { return (Color)GetValue(BadgeBackgroundColorProperty); }
            set { SetValue(BadgeBackgroundColorProperty, value); }
        }

        public ImageSource ImageSource
        {
            get { return (ImageSource)GetValue(ImageSourceProperty); }
            set { SetValue(ImageSourceProperty, value); }
        }

        public string BadgeText
        {
            get { return (string)GetValue(BadgeTextProperty); }
            set { SetValue(BadgeTextProperty, value); }
        }

        [TypeConverter(typeof(FontSizeConverter))]
        public double BadgeFontSize
        {
            get { return (double)GetValue(BadgeFontSizeProperty); }
            set { SetValue(BadgeFontSizeProperty, value); }
        }

        public bool HideBadgeIfTextIsZero
        {
            get
            {
                return _hideBadgeIfTextIsZero;
            }
            set
            {
                _hideBadgeIfTextIsZero = value;

                if (int.TryParse(BadgeText, out int parsedValue))
                {
                    BadgeFrame.IsVisible = parsedValue != 0;
                }
                else
                    BadgeFrame.IsVisible = true;
            }
        }

        public BadgeButton()
        {
            InitializeComponent();

            GestureRecognizers.Add(new TapGestureRecognizer
            {
                Command = new Command(() =>
                {
                    Command?.Execute(CommandParameter);
                    Clicked?.Invoke(this, new EventArgs());
                })
            });

            BadgeFrame.BackgroundColor = BadgeBackgroundColor;
            BadgeTextLabel.Text = BadgeText;
            BadgeTextLabel.TextColor = BadgeTextColor;
            BadgeTextLabel.FontSize = BadgeFontSize;
            BadgeIconImage.Source = ImageSource;
        }

        protected override void OnPropertyChanged(string propertyName = null)
        {
            base.OnPropertyChanged(propertyName);

            if (BadgeFrame != null && propertyName == BadgeBackgroundColorProperty.PropertyName)
            {
                BadgeFrame.BackgroundColor = BadgeBackgroundColor;
            }

            if (BadgeTextLabel != null && propertyName == BadgeTextProperty.PropertyName)
            {
                BadgeTextLabel.Text = BadgeText;

                if (HideBadgeIfTextIsZero && int.TryParse(BadgeText, out int parsedValue))
                {
                    BadgeFrame.IsVisible = parsedValue != 0;
                }
                else
                    BadgeFrame.IsVisible = !string.IsNullOrEmpty(BadgeText);
            }

            if (BadgeTextLabel != null && propertyName == BadgeTextColorProperty.PropertyName)
            {
                BadgeTextLabel.TextColor = BadgeTextColor;
            }

            if (BadgeTextLabel != null && propertyName == BadgeFontSizeProperty.PropertyName)
            {
                BadgeTextLabel.FontSize = BadgeFontSize;

                if (BadgeFontSize <= 6)
                {
                    BadgeFrame.Padding = new Thickness(0, 2);
                    BadgeFrame.CornerRadius = 2;
                }

                if (BadgeFontSize <= 8)
                {
                    BadgeFrame.Padding = new Thickness(0, 2);
                    BadgeFrame.CornerRadius = 8;
                }

                if (BadgeFontSize <= 10)
                {
                    BadgeFrame.Padding = new Thickness(2, 2);
                    BadgeFrame.CornerRadius = 10;
                }

                if (BadgeFontSize <= 12)
                {
                    BadgeFrame.Padding = new Thickness(8, 4);
                }
            }

            if (BadgeIconImage != null && propertyName == ImageSourceProperty.PropertyName)
            {
                BadgeIconImage.Source = ImageSource;
            }
        }
    }
}


text:
'use strict';

angular.module('IntermapaApp')
.directive('entitypicker', function () {
	return {
		restrict : 'E',
		scope : {
			ngModel : '=',
			wsClass : '=',
			wsFields : '=', //There's a little change here in comparison to List or crudtypetable
			wsLabel : '=?',
			filterByOwner : '=?',
			goTo : '&?',
			ngChange : '&?',
			disable : '=',
			wsList : '=',
			wsDefault : '='
		},
		templateUrl : 'views/directives/entitypicker.html',
		controller : function ($scope, $timeout, dialogs, toaster) {
			$scope.wsLabel = $scope.wsLabel || 'entity.fullName';
			console.log($scope.disable)
			$scope.showModal = function () {
				var dialog = dialogs.create('views/directives/entitypicker.modal.html', 'EntityPickerCtrl', {
						wsClass : $scope.wsClass,
						wsFields : $scope.wsFields,
						filterByOwner : $scope.filterByOwner,
						list : $scope.wsList,
					default:
						$scope.wsDefault
					});
				dialog.result.then(function (res) {
					$scope.ngModel = res;
					$timeout(function () {
						if ($scope.ngChange) {
							$scope.ngChange();
						}
					});
				}, function (res) {});
			};
			$scope.clean = function () {
				$scope.ngModel = undefined;
				$scope.selectedName = '';
				$timeout(function () {
					if ($scope.ngChange) {
						$scope.ngChange();
					}
				});
			};
			$scope.$watch('ngModel', function (value) {

				var labels = $scope.wsLabel.split('.');
				var name = angular.copy(value);
				for (var i in labels) {
					if (name) {
						name = name[labels[i]];
					}
				}

				if (value && value.baseApiPath && value.baseApiPath == '/api/centroMedico')
					$scope.selectedName = value.entity.name || '';
				else if (value && value.baseApiPath && value.baseApiPath == '/api/paciente')
					$scope.selectedName = value.fullName || '';
				else
					$scope.selectedName = name || '';
			}, true);
		}
	};
})
.controller('EntityPickerCtrl', function ($scope, $rootScope, $uibModalInstance, $q, toaster, data) {
	$scope.defaultObj = angular.copy(data.default);
			$scope.isCollapsed = true;
			$scope.entitySelected = {};
			$scope.currentPage = 1;
			$scope.maxPage = 0;
			var wsClassHandler = new data.wsClass();
			$scope.orderBy = {
				sort : {},
				reverse : false,
				field : '_id'
			};
			var searchFields = ['_id'];
			$scope.filtro = {};
			if (data.filterByOwner) {
				$scope.filtro[data.filterByOwner] = ownerId;
			}
			$scope.wsFields = data.wsFields;
			//Setting searchFields
			var setSearchFields = function () {
				searchFields = ['_id'];
				for (var i = 0; i < $scope.wsFields.length; i++) {
					searchFields.push($scope.wsFields[i].field);
				}
			};
			//Check if there are "OPTIONS" filters, if its so then find distinct values from the database of that field
			var setSearchFilter = function () {
				var promises = [];
				$scope.wsFields.forEach(function (field, index) {
					if (field.type.toUpperCase() == 'OPTIONS') {
						wsClassHandler.distinct(field.field)
						.then(function (data) {
							field.data = data;
							field.data.unshift('Seleccionar Todos');
							if (field.field == 'branchId' && $scope.defaultObj && JSON.stringify($scope.defaultObj) != '{}') {
								$scope.filtro[field.field] = angular.copy($scope.defaultObj._id);
							} else {
								$scope.filtro[field.field] != 'Seleccionar Todos'
							}
						});
					}
				});
			};

			setSearchFields();
			$scope.params = {
				filter : angular.copy($scope.filtro),
				limit : 10,
				skip : 0,
				sort : $scope.orderBy.sort,
				search : '',
				fields : searchFields,
				startDate : '',
				endDate : '',
				all : true
			};
			setSearchFilter();

			$scope.getData = function (entity, field) {
				var data = angular.copy(entity);

				if (typeof field == 'function') {
					data = field(data);
				} else {
					var properties = field.toString().split('.');
					for (var i = 0; i < properties.length; i++) {
						data = data[properties[i]];
					}
				}
				return data;
			};

			//Pagination

			var getPaginatedSearch = function (pParams) {
				if (pParams.filter && JSON.stringify(pParams.filter) != '{}' && pParams.filter.branchId && pParams.filter.branchId.$regex) {
					pParams.filter.branchId = pParams.filter.branchId.$regex;
				}
				wsClassHandler.paginatedSearch(pParams).then(function (data) {
					$scope.list = angular.copy(data.data);
					for (var i in $scope.list) {
						var ent = $scope.list[i];
					}
				}, function (error) {
					toaster.pop('error', '', 'No se pudo cargar los registros!', 5000);
				});
				wsClassHandler.paginatedCount(pParams).then(function (res) {
					res = res.count;
					$scope.maxPage = res < pParams.limit ? 1 : Math.ceil(res / pParams.limit);
				}, function (error) {
					console.log(error);
				});
			};
			$scope.selectPerson = function (ent) {
				$scope.entitySelected = ent;
				$scope.done();
			};
			$scope.done = function () {
				$uibModalInstance.close($scope.entitySelected);
			};
			$scope.close = function () {
				$uibModalInstance.dismiss();
			};
			$scope.search = function () {
				getPaginatedSearch($scope.params);
			};
			$scope.prevPage = function () {
				if ($scope.currentPage > 1) {
					$scope.currentPage--;
					$scope.params.skip = (($scope.currentPage - 1) * $scope.params.limit);
					getPaginatedSearch($scope.params);
				}
			};
			$scope.nextPage = function () {
				if ($scope.currentPage < $scope.maxPage) {
					$scope.currentPage++;
					$scope.params.skip += $scope.list.length;
					getPaginatedSearch($scope.params);
				}
			};
			$scope.changeOrder = function (field) {
				$scope.orderBy.sort = {};
				if ($scope.orderBy.field === field) {
					$scope.orderBy.reverse = !$scope.orderBy.reverse;
					$scope.orderBy.sort[field] = $scope.orderBy.reverse ? -1 : 1;
				} else {
					$scope.orderBy.field = field;
					$scope.orderBy.sort[field] = 1;
					$scope.orderBy.reverse = false;
				}
				$scope.params.sort = $scope.orderBy.sort;
			};
			$scope.filter = function (field, isDown, isSelect) {
				for (var i in $scope.filtro) {
					if ($scope.filtro[i] != '' && $scope.filtro[i] != 'Seleccionar Todos') {
						var fltr = angular.copy($scope.filtro[i]);
						$scope.params.filter[i] = {
							$regex : fltr,
							$options : 'i'
						};
					} else {
						delete $scope.params.filter[i];
					}
				}
				if (isDown == false && ($scope.filtro.branchId || $scope.defaultObj && JSON.stringify($scope.defaultObj) != '{}')) {
					$scope.params.filter['branchId'] = ($scope.filtro.branchId) ? $scope.filtro.branchId : angular.copy($scope.defaultObj._id);
				} else {
					delete $scope.params.filter.branchId;
				}
				getPaginatedSearch($scope.params);
			};
			$scope.setOrderClass = function (field) {
				if ($scope.orderBy.field === field) {
					if ($scope.orderBy.reverse) {
						return {
							'fa-sort-asc' : true,
							'fa-sort-desc' : false
						};
					} else {
						return {
							'fa-sort-asc' : false,
							'fa-sort-desc' : true
						};
					}
				} else {
					return {
						'fa-sort-asc' : false,
						'fa-sort-desc' : false
					};
				}
			};
			getPaginatedSearch($scope.params);
});


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

    <TITLE>
        org.apache.jmeter.samplers.gui (Apache JMeter API)
    </TITLE>

    <META NAME="keywords" CONTENT="org.apache.jmeter.samplers.gui package">

    <LINK REL="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

    org.apache.jmeter.samplers.gui

            Classes

                AbstractSamplerGui


text:
package plugins

import (
	"errors"

	"github.com/blang/semver"
	"gopkg.in/src-d/go-git.v4/plumbing"
)

type Versions []Version
type Version struct {
	plumbing.ReferenceName
	semver.Version
}

func (versions Versions) Len() int {
	return len(versions)
}

func (versions Versions) Swap(i, j int) {
	versions[i], versions[j] = versions[j], versions[i]
}

func (versions Versions) Less(i, j int) bool {
	return versions[i].LE(versions[j].Version)
}

// Last returns the last version from a silce
// The slice should be sorted
func (versions Versions) Last() (Version, error) {
	if len(versions) == 0 {
		return Version{}, errors.New("No versions")
	}
	return versions[len(versions)-1], nil
}

func (version Version) String() string {
	return version.Version.String()
}


text:
/* eslint spaced-comment: 0 */
/* eslint no-redeclare: 0 */
/* eslint no-unused-vars: 0 */
/* eslint no-prototype-builtins: 0 */

const assert = require('assert');

/// title: Word wrap
/// difficulty: 2
/// type: rosetta-code

/// categories:
/// strings

/// description:
///

///

/// Even today, with proportional fonts and complex layouts, there are still
/// cases where you need to wrap text at a specified
/// column.  The basic task is to wrap a paragraph of text in a simple way.
/// Example text:
///

///

/// Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
/// If your language provides this, you get easy extra credit,
/// but you ''must reference documentation'' indicating that the algorithm
/// is something better than a simple minimimum length algorithm.
///

///

///

Task:

///

///

///     Write a function that can wrap this text to any number of characters.
///

///

///

/// As an example, the text wrapped to 80 characters should look like the following:
///

///

/// Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX
/// algorithm. If your language provides this, you get easy extra credit, but you
/// must reference documentation indicating that the algorithm is something better
/// than a simple minimimum length algorithm.
///

///

/// challengeSeed:
function wrap (text, limit) {
  return text;
}

/// solutions:
function wrap (text, limit) {
  const noNewlines = text.replace('\n', '');
  if (noNewlines.length > limit) {
    // find the last space within limit
    const edge = noNewlines.slice(0, limit).lastIndexOf(' ');
    if (edge > 0) {
      const line = noNewlines.slice(0, edge);
      const remainder = noNewlines.slice(edge + 1);
      return line + '\n' + wrap(remainder, limit);
    }
  }
  return text;
}

/// tail:
const text =
`Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you ''must reference documentation'' indicating that the algorithm
is something better than a simple minimimum length algorithm.`;

const wrapped80 = wrap(text, 80);
const wrapped42 = wrap(text, 42);

const firstRow80 =
    'Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX';

const firstRow42 = 'Wrap text using a more sophisticated';

/// tests:
assert.equal(typeof wrap, 'function', 'message: wrap must be a function.');
assert.equal(typeof wrap('abc', 10), 'string', 'message: wrap must return a string.');
assert(wrapped80.split('\n').length === 4, 'message: wrap(80) must return 4 lines.');
assert.equal(wrapped80.split('\n')[0], firstRow80);
assert(wrapped42.split('\n').length === 7, 'message: wrap(42) must return 7 lines.');
assert.equal(wrapped42.split('\n')[0], firstRow42);
/// id: 594810f028c0303b75339ad4


text:
import datetime

from flask import Flask, jsonify, request
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.exc import IntegrityError
from marshmallow import Schema, fields, ValidationError, pre_load

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:////tmp/quotes.db'
db = SQLAlchemy(app)

##### MODELS #####

class Author(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    first = db.Column(db.String(80))
    last = db.Column(db.String(80))

class Quote(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.String, nullable=False)
    author_id = db.Column(db.Integer, db.ForeignKey("author.id"))
    author = db.relationship("Author",
                        backref=db.backref("quotes", lazy="dynamic"))
    posted_at = db.Column(db.DateTime)

##### SCHEMAS #####

class AuthorSchema(Schema):
    id = fields.Int(dump_only=True)
    first = fields.Str()
    last = fields.Str()
    formatted_name = fields.Method("format_name", dump_only=True)

    def format_name(self, author):
        return "{}, {}".format(author.last, author.first)

# Custom validator
def must_not_be_blank(data):
    if not data:
        raise ValidationError('Data not provided.')

class QuoteSchema(Schema):
    id = fields.Int(dump_only=True)
    author = fields.Nested(AuthorSchema, validate=must_not_be_blank)
    content = fields.Str(required=True, validate=must_not_be_blank)
    posted_at = fields.DateTime(dump_only=True)

    # Allow client to pass author's full name in request body
    # e.g. {"author': 'Tim Peters"} rather than {"first": "Tim", "last": "Peters"}
    @pre_load
    def process_author(self, data):
        author_name = data.get('author')
        if author_name:
            first, last = author_name.split(' ')
            author_dict = dict(first=first, last=last)
        else:
            author_dict = {}
        data['author'] = author_dict
        return data

author_schema = AuthorSchema()
authors_schema = AuthorSchema(many=True)
quote_schema = QuoteSchema()
quotes_schema = QuoteSchema(many=True, only=('id', 'content'))

##### API #####

@app.route('/authors')
def get_authors():
    authors = Author.query.all()
    # Serialize the queryset
    result = authors_schema.dump(authors)
    return jsonify({'authors': result.data})

@app.route("/authors/<int:pk>")
def get_author(pk):
    try:
        author = Author.query.get(pk)
    except IntegrityError:
        return jsonify({"message": "Author could not be found."}), 400
    author_result = author_schema.dump(author)
    quotes_result = quotes_schema.dump(author.quotes.all())
    return jsonify({'author': author_result.data, 'quotes': quotes_result.data})

@app.route('/quotes/', methods=['GET'])
def get_quotes():
    quotes = Quote.query.all()
    result = quotes_schema.dump(quotes)
    return jsonify({"quotes": result.data})

@app.route("/quotes/<int:pk>")
def get_quote(pk):
    try:
        quote = Quote.query.get(pk)
    except IntegrityError:
        return jsonify({"message": "Quote could not be found."}), 400
    result = quote_schema.dump(quote)
    return jsonify({"quote": result.data})

@app.route("/quotes/", methods=["POST"])
def new_quote():
    json_data = request.get_json()
    if not json_data:
        return jsonify({'message': 'No input data provided'}), 400
    # Validate and deserialize input
    data, errors = quote_schema.load(json_data)
    if errors:
        return jsonify(errors), 422
    first, last = data['author']['first'], data['author']['last']
    author = Author.query.filter_by(first=first, last=last).first()
    if author is None:
        # Create a new author
        author = Author(first=first, last=last)
        db.session.add(author)
    # Create new quote
    quote = Quote(
        content=data['content'],
        author=author,
        posted_at=datetime.datetime.utcnow()
    )
    db.session.add(quote)
    db.session.commit()
    result = quote_schema.dump(Quote.query.get(quote.id))
    return jsonify({"message": "Created new quote.",
                    "quote": result.data})

if __name__ == '__main__':
    db.create_all()
    app.run(debug=True, port=5000)


text:
package ca.eandb.jmist.framework.loader.openexr.attribute;

public final class KeyCode {}


text:
package com.amazonaws.util.awsclientgenerator.domainmodels.c2j;

import lombok.Data;

@Data
public class C2jEndpoint {
    private String hostPrefix;
}


text:
<service name="sec_echo">
    <parameter name="ServiceClass" locked="xsd:false">sec_echo</parameter>

   <description>
        This is a testing service , to test the system is working or not
   </description>

    <module ref="rampart"/>

    <operation name="echoString">
            <parameter name="wsamapping">http://example.com/ws/2004/09/policy/Test/EchoRequest</parameter>
    </operation>

    <wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
        <wsp:ExactlyOne>
            <wsp:All>
                <sp:AsymmetricBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                    <wsp:Policy>
                        <sp:InitiatorToken>
                            <wsp:Policy>
                                <sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/AlwaysToRecipient">
                                    <wsp:Policy>
                                        <sp:WssX509V3Token10/>
                                    </wsp:Policy>
                                </sp:X509Token>
                            </wsp:Policy>
                        </sp:InitiatorToken>
                        <sp:RecipientToken>
                            <wsp:Policy>
                                <sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Never">
                                    <wsp:Policy>
                                        <sp:WssX509V3Token10/>
                                    </wsp:Policy>
                                </sp:X509Token>
                            </wsp:Policy>
                        </sp:RecipientToken>
                        <sp:Layout>
                            <wsp:Policy>
                                <sp:Strict/>
                            </wsp:Policy>
                        </sp:Layout>
                        <sp:AlgorithmSuite>
                            <wsp:Policy>
                                <sp:Basic256Rsa15/>
                            </wsp:Policy>
                        </sp:AlgorithmSuite>
                        <sp:IncludeTimestamp/>
                    </wsp:Policy>
                </sp:AsymmetricBinding>
                <sp:Wss10 xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                    <wsp:Policy>
                        <sp:MustSupportRefKeyIdentifier/>
                        <sp:MustSupportRefEmbeddedToken/>
                        <sp:MustSupportRefIssuerSerial/>
                    </wsp:Policy>
                </sp:Wss10>
                <rampc:RampartConfig xmlns:rampc="http://ws.apache.org/rampart/c/policy">
                    <!--rampc:TimeToLive>360</rampc:TimeToLive-->
					<rampc:ClockSkewBuffer>60</rampc:ClockSkewBuffer>
					<rampc:PrecisionInMilliseconds>True</rampc:PrecisionInMilliseconds>
					<rampc:Certificate>WSFC_HOME/samples/src/rampartc/data/keys/bhome/bob_cert.cert</rampc:Certificate>
                    <rampc:PrivateKey>WSFC_HOME/samples/src/rampartc/data/keys/bhome/bob_key.pem</rampc:PrivateKey>
                </rampc:RampartConfig>
            </wsp:All>
        </wsp:ExactlyOne>
    </wsp:Policy>
</service>


text:
using System.ComponentModel.Composition;
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;

// [010810][Powered] Fight! Makoto

namespace GameRes.Formats.Powerd
{
    [Export(typeof(ImageFormat))]
    public class NclFormat : ImageFormat
    {
        public override string         Tag { get { return "NCL"; } }
        public override string Description { get { return "Powerd image format"; } }
        public override uint     Signature { get { return 0x4C4C4543; } } // 'CELL'

        public override ImageMetaData ReadMetaData (IBinaryStream file)
        {
            var header = file.ReadHeader (0x20);
            if (header.ToInt32 (4) != 0x010100)
                return null;
            return new ImageMetaData {
                Width  = header.ToUInt32 (0x18),
                Height = header.ToUInt32 (0x1C),
                BPP    = 24,
            };
        }

        public override ImageData Read (IBinaryStream file, ImageMetaData info)
        {
            ImageData base_img;
            using (var input = new StreamRegion (file.AsStream, 0x24, true))
            using (var bmp = new BinaryStream (input, file.Name))
            {
                var bmp_info = Bmp.ReadMetaData (bmp) as BmpMetaData;
                if (null == bmp_info)
                    throw new InvalidFormatException();
                bmp.Position = 0;
                base_img = Bmp.Read (bmp, bmp_info);
                file.Position = 0x24 + bmp_info.ImageLength;
                if (file.PeekByte() == -1)
                    return base_img;
            }
            using (var input = new StreamRegion (file.AsStream, file.Position, true))
            using (var bmp = new BinaryStream (input, file.Name))
            {
                var bmp_info = Bmp.ReadMetaData (bmp) as BmpMetaData;
                if (null == bmp_info)
                    return base_img;
                bmp.Position = 0;
                var alpha_img = Bmp.Read (bmp, bmp_info);
                var alpha_bmp = new FormatConvertedBitmap (alpha_img.Bitmap, PixelFormats.Gray8, null, 0);
                var alpha = new byte[alpha_bmp.PixelWidth * alpha_bmp.PixelHeight];
                alpha_bmp.CopyPixels (alpha, alpha_bmp.PixelWidth, 0);

                var base_bmp = new FormatConvertedBitmap (base_img.Bitmap, PixelFormats.Bgr32, null, 0);
                int stride = base_bmp.PixelWidth * 4;
                var pixels = new byte[stride * base_bmp.PixelHeight];
                base_bmp.CopyPixels (pixels, stride, 0);
                int asrc = 0;
                for (int dst = 3; dst < pixels.Length; dst += 4)
                {
                    pixels[dst] = alpha[asrc++];
                }
                return ImageData.Create (info, PixelFormats.Bgra32, null, pixels, stride);
            }
        }

        public override void Write (Stream file, ImageData image)
        {
            throw new System.NotImplementedException ("NclFormat.Write not implemented");
        }
    }
}


text:
#pragma checksum "C:\Users\Bharath\Documents\Visual Studio 2012\Projects\DesiSongs\DesiSongs\Page1.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "E5338FBE17C3E5CE60FD569659D15A6E"
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18051
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using Microsoft.Phone.Controls;
using System;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Resources;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace DesiSongs {

    public partial class Page1 : Microsoft.Phone.Controls.PhoneApplicationPage {

        internal System.Windows.Controls.Grid LayoutRoot;

        internal System.Windows.Controls.Grid ContentPanel;

        internal Microsoft.Phone.Controls.PhoneTextBox MusicTextBox;

        private bool _contentLoaded;

        /// <summary>
        /// InitializeComponent
        /// </summary>
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public void InitializeComponent() {
            if (_contentLoaded) {
                return;
            }
            _contentLoaded = true;
            System.Windows.Application.LoadComponent(this, new System.Uri("/DesiSongs;component/Page1.xaml", System.UriKind.Relative));
            this.LayoutRoot = ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot")));
            this.ContentPanel = ((System.Windows.Controls.Grid)(this.FindName("ContentPanel")));
            this.MusicTextBox = ((Microsoft.Phone.Controls.PhoneTextBox)(this.FindName("MusicTextBox")));
        }
    }
}


text:
void expected_results()
{
   //
   // Define the max and mean errors expected for
   // various compilers and platforms.
   //
   const char* largest_type;
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
   if(boost::math::policies::digits<double, boost::math::policies::policy<> >() == boost::math::policies::digits<long double, boost::math::policies::policy<> >())
   {
      largest_type = "(long\\s+)?double|real_concept";
   }
   else
   {
      largest_type = "long double|real_concept";
   }
#else
   largest_type = "(long\\s+)?double|real_concept";
#endif
   //
   // On MacOS X cyl_bessel_k has much higher error levels than
   // expected: given that the implementation is basically
   // just a continued fraction evaluation combined with
   // exponentiation, we conclude that exp and pow are less
   // accurate on this platform, especially when the result
   // is outside the range of a double.
   //
   add_expected_result(
      ".*",                          // compiler
      ".*",                          // stdlib
      "Mac OS",                      // platform
      largest_type,                  // test type(s)
      ".*",                          // test data group
      ".*", 4000, 1300);             // test function

   add_expected_result(
      "GNU.*",                          // compiler
      ".*",                          // stdlib
      "Win32.*",                          // platform
      largest_type,                  // test type(s)
      ".*large.*",                   // test data group
      ".*", 250, 100);                 // test function
   add_expected_result(
      ".*",                          // compiler
      ".*",                          // stdlib
      ".*",                          // platform
      largest_type,                  // test type(s)
      ".*large.*",                   // test data group
      ".*", 80, 50);                 // test function
   add_expected_result(
      ".*",                          // compiler
      ".*",                          // stdlib
      ".*",                          // platform
      largest_type,                  // test type(s)
      ".*",                          // test data group
      ".*", 35, 15);                 // test function
   //
   // Finish off by printing out the compiler/stdlib/platform names,
   // we do this to make it easier to mark up expected error rates.
   //
   std::cout << "Tests run with " << BOOST_COMPILER << ", "
      << BOOST_STDLIB << ", " << BOOST_PLATFORM << std::endl;
}

int test_main(int, char* [])
{
#ifdef TEST_GSL
   gsl_set_error_handler_off();
#endif
   expected_results();
   BOOST_MATH_CONTROL_FP;

#ifndef BOOST_MATH_BUGGY_LARGE_FLOAT_CONSTANTS
   test_bessel(0.1F, "float");
#endif
   test_bessel(0.1, "double");
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
   test_bessel(0.1L, "long double");
#ifndef BOOST_MATH_NO_REAL_CONCEPT_TESTS
   test_bessel(boost::math::concepts::real_concept(0.1), "real_concept");
#endif
#else
   std::cout << "<note>The long double tests have been disabled on this platform "
      "either because the long double overloads of the usual math functions are "
      "not available at all, or because they are too inaccurate for these tests "
      "to pass.</note>" << std::cout;
#endif
   return 0;
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>Beware the Connection Header in HTTP/2</title>
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests" />
    <meta name="description" content="" />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="twitter:site" content="@marcsavy" />
    <meta name="twitter:creator" content="@marcsavy" />
    <meta name="twitter:creator:id" content="205774796" />

    <link rel="shortcut icon" href="http://www.rhymewithgravy.com/favicon.ico">

    <link rel="stylesheet" type="text/css" href="//www.rhymewithgravy.com/themes/casper-msavy/assets/css/screen.css?v=1476869899614" />
    <link rel="stylesheet" type="text/css" href="//www.rhymewithgravy.com/themes/casper-msavy/assets/css/atom-one-light.css?v=1476869899614" />
    <link rel="stylesheet" type="text/css" href="//www.rhymewithgravy.com/themes/casper-msavy/assets/css/font-awesome.min.css?v=1476869899614" />

    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />

    <link rel="canonical" href="http://www.rhymewithgravy.com/2016/08/23/Beware-the-Connection-Header-in-HTT-P.html" />
    <meta name="referrer" content="origin" />

    <meta property="og:site_name" content="The Musings of Marc" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="Beware the Connection Header in HTTP/2" />
    <meta property="og:description" content="Whilst tinkering apiman&#8217;s Vert.x gateway implementation I ran into a strange issue when invoking an API via curl --http2. It seemed to work fine in Chrome and using Go&#8217;s h2c: $ * http2 error: Invalid HTTP header field was received: frame type: 1, stream: 1, name: [connection]" />
    <meta property="og:url" content="http://www.rhymewithgravy.com/2016/08/23/Beware-the-Connection-Header-in-HTT-P.html" />
    <meta property="article:tag" content="vertx" />
    <meta property="article:tag" content=" apiman" />
    <meta property="article:tag" content=" http2" />

    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content="Beware the Connection Header in HTTP/2" />
    <meta name="twitter:description" content="Whilst tinkering apiman&#8217;s Vert.x gateway implementation I ran into a strange issue when invoking an API via curl --http2. It seemed to work fine in Chrome and using Go&#8217;s h2c: $ * http2 error: Invalid HTTP header field was received: frame type: 1, stream: 1, name: [connection]" />
    <meta name="twitter:url" content="http://www.rhymewithgravy.com/2016/08/23/Beware-the-Connection-Header-in-HTT-P.html" />

    <meta name="generator" content="HubPress" />
    <link rel="alternate" type="application/rss+xml" title="The Musings of Marc" href="http://www.rhymewithgravy.com/rss/" />

Beware the Connection Header in HTTP/2

                <time class="post-date" datetime="2016-08-23">23 August 2016</time>  on vertx,  apiman,  http2

                            Marc Savy

                                @marcsavy

                                marcsavy

                                msavy

Whilst tinkering apiman’s Vert.x gateway implementation I ran into a strange issue when invoking an API via curl --http2. It seemed to work fine in Chrome and using Go’s h2c:

$ * http2 error: Invalid HTTP header field was received: frame type: 1, stream: 1, name: [connection], value: [keep-alive]

This is what the setup looks like (distilled):

HTTP/2 Client <--> Apiman Gateway (HTTP/2) <--> Test API (HTTP/1)

What’s going on?

I took to Twitter to figure out what was going on.

@apiman_io @clementplop although the cURL --http2 doesn't like the headers Vert.x sends - interesting https://t.co/0dK81huCmb
— Marc Savy (@marcsavy) August 20, 2016

Out of the blue, Mr cURL himself (Daniel Stenberg) popped up with the answer quoted from RFC 7540:

@marcsavy @apiman_io @clementplop "An endpoint MUST NOT generate an HTTP/2 message containing connection-specific header fields"
— Daniel Stenberg (@bagder) August 20, 2016

Mystery solved

Aha! The backend API apiman was proxying the response from returned a Connection: keep-alive header. Apiman simply forwarded this on, but it turns out this violates the HTTP/2 spec as there should be no connection-specific header fields - in response cURL spits out the error we see above. [1]

HTTP/2 Client (http2 error...) <- Apiman Gateway <- Test API (sets "Connection: keep-alive")

The solution was just to filter out Connection headers in apiman, but I wonder whether Vert.x should do it by default (or show an error message, exception, etc).

That said, I think "it’s the app’s responsibility not to do stupid things" or "we should handle it and filter out Connection headers" are both valid responses depending upon philosophy.

So, I let the Vert.x guys know, and let’s see.

<meta name="og:image" content="https://www.rhymewithgravy.com/images/Vert-x-Logo-X.png" />

1. Other implementations seem to just ignore these irrelevant fields.

                Marc Savy's Picture

Marc Savy

Core developer on the @apiman API Management project

                    http://www.rhymewithgravy.com

Share this post

                    Twitter

                    Facebook

                    Google+

          Please enable JavaScript to view the comments powered by Disqus.
          comments powered by Disqus

The Musings of Marc © 2016

Proudly published with HubPress


text:
#import <Foundation/NSCharacterSet.h>

// Not exported
@interface _NSPlaceholderCharacterSet : NSCharacterSet
{
    NSCharacterSet *_original;
    NSCharacterSet *_invertedSet;
    struct {
        unsigned int _inverted:1;
        unsigned int _builtin:1;
        unsigned int _isCF:1;
        unsigned int _reserved:29;
    } _flags;
}

- (id)replacementObjectForCoder:(id)arg1;
- (id)replacementObjectForKeyedArchiver:(id)arg1;
- (void)dealloc;
- (_Bool)_tryRetain;
- (_Bool)_isDeallocating;
- (oneway void)release;
- (unsigned long long)retainCount;
- (id)retain;
- (id)autorelease;
- (id)invertedSet;
- (_Bool)isEmpty;
- (id)bitmapRepresentation;
- (_Bool)isEqual:(id)arg1;
- (_Bool)hasMemberInPlane:(unsigned char)arg1;
- (_Bool)isSupersetOfSet:(id)arg1;
- (_Bool)longCharacterIsMember:(unsigned int)arg1;
- (_Bool)characterIsMember:(unsigned short)arg1;
- (id)mutableCopyWithZone:(struct _NSZone *)arg1;
- (void)_expandInverted;
- (struct __CFCharacterSet *)_expandedCFCharacterSet;
- (id)initWithSet:(id)arg1 options:(unsigned long long)arg2;

@end