text
stringlengths
2
1.04M
meta
dict
When the login link is clicked, the portlets utilize the MAP-Works webservice to generate a login URL in MAP-Works to redirect a user to. There are two portlets because the URL parameters are slightly different for Faculty/Staff and Students. At present, the webservice URLs are hard-coded because the presumption is that if the URLs change, the functionality is likely changing as well. ##Prerequisites Luminis 5.x (Luminis 4 is not supported) Grails 2.2.5 (the portlets plugins have not been ported to a newer version) Check BuildConfig.groovy for Grails dependencies/plugins. It definitely needs Ellucian Luminis libraries to build properly. You will need to install these in your local maven or other Grails-compatible repository. NO ELLUCIAN, SKYFACTOR, OR OTHER PROPRIETARY CODE IS INCLUDED WITH THIS DISTRIBUTION. Notate your Institution ID given to you by MAP-Works. It is utilized as a shared secret by their webservice. ##Clone upstream git clone https://github.com/StEdwardsTeam/Mapworks-Luminis-SSO.git cd MAP-Works/[StudentMAPWorks|FacultyMAPWorks] ##Build grails war ##Deploy Copy the generated war to your Luminis 5 deployment directory. ##Add Add the new portlet to a page. It will be under the category "SEU Custom". ##Configure As an administrator, click the configure link in the portlet. Add your site-specific information. Enter the Institution ID. Save. ##Test As a valid MAP-Works user (not "lumadmin"), click on the portlet URL to attempt to sign on to MAP-Works. ##Debugging Tips Check the catalina and luminis logs. You may need to import the MAP-Works SSL certificates into the Java keystore. You may need to patch Luminis' Java to have unlimited encryption. ##License This software is released under the open source MIT license. Please refer to the file [LICENSE](LICENSE) for more information.
{ "content_hash": "49dbc48bf20e83ce3ef4e4577ab508eb", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 80, "avg_line_length": 29.555555555555557, "alnum_prop": 0.784640171858217, "repo_name": "StEdwardsTeam/Mapworks-Luminis-SSO", "id": "85a36ca4881d56b6a942dd80b93d964d06b032c3", "size": "1917", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "28816" }, { "name": "Groovy", "bytes": "41225" }, { "name": "Java", "bytes": "6762" }, { "name": "JavaScript", "bytes": "366" } ], "symlink_target": "" }
'use strict'; module.exports = function (grunt) { grunt.initConfig({ jshint: { options: { jshintrc: '.jshintrc' }, files: ['Gruntfile.js', 'bin/*', 'lib/**/*.js', 'test/*.js'] }, simplemocha: { options: { reporter: 'spec', timeout: '5000' }, full: { src: ['test/*.js'] }, short: { options: { reporter: 'dot' }, src: ['<%= simplemocha.full.src %>'] } }, exec: { coverage: { command: 'node node_modules/istanbul/lib/cli.js cover --dir ./coverage node_modules/mocha/bin/_mocha -- -R dot test/*.js' }, 'test-files': { command: 'node download-test-assets.js' } }, watch: { files: ['<%= jshint.files %>'], tasks: ['jshint', 'simplemocha:short'] } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-simple-mocha'); grunt.loadNpmTasks('grunt-exec'); grunt.registerTask('test', ['jshint', 'simplemocha:full']); grunt.registerTask('coverage', 'exec:coverage'); grunt.registerTask('test-files', 'exec:test-files'); grunt.registerTask('default', 'test'); };
{ "content_hash": "118b536847b837164b90749aab9aea64", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 137, "avg_line_length": 31.53191489361702, "alnum_prop": 0.451417004048583, "repo_name": "elisam98/mikomos-ember", "id": "350e415ead7c15b5b95c01b97b51cb86903b7053", "size": "1482", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "node_modules/bower/node_modules/decompress-zip/Gruntfile.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "76" }, { "name": "JavaScript", "bytes": "57634" } ], "symlink_target": "" }
id: bad87fee1348bd9aed608826 title: Use appendTo to Move Elements with jQuery challengeType: 6 forumTopicId: 18340 localeTitle: Используйте appendTo для перемещения элементов с помощью jQuery --- ## Description <section id='description'> Теперь давайте попробуем переместить элементы из одного <code>div</code> в другой. Функция jQuery имеет функцию <code>appendTo()</code> которая позволяет вам выбирать элементы HTML и добавлять их к другому элементу. Например, если мы хотим перенести <code>target4</code> с нашей правой скважины на нашу левую скважину, мы будем использовать: <code>$(&quot;#target4&quot;).appendTo(&quot;#left-well&quot;);</code> Переместите элемент <code>target2</code> с <code>left-well</code> на <code>right-well</code> . </section> ## Instructions <section id='instructions'> </section> ## Tests <section id='tests'> ```yml tests: - text: Your <code>target2</code> element should not be inside your <code>left-well</code>. testString: assert($("#left-well").children("#target2").length === 0); - text: Your <code>target2</code> element should be inside your <code>right-well</code>. testString: assert($("#right-well").children("#target2").length > 0); - text: Only use jQuery to move these elements. testString: assert(!code.match(/class.*animated/g)); ``` </section> ## Challenge Seed <section id='challengeSeed'> <div id='html-seed'> ```html <script> $(document).ready(function() { $("#target1").css("color", "red"); $("#target1").prop("disabled", true); $("#target4").remove(); }); </script> <!-- Only change code above this line. --> <div class="container-fluid"> <h3 class="text-primary text-center">jQuery Playground</h3> <div class="row"> <div class="col-xs-6"> <h4>#left-well</h4> <div class="well" id="left-well"> <button class="btn btn-default target" id="target1">#target1</button> <button class="btn btn-default target" id="target2">#target2</button> <button class="btn btn-default target" id="target3">#target3</button> </div> </div> <div class="col-xs-6"> <h4>#right-well</h4> <div class="well" id="right-well"> <button class="btn btn-default target" id="target4">#target4</button> <button class="btn btn-default target" id="target5">#target5</button> <button class="btn btn-default target" id="target6">#target6</button> </div> </div> </div> </div> ``` </div> </section> ## Solution <section id='solution'> ```html <script> $(document).ready(function() { $("#target1").css("color", "red"); $("#target1").prop("disabled", true); $("#target4").remove(); $("#target2").appendTo("#right-well"); }); </script> <!-- Only change code above this line. --> <div class="container-fluid"> <h3 class="text-primary text-center">jQuery Playground</h3> <div class="row"> <div class="col-xs-6"> <h4>#left-well</h4> <div class="well" id="left-well"> <button class="btn btn-default target" id="target1">#target1</button> <button class="btn btn-default target" id="target2">#target2</button> <button class="btn btn-default target" id="target3">#target3</button> </div> </div> <div class="col-xs-6"> <h4>#right-well</h4> <div class="well" id="right-well"> <button class="btn btn-default target" id="target4">#target4</button> <button class="btn btn-default target" id="target5">#target5</button> <button class="btn btn-default target" id="target6">#target6</button> </div> </div> </div> </div> ``` </section>
{ "content_hash": "63537e2bf0cfa74462d594f0bb2dc3fa", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 507, "avg_line_length": 30.914529914529915, "alnum_prop": 0.6447332043129665, "repo_name": "jonathanihm/freeCodeCamp", "id": "8597fdd335d1df4d32f548b7975b85515e48a42b", "size": "3908", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "curriculum/challenges/russian/03-front-end-libraries/jquery/use-appendto-to-move-elements-with-jquery.russian.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "193850" }, { "name": "HTML", "bytes": "100244" }, { "name": "JavaScript", "bytes": "522335" } ], "symlink_target": "" }
 CKEDITOR.plugins.setLang( 'basicstyles', 'ro', { bold: 'Îngroşat (bold)', italic: 'Înclinat (italic)', strike: 'Tăiat (strike through)', subscript: 'Indice (subscript)', superscript: 'Putere (superscript)', underline: 'Subliniat (underline)' } );
{ "content_hash": "075bda993e7f13d4b96db713acb5b590", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 48, "avg_line_length": 28.333333333333332, "alnum_prop": 0.6823529411764706, "repo_name": "Rudhie/simlab", "id": "da4dbca282f7a2a543da70552891878913ee3d1b", "size": "403", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "assets/ckeditor/plugins/basicstyles/lang/ro.js", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "364" }, { "name": "CSS", "bytes": "186843" }, { "name": "HTML", "bytes": "427207" }, { "name": "JavaScript", "bytes": "5743945" }, { "name": "PHP", "bytes": "1987763" } ], "symlink_target": "" }
package i2c import ( "errors" "fmt" "os" "reflect" "sync" "syscall" "unsafe" ) // S (1 bit) : Start bit // P (1 bit) : Stop bit // Rd/Wr (1 bit) : Read/Write bit. Rd equals 1, Wr equals 0. // A, NA (1 bit) : Accept and reverse accept bit. // Addr (7 bits): I2C 7 bit address. Note that this can be expanded as usual to // get a 10 bit I2C address. // Comm (8 bits): Command byte, a data byte which often selects a register on // the device. // Data (8 bits): A plain data byte. Sometimes, I write DataLow, DataHigh // for 16 bit data. // Count (8 bits): A data byte containing the length of a block operation. // {..}: Data sent by I2C slave, as opposed to data sent by master. type I2CBus interface { // ReadByte reads a byte from the given address. // S Addr Rd {A} {value} NA P ReadByte(addr byte) (value byte, err error) // WriteByte writes a byte to the given address. // S Addr Wr {A} value {A} P WriteByte(addr, value byte) error // WriteBytes writes a slice bytes to the given address. // S Addr Wr {A} value[0] {A} value[1] {A} ... {A} value[n] {A} NA P WriteBytes(addr byte, value []byte) error ReadBytes(addr byte, rxbuff []byte) error // ReadFromReg reads n (len(value)) bytes from the given address and register. ReadFromReg(addr, reg byte, value []byte) error // ReadByteFromReg reads a byte from the given address and register. ReadByteFromReg(addr, reg byte) (value byte, err error) // ReadU16FromReg reads a unsigned 16 bit integer from the given address and register. ReadWordFromReg(addr, reg byte) (value uint16, err error) ReadWordFromRegLSBF(addr, reg byte) (value uint16, err error) // WriteToReg writes len(value) bytes to the given address and register. WriteToReg(addr, reg byte, value []byte) error // WriteByteToReg writes a byte to the given address and register. WriteByteToReg(addr, reg, value byte) error // WriteU16ToReg WriteWordToReg(addr, reg byte, value uint16) error // Close releases the resources associated with the bus. Close() error } const ( delay = 1 // delay in milliseconds slaveCmd = 0x0703 // Cmd to set slave address rdrwCmd = 0x0707 // Cmd to read/write data together rd = 0x0001 ) type i2c_msg struct { addr uint16 flags uint16 len uint16 buf uintptr } type i2c_rdwr_ioctl_data struct { msgs uintptr nmsg uint32 } type i2cBus struct { l byte file *os.File addr byte mu sync.Mutex initialized bool } // Returns New i2c interfce on bus use i2cdetect to find out which bus you to use func NewI2CBus(l byte) I2CBus { return &i2cBus{l: l} } func (b *i2cBus) init() error { if b.initialized { return nil } var err error if b.file, err = os.OpenFile(fmt.Sprintf("/dev/i2c-%v", b.l), os.O_RDWR, os.ModeExclusive); err != nil { return err } fmt.Println("i2c: bus %v initialized", b.l) b.initialized = true return nil } func (b *i2cBus) setAddress(addr byte) error { if addr != b.addr { fmt.Println("i2c: setting bus %v address to %#02x", b.l, addr) if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, b.file.Fd(), slaveCmd, uintptr(addr)); errno != 0 { return syscall.Errno(errno) } b.addr = addr } return nil } // ReadByte reads a byte from the given address. func (b *i2cBus) ReadByte(addr byte) (byte, error) { b.mu.Lock() defer b.mu.Unlock() if err := b.init(); err != nil { return 0, err } if err := b.setAddress(addr); err != nil { return 0, err } bytes := make([]byte, 1) n, _ := b.file.Read(bytes) if n != 1 { return 0, fmt.Errorf("i2c: Unexpected number (%v) of bytes read", n) } return bytes[0], nil } func (b *i2cBus) ReadBytes(addr byte, rx []byte) error { if len(rx) == 0 || rx == nil { return errors.New("rx buffer must be initiated before calling") } b.mu.Lock() defer b.mu.Unlock() if err := b.init(); err != nil { return err } if err := b.setAddress(addr); err != nil { return err } // bytes := make([]byte, len(rx)) n, _ := b.file.Read(rx) if n != len(rx) { return fmt.Errorf("i2c: Unexpected number (%v) of bytes read", n) } return nil } // WriteByte writes a byte to the given address. func (b *i2cBus) WriteByte(addr, value byte) error { b.mu.Lock() defer b.mu.Unlock() if err := b.init(); err != nil { return err } if err := b.setAddress(addr); err != nil { return err } n, err := b.file.Write([]byte{value}) if n != 1 { err = fmt.Errorf("i2c: Unexpected number (%v) of bytes written in WriteByte", n) } return err } // WriteBytes writes a slice bytes to the given address. func (b *i2cBus) WriteBytes(addr byte, value []byte) error { b.mu.Lock() defer b.mu.Unlock() if err := b.init(); err != nil { return errors.New("could not initialise:" + err.Error()) } if err := b.setAddress(addr); err != nil { return errors.New("could not set adress:" + err.Error()) } outbuf := value hdrp := (*reflect.SliceHeader)(unsafe.Pointer(&outbuf)) var message i2c_msg message.addr = uint16(addr) message.flags = 0 message.len = uint16(len(outbuf)) message.buf = uintptr(unsafe.Pointer(&hdrp.Data)) var packets i2c_rdwr_ioctl_data packets.msgs = uintptr(unsafe.Pointer(&message)) packets.nmsg = 1 if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, b.file.Fd(), rdrwCmd, uintptr(unsafe.Pointer(&packets))); errno != 0 { return syscall.Errno(errno) } return nil } // ReadFromReg reads n (len(value)) bytes from the given address and register. func (b *i2cBus) ReadFromReg(addr, reg byte, value []byte) error { b.mu.Lock() defer b.mu.Unlock() if err := b.init(); err != nil { return err } if err := b.setAddress(addr); err != nil { return err } hdrp := (*reflect.SliceHeader)(unsafe.Pointer(&value)) var messages [2]i2c_msg messages[0].addr = uint16(addr) messages[0].flags = 0 messages[0].len = 1 messages[0].buf = uintptr(unsafe.Pointer(&reg)) messages[1].addr = uint16(addr) messages[1].flags = rd messages[1].len = uint16(len(value)) messages[1].buf = uintptr(unsafe.Pointer(hdrp.Data)) var packets i2c_rdwr_ioctl_data packets.msgs = uintptr(unsafe.Pointer(&messages)) packets.nmsg = 2 if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, b.file.Fd(), rdrwCmd, uintptr(unsafe.Pointer(&packets))); errno != 0 { return syscall.Errno(errno) } return nil } // ReadByteFromReg reads a byte from the given address and register. func (b *i2cBus) ReadByteFromReg(addr, reg byte) (byte, error) { buf := make([]byte, 1) if err := b.ReadFromReg(addr, reg, buf); err != nil { return 0, err } return buf[0], nil } // Read single word from register first byte is MSB func (b *i2cBus) ReadWordFromReg(addr, reg byte) (uint16, error) { buf := make([]byte, 2) if err := b.ReadFromReg(addr, reg, buf); err != nil { return 0, err } return uint16((uint16(buf[0]) << 8) | uint16(buf[1])), nil } // Read single word from register first byte is LSB func (b *i2cBus) ReadWordFromRegLSBF(addr, reg byte) (uint16, error) { buf := make([]byte, 2) if err := b.ReadFromReg(addr, reg, buf); err != nil { return 0, err } return uint16((uint16(buf[1]) << 8) | uint16(buf[0])), nil } //Write []byte word to resgister func (b *i2cBus) WriteToReg(addr, reg byte, value []byte) error { b.mu.Lock() defer b.mu.Unlock() if err := b.init(); err != nil { return err } if err := b.setAddress(addr); err != nil { return err } outbuf := append([]byte{reg}, value...) hdrp := (*reflect.SliceHeader)(unsafe.Pointer(&outbuf)) var message i2c_msg message.addr = uint16(addr) message.flags = 0 message.len = uint16(len(outbuf)) message.buf = uintptr(unsafe.Pointer(&hdrp.Data)) var packets i2c_rdwr_ioctl_data packets.msgs = uintptr(unsafe.Pointer(&message)) packets.nmsg = 1 if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, b.file.Fd(), rdrwCmd, uintptr(unsafe.Pointer(&packets))); errno != 0 { return syscall.Errno(errno) } return nil } // Write single Byte to register func (b *i2cBus) WriteByteToReg(addr, reg, value byte) error { b.mu.Lock() defer b.mu.Unlock() if err := b.init(); err != nil { return err } if err := b.setAddress(addr); err != nil { return err } outbuf := [...]byte{ reg, value, } var message i2c_msg message.addr = uint16(addr) message.flags = 0 message.len = uint16(len(outbuf)) message.buf = uintptr(unsafe.Pointer(&outbuf)) var packets i2c_rdwr_ioctl_data packets.msgs = uintptr(unsafe.Pointer(&message)) packets.nmsg = 1 if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, b.file.Fd(), rdrwCmd, uintptr(unsafe.Pointer(&packets))); errno != 0 { return syscall.Errno(errno) } return nil } // Write Single Word to Register func (b *i2cBus) WriteWordToReg(addr, reg byte, value uint16) error { b.mu.Lock() defer b.mu.Unlock() if err := b.init(); err != nil { return err } if err := b.setAddress(addr); err != nil { return err } outbuf := [...]byte{ reg, byte(value >> 8), byte(value), } var messages i2c_msg messages.addr = uint16(addr) messages.flags = 0 messages.len = uint16(len(outbuf)) messages.buf = uintptr(unsafe.Pointer(&outbuf)) var packets i2c_rdwr_ioctl_data packets.msgs = uintptr(unsafe.Pointer(&messages)) packets.nmsg = 1 if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, b.file.Fd(), rdrwCmd, uintptr(unsafe.Pointer(&packets))); errno != 0 { return syscall.Errno(errno) } return nil } // Close i2c file func (b *i2cBus) Close() error { b.mu.Lock() defer b.mu.Unlock() if !b.initialized { return nil } return b.file.Close() }
{ "content_hash": "c173ae3a6bf98ed0a99b8aa15576d948", "timestamp": "", "source": "github", "line_count": 404, "max_line_length": 124, "avg_line_length": 23.61881188118812, "alnum_prop": 0.6598197442884092, "repo_name": "NeuralSpaz/i2c", "id": "6bd4d138399b0e92f001a32e50afc6ea9810bb98", "size": "10759", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "i2c.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "10759" } ], "symlink_target": "" }
Code examples referenced on the AE blogsite: http://blog.ae.be/combining-the-power-of-r-and-d3-js/
{ "content_hash": "112d468878dc5ae5c9aa6d01e5c7089f", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 53, "avg_line_length": 49.5, "alnum_prop": 0.7676767676767676, "repo_name": "sukhdeepsingh/codewaffle", "id": "8df20e47a0398bfb4d9d57370bdc6949bfccbfa0", "size": "111", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "d3/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "57970" }, { "name": "HTML", "bytes": "249682" }, { "name": "JavaScript", "bytes": "64716" }, { "name": "R", "bytes": "12688" }, { "name": "Ruby", "bytes": "2490" } ], "symlink_target": "" }
<component name="libraryTable"> <library name="support-v4-23.3.0"> <ANNOTATIONS> <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/support-v4/23.3.0/annotations.zip!/" /> </ANNOTATIONS> <CLASSES> <root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/support-v4/23.3.0/res" /> <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/support-v4/23.3.0/jars/classes.jar!/" /> <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/support-v4/23.3.0/jars/libs/internal_impl-23.3.0.jar!/" /> </CLASSES> <JAVADOC /> <SOURCES> <root url="jar://$PROJECT_DIR$/../../Android_SDK/extras/android/m2repository/com/android/support/support-v4/23.3.0/support-v4-23.3.0-sources.jar!/" /> </SOURCES> </library> </component>
{ "content_hash": "18347e65ade4bd68666126605981e571", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 156, "avg_line_length": 56.5625, "alnum_prop": 0.6817679558011049, "repo_name": "Mr-Viker/vweather", "id": "c0cf440e62c029349ef266014a2ff8a35bf3caa4", "size": "905", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".idea/libraries/support_v4_23_3_0.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "35237" } ], "symlink_target": "" }
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { LanguageWordComponent } from './language-word.component'; describe('LanguageWordComponent', () => { let component: LanguageWordComponent; let fixture: ComponentFixture<LanguageWordComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ LanguageWordComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(LanguageWordComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should be created', () => { expect(component).toBeTruthy(); }); });
{ "content_hash": "c2923b3a409399682d338f903f5bc7d9", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 73, "avg_line_length": 27, "alnum_prop": 0.6903703703703704, "repo_name": "chimple/lplatform", "id": "15066d2416243013dc4e457f35e430cd4ea70c34", "size": "675", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/course-detail/lessons/language-word/language-word.component.spec.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "10783" }, { "name": "HTML", "bytes": "64769" }, { "name": "JavaScript", "bytes": "1962" }, { "name": "TypeScript", "bytes": "143862" } ], "symlink_target": "" }
using System; using System.ComponentModel; namespace System.Windows.Forms { class WebBrowserUriTypeConverter : UriTypeConverter { public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { //The UriTypeConverter gives back a relative Uri for things like "www.microsoft.com". If //the Uri is relative, we'll try sticking "http://" on the front to see whether that fixes it up. Uri uri = base.ConvertFrom(context, culture, value) as Uri; if (uri != null && !string.IsNullOrEmpty(uri.OriginalString) && !uri.IsAbsoluteUri) { try { uri = new Uri("http://" + uri.OriginalString.Trim()); } catch (UriFormatException) { //We can't throw "http://" on the front: just return the original (relative) Uri, //which will throw an exception with reasonable text later. } } return uri; } } }
{ "content_hash": "3c2cc06a7f45307f15bc3499e23bbc42", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 130, "avg_line_length": 40.25, "alnum_prop": 0.5661047027506655, "repo_name": "mind0n/hive", "id": "e46705989add151b610593d3c80a3e82332cb89c", "size": "1507", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Cache/Libs/net46/ndp/fx/src/winforms/Managed/System/WinForms/WebBrowserUriTypeConverter.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "670329" }, { "name": "ActionScript", "bytes": "7830" }, { "name": "ApacheConf", "bytes": "47" }, { "name": "Batchfile", "bytes": "18096" }, { "name": "C", "bytes": "19746409" }, { "name": "C#", "bytes": "258148996" }, { "name": "C++", "bytes": "48534520" }, { "name": "CSS", "bytes": "933736" }, { "name": "ColdFusion", "bytes": "10780" }, { "name": "GLSL", "bytes": "3935" }, { "name": "HTML", "bytes": "4631854" }, { "name": "Java", "bytes": "10881" }, { "name": "JavaScript", "bytes": "10250558" }, { "name": "Logos", "bytes": "1526844" }, { "name": "MAXScript", "bytes": "18182" }, { "name": "Mathematica", "bytes": "1166912" }, { "name": "Objective-C", "bytes": "2937200" }, { "name": "PHP", "bytes": "81898" }, { "name": "Perl", "bytes": "9496" }, { "name": "PowerShell", "bytes": "44339" }, { "name": "Python", "bytes": "188058" }, { "name": "Shell", "bytes": "758" }, { "name": "Smalltalk", "bytes": "5818" }, { "name": "TypeScript", "bytes": "50090" } ], "symlink_target": "" }
<!DOCTYPE html> <!-- DO NOT EDIT! This test has been generated by /html/canvas/tools/gentest.py. --> <title>Canvas test: 2d.gradient.interpolate.colouralpha</title> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/html/canvas/resources/canvas-tests.js"></script> <link rel="stylesheet" href="/html/canvas/resources/canvas-tests.css"> <body class="show_output"> <h1>2d.gradient.interpolate.colouralpha</h1> <p class="desc"></p> <p class="output">Actual output:</p> <canvas id="c" class="output" width="100" height="50"><p class="fallback">FAIL (fallback content)</p></canvas> <p class="output expectedtext">Expected output:<p><img src="2d.gradient.interpolate.colouralpha.png" class="output expected" id="expected" alt=""> <ul id="d"></ul> <script> var t = async_test(""); _addTest(function(canvas, ctx) { var g = ctx.createLinearGradient(0, 0, 100, 0); g.addColorStop(0, 'rgba(255,255,0, 0)'); g.addColorStop(1, 'rgba(0,0,255, 1)'); ctx.fillStyle = g; ctx.fillRect(0, 0, 100, 50); _assertPixelApprox(canvas, 25,25, 190,190,65,65, "25,25", "190,190,65,65", 3); _assertPixelApprox(canvas, 50,25, 126,126,128,128, "50,25", "126,126,128,128", 3); _assertPixelApprox(canvas, 75,25, 62,62,192,192, "75,25", "62,62,192,192", 3); }); </script>
{ "content_hash": "6f03f2527e40acac8227af81449d55b5", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 146, "avg_line_length": 38.64705882352941, "alnum_prop": 0.6940639269406392, "repo_name": "ric2b/Vivaldi-browser", "id": "cdeeaf9328b169a88c71ed6b586ebc9fb8f1bdb5", "size": "1314", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "chromium/third_party/blink/web_tests/external/wpt/html/canvas/element/fill-and-stroke-styles/2d.gradient.interpolate.colouralpha.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
define([ 'dijit/form/CheckBox', 'dojo/_base/declare' ], function(CheckBox, declare) { return declare('', [ CheckBox ], { _onClick : function(/* Event */e) { e.stopPropagation(); this.inherited(arguments); } }); });
{ "content_hash": "7cac5c5b69ae09a43fc6e438d7417135", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 43, "avg_line_length": 16.823529411764707, "alnum_prop": 0.493006993006993, "repo_name": "jpgtama/hello-dojo", "id": "42e9a68ee4e1ae182212da75aef4a4dd9b8e60ff", "size": "990", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WebContent/widget/permissionTree/treeNode/CheckBox.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "63862" }, { "name": "HTML", "bytes": "491852" }, { "name": "Java", "bytes": "125198" }, { "name": "JavaScript", "bytes": "2282631" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "6fb6a860276dee44a489c4a0ef5669c8", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "d9977b2747d4f03c181ad75c885bf12762392b60", "size": "199", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Lathyrus/Lathyrus biflorus/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Problem_2-FloatOrDouble")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Problem_2-FloatOrDouble")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8a720c0c-654b-4604-bdc2-a462de7286a0")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "1adeb86c4f6a9aace9e1ac54fdd0e839", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 84, "avg_line_length": 39.416666666666664, "alnum_prop": 0.7463002114164905, "repo_name": "glifada/TelerikAcademy", "id": "728480437339834a0ff83eaf13206d88dfee62b2", "size": "1422", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "C#-Part1/02. PrimitiveDataTypesAndVariables/Problem_2-FloatOrDouble/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "937980" }, { "name": "HTML", "bytes": "8706" }, { "name": "JavaScript", "bytes": "19608" }, { "name": "Visual Basic", "bytes": "10548" }, { "name": "XSLT", "bytes": "5405" } ], "symlink_target": "" }
======= ========================================= SEP 06 Title Extractors Author Ismael Carnales and a bunch of rabid mice Created 2009-07-28 Status Obsolete (discarded) ======= ========================================= ========================================== SEP-006: Rename of Selectors to Extractors ========================================== This SEP proposes a more meaningful naming of XPathSelectors or "Selectors" and their ``x`` method. Motivation ========== When you use Selectors in Scrapy, your final goal is to "extract" the data that you've selected, as the [https://docs.scrapy.org/en/latest/topics/selectors.html XPath Selectors documentation] says (bolding by me): When you’re scraping web pages, the most common task you need to perform is to **extract** data from the HTML source. .. Scrapy comes with its own mechanism for **extracting** data. They’re called ``XPath`` selectors (or just “selectors”, for short) because they “select” certain parts of the HTML document specified by ``XPath`` expressions. .. To actually **extract** the textual data you must call the selector ``extract()`` method, as follows .. Selectors also have a ``re()`` method for **extracting** data using regular expressions. .. For example, suppose you want to **extract** all <p> elements inside <div> elements. First you get would get all <div> elements Rationale ========= As and there is no ``Extractor`` object in Scrapy and what you want to finally perform with ``Selectors`` is extracting data, we propose the renaming of ``Selectors`` to ``Extractors``. (In Scrapy for extracting you use selectors is really weird :) ) Additional changes ================== As the name of the method for performing selection (the ``x`` method) is not descriptive nor mnemotechnic enough and clearly clashes with ``extract`` method (x sounds like a short for extract in english), we propose to rename it to ``select``, ``sel`` (is shortness if required), or ``xpath`` after `lxml's <http://lxml.de/xpathxslt.html>`_ ``xpath`` method. Bonus (ItemBuilder) =================== After this renaming we propose also renaming ``ItemBuilder`` to ``ItemExtractor``, because the ``ItemBuilder``/``Extractor`` will act as a bridge between a set of ``Extractors`` and an ``Item`` and because it will literally "extract" an item from a webpage or set of pages. References ========== 1. XPath Selectors (https://docs.scrapy.org/topics/selectors.html) 2. XPath and XSLT with lxml (http://lxml.de/xpathxslt.html)
{ "content_hash": "69d694b1a8f3bc4f32edc99aea0f3906", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 85, "avg_line_length": 33.64473684210526, "alnum_prop": 0.6585842784513102, "repo_name": "pawelmhm/scrapy", "id": "eb362e945c64aab51ff64d52e143eb55c8ee7bbb", "size": "2569", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "sep/sep-006.rst", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "2790" }, { "name": "Python", "bytes": "1889675" }, { "name": "Roff", "bytes": "2010" }, { "name": "Shell", "bytes": "259" } ], "symlink_target": "" }
package test.net.sf.sojo.navigation; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import junit.framework.TestCase; import net.sf.sojo.core.Converter; import net.sf.sojo.core.conversion.ComplexBean2MapConversion; import net.sf.sojo.navigation.PathAction; import net.sf.sojo.navigation.PathExecuter; import net.sf.sojo.navigation.PathParseException; import net.sf.sojo.navigation.PathParser; import test.net.sf.sojo.model.Car; import test.net.sf.sojo.model.Customer; import test.net.sf.sojo.model.Node; public class PathParserTest extends TestCase { public void testParseWithNullPath() throws Exception { PathAction lvAction[] = PathParser.parse(null); assertNotNull(lvAction); assertEquals(0, lvAction.length); } public void testParseWithEmptyPath() throws Exception { PathAction lvAction[] = PathParser.parse(""); assertNotNull(lvAction); assertEquals(0, lvAction.length); lvAction = PathParser.parse(" "); assertNotNull(lvAction); assertEquals(0, lvAction.length); } public void testParseWithEmptyPathButOnePoint() throws Exception { PathAction lvAction[] = PathParser.parse("."); assertNotNull(lvAction); assertEquals(0, lvAction.length); lvAction = PathParser.parse(" . "); assertNotNull(lvAction); assertEquals(0, lvAction.length); } public void testParseWithSimpleAction() throws Exception { PathAction lvAction[] = PathParser.parse("name"); assertNotNull(lvAction); assertEquals(1, lvAction.length); assertEquals("name", lvAction[0].getPath()); assertEquals("name", lvAction[0].getProperty()); assertNull(lvAction[0].getKey()); assertEquals(PathAction.ACTION_TYPE_SIMPLE, lvAction[0].getType()); } public void testParseWithMoreThanOneBracketKey() throws Exception { try { PathParser.parse("fail(aa(1)"); fail("It is only one open bracket allowed."); } catch (PathParseException e) { assertNotNull(e); } try { PathParser.parse("fail)aa(1)"); fail("It is only one closed bracket allowed."); } catch (PathParseException e) { assertNotNull(e); } try { PathParser.parse("failaa)1("); fail("It is only one open bracket allowed."); } catch (PathParseException e) { assertNotNull(e); } PathAction lvAction[] = PathParser.parse("long(2).path(1).name"); assertEquals(3, lvAction.length); } public void testParseWithMoreThanOneBracketIndex() throws Exception { try { PathParser.parse("fail[aa[1]"); fail("It is only one open bracket allowed."); } catch (PathParseException e) { assertNotNull(e); } try { PathParser.parse("fail]aa[1]"); fail("It is only one closed bracket allowed."); } catch (PathParseException e) { assertNotNull(e); } try { PathParser.parse("failaa]1["); fail("It is only one open bracket allowed."); } catch (PathParseException e) { assertNotNull(e); } PathAction lvAction[] = PathParser.parse("long[2].path[1].name"); assertEquals(3, lvAction.length); } public void testParseWithIndexAction() throws Exception { PathAction lvAction[] = PathParser.parse("address[0].city"); assertNotNull(lvAction); assertEquals(2, lvAction.length); assertEquals("address[0]", lvAction[0].getPath()); assertEquals("address", lvAction[0].getProperty()); assertEquals(0, lvAction[0].getIndex()); assertEquals(PathAction.ACTION_TYPE_INDEX, lvAction[0].getType()); assertEquals("city", lvAction[1].getPath()); assertEquals("city", lvAction[1].getProperty()); assertNull(lvAction[1].getKey()); assertEquals(PathAction.ACTION_TYPE_SIMPLE, lvAction[1].getType()); } public void testParseWithIndexActionInValid() throws Exception { try { PathParser.parse("address0].city"); fail("Missing open bracket."); } catch (PathParseException e) { assertNotNull(e); } } public void testParseWithKeyAction() throws Exception { PathAction lvAction[] = PathParser.parse("address(London).postcode"); assertNotNull(lvAction); assertEquals(2, lvAction.length); assertEquals("address(London)", lvAction[0].getPath()); assertEquals("address", lvAction[0].getProperty()); assertEquals("London", lvAction[0].getKey()); assertEquals(PathAction.ACTION_TYPE_KEY, lvAction[0].getType()); assertEquals("postcode", lvAction[1].getPath()); assertEquals("postcode", lvAction[1].getProperty()); assertNull(lvAction[1].getKey()); assertEquals(PathAction.ACTION_TYPE_SIMPLE, lvAction[1].getType()); } public void testParseWithKeyActionInValid() throws Exception { try { PathParser.parse("addressLondon).postcode"); fail("Missing open bracket."); } catch (PathParseException e) { assertNotNull(e); } } public void testIndexIsNotInteger() throws Exception { try { PathParser.parse("get[a]"); fail("Index must be a integer."); } catch (PathParseException e) { assertNotNull(e); } } public void testIndexIsEmpty() throws Exception { PathAction[] lvActions = PathParser.parse("get[]"); assertEquals(1, lvActions.length); assertEquals("get", lvActions[0].getProperty()); assertEquals("get[]", lvActions[0].getPath()); assertEquals(-1, lvActions[0].getIndex()); assertEquals(PathAction.ACTION_TYPE_INDEX, lvActions[0].getType()); assertNull(lvActions[0].getKey()); } public void testIndexWithWhitespaces() throws Exception { PathAction[] lvActions = PathParser.parse("get[ 1 ]"); assertEquals(1, lvActions.length); assertEquals("get", lvActions[0].getProperty()); assertEquals("get[ 1 ]", lvActions[0].getPath()); assertEquals(1, lvActions[0].getIndex()); assertEquals(PathAction.ACTION_TYPE_INDEX, lvActions[0].getType()); assertNull(lvActions[0].getKey()); } public void testKeyIsEmpty() throws Exception { PathAction[] lvActions = PathParser.parse("get()"); assertEquals(1, lvActions.length); assertEquals("get", lvActions[0].getProperty()); assertEquals("get()", lvActions[0].getPath()); assertEquals(-1, lvActions[0].getIndex()); assertEquals(PathAction.ACTION_TYPE_KEY, lvActions[0].getType()); assertEquals("", lvActions[0].getKey()); } public void testKeyWithWhitespaces() throws Exception { PathAction[] lvActions = PathParser.parse("get( 1 )"); assertEquals(1, lvActions.length); assertEquals("get", lvActions[0].getProperty()); assertEquals("get( 1 )", lvActions[0].getPath()); assertEquals(-1, lvActions[0].getIndex()); assertEquals(PathAction.ACTION_TYPE_KEY, lvActions[0].getType()); assertEquals(" 1 ", lvActions[0].getKey()); } public void testExceuteSimpleFromObject() throws Exception { PathAction lvAction[] = PathParser.parse("name"); Car lvCar = new Car("Ferrari"); Object lvResult = PathExecuter.getNestedProperty(lvCar, lvAction[0]); assertEquals(lvCar.getName(), lvResult); } public void testExceuteSimpleFromConvertedObject() throws Exception { PathAction lvAction[] = PathParser.parse("name"); Car lvCar = new Car("Ferrari"); Converter c = new Converter(); c.addConversion(new ComplexBean2MapConversion()); Object lvSimple = c.convert(lvCar); assertNotNull(lvSimple); Map<?, ?> lvMap = (Map<?, ?>) lvSimple; assertEquals(lvCar.getName(), lvMap.get("name")); Object lvResult = PathExecuter.getNestedProperty(lvSimple, lvAction[0]); assertEquals(lvCar.getName(), lvResult); } public void testExceuteIndexFromList() throws Exception { PathAction lvAction = new PathAction(); lvAction.setIndex(0); lvAction.setType(PathAction.ACTION_TYPE_INDEX); List<String> lvList = new ArrayList<String>(); lvList.add("TestString_1"); Object lvResult = PathExecuter.getNestedProperty(lvList, lvAction); assertEquals("TestString_1", lvResult); lvList.add("TestString_2"); lvList.add("TestString_3"); lvAction.setIndex(2); lvResult = PathExecuter.getNestedProperty(lvList, lvAction); assertEquals("TestString_3", lvResult); } public void testExceuteIndexFromListWithPropertyName() throws Exception { PathAction lvAction[] = PathParser.parse("children[0]"); Node lvNode = new Node("Node"); lvNode.getChildren().add("TestString_1"); lvNode.getChildren().add("TestString_2"); lvNode.getChildren().add("TestString_3"); lvNode.getChildren().add("TestString_4"); Object lvResult = PathExecuter.getNestedProperty(lvNode, lvAction[0]); assertEquals("TestString_1", lvResult); lvAction = PathParser.parse("children[3]"); lvResult = PathExecuter.getNestedProperty(lvNode, lvAction[0]); assertEquals("TestString_4", lvResult); } public void testExceuteIndexFromSet() throws Exception { PathAction lvAction = new PathAction(); lvAction.setIndex(0); lvAction.setType(PathAction.ACTION_TYPE_INDEX); Set<String> lvSet = new LinkedHashSet<String>(); lvSet.add("TestString_1"); Object lvResult = PathExecuter.getNestedProperty(lvSet, lvAction); assertEquals("TestString_1", lvResult); lvSet.add("TestString_2"); lvSet.add("TestString_3"); lvAction.setIndex(2); lvResult = PathExecuter.getNestedProperty(lvSet, lvAction); assertEquals("TestString_3", lvResult); } public void testExceuteIndexFromSetWithPropertyName() throws Exception { PathAction lvAction[] = PathParser.parse("addresses[0]"); Customer c = new Customer(); c.setAddresses(new LinkedHashSet<Object>()); c.getAddresses().add("TestString_1"); Object lvResult = PathExecuter.getNestedProperty(c, lvAction[0]); assertEquals("TestString_1", lvResult); c.getAddresses().add("TestString_2"); c.getAddresses().add("TestString_3"); lvAction = PathParser.parse("addresses[2]"); lvResult = PathExecuter.getNestedProperty(c, lvAction[0]); assertEquals("TestString_3", lvResult); } public void testExceuteKey() throws Exception { PathAction lvAction = new PathAction(); lvAction.setKey("Key_1"); lvAction.setType(PathAction.ACTION_TYPE_KEY); Map<String, String> lvMap = new HashMap<String, String>(); lvMap.put("Key_1", "TestString_1"); Object lvResult = PathExecuter.getNestedProperty(lvMap, lvAction); assertEquals("TestString_1", lvResult); lvMap.put("Key_2", "TestString_2"); lvMap.put("Key_3", "TestString_3"); lvAction.setKey("Key_3"); lvResult = PathExecuter.getNestedProperty(lvMap, lvAction); assertEquals("TestString_3", lvResult); } public void testExceuteKeyWithPropertyName() throws Exception { PathAction lvAction[] = PathParser.parse("namedChildren(Key_1)"); Node lvNode = new Node(); lvNode.getNamedChildren().put("Key_1", "Test_String_1"); Object lvResult = PathExecuter.getNestedProperty(lvNode, lvAction[0]); assertEquals("Test_String_1", lvResult); lvNode.getNamedChildren().put("Key_2", "Test_String_2"); lvNode.getNamedChildren().put("Key_3", "Test_String_3"); lvAction = PathParser.parse("namedChildren(Key_3)"); lvResult = PathExecuter.getNestedProperty(lvNode, lvAction[0]); assertEquals("Test_String_3", lvResult); } public void testExceuteKeyWithNestedPropertyNames() throws Exception { Node lvNode = new Node("Node_1"); lvNode.getNamedChildren().put("Key_1", lvNode); Object lvResult = PathExecuter.getNestedProperty(lvNode, "namedChildren(Key_1).name"); assertEquals("Node_1", lvResult); lvNode.getNamedChildren().put("Key_2", new Node("Node_2")); lvNode.getNamedChildren().put("Key_3", new Node("Node_3")); lvResult = PathExecuter.getNestedProperty(lvNode, "namedChildren(Key_3).name"); assertEquals("Node_3", lvResult); Node lvNode4 = new Node("Node_4"); lvNode4.setParent(lvNode); lvNode.getNamedChildren().put("Key_3", lvNode4); lvResult = PathExecuter.getNestedProperty(lvNode, "namedChildren(Key_3).parent.name"); assertEquals("Node_1", lvResult); } public void testWithOutPropertyName() throws Exception { PathAction pa = PathParser.getActionByPath("(1)"); assertNull(pa.getProperty()); assertEquals(PathAction.ACTION_TYPE_KEY, pa.getType()); assertEquals(-1, pa.getIndex()); assertEquals("1", pa.getKey()); } public void testWithOutPropertyName2() throws Exception { PathAction pa = PathParser.getActionByPath("[1]"); assertNull(pa.getProperty()); assertEquals(PathAction.ACTION_TYPE_INDEX, pa.getType()); assertEquals(1, pa.getIndex()); assertEquals(null, pa.getKey()); } }
{ "content_hash": "a8063a7220b194cc09f494d1b8fe0993", "timestamp": "", "source": "github", "line_count": 361, "max_line_length": 88, "avg_line_length": 35, "alnum_prop": 0.7005144440047487, "repo_name": "maddingo/sojo", "id": "16c184c513cc2030e526a29e4cfc15a813b9ade3", "size": "13269", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/test/net/sf/sojo/navigation/PathParserTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1662" }, { "name": "HTML", "bytes": "5563" }, { "name": "Java", "bytes": "893807" } ], "symlink_target": "" }
/*! * \file * \brief Transform feedback tests. *//*--------------------------------------------------------------------*/ #include "es3fTransformFeedbackTests.hpp" #include "tcuTestLog.hpp" #include "tcuSurface.hpp" #include "tcuImageCompare.hpp" #include "tcuVector.hpp" #include "tcuFormatUtil.hpp" #include "tcuRenderTarget.hpp" #include "gluShaderUtil.hpp" #include "gluVarType.hpp" #include "gluVarTypeUtil.hpp" #include "gluPixelTransfer.hpp" #include "gluRenderContext.hpp" #include "gluShaderProgram.hpp" #include "gluObjectWrapper.hpp" #include "glwFunctions.hpp" #include "glwEnums.hpp" #include "deRandom.hpp" #include "deStringUtil.hpp" #include "deMemory.h" #include "deString.h" #include <set> #include <map> #include <algorithm> using std::string; using std::vector; using std::set; using std::map; using std::set; using tcu::TestLog; namespace deqp { namespace gles3 { namespace Functional { namespace TransformFeedback { enum { VIEWPORT_WIDTH = 128, VIEWPORT_HEIGHT = 128, BUFFER_GUARD_MULTIPLIER = 2 //!< stride*BUFFER_GUARD_MULTIPLIER bytes are added to the end of tf buffer and used to check for overruns. }; enum Interpolation { INTERPOLATION_SMOOTH = 0, INTERPOLATION_FLAT, INTERPOLATION_CENTROID, INTERPOLATION_LAST }; static const char* getInterpolationName (Interpolation interp) { switch (interp) { case INTERPOLATION_SMOOTH: return "smooth"; case INTERPOLATION_FLAT: return "flat"; case INTERPOLATION_CENTROID: return "centroid"; default: DE_ASSERT(false); return DE_NULL; } } struct Varying { Varying (const char* name_, const glu::VarType& type_, Interpolation interp_) : name (name_) , type (type_) , interpolation (interp_) { } std::string name; //!< Variable name. glu::VarType type; //!< Variable type. Interpolation interpolation; //!< Interpolation mode (smooth, flat, centroid). }; struct VaryingNameEquals { VaryingNameEquals (const std::string& name_) : name(name_) {} bool operator() (const Varying& var) const { return var.name == name; } std::string name; }; struct Attribute { Attribute (const std::string& name_, const glu::VarType& type_, int offset_) : name (name_) , type (type_) , offset (offset_) { } std::string name; glu::VarType type; int offset; }; struct AttributeNameEquals { AttributeNameEquals (const std::string& name_) : name(name_) {} bool operator() (const Attribute& attr) const { return attr.name == name; } std::string name; }; struct Output { Output (void) : bufferNdx (0) , offset (0) { } std::string name; glu::VarType type; int bufferNdx; int offset; vector<const Attribute*> inputs; }; struct DrawCall { DrawCall (int numElements_, bool tfEnabled_) : numElements (numElements_) , transformFeedbackEnabled (tfEnabled_) { } DrawCall (void) : numElements (0) , transformFeedbackEnabled (false) { } int numElements; bool transformFeedbackEnabled; }; std::ostream& operator<< (std::ostream& str, const DrawCall& call) { return str << "(" << call.numElements << ", " << (call.transformFeedbackEnabled ? "resumed" : "paused") << ")"; } class ProgramSpec { public: ProgramSpec (void); ~ProgramSpec (void); glu::StructType* createStruct (const char* name); void addVarying (const char* name, const glu::VarType& type, Interpolation interp); void addTransformFeedbackVarying (const char* name); const vector<glu::StructType*>& getStructs (void) const { return m_structs; } const vector<Varying>& getVaryings (void) const { return m_varyings; } const vector<string>& getTransformFeedbackVaryings (void) const { return m_transformFeedbackVaryings; } bool isPointSizeUsed (void) const; private: ProgramSpec (const ProgramSpec& other); ProgramSpec& operator= (const ProgramSpec& other); vector<glu::StructType*> m_structs; vector<Varying> m_varyings; vector<string> m_transformFeedbackVaryings; }; // ProgramSpec ProgramSpec::ProgramSpec (void) { } ProgramSpec::~ProgramSpec (void) { for (vector<glu::StructType*>::iterator i = m_structs.begin(); i != m_structs.end(); i++) delete *i; } glu::StructType* ProgramSpec::createStruct (const char* name) { m_structs.reserve(m_structs.size()+1); m_structs.push_back(new glu::StructType(name)); return m_structs.back(); } void ProgramSpec::addVarying (const char* name, const glu::VarType& type, Interpolation interp) { m_varyings.push_back(Varying(name, type, interp)); } void ProgramSpec::addTransformFeedbackVarying (const char* name) { m_transformFeedbackVaryings.push_back(name); } bool ProgramSpec::isPointSizeUsed (void) const { return std::find(m_transformFeedbackVaryings.begin(), m_transformFeedbackVaryings.end(), "gl_PointSize") != m_transformFeedbackVaryings.end(); } static bool isProgramSupported (const glw::Functions& gl, const ProgramSpec& spec, deUint32 tfMode) { int maxVertexAttribs = 0; int maxTfInterleavedComponents = 0; int maxTfSeparateAttribs = 0; int maxTfSeparateComponents = 0; gl.getIntegerv(GL_MAX_VERTEX_ATTRIBS, &maxVertexAttribs); gl.getIntegerv(GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS, &maxTfInterleavedComponents); gl.getIntegerv(GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS, &maxTfSeparateAttribs); gl.getIntegerv(GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS, &maxTfSeparateComponents); // Check vertex attribs. int totalVertexAttribs = 1 /* a_position */ + (spec.isPointSizeUsed() ? 1 : 0); for (vector<Varying>::const_iterator var = spec.getVaryings().begin(); var != spec.getVaryings().end(); var++) { for (glu::VectorTypeIterator vecIter = glu::VectorTypeIterator::begin(&var->type); vecIter != glu::VectorTypeIterator::end(&var->type); vecIter++) totalVertexAttribs += 1; } if (totalVertexAttribs > maxVertexAttribs) return false; // Vertex attribute count exceeded. // Check varyings. int totalTfComponents = 0; int totalTfAttribs = 0; for (vector<string>::const_iterator iter = spec.getTransformFeedbackVaryings().begin(); iter != spec.getTransformFeedbackVaryings().end(); iter++) { const string& name = *iter; int numComponents = 0; if (name == "gl_Position") numComponents = 4; else if (name == "gl_PointSize") numComponents = 1; else { string varName = glu::parseVariableName(name.c_str()); const Varying& varying = *std::find_if(spec.getVaryings().begin(), spec.getVaryings().end(), VaryingNameEquals(varName)); glu::TypeComponentVector varPath; glu::parseTypePath(name.c_str(), varying.type, varPath); numComponents = glu::getVarType(varying.type, varPath).getScalarSize(); } if (tfMode == GL_SEPARATE_ATTRIBS && numComponents > maxTfSeparateComponents) return false; // Per-attribute component count exceeded. totalTfComponents += numComponents; totalTfAttribs += 1; } if (tfMode == GL_SEPARATE_ATTRIBS && totalTfAttribs > maxTfSeparateAttribs) return false; if (tfMode == GL_INTERLEAVED_ATTRIBS && totalTfComponents > maxTfInterleavedComponents) return false; return true; } // Program static std::string getAttributeName (const char* varyingName, const glu::TypeComponentVector& path) { std::ostringstream str; str << "a_" << (deStringBeginsWith(varyingName, "v_") ? varyingName+2 : varyingName); for (glu::TypeComponentVector::const_iterator iter = path.begin(); iter != path.end(); iter++) { const char* prefix = DE_NULL; switch (iter->type) { case glu::VarTypeComponent::STRUCT_MEMBER: prefix = "_m"; break; case glu::VarTypeComponent::ARRAY_ELEMENT: prefix = "_e"; break; case glu::VarTypeComponent::MATRIX_COLUMN: prefix = "_c"; break; case glu::VarTypeComponent::VECTOR_COMPONENT: prefix = "_s"; break; default: DE_ASSERT(false); } str << prefix << iter->index; } return str.str(); } static void genShaderSources (const ProgramSpec& spec, std::string& vertSource, std::string& fragSource, bool pointSizeRequired) { std::ostringstream vtx; std::ostringstream frag; bool addPointSize = spec.isPointSizeUsed(); vtx << "#version 300 es\n" << "in highp vec4 a_position;\n"; frag << "#version 300 es\n" << "layout(location = 0) out mediump vec4 o_color;\n" << "uniform highp vec4 u_scale;\n" << "uniform highp vec4 u_bias;\n"; if (addPointSize) vtx << "in highp float a_pointSize;\n"; // Declare attributes. for (vector<Varying>::const_iterator var = spec.getVaryings().begin(); var != spec.getVaryings().end(); var++) { const char* name = var->name.c_str(); const glu::VarType& type = var->type; for (glu::VectorTypeIterator vecIter = glu::VectorTypeIterator::begin(&type); vecIter != glu::VectorTypeIterator::end(&type); vecIter++) { glu::VarType attribType = glu::getVarType(type, vecIter.getPath()); string attribName = getAttributeName(name, vecIter.getPath()); vtx << "in " << glu::declare(attribType, attribName.c_str()) << ";\n"; } } // Declare vayrings. for (int ndx = 0; ndx < 2; ndx++) { const char* inout = ndx ? "in" : "out"; std::ostringstream& str = ndx ? frag : vtx; // Declare structs that have type name. for (vector<glu::StructType*>::const_iterator structIter = spec.getStructs().begin(); structIter != spec.getStructs().end(); structIter++) { const glu::StructType* structPtr = *structIter; if (structPtr->hasTypeName()) str << glu::declare(structPtr) << ";\n"; } for (vector<Varying>::const_iterator var = spec.getVaryings().begin(); var != spec.getVaryings().end(); var++) str << getInterpolationName(var->interpolation) << " " << inout << " " << glu::declare(var->type, var->name.c_str()) << ";\n"; } vtx << "\nvoid main (void)\n{\n" << "\tgl_Position = a_position;\n"; frag << "\nvoid main (void)\n{\n" << "\thighp vec4 res = vec4(0.0);\n"; if (addPointSize) vtx << "\tgl_PointSize = a_pointSize;\n"; else if (pointSizeRequired) vtx << "\tgl_PointSize = 1.0;\n"; // Generate assignments / usage. for (vector<Varying>::const_iterator var = spec.getVaryings().begin(); var != spec.getVaryings().end(); var++) { const char* name = var->name.c_str(); const glu::VarType& type = var->type; for (glu::VectorTypeIterator vecIter = glu::VectorTypeIterator::begin(&type); vecIter != glu::VectorTypeIterator::end(&type); vecIter++) { glu::VarType subType = glu::getVarType(type, vecIter.getPath()); string attribName = getAttributeName(name, vecIter.getPath()); DE_ASSERT(subType.isBasicType() && glu::isDataTypeScalarOrVector(subType.getBasicType())); // Vertex: assign from attribute. vtx << "\t" << name << vecIter << " = " << attribName << ";\n"; // Fragment: add to res variable. int scalarSize = glu::getDataTypeScalarSize(subType.getBasicType()); frag << "\tres += "; if (scalarSize == 1) frag << "vec4(" << name << vecIter << ")"; else if (scalarSize == 2) frag << "vec2(" << name << vecIter << ").xxyy"; else if (scalarSize == 3) frag << "vec3(" << name << vecIter << ").xyzx"; else if (scalarSize == 4) frag << "vec4(" << name << vecIter << ")"; frag << ";\n"; } } frag << "\to_color = res * u_scale + u_bias;\n"; vtx << "}\n"; frag << "}\n"; vertSource = vtx.str(); fragSource = frag.str(); } static glu::ShaderProgram* createVertexCaptureProgram (const glu::RenderContext& context, const ProgramSpec& spec, deUint32 bufferMode, deUint32 primitiveType) { std::string vertSource, fragSource; genShaderSources(spec, vertSource, fragSource, primitiveType == GL_POINTS /* Is point size required? */); return new glu::ShaderProgram(context, glu::ProgramSources() << glu::VertexSource(vertSource) << glu::FragmentSource(fragSource) << glu::TransformFeedbackVaryings<vector<string>::const_iterator>(spec.getTransformFeedbackVaryings().begin(), spec.getTransformFeedbackVaryings().end()) << glu::TransformFeedbackMode(bufferMode)); } // Helpers. static void computeInputLayout (vector<Attribute>& attributes, int& inputStride, const vector<Varying>& varyings, bool usePointSize) { inputStride = 0; // Add position. attributes.push_back(Attribute("a_position", glu::VarType(glu::TYPE_FLOAT_VEC4, glu::PRECISION_HIGHP), inputStride)); inputStride += 4*sizeof(deUint32); if (usePointSize) { attributes.push_back(Attribute("a_pointSize", glu::VarType(glu::TYPE_FLOAT, glu::PRECISION_HIGHP), inputStride)); inputStride += 1*sizeof(deUint32); } // Compute attribute vector. for (vector<Varying>::const_iterator var = varyings.begin(); var != varyings.end(); var++) { for (glu::VectorTypeIterator vecIter = glu::VectorTypeIterator::begin(&var->type); vecIter != glu::VectorTypeIterator::end(&var->type); vecIter++) { glu::VarType type = vecIter.getType(); string name = getAttributeName(var->name.c_str(), vecIter.getPath()); attributes.push_back(Attribute(name, type, inputStride)); inputStride += glu::getDataTypeScalarSize(type.getBasicType())*sizeof(deUint32); } } } static void computeTransformFeedbackOutputs (vector<Output>& transformFeedbackOutputs, const vector<Attribute>& attributes, const vector<Varying>& varyings, const vector<string>& transformFeedbackVaryings, deUint32 bufferMode) { int accumulatedSize = 0; transformFeedbackOutputs.resize(transformFeedbackVaryings.size()); for (int varNdx = 0; varNdx < (int)transformFeedbackVaryings.size(); varNdx++) { const string& name = transformFeedbackVaryings[varNdx]; int bufNdx = (bufferMode == GL_SEPARATE_ATTRIBS ? varNdx : 0); int offset = (bufferMode == GL_SEPARATE_ATTRIBS ? 0 : accumulatedSize); Output& output = transformFeedbackOutputs[varNdx]; output.name = name; output.bufferNdx = bufNdx; output.offset = offset; if (name == "gl_Position") { const Attribute* posIn = &(*std::find_if(attributes.begin(), attributes.end(), AttributeNameEquals("a_position"))); output.type = posIn->type; output.inputs.push_back(posIn); } else if (name == "gl_PointSize") { const Attribute* sizeIn = &(*std::find_if(attributes.begin(), attributes.end(), AttributeNameEquals("a_pointSize"))); output.type = sizeIn->type; output.inputs.push_back(sizeIn); } else { string varName = glu::parseVariableName(name.c_str()); const Varying& varying = *std::find_if(varyings.begin(), varyings.end(), VaryingNameEquals(varName)); glu::TypeComponentVector varPath; glu::parseTypePath(name.c_str(), varying.type, varPath); output.type = glu::getVarType(varying.type, varPath); // Add all vectorized attributes as inputs. for (glu::VectorTypeIterator iter = glu::VectorTypeIterator::begin(&output.type); iter != glu::VectorTypeIterator::end(&output.type); iter++) { // Full path. glu::TypeComponentVector fullPath(varPath.size() + iter.getPath().size()); std::copy(varPath.begin(), varPath.end(), fullPath.begin()); std::copy(iter.getPath().begin(), iter.getPath().end(), fullPath.begin()+varPath.size()); string attribName = getAttributeName(varName.c_str(), fullPath); const Attribute* attrib = &(*std::find_if(attributes.begin(), attributes.end(), AttributeNameEquals(attribName))); output.inputs.push_back(attrib); } } accumulatedSize += output.type.getScalarSize()*sizeof(deUint32); } } static deUint32 signExtend (deUint32 value, deUint32 numBits) { DE_ASSERT(numBits >= 1u && numBits <= 32u); if (numBits == 32u) return value; else if ((value & (1u << (numBits-1u))) == 0u) return value; else return value | ~((1u << numBits) - 1u); } static void genAttributeData (const Attribute& attrib, deUint8* basePtr, int stride, int numElements, de::Random& rnd) { const int elementSize = (int)sizeof(deUint32); const bool isFloat = glu::isDataTypeFloatOrVec(attrib.type.getBasicType()); const bool isInt = glu::isDataTypeIntOrIVec(attrib.type.getBasicType()); const bool isUint = glu::isDataTypeUintOrUVec(attrib.type.getBasicType()); const glu::Precision precision = attrib.type.getPrecision(); const int numComps = glu::getDataTypeScalarSize(attrib.type.getBasicType()); for (int elemNdx = 0; elemNdx < numElements; elemNdx++) { for (int compNdx = 0; compNdx < numComps; compNdx++) { int offset = attrib.offset+elemNdx*stride+compNdx*elementSize; if (isFloat) { float* comp = (float*)(basePtr+offset); switch (precision) { case glu::PRECISION_LOWP: *comp = 0.0f + 0.25f*(float)rnd.getInt(0, 4); break; case glu::PRECISION_MEDIUMP: *comp = rnd.getFloat(-1e3f, 1e3f); break; case glu::PRECISION_HIGHP: *comp = rnd.getFloat(-1e5f, 1e5f); break; default: DE_ASSERT(false); } } else if (isInt) { int* comp = (int*)(basePtr+offset); switch (precision) { case glu::PRECISION_LOWP: *comp = (int)signExtend(rnd.getUint32()&0xff, 8); break; case glu::PRECISION_MEDIUMP: *comp = (int)signExtend(rnd.getUint32()&0xffff, 16); break; case glu::PRECISION_HIGHP: *comp = (int)rnd.getUint32(); break; default: DE_ASSERT(false); } } else if (isUint) { deUint32* comp = (deUint32*)(basePtr+offset); switch (precision) { case glu::PRECISION_LOWP: *comp = rnd.getUint32()&0xff; break; case glu::PRECISION_MEDIUMP: *comp = rnd.getUint32()&0xffff; break; case glu::PRECISION_HIGHP: *comp = rnd.getUint32(); break; default: DE_ASSERT(false); } } else DE_ASSERT(false); } } } static void genInputData (const vector<Attribute>& attributes, int numInputs, int inputStride, deUint8* inputBasePtr, de::Random& rnd) { // Random positions. const Attribute& position = *std::find_if(attributes.begin(), attributes.end(), AttributeNameEquals("a_position")); for (int ndx = 0; ndx < numInputs; ndx++) { deUint8* ptr = inputBasePtr + position.offset + inputStride*ndx; *((float*)(ptr+ 0)) = rnd.getFloat(-1.2f, 1.2f); *((float*)(ptr+ 4)) = rnd.getFloat(-1.2f, 1.2f); *((float*)(ptr+ 8)) = rnd.getFloat(-1.2f, 1.2f); *((float*)(ptr+12)) = rnd.getFloat(0.1f, 2.0f); } // Point size. vector<Attribute>::const_iterator pointSizePos = std::find_if(attributes.begin(), attributes.end(), AttributeNameEquals("a_pointSize")); if (pointSizePos != attributes.end()) { for (int ndx = 0; ndx < numInputs; ndx++) { deUint8* ptr = inputBasePtr + pointSizePos->offset + inputStride*ndx; *((float*)ptr) = rnd.getFloat(1.0f, 8.0f); } } // Random data for rest of components. for (vector<Attribute>::const_iterator attrib = attributes.begin(); attrib != attributes.end(); attrib++) { if (attrib->name == "a_position" || attrib->name == "a_pointSize") continue; genAttributeData(*attrib, inputBasePtr, inputStride, numInputs, rnd); } } static deUint32 getTransformFeedbackOutputCount (deUint32 primitiveType, int numElements) { switch (primitiveType) { case GL_TRIANGLES: return numElements - numElements%3; case GL_TRIANGLE_STRIP: return de::max(0, numElements-2)*3; case GL_TRIANGLE_FAN: return de::max(0, numElements-2)*3; case GL_LINES: return numElements - numElements%2; case GL_LINE_STRIP: return de::max(0, numElements-1)*2; case GL_LINE_LOOP: return numElements > 1 ? numElements*2 : 0; case GL_POINTS: return numElements; default: DE_ASSERT(false); return 0; } } static deUint32 getTransformFeedbackPrimitiveCount (deUint32 primitiveType, int numElements) { switch (primitiveType) { case GL_TRIANGLES: return numElements/3; case GL_TRIANGLE_STRIP: return de::max(0, numElements-2); case GL_TRIANGLE_FAN: return de::max(0, numElements-2); case GL_LINES: return numElements/2; case GL_LINE_STRIP: return de::max(0, numElements-1); case GL_LINE_LOOP: return numElements > 1 ? numElements : 0; case GL_POINTS: return numElements; default: DE_ASSERT(false); return 0; } } static deUint32 getTransformFeedbackPrimitiveMode (deUint32 primitiveType) { switch (primitiveType) { case GL_TRIANGLES: case GL_TRIANGLE_STRIP: case GL_TRIANGLE_FAN: return GL_TRIANGLES; case GL_LINES: case GL_LINE_LOOP: case GL_LINE_STRIP: return GL_LINES; case GL_POINTS: return GL_POINTS; default: DE_ASSERT(false); return 0; } } static int getAttributeIndex (deUint32 primitiveType, int numInputs, int outNdx) { switch (primitiveType) { case GL_TRIANGLES: return outNdx; case GL_LINES: return outNdx; case GL_POINTS: return outNdx; case GL_TRIANGLE_STRIP: { int triNdx = outNdx/3; int vtxNdx = outNdx%3; return (triNdx%2 != 0 && vtxNdx < 2) ? (triNdx+1-vtxNdx) : (triNdx+vtxNdx); } case GL_TRIANGLE_FAN: return (outNdx%3 != 0) ? (outNdx/3 + outNdx%3) : 0; case GL_LINE_STRIP: return outNdx/2 + outNdx%2; case GL_LINE_LOOP: { int inNdx = outNdx/2 + outNdx%2; return inNdx < numInputs ? inNdx : 0; } default: DE_ASSERT(false); return 0; } } static bool compareTransformFeedbackOutput (tcu::TestLog& log, deUint32 primitiveType, const Output& output, int numInputs, const deUint8* inBasePtr, int inStride, const deUint8* outBasePtr, int outStride) { bool isOk = true; int outOffset = output.offset; for (int attrNdx = 0; attrNdx < (int)output.inputs.size(); attrNdx++) { const Attribute& attribute = *output.inputs[attrNdx]; glu::DataType type = attribute.type.getBasicType(); int numComponents = glu::getDataTypeScalarSize(type); glu::Precision precision = attribute.type.getPrecision(); glu::DataType scalarType = glu::getDataTypeScalarType(type); int numOutputs = getTransformFeedbackOutputCount(primitiveType, numInputs); for (int outNdx = 0; outNdx < numOutputs; outNdx++) { int inNdx = getAttributeIndex(primitiveType, numInputs, outNdx); for (int compNdx = 0; compNdx < numComponents; compNdx++) { const deUint8* inPtr = inBasePtr + inStride*inNdx + attribute.offset + compNdx*sizeof(deUint32); const deUint8* outPtr = outBasePtr + outStride*outNdx + outOffset + compNdx*sizeof(deUint32); deUint32 inVal = *(const deUint32*)inPtr; deUint32 outVal = *(const deUint32*)outPtr; bool isEqual = false; if (scalarType == glu::TYPE_FLOAT) { // ULP comparison is used for highp and mediump. Lowp uses threshold-comparison. switch (precision) { case glu::PRECISION_HIGHP: isEqual = de::abs((int)inVal - (int)outVal) < 2; break; case glu::PRECISION_MEDIUMP: isEqual = de::abs((int)inVal - (int)outVal) < 2+(1<<13); break; case glu::PRECISION_LOWP: { float inF = *(const float*)inPtr; float outF = *(const float*)outPtr; isEqual = de::abs(inF - outF) < 0.1f; break; } default: DE_ASSERT(false); } } else isEqual = (inVal == outVal); // Bit-exact match required for integer types. if (!isEqual) { log << TestLog::Message << "Mismatch in " << output.name << " (" << attribute.name << "), output = " << outNdx << ", input = " << inNdx << ", component = " << compNdx << TestLog::EndMessage; isOk = false; break; } } if (!isOk) break; } if (!isOk) break; outOffset += numComponents*sizeof(deUint32); } return isOk; } static int computeTransformFeedbackPrimitiveCount (deUint32 primitiveType, const DrawCall* first, const DrawCall* end) { int primCount = 0; for (const DrawCall* call = first; call != end; ++call) { if (call->transformFeedbackEnabled) primCount += getTransformFeedbackPrimitiveCount(primitiveType, call->numElements); } return primCount; } static void writeBufferGuard (const glw::Functions& gl, deUint32 target, int bufferSize, int guardSize) { deUint8* ptr = (deUint8*)gl.mapBufferRange(target, bufferSize, guardSize, GL_MAP_WRITE_BIT); if (ptr) deMemset(ptr, 0xcd, guardSize); gl.unmapBuffer(target); GLU_EXPECT_NO_ERROR(gl.getError(), "guardband write"); } static bool verifyGuard (const deUint8* ptr, int guardSize) { for (int ndx = 0; ndx < guardSize; ndx++) { if (ptr[ndx] != 0xcd) return false; } return true; } static void logTransformFeedbackVaryings (TestLog& log, const glw::Functions& gl, deUint32 program) { int numTfVaryings = 0; int maxNameLen = 0; gl.getProgramiv(program, GL_TRANSFORM_FEEDBACK_VARYINGS, &numTfVaryings); gl.getProgramiv(program, GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH, &maxNameLen); GLU_EXPECT_NO_ERROR(gl.getError(), "Query TF varyings"); log << TestLog::Message << "GL_TRANSFORM_FEEDBACK_VARYINGS = " << numTfVaryings << TestLog::EndMessage; vector<char> nameBuf(maxNameLen+1); for (int ndx = 0; ndx < numTfVaryings; ndx++) { glw::GLsizei size = 0; glw::GLenum type = 0; gl.getTransformFeedbackVarying(program, ndx, (glw::GLsizei)nameBuf.size(), DE_NULL, &size, &type, &nameBuf[0]); GLU_EXPECT_NO_ERROR(gl.getError(), "glGetTransformFeedbackVarying()"); const glu::DataType dataType = glu::getDataTypeFromGLType(type); const std::string typeName = dataType != glu::TYPE_LAST ? std::string(glu::getDataTypeName(dataType)) : (std::string("unknown(") + tcu::toHex(type).toString() + ")"); log << TestLog::Message << (const char*)&nameBuf[0] << ": " << typeName << "[" << size << "]" << TestLog::EndMessage; } } class TransformFeedbackCase : public TestCase { public: TransformFeedbackCase (Context& context, const char* name, const char* desc, deUint32 bufferMode, deUint32 primitiveType); ~TransformFeedbackCase (void); void init (void); void deinit (void); IterateResult iterate (void); protected: ProgramSpec m_progSpec; deUint32 m_bufferMode; deUint32 m_primitiveType; private: TransformFeedbackCase (const TransformFeedbackCase& other); TransformFeedbackCase& operator= (const TransformFeedbackCase& other); bool runTest (const DrawCall* first, const DrawCall* end, deUint32 seed); // Derived from ProgramSpec in init() int m_inputStride; vector<Attribute> m_attributes; vector<Output> m_transformFeedbackOutputs; vector<int> m_bufferStrides; // GL state. glu::ShaderProgram* m_program; glu::TransformFeedback* m_transformFeedback; vector<deUint32> m_outputBuffers; int m_iterNdx; }; TransformFeedbackCase::TransformFeedbackCase (Context& context, const char* name, const char* desc, deUint32 bufferMode, deUint32 primitiveType) : TestCase (context, name, desc) , m_bufferMode (bufferMode) , m_primitiveType (primitiveType) , m_inputStride (0) , m_program (DE_NULL) , m_transformFeedback (DE_NULL) , m_iterNdx (0) { } TransformFeedbackCase::~TransformFeedbackCase (void) { TransformFeedbackCase::deinit(); } static bool hasArraysInTFVaryings (const ProgramSpec& spec) { for (vector<string>::const_iterator tfVar = spec.getTransformFeedbackVaryings().begin(); tfVar != spec.getTransformFeedbackVaryings().end(); ++tfVar) { string varName = glu::parseVariableName(tfVar->c_str()); vector<Varying>::const_iterator varIter = std::find_if(spec.getVaryings().begin(), spec.getVaryings().end(), VaryingNameEquals(varName)); if (varName == "gl_Position" || varName == "gl_PointSize") continue; DE_ASSERT(varIter != spec.getVaryings().end()); if (varIter->type.isArrayType()) return true; } return false; } void TransformFeedbackCase::init (void) { TestLog& log = m_testCtx.getLog(); const glw::Functions& gl = m_context.getRenderContext().getFunctions(); DE_ASSERT(!m_program); m_program = createVertexCaptureProgram(m_context.getRenderContext(), m_progSpec, m_bufferMode, m_primitiveType); log << *m_program; if (!m_program->isOk()) { const bool linkFail = m_program->getShaderInfo(glu::SHADERTYPE_VERTEX).compileOk && m_program->getShaderInfo(glu::SHADERTYPE_FRAGMENT).compileOk && !m_program->getProgramInfo().linkOk; if (linkFail) { if (!isProgramSupported(gl, m_progSpec, m_bufferMode)) throw tcu::NotSupportedError("Implementation limits execeeded", "", __FILE__, __LINE__); else if (hasArraysInTFVaryings(m_progSpec)) throw tcu::NotSupportedError("Capturing arrays is not supported (undefined in specification)", "", __FILE__, __LINE__); else throw tcu::TestError("Link failed", "", __FILE__, __LINE__); } else throw tcu::TestError("Compile failed", "", __FILE__, __LINE__); } log << TestLog::Message << "Transform feedback varyings: " << tcu::formatArray(m_progSpec.getTransformFeedbackVaryings().begin(), m_progSpec.getTransformFeedbackVaryings().end()) << TestLog::EndMessage; // Print out transform feedback points reported by GL. log << TestLog::Message << "Transform feedback varyings reported by compiler:" << TestLog::EndMessage; logTransformFeedbackVaryings(log, gl, m_program->getProgram()); // Compute input specification. computeInputLayout(m_attributes, m_inputStride, m_progSpec.getVaryings(), m_progSpec.isPointSizeUsed()); // Build list of varyings used in transform feedback. computeTransformFeedbackOutputs(m_transformFeedbackOutputs, m_attributes, m_progSpec.getVaryings(), m_progSpec.getTransformFeedbackVaryings(), m_bufferMode); DE_ASSERT(!m_transformFeedbackOutputs.empty()); // Buffer strides. DE_ASSERT(m_bufferStrides.empty()); if (m_bufferMode == GL_SEPARATE_ATTRIBS) { for (vector<Output>::const_iterator outIter = m_transformFeedbackOutputs.begin(); outIter != m_transformFeedbackOutputs.end(); outIter++) m_bufferStrides.push_back(outIter->type.getScalarSize()*sizeof(deUint32)); } else { int totalSize = 0; for (vector<Output>::const_iterator outIter = m_transformFeedbackOutputs.begin(); outIter != m_transformFeedbackOutputs.end(); outIter++) totalSize += outIter->type.getScalarSize()*sizeof(deUint32); m_bufferStrides.push_back(totalSize); } // \note Actual storage is allocated in iterate(). m_outputBuffers.resize(m_bufferStrides.size()); gl.genBuffers((glw::GLsizei)m_outputBuffers.size(), &m_outputBuffers[0]); DE_ASSERT(!m_transformFeedback); m_transformFeedback = new glu::TransformFeedback(m_context.getRenderContext()); GLU_EXPECT_NO_ERROR(gl.getError(), "init"); m_iterNdx = 0; m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); } void TransformFeedbackCase::deinit (void) { const glw::Functions& gl = m_context.getRenderContext().getFunctions(); if (!m_outputBuffers.empty()) { gl.deleteBuffers((glw::GLsizei)m_outputBuffers.size(), &m_outputBuffers[0]); m_outputBuffers.clear(); } delete m_transformFeedback; m_transformFeedback = DE_NULL; delete m_program; m_program = DE_NULL; // Clean up state. m_attributes.clear(); m_transformFeedbackOutputs.clear(); m_bufferStrides.clear(); m_inputStride = 0; } TransformFeedbackCase::IterateResult TransformFeedbackCase::iterate (void) { // Test cases. static const DrawCall s_elemCount1[] = { DrawCall(1, true) }; static const DrawCall s_elemCount2[] = { DrawCall(2, true) }; static const DrawCall s_elemCount3[] = { DrawCall(3, true) }; static const DrawCall s_elemCount4[] = { DrawCall(4, true) }; static const DrawCall s_elemCount123[] = { DrawCall(123, true) }; static const DrawCall s_basicPause1[] = { DrawCall(64, true), DrawCall(64, false), DrawCall(64, true) }; static const DrawCall s_basicPause2[] = { DrawCall(13, true), DrawCall(5, true), DrawCall(17, false), DrawCall(3, true), DrawCall(7, false) }; static const DrawCall s_startPaused[] = { DrawCall(123, false), DrawCall(123, true) }; static const DrawCall s_random1[] = { DrawCall(65, true), DrawCall(135, false), DrawCall(74, true), DrawCall(16, false), DrawCall(226, false), DrawCall(9, true), DrawCall(174, false) }; static const DrawCall s_random2[] = { DrawCall(217, true), DrawCall(171, true), DrawCall(147, true), DrawCall(152, false), DrawCall(55, true) }; static const struct { const DrawCall* calls; int numCalls; } s_iterations[] = { #define ITER(ARR) { ARR, DE_LENGTH_OF_ARRAY(ARR) } ITER(s_elemCount1), ITER(s_elemCount2), ITER(s_elemCount3), ITER(s_elemCount4), ITER(s_elemCount123), ITER(s_basicPause1), ITER(s_basicPause2), ITER(s_startPaused), ITER(s_random1), ITER(s_random2) #undef ITER }; TestLog& log = m_testCtx.getLog(); bool isOk = true; deUint32 seed = deStringHash(getName()) ^ deInt32Hash(m_iterNdx); int numIterations = DE_LENGTH_OF_ARRAY(s_iterations); const DrawCall* first = s_iterations[m_iterNdx].calls; const DrawCall* end = s_iterations[m_iterNdx].calls + s_iterations[m_iterNdx].numCalls; std::string sectionName = std::string("Iteration") + de::toString(m_iterNdx+1); std::string sectionDesc = std::string("Iteration ") + de::toString(m_iterNdx+1) + " / " + de::toString(numIterations); tcu::ScopedLogSection section (log, sectionName, sectionDesc); log << TestLog::Message << "Testing " << s_iterations[m_iterNdx].numCalls << " draw calls, (element count, TF state): " << tcu::formatArray(first, end) << TestLog::EndMessage; isOk = runTest(first, end, seed); if (!isOk) m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Result comparison failed"); m_iterNdx += 1; return (isOk && m_iterNdx < numIterations) ? CONTINUE : STOP; } bool TransformFeedbackCase::runTest (const DrawCall* first, const DrawCall* end, deUint32 seed) { TestLog& log = m_testCtx.getLog(); const glw::Functions& gl = m_context.getRenderContext().getFunctions(); de::Random rnd (seed); int numInputs = 0; //!< Sum of element counts in calls. int numOutputs = 0; //!< Sum of output counts for calls that have transform feedback enabled. int width = m_context.getRenderContext().getRenderTarget().getWidth(); int height = m_context.getRenderContext().getRenderTarget().getHeight(); int viewportW = de::min((int)VIEWPORT_WIDTH, width); int viewportH = de::min((int)VIEWPORT_HEIGHT, height); int viewportX = rnd.getInt(0, width-viewportW); int viewportY = rnd.getInt(0, height-viewportH); tcu::Surface frameWithTf (viewportW, viewportH); tcu::Surface frameWithoutTf (viewportW, viewportH); glu::Query primitiveQuery (m_context.getRenderContext()); bool outputsOk = true; bool imagesOk = true; bool queryOk = true; // Compute totals. for (const DrawCall* call = first; call != end; call++) { numInputs += call->numElements; numOutputs += call->transformFeedbackEnabled ? getTransformFeedbackOutputCount(m_primitiveType, call->numElements) : 0; } // Input data. vector<deUint8> inputData(m_inputStride*numInputs); genInputData(m_attributes, numInputs, m_inputStride, &inputData[0], rnd); gl.bindTransformFeedback(GL_TRANSFORM_FEEDBACK, m_transformFeedback->get()); GLU_EXPECT_NO_ERROR(gl.getError(), "glBindTransformFeedback()"); // Allocate storage for transform feedback output buffers and bind to targets. for (int bufNdx = 0; bufNdx < (int)m_outputBuffers.size(); bufNdx++) { deUint32 buffer = m_outputBuffers[bufNdx]; int stride = m_bufferStrides[bufNdx]; int target = bufNdx; int size = stride*numOutputs; int guardSize = stride*BUFFER_GUARD_MULTIPLIER; const deUint32 usage = GL_DYNAMIC_READ; gl.bindBuffer(GL_TRANSFORM_FEEDBACK_BUFFER, buffer); gl.bufferData(GL_TRANSFORM_FEEDBACK_BUFFER, size+guardSize, DE_NULL, usage); writeBufferGuard(gl, GL_TRANSFORM_FEEDBACK_BUFFER, size, guardSize); // \todo [2012-07-30 pyry] glBindBufferRange()? gl.bindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, target, buffer); GLU_EXPECT_NO_ERROR(gl.getError(), "transform feedback buffer setup"); } // Setup attributes. for (vector<Attribute>::const_iterator attrib = m_attributes.begin(); attrib != m_attributes.end(); attrib++) { int loc = gl.getAttribLocation(m_program->getProgram(), attrib->name.c_str()); glu::DataType scalarType = glu::getDataTypeScalarType(attrib->type.getBasicType()); int numComponents = glu::getDataTypeScalarSize(attrib->type.getBasicType()); const void* ptr = &inputData[0] + attrib->offset; if (loc >= 0) { gl.enableVertexAttribArray(loc); if (scalarType == glu::TYPE_FLOAT) gl.vertexAttribPointer (loc, numComponents, GL_FLOAT, GL_FALSE, m_inputStride, ptr); else if (scalarType == glu::TYPE_INT) gl.vertexAttribIPointer (loc, numComponents, GL_INT, m_inputStride, ptr); else if (scalarType == glu::TYPE_UINT) gl.vertexAttribIPointer (loc, numComponents, GL_UNSIGNED_INT, m_inputStride, ptr); } } // Setup viewport. gl.viewport(viewportX, viewportY, viewportW, viewportH); // Setup program. gl.useProgram(m_program->getProgram()); gl.uniform4fv(gl.getUniformLocation(m_program->getProgram(), "u_scale"), 1, tcu::Vec4(0.01f).getPtr()); gl.uniform4fv(gl.getUniformLocation(m_program->getProgram(), "u_bias"), 1, tcu::Vec4(0.5f).getPtr()); // Enable query. gl.beginQuery(GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN, *primitiveQuery); GLU_EXPECT_NO_ERROR(gl.getError(), "glBeginQuery(GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN)"); // Draw. { int offset = 0; bool tfEnabled = true; gl.clear(GL_COLOR_BUFFER_BIT); gl.beginTransformFeedback(getTransformFeedbackPrimitiveMode(m_primitiveType)); for (const DrawCall* call = first; call != end; call++) { // Pause or resume transform feedback if necessary. if (call->transformFeedbackEnabled != tfEnabled) { if (call->transformFeedbackEnabled) gl.resumeTransformFeedback(); else gl.pauseTransformFeedback(); tfEnabled = call->transformFeedbackEnabled; } gl.drawArrays(m_primitiveType, offset, call->numElements); offset += call->numElements; } // Resume feedback before finishing it. if (!tfEnabled) gl.resumeTransformFeedback(); gl.endTransformFeedback(); GLU_EXPECT_NO_ERROR(gl.getError(), "render"); } gl.endQuery(GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN); GLU_EXPECT_NO_ERROR(gl.getError(), "glEndQuery(GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN)"); // Check and log query status right after submit { deUint32 available = GL_FALSE; gl.getQueryObjectuiv(*primitiveQuery, GL_QUERY_RESULT_AVAILABLE, &available); GLU_EXPECT_NO_ERROR(gl.getError(), "glGetQueryObjectuiv()"); log << TestLog::Message << "GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN status after submit: " << (available != GL_FALSE ? "GL_TRUE" : "GL_FALSE") << TestLog::EndMessage; } // Compare result buffers. for (int bufferNdx = 0; bufferNdx < (int)m_outputBuffers.size(); bufferNdx++) { deUint32 buffer = m_outputBuffers[bufferNdx]; int stride = m_bufferStrides[bufferNdx]; int size = stride*numOutputs; int guardSize = stride*BUFFER_GUARD_MULTIPLIER; const void* bufPtr = DE_NULL; // Bind buffer for reading. gl.bindBuffer(GL_TRANSFORM_FEEDBACK_BUFFER, buffer); bufPtr = gl.mapBufferRange(GL_TRANSFORM_FEEDBACK_BUFFER, 0, size+guardSize, GL_MAP_READ_BIT); GLU_EXPECT_NO_ERROR(gl.getError(), "mapping buffer"); // Verify all output variables that are written to this buffer. for (vector<Output>::const_iterator out = m_transformFeedbackOutputs.begin(); out != m_transformFeedbackOutputs.end(); out++) { if (out->bufferNdx != bufferNdx) continue; int inputOffset = 0; int outputOffset = 0; // Process all draw calls and check ones with transform feedback enabled. for (const DrawCall* call = first; call != end; call++) { if (call->transformFeedbackEnabled) { const deUint8* inputPtr = &inputData[0] + inputOffset*m_inputStride; const deUint8* outputPtr = (const deUint8*)bufPtr + outputOffset*stride; if (!compareTransformFeedbackOutput(log, m_primitiveType, *out, call->numElements, inputPtr, m_inputStride, outputPtr, stride)) { outputsOk = false; break; } } inputOffset += call->numElements; outputOffset += call->transformFeedbackEnabled ? getTransformFeedbackOutputCount(m_primitiveType, call->numElements) : 0; } } // Verify guardband. if (!verifyGuard((const deUint8*)bufPtr + size, guardSize)) { log << TestLog::Message << "Error: Transform feedback buffer overrun detected" << TestLog::EndMessage; outputsOk = false; } gl.unmapBuffer(GL_TRANSFORM_FEEDBACK_BUFFER); } // Check status after mapping buffers. { const bool mustBeReady = !m_outputBuffers.empty(); // Mapping buffer forces synchronization. const int expectedCount = computeTransformFeedbackPrimitiveCount(m_primitiveType, first, end); deUint32 available = GL_FALSE; deUint32 numPrimitives = 0; gl.getQueryObjectuiv(*primitiveQuery, GL_QUERY_RESULT_AVAILABLE, &available); gl.getQueryObjectuiv(*primitiveQuery, GL_QUERY_RESULT, &numPrimitives); GLU_EXPECT_NO_ERROR(gl.getError(), "glGetQueryObjectuiv()"); if (!mustBeReady && available == GL_FALSE) { log << TestLog::Message << "ERROR: GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN result not available after mapping buffers!" << TestLog::EndMessage; queryOk = false; } log << TestLog::Message << "GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN = " << numPrimitives << TestLog::EndMessage; if ((int)numPrimitives != expectedCount) { log << TestLog::Message << "ERROR: Expected " << expectedCount << " primitives!" << TestLog::EndMessage; queryOk = false; } } // Clear transform feedback state. gl.bindTransformFeedback(GL_TRANSFORM_FEEDBACK, 0); for (int bufNdx = 0; bufNdx < (int)m_outputBuffers.size(); bufNdx++) { gl.bindBuffer (GL_TRANSFORM_FEEDBACK_BUFFER, 0); gl.bindBufferBase (GL_TRANSFORM_FEEDBACK_BUFFER, bufNdx, 0); } // Read back rendered image. glu::readPixels(m_context.getRenderContext(), viewportX, viewportY, frameWithTf.getAccess()); // Render without transform feedback. { int offset = 0; gl.clear(GL_COLOR_BUFFER_BIT); for (const DrawCall* call = first; call != end; call++) { gl.drawArrays(m_primitiveType, offset, call->numElements); offset += call->numElements; } GLU_EXPECT_NO_ERROR(gl.getError(), "render"); glu::readPixels(m_context.getRenderContext(), viewportX, viewportY, frameWithoutTf.getAccess()); } // Compare images with and without transform feedback. imagesOk = tcu::pixelThresholdCompare(log, "Result", "Image comparison result", frameWithoutTf, frameWithTf, tcu::RGBA(1, 1, 1, 1), tcu::COMPARE_LOG_ON_ERROR); if (imagesOk) m_testCtx.getLog() << TestLog::Message << "Rendering result comparison between TF enabled and TF disabled passed." << TestLog::EndMessage; else m_testCtx.getLog() << TestLog::Message << "ERROR: Rendering result comparison between TF enabled and TF disabled failed!" << TestLog::EndMessage; return outputsOk && imagesOk && queryOk; } // Test cases. class PositionCase : public TransformFeedbackCase { public: PositionCase (Context& context, const char* name, const char* desc, deUint32 bufferType, deUint32 primitiveType) : TransformFeedbackCase(context, name, desc, bufferType, primitiveType) { m_progSpec.addTransformFeedbackVarying("gl_Position"); } }; class PointSizeCase : public TransformFeedbackCase { public: PointSizeCase (Context& context, const char* name, const char* desc, deUint32 bufferType, deUint32 primitiveType) : TransformFeedbackCase(context, name, desc, bufferType, primitiveType) { m_progSpec.addTransformFeedbackVarying("gl_PointSize"); } }; class BasicTypeCase : public TransformFeedbackCase { public: BasicTypeCase (Context& context, const char* name, const char* desc, deUint32 bufferType, deUint32 primitiveType, glu::DataType type, glu::Precision precision, Interpolation interpolation) : TransformFeedbackCase(context, name, desc, bufferType, primitiveType) { m_progSpec.addVarying("v_varA", glu::VarType(type, precision), interpolation); m_progSpec.addVarying("v_varB", glu::VarType(type, precision), interpolation); m_progSpec.addTransformFeedbackVarying("v_varA"); m_progSpec.addTransformFeedbackVarying("v_varB"); } }; class BasicArrayCase : public TransformFeedbackCase { public: BasicArrayCase (Context& context, const char* name, const char* desc, deUint32 bufferType, deUint32 primitiveType, glu::DataType type, glu::Precision precision, Interpolation interpolation) : TransformFeedbackCase(context, name, desc, bufferType, primitiveType) { if (glu::isDataTypeMatrix(type) || m_bufferMode == GL_SEPARATE_ATTRIBS) { // \note For matrix types we need to use reduced array sizes or otherwise we will exceed maximum attribute (16) // or transform feedback component count (64). // On separate attribs mode maximum component count per varying is 4. m_progSpec.addVarying("v_varA", glu::VarType(glu::VarType(type, precision), 1), interpolation); m_progSpec.addVarying("v_varB", glu::VarType(glu::VarType(type, precision), 2), interpolation); } else { m_progSpec.addVarying("v_varA", glu::VarType(glu::VarType(type, precision), 3), interpolation); m_progSpec.addVarying("v_varB", glu::VarType(glu::VarType(type, precision), 4), interpolation); } m_progSpec.addTransformFeedbackVarying("v_varA"); m_progSpec.addTransformFeedbackVarying("v_varB"); } }; class ArrayElementCase : public TransformFeedbackCase { public: ArrayElementCase (Context& context, const char* name, const char* desc, deUint32 bufferType, deUint32 primitiveType, glu::DataType type, glu::Precision precision, Interpolation interpolation) : TransformFeedbackCase(context, name, desc, bufferType, primitiveType) { m_progSpec.addVarying("v_varA", glu::VarType(glu::VarType(type, precision), 3), interpolation); m_progSpec.addVarying("v_varB", glu::VarType(glu::VarType(type, precision), 4), interpolation); m_progSpec.addTransformFeedbackVarying("v_varA[1]"); m_progSpec.addTransformFeedbackVarying("v_varB[0]"); m_progSpec.addTransformFeedbackVarying("v_varB[3]"); } }; class RandomCase : public TransformFeedbackCase { public: RandomCase (Context& context, const char* name, const char* desc, deUint32 bufferType, deUint32 primitiveType, deUint32 seed) : TransformFeedbackCase (context, name, desc, bufferType, primitiveType) , m_seed (seed) { } void init (void) { // \note Hard-coded indices and hackery are used when indexing this, beware. static const glu::DataType typeCandidates[] = { glu::TYPE_FLOAT, glu::TYPE_FLOAT_VEC2, glu::TYPE_FLOAT_VEC3, glu::TYPE_FLOAT_VEC4, glu::TYPE_INT, glu::TYPE_INT_VEC2, glu::TYPE_INT_VEC3, glu::TYPE_INT_VEC4, glu::TYPE_UINT, glu::TYPE_UINT_VEC2, glu::TYPE_UINT_VEC3, glu::TYPE_UINT_VEC4, glu::TYPE_FLOAT_MAT2, glu::TYPE_FLOAT_MAT2X3, glu::TYPE_FLOAT_MAT2X4, glu::TYPE_FLOAT_MAT3X2, glu::TYPE_FLOAT_MAT3, glu::TYPE_FLOAT_MAT3X4, glu::TYPE_FLOAT_MAT4X2, glu::TYPE_FLOAT_MAT4X3, glu::TYPE_FLOAT_MAT4 }; static const glu::Precision precisions[] = { glu::PRECISION_LOWP, glu::PRECISION_MEDIUMP, glu::PRECISION_HIGHP }; static const Interpolation interpModes[] = { INTERPOLATION_FLAT, INTERPOLATION_SMOOTH, INTERPOLATION_CENTROID }; const int maxAttributeVectors = 16; // const int maxTransformFeedbackComponents = 64; // \note It is enough to limit attribute set size. bool isSeparateMode = m_bufferMode == GL_SEPARATE_ATTRIBS; int maxTransformFeedbackVars = isSeparateMode ? 4 : maxAttributeVectors; const float arrayWeight = 0.3f; const float positionWeight = 0.7f; const float pointSizeWeight = 0.1f; const float captureFullArrayWeight = 0.5f; de::Random rnd (m_seed); bool usePosition = rnd.getFloat() < positionWeight; bool usePointSize = rnd.getFloat() < pointSizeWeight; int numAttribVectorsToUse = rnd.getInt(1, maxAttributeVectors - 1/*position*/ - (usePointSize ? 1 : 0)); int numAttributeVectors = 0; int varNdx = 0; // Generate varyings. while (numAttributeVectors < numAttribVectorsToUse) { int maxVecs = isSeparateMode ? de::min(2 /*at most 2*mat2*/, numAttribVectorsToUse-numAttributeVectors) : numAttribVectorsToUse-numAttributeVectors; const glu::DataType* begin = &typeCandidates[0]; const glu::DataType* end = begin + (maxVecs >= 4 ? 21 : maxVecs >= 3 ? 18 : maxVecs >= 2 ? (isSeparateMode ? 13 : 15) : 12); glu::DataType type = rnd.choose<glu::DataType>(begin, end); glu::Precision precision = rnd.choose<glu::Precision>(&precisions[0], &precisions[0]+DE_LENGTH_OF_ARRAY(precisions)); Interpolation interp = glu::getDataTypeScalarType(type) == glu::TYPE_FLOAT ? rnd.choose<Interpolation>(&interpModes[0], &interpModes[0]+DE_LENGTH_OF_ARRAY(interpModes)) : INTERPOLATION_FLAT; int numVecs = glu::isDataTypeMatrix(type) ? glu::getDataTypeMatrixNumColumns(type) : 1; int numComps = glu::getDataTypeScalarSize(type); int maxArrayLen = de::max(1, isSeparateMode ? 4/numComps : maxVecs/numVecs); bool useArray = rnd.getFloat() < arrayWeight; int arrayLen = useArray ? rnd.getInt(1, maxArrayLen) : 1; std::string name = "v_var" + de::toString(varNdx); if (useArray) m_progSpec.addVarying(name.c_str(), glu::VarType(glu::VarType(type, precision), arrayLen), interp); else m_progSpec.addVarying(name.c_str(), glu::VarType(type, precision), interp); numAttributeVectors += arrayLen*numVecs; varNdx += 1; } // Generate transform feedback candidate set. vector<string> tfCandidates; if (usePosition) tfCandidates.push_back("gl_Position"); if (usePointSize) tfCandidates.push_back("gl_PointSize"); for (int ndx = 0; ndx < varNdx /* num varyings */; ndx++) { const Varying& var = m_progSpec.getVaryings()[ndx]; if (var.type.isArrayType()) { const bool captureFull = rnd.getFloat() < captureFullArrayWeight; if (captureFull) tfCandidates.push_back(var.name); else { const int numElem = var.type.getArraySize(); for (int elemNdx = 0; elemNdx < numElem; elemNdx++) tfCandidates.push_back(var.name + "[" + de::toString(elemNdx) + "]"); } } else tfCandidates.push_back(var.name); } // Pick random selection. vector<string> tfVaryings(de::min((int)tfCandidates.size(), maxTransformFeedbackVars)); rnd.choose(tfCandidates.begin(), tfCandidates.end(), tfVaryings.begin(), (int)tfVaryings.size()); rnd.shuffle(tfVaryings.begin(), tfVaryings.end()); for (vector<string>::const_iterator var = tfVaryings.begin(); var != tfVaryings.end(); var++) m_progSpec.addTransformFeedbackVarying(var->c_str()); TransformFeedbackCase::init(); } private: deUint32 m_seed; }; } // TransformFeedback using namespace TransformFeedback; TransformFeedbackTests::TransformFeedbackTests (Context& context) : TestCaseGroup(context, "transform_feedback", "Transform feedback tests") { } TransformFeedbackTests::~TransformFeedbackTests (void) { } void TransformFeedbackTests::init (void) { static const struct { const char* name; deUint32 mode; } bufferModes[] = { { "separate", GL_SEPARATE_ATTRIBS }, { "interleaved", GL_INTERLEAVED_ATTRIBS } }; static const struct { const char* name; deUint32 type; } primitiveTypes[] = { { "points", GL_POINTS }, { "lines", GL_LINES }, { "triangles", GL_TRIANGLES } // Not supported by GLES3. // { "line_strip", GL_LINE_STRIP }, // { "line_loop", GL_LINE_LOOP }, // { "triangle_fan", GL_TRIANGLE_FAN }, // { "triangle_strip", GL_TRIANGLE_STRIP } }; static const glu::DataType basicTypes[] = { glu::TYPE_FLOAT, glu::TYPE_FLOAT_VEC2, glu::TYPE_FLOAT_VEC3, glu::TYPE_FLOAT_VEC4, glu::TYPE_FLOAT_MAT2, glu::TYPE_FLOAT_MAT2X3, glu::TYPE_FLOAT_MAT2X4, glu::TYPE_FLOAT_MAT3X2, glu::TYPE_FLOAT_MAT3, glu::TYPE_FLOAT_MAT3X4, glu::TYPE_FLOAT_MAT4X2, glu::TYPE_FLOAT_MAT4X3, glu::TYPE_FLOAT_MAT4, glu::TYPE_INT, glu::TYPE_INT_VEC2, glu::TYPE_INT_VEC3, glu::TYPE_INT_VEC4, glu::TYPE_UINT, glu::TYPE_UINT_VEC2, glu::TYPE_UINT_VEC3, glu::TYPE_UINT_VEC4 }; static const glu::Precision precisions[] = { glu::PRECISION_LOWP, glu::PRECISION_MEDIUMP, glu::PRECISION_HIGHP }; static const struct { const char* name; Interpolation interp; } interpModes[] = { { "smooth", INTERPOLATION_SMOOTH }, { "flat", INTERPOLATION_FLAT }, { "centroid", INTERPOLATION_CENTROID } }; // .position { tcu::TestCaseGroup* positionGroup = new tcu::TestCaseGroup(m_testCtx, "position", "gl_Position capture using transform feedback"); addChild(positionGroup); for (int primitiveType = 0; primitiveType < DE_LENGTH_OF_ARRAY(primitiveTypes); primitiveType++) { for (int bufferMode = 0; bufferMode < DE_LENGTH_OF_ARRAY(bufferModes); bufferMode++) { string name = string(primitiveTypes[primitiveType].name) + "_" + bufferModes[bufferMode].name; positionGroup->addChild(new PositionCase(m_context, name.c_str(), "", bufferModes[bufferMode].mode, primitiveTypes[primitiveType].type)); } } } // .point_size { tcu::TestCaseGroup* pointSizeGroup = new tcu::TestCaseGroup(m_testCtx, "point_size", "gl_PointSize capture using transform feedback"); addChild(pointSizeGroup); for (int primitiveType = 0; primitiveType < DE_LENGTH_OF_ARRAY(primitiveTypes); primitiveType++) { for (int bufferMode = 0; bufferMode < DE_LENGTH_OF_ARRAY(bufferModes); bufferMode++) { string name = string(primitiveTypes[primitiveType].name) + "_" + bufferModes[bufferMode].name; pointSizeGroup->addChild(new PointSizeCase(m_context, name.c_str(), "", bufferModes[bufferMode].mode, primitiveTypes[primitiveType].type)); } } } // .basic_type { tcu::TestCaseGroup* basicTypeGroup = new tcu::TestCaseGroup(m_testCtx, "basic_types", "Basic types in transform feedback"); addChild(basicTypeGroup); for (int bufferModeNdx = 0; bufferModeNdx < DE_LENGTH_OF_ARRAY(bufferModes); bufferModeNdx++) { tcu::TestCaseGroup* modeGroup = new tcu::TestCaseGroup(m_testCtx, bufferModes[bufferModeNdx].name, ""); deUint32 bufferMode = bufferModes[bufferModeNdx].mode; basicTypeGroup->addChild(modeGroup); for (int primitiveTypeNdx = 0; primitiveTypeNdx < DE_LENGTH_OF_ARRAY(primitiveTypes); primitiveTypeNdx++) { tcu::TestCaseGroup* primitiveGroup = new tcu::TestCaseGroup(m_testCtx, primitiveTypes[primitiveTypeNdx].name, ""); deUint32 primitiveType = primitiveTypes[primitiveTypeNdx].type; modeGroup->addChild(primitiveGroup); for (int typeNdx = 0; typeNdx < DE_LENGTH_OF_ARRAY(basicTypes); typeNdx++) { glu::DataType type = basicTypes[typeNdx]; bool isFloat = glu::getDataTypeScalarType(type) == glu::TYPE_FLOAT; for (int precNdx = 0; precNdx < DE_LENGTH_OF_ARRAY(precisions); precNdx++) { glu::Precision precision = precisions[precNdx]; string name = string(glu::getPrecisionName(precision)) + "_" + glu::getDataTypeName(type); primitiveGroup->addChild(new BasicTypeCase(m_context, name.c_str(), "", bufferMode, primitiveType, type, precision, isFloat ? INTERPOLATION_SMOOTH : INTERPOLATION_FLAT)); } } } } } // .array { tcu::TestCaseGroup* arrayGroup = new tcu::TestCaseGroup(m_testCtx, "array", "Capturing whole array in TF"); addChild(arrayGroup); for (int bufferModeNdx = 0; bufferModeNdx < DE_LENGTH_OF_ARRAY(bufferModes); bufferModeNdx++) { tcu::TestCaseGroup* modeGroup = new tcu::TestCaseGroup(m_testCtx, bufferModes[bufferModeNdx].name, ""); deUint32 bufferMode = bufferModes[bufferModeNdx].mode; arrayGroup->addChild(modeGroup); for (int primitiveTypeNdx = 0; primitiveTypeNdx < DE_LENGTH_OF_ARRAY(primitiveTypes); primitiveTypeNdx++) { tcu::TestCaseGroup* primitiveGroup = new tcu::TestCaseGroup(m_testCtx, primitiveTypes[primitiveTypeNdx].name, ""); deUint32 primitiveType = primitiveTypes[primitiveTypeNdx].type; modeGroup->addChild(primitiveGroup); for (int typeNdx = 0; typeNdx < DE_LENGTH_OF_ARRAY(basicTypes); typeNdx++) { glu::DataType type = basicTypes[typeNdx]; bool isFloat = glu::getDataTypeScalarType(type) == glu::TYPE_FLOAT; for (int precNdx = 0; precNdx < DE_LENGTH_OF_ARRAY(precisions); precNdx++) { glu::Precision precision = precisions[precNdx]; string name = string(glu::getPrecisionName(precision)) + "_" + glu::getDataTypeName(type); primitiveGroup->addChild(new BasicArrayCase(m_context, name.c_str(), "", bufferMode, primitiveType, type, precision, isFloat ? INTERPOLATION_SMOOTH : INTERPOLATION_FLAT)); } } } } } // .array_element { tcu::TestCaseGroup* arrayElemGroup = new tcu::TestCaseGroup(m_testCtx, "array_element", "Capturing single array element in TF"); addChild(arrayElemGroup); for (int bufferModeNdx = 0; bufferModeNdx < DE_LENGTH_OF_ARRAY(bufferModes); bufferModeNdx++) { tcu::TestCaseGroup* modeGroup = new tcu::TestCaseGroup(m_testCtx, bufferModes[bufferModeNdx].name, ""); deUint32 bufferMode = bufferModes[bufferModeNdx].mode; arrayElemGroup->addChild(modeGroup); for (int primitiveTypeNdx = 0; primitiveTypeNdx < DE_LENGTH_OF_ARRAY(primitiveTypes); primitiveTypeNdx++) { tcu::TestCaseGroup* primitiveGroup = new tcu::TestCaseGroup(m_testCtx, primitiveTypes[primitiveTypeNdx].name, ""); deUint32 primitiveType = primitiveTypes[primitiveTypeNdx].type; modeGroup->addChild(primitiveGroup); for (int typeNdx = 0; typeNdx < DE_LENGTH_OF_ARRAY(basicTypes); typeNdx++) { glu::DataType type = basicTypes[typeNdx]; bool isFloat = glu::getDataTypeScalarType(type) == glu::TYPE_FLOAT; for (int precNdx = 0; precNdx < DE_LENGTH_OF_ARRAY(precisions); precNdx++) { glu::Precision precision = precisions[precNdx]; string name = string(glu::getPrecisionName(precision)) + "_" + glu::getDataTypeName(type); primitiveGroup->addChild(new ArrayElementCase(m_context, name.c_str(), "", bufferMode, primitiveType, type, precision, isFloat ? INTERPOLATION_SMOOTH : INTERPOLATION_FLAT)); } } } } } // .interpolation { tcu::TestCaseGroup* interpolationGroup = new tcu::TestCaseGroup(m_testCtx, "interpolation", "Different interpolation modes in transform feedback varyings"); addChild(interpolationGroup); for (int modeNdx = 0; modeNdx < DE_LENGTH_OF_ARRAY(interpModes); modeNdx++) { Interpolation interp = interpModes[modeNdx].interp; tcu::TestCaseGroup* modeGroup = new tcu::TestCaseGroup(m_testCtx, interpModes[modeNdx].name, ""); interpolationGroup->addChild(modeGroup); for (int precNdx = 0; precNdx < DE_LENGTH_OF_ARRAY(precisions); precNdx++) { glu::Precision precision = precisions[precNdx]; for (int primitiveType = 0; primitiveType < DE_LENGTH_OF_ARRAY(primitiveTypes); primitiveType++) { for (int bufferMode = 0; bufferMode < DE_LENGTH_OF_ARRAY(bufferModes); bufferMode++) { string name = string(glu::getPrecisionName(precision)) + "_vec4_" + primitiveTypes[primitiveType].name + "_" + bufferModes[bufferMode].name; modeGroup->addChild(new BasicTypeCase(m_context, name.c_str(), "", bufferModes[bufferMode].mode, primitiveTypes[primitiveType].type, glu::TYPE_FLOAT_VEC4, precision, interp)); } } } } } // .random { tcu::TestCaseGroup* randomGroup = new tcu::TestCaseGroup(m_testCtx, "random", "Randomized transform feedback cases"); addChild(randomGroup); for (int bufferModeNdx = 0; bufferModeNdx < DE_LENGTH_OF_ARRAY(bufferModes); bufferModeNdx++) { tcu::TestCaseGroup* modeGroup = new tcu::TestCaseGroup(m_testCtx, bufferModes[bufferModeNdx].name, ""); deUint32 bufferMode = bufferModes[bufferModeNdx].mode; randomGroup->addChild(modeGroup); for (int primitiveTypeNdx = 0; primitiveTypeNdx < DE_LENGTH_OF_ARRAY(primitiveTypes); primitiveTypeNdx++) { tcu::TestCaseGroup* primitiveGroup = new tcu::TestCaseGroup(m_testCtx, primitiveTypes[primitiveTypeNdx].name, ""); deUint32 primitiveType = primitiveTypes[primitiveTypeNdx].type; modeGroup->addChild(primitiveGroup); for (int ndx = 0; ndx < 10; ndx++) { deUint32 seed = deInt32Hash(bufferMode) ^ deInt32Hash(primitiveType) ^ deInt32Hash(ndx); primitiveGroup->addChild(new RandomCase(m_context, de::toString(ndx+1).c_str(), "", bufferMode, primitiveType, seed)); } } } } } } // Functional } // gles3 } // deqp
{ "content_hash": "60e577fa1205980762376324184e501c", "timestamp": "", "source": "github", "line_count": 1787, "max_line_length": 226, "avg_line_length": 33.90039171796307, "alnum_prop": 0.6908385605810499, "repo_name": "geekboxzone/mmallow_external_deqp", "id": "6ddd9c84ba44cddc695a177860e14ea325cae0ff", "size": "61380", "binary": false, "copies": "1", "ref": "refs/heads/geekbox", "path": "modules/gles3/functional/es3fTransformFeedbackTests.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "320" }, { "name": "C", "bytes": "472688" }, { "name": "C++", "bytes": "20638791" }, { "name": "CMake", "bytes": "169072" }, { "name": "HTML", "bytes": "55736" }, { "name": "Java", "bytes": "25615" }, { "name": "Makefile", "bytes": "34568" }, { "name": "Objective-C", "bytes": "20396" }, { "name": "Objective-C++", "bytes": "17364" }, { "name": "Python", "bytes": "520672" }, { "name": "Shell", "bytes": "166" } ], "symlink_target": "" }
package com.tremolosecurity.provisioning.listeners; import java.util.HashMap; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.jms.Message; import com.google.gson.Gson; import com.tremolosecurity.config.util.ConfigManager; import com.tremolosecurity.json.Token; import com.tremolosecurity.provisioning.core.ProvisioningException; import com.tremolosecurity.provisioning.core.UnisonMessageListener; import com.tremolosecurity.provisioning.scheduler.jobs.util.FailApproval; import com.tremolosecurity.saml.Attribute; import com.tremolosecurity.server.GlobalEntries; public class AutoFailApprovalListener extends UnisonMessageListener { @Override public void onMessage(ConfigManager cfg, Object payload, Message msg) throws ProvisioningException { FailApproval fa = (FailApproval) payload; GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().doApproval(fa.getApprovalID(), fa.getApprover(), false, fa.getMsg()); } @Override public void init(ConfigManager cfg, HashMap<String, Attribute> attributes) throws ProvisioningException { } }
{ "content_hash": "2433513508ac1e545a62499ace22999d", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 147, "avg_line_length": 31.054054054054053, "alnum_prop": 0.8233246301131418, "repo_name": "TremoloSecurity/OpenUnison", "id": "c15c07f0fff2c83d90f6110362f533e56c5953ec", "size": "1910", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "unison/unison-server-core/src/main/java/com/tremolosecurity/provisioning/listeners/AutoFailApprovalListener.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "73482" }, { "name": "HTML", "bytes": "82622" }, { "name": "Java", "bytes": "4512620" }, { "name": "JavaScript", "bytes": "164377" }, { "name": "Less", "bytes": "426660" }, { "name": "Python", "bytes": "2113" }, { "name": "SCSS", "bytes": "419604" }, { "name": "Shell", "bytes": "5354" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head> <title>Source code</title> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> </head> <body> <div class="sourceContainer"> <pre><span class="sourceLineNo">001</span>package squidpony.squidgrid;<a name="line.1"></a> <span class="sourceLineNo">002</span><a name="line.2"></a> <span class="sourceLineNo">003</span>import squidpony.ArrayTools;<a name="line.3"></a> <span class="sourceLineNo">004</span>import squidpony.GwtCompatibility;<a name="line.4"></a> <span class="sourceLineNo">005</span>import squidpony.annotation.Beta;<a name="line.5"></a> <span class="sourceLineNo">006</span>import squidpony.squidmath.GreasedRegion;<a name="line.6"></a> <span class="sourceLineNo">007</span><a name="line.7"></a> <span class="sourceLineNo">008</span>/**<a name="line.8"></a> <span class="sourceLineNo">009</span> * Use FOV instead, probably with type SHADOW; this has the same results as shadowcasting FOV but is slower, currently.<a name="line.9"></a> <span class="sourceLineNo">010</span> * This will probably be rewritten in a very different way.<a name="line.10"></a> <span class="sourceLineNo">011</span> * &lt;br&gt;<a name="line.11"></a> <span class="sourceLineNo">012</span> * A different kind of FOV implementation that pre-processes the map to better analyze the locations of corners.<a name="line.12"></a> <span class="sourceLineNo">013</span> * Based loosely on Adam Milazzo's FOV, http://www.adammil.net/blog/v125_Roguelike_Vision_Algorithms.html , which in<a name="line.13"></a> <span class="sourceLineNo">014</span> * turn is based on the diamond walls technique (on the same page).<a name="line.14"></a> <span class="sourceLineNo">015</span> */<a name="line.15"></a> <span class="sourceLineNo">016</span>@Beta<a name="line.16"></a> <span class="sourceLineNo">017</span>public class BevelFOV extends FOV {<a name="line.17"></a> <span class="sourceLineNo">018</span><a name="line.18"></a> <span class="sourceLineNo">019</span> protected GreasedRegion map = null;<a name="line.19"></a> <span class="sourceLineNo">020</span> private double[][] resMapCache = null;<a name="line.20"></a> <span class="sourceLineNo">021</span><a name="line.21"></a> <span class="sourceLineNo">022</span> /**<a name="line.22"></a> <span class="sourceLineNo">023</span> * Creates a BevelFOV solver.<a name="line.23"></a> <span class="sourceLineNo">024</span> */<a name="line.24"></a> <span class="sourceLineNo">025</span> public BevelFOV() {<a name="line.25"></a> <span class="sourceLineNo">026</span> }<a name="line.26"></a> <span class="sourceLineNo">027</span><a name="line.27"></a> <span class="sourceLineNo">028</span> /**<a name="line.28"></a> <span class="sourceLineNo">029</span> * Included for compatibility; ignores the parameter and calls the default parameter with no argument.<a name="line.29"></a> <span class="sourceLineNo">030</span> *<a name="line.30"></a> <span class="sourceLineNo">031</span> * @param type ignored<a name="line.31"></a> <span class="sourceLineNo">032</span> */<a name="line.32"></a> <span class="sourceLineNo">033</span> public BevelFOV(int type) {<a name="line.33"></a> <span class="sourceLineNo">034</span> this();<a name="line.34"></a> <span class="sourceLineNo">035</span> }<a name="line.35"></a> <span class="sourceLineNo">036</span><a name="line.36"></a> <span class="sourceLineNo">037</span> /**<a name="line.37"></a> <span class="sourceLineNo">038</span> * Calculates the Field Of View for the provided map from the given x, y<a name="line.38"></a> <span class="sourceLineNo">039</span> * coordinates. Returns a light map where the values represent a percentage<a name="line.39"></a> <span class="sourceLineNo">040</span> * of fully lit.<a name="line.40"></a> <span class="sourceLineNo">041</span> * &lt;p&gt;<a name="line.41"></a> <span class="sourceLineNo">042</span> * The starting point for the calculation is considered to be at the center<a name="line.42"></a> <span class="sourceLineNo">043</span> * of the origin cell. Radius determinations based on Euclidean<a name="line.43"></a> <span class="sourceLineNo">044</span> * calculations. The light will be treated as having infinite possible<a name="line.44"></a> <span class="sourceLineNo">045</span> * radius.<a name="line.45"></a> <span class="sourceLineNo">046</span> *<a name="line.46"></a> <span class="sourceLineNo">047</span> * @param resistanceMap the grid of cells to calculate on; the kind made by DungeonUtility.generateResistances()<a name="line.47"></a> <span class="sourceLineNo">048</span> * @param startx the horizontal component of the starting location<a name="line.48"></a> <span class="sourceLineNo">049</span> * @param starty the vertical component of the starting location<a name="line.49"></a> <span class="sourceLineNo">050</span> * @return the computed light grid<a name="line.50"></a> <span class="sourceLineNo">051</span> */<a name="line.51"></a> <span class="sourceLineNo">052</span> @Override<a name="line.52"></a> <span class="sourceLineNo">053</span> public double[][] calculateFOV(double[][] resistanceMap, int startx, int starty) {<a name="line.53"></a> <span class="sourceLineNo">054</span> return calculateFOV(resistanceMap, startx, starty, Integer.MAX_VALUE);<a name="line.54"></a> <span class="sourceLineNo">055</span> }<a name="line.55"></a> <span class="sourceLineNo">056</span><a name="line.56"></a> <span class="sourceLineNo">057</span> /**<a name="line.57"></a> <span class="sourceLineNo">058</span> * Calculates the Field Of View for the provided map from the given x, y<a name="line.58"></a> <span class="sourceLineNo">059</span> * coordinates. Returns a light map where the values represent a percentage<a name="line.59"></a> <span class="sourceLineNo">060</span> * of fully lit.<a name="line.60"></a> <span class="sourceLineNo">061</span> * &lt;p&gt;<a name="line.61"></a> <span class="sourceLineNo">062</span> * The starting point for the calculation is considered to be at the center<a name="line.62"></a> <span class="sourceLineNo">063</span> * of the origin cell. Radius determinations based on Euclidean<a name="line.63"></a> <span class="sourceLineNo">064</span> * calculations.<a name="line.64"></a> <span class="sourceLineNo">065</span> *<a name="line.65"></a> <span class="sourceLineNo">066</span> * @param resistanceMap the grid of cells to calculate on; the kind made by DungeonUtility.generateResistances()<a name="line.66"></a> <span class="sourceLineNo">067</span> * @param startx the horizontal component of the starting location<a name="line.67"></a> <span class="sourceLineNo">068</span> * @param starty the vertical component of the starting location<a name="line.68"></a> <span class="sourceLineNo">069</span> * @param radius the distance the light will extend to<a name="line.69"></a> <span class="sourceLineNo">070</span> * @return the computed light grid<a name="line.70"></a> <span class="sourceLineNo">071</span> */<a name="line.71"></a> <span class="sourceLineNo">072</span> @Override<a name="line.72"></a> <span class="sourceLineNo">073</span> public double[][] calculateFOV(double[][] resistanceMap, int startx, int starty, double radius) {<a name="line.73"></a> <span class="sourceLineNo">074</span> return calculateFOV(resistanceMap, startx, starty, radius, Radius.CIRCLE);<a name="line.74"></a> <span class="sourceLineNo">075</span> }<a name="line.75"></a> <span class="sourceLineNo">076</span><a name="line.76"></a> <span class="sourceLineNo">077</span> /**<a name="line.77"></a> <span class="sourceLineNo">078</span> * Calculates the Field Of View for the provided map from the given x, y<a name="line.78"></a> <span class="sourceLineNo">079</span> * coordinates. Returns a light map where the values represent a percentage<a name="line.79"></a> <span class="sourceLineNo">080</span> * of fully lit.<a name="line.80"></a> <span class="sourceLineNo">081</span> * &lt;p&gt;<a name="line.81"></a> <span class="sourceLineNo">082</span> * The starting point for the calculation is considered to be at the center<a name="line.82"></a> <span class="sourceLineNo">083</span> * of the origin cell. Radius determinations are determined by the provided<a name="line.83"></a> <span class="sourceLineNo">084</span> * RadiusStrategy.<a name="line.84"></a> <span class="sourceLineNo">085</span> *<a name="line.85"></a> <span class="sourceLineNo">086</span> * @param resistanceMap the grid of cells to calculate on; the kind made by DungeonUtility.generateResistances()<a name="line.86"></a> <span class="sourceLineNo">087</span> * @param startX the horizontal component of the starting location<a name="line.87"></a> <span class="sourceLineNo">088</span> * @param startY the vertical component of the starting location<a name="line.88"></a> <span class="sourceLineNo">089</span> * @param radius the distance the light will extend to<a name="line.89"></a> <span class="sourceLineNo">090</span> * @param radiusTechnique provides a means to calculate the radius as desired<a name="line.90"></a> <span class="sourceLineNo">091</span> * @return the computed light grid<a name="line.91"></a> <span class="sourceLineNo">092</span> */<a name="line.92"></a> <span class="sourceLineNo">093</span> @Override<a name="line.93"></a> <span class="sourceLineNo">094</span> public double[][] calculateFOV(double[][] resistanceMap, int startX, int startY, double radius, Radius radiusTechnique) {<a name="line.94"></a> <span class="sourceLineNo">095</span> double rad = Math.max(1, radius);<a name="line.95"></a> <span class="sourceLineNo">096</span> double decay = 1.0 / rad;<a name="line.96"></a> <span class="sourceLineNo">097</span><a name="line.97"></a> <span class="sourceLineNo">098</span> int width = resistanceMap.length;<a name="line.98"></a> <span class="sourceLineNo">099</span> int height = resistanceMap[0].length;<a name="line.99"></a> <span class="sourceLineNo">100</span><a name="line.100"></a> <span class="sourceLineNo">101</span> if (light == null)<a name="line.101"></a> <span class="sourceLineNo">102</span> light = new double[width][height];<a name="line.102"></a> <span class="sourceLineNo">103</span> else {<a name="line.103"></a> <span class="sourceLineNo">104</span> if (light.length != width || light[0].length != height)<a name="line.104"></a> <span class="sourceLineNo">105</span> light = new double[width][height];<a name="line.105"></a> <span class="sourceLineNo">106</span> else {<a name="line.106"></a> <span class="sourceLineNo">107</span> ArrayTools.fill(light, 0.0);<a name="line.107"></a> <span class="sourceLineNo">108</span> }<a name="line.108"></a> <span class="sourceLineNo">109</span> }<a name="line.109"></a> <span class="sourceLineNo">110</span> light[startX][startY] = 1;//make the starting space full power<a name="line.110"></a> <span class="sourceLineNo">111</span> maybeCache(resistanceMap);<a name="line.111"></a> <span class="sourceLineNo">112</span> for (Direction d : Direction.DIAGONALS) {<a name="line.112"></a> <span class="sourceLineNo">113</span> shadowCast(1, 1.0, 0.0, 0, d.deltaX, d.deltaY, 0, rad, startX, startY, decay, radiusTechnique);<a name="line.113"></a> <span class="sourceLineNo">114</span> shadowCast(1, 1.0, 0.0, d.deltaX, 0, 0, d.deltaY, rad, startX, startY, decay, radiusTechnique);<a name="line.114"></a> <span class="sourceLineNo">115</span> }<a name="line.115"></a> <span class="sourceLineNo">116</span> return light;<a name="line.116"></a> <span class="sourceLineNo">117</span> }<a name="line.117"></a> <span class="sourceLineNo">118</span><a name="line.118"></a> <span class="sourceLineNo">119</span> /**<a name="line.119"></a> <span class="sourceLineNo">120</span> * Calculates the Field Of View for the provided map from the given x, y<a name="line.120"></a> <span class="sourceLineNo">121</span> * coordinates. Returns a light map where the values represent a percentage<a name="line.121"></a> <span class="sourceLineNo">122</span> * of fully lit.<a name="line.122"></a> <span class="sourceLineNo">123</span> * &lt;p&gt;<a name="line.123"></a> <span class="sourceLineNo">124</span> * The starting point for the calculation is considered to be at the center<a name="line.124"></a> <span class="sourceLineNo">125</span> * of the origin cell. Radius determinations are determined by the provided<a name="line.125"></a> <span class="sourceLineNo">126</span> * RadiusStrategy. A conical section of FOV is lit by this method if<a name="line.126"></a> <span class="sourceLineNo">127</span> * span is greater than 0.<a name="line.127"></a> <span class="sourceLineNo">128</span> *<a name="line.128"></a> <span class="sourceLineNo">129</span> * @param resistanceMap the grid of cells to calculate on; the kind made by DungeonUtility.generateResistances()<a name="line.129"></a> <span class="sourceLineNo">130</span> * @param startX the horizontal component of the starting location<a name="line.130"></a> <span class="sourceLineNo">131</span> * @param startY the vertical component of the starting location<a name="line.131"></a> <span class="sourceLineNo">132</span> * @param radius the distance the light will extend to<a name="line.132"></a> <span class="sourceLineNo">133</span> * @param radiusTechnique provides a means to calculate the radius as desired<a name="line.133"></a> <span class="sourceLineNo">134</span> * @param angle the angle in degrees that will be the center of the FOV cone, 0 points right<a name="line.134"></a> <span class="sourceLineNo">135</span> * @param span the angle in degrees that measures the full arc contained in the FOV cone<a name="line.135"></a> <span class="sourceLineNo">136</span> * @return the computed light grid<a name="line.136"></a> <span class="sourceLineNo">137</span> */<a name="line.137"></a> <span class="sourceLineNo">138</span> @Override<a name="line.138"></a> <span class="sourceLineNo">139</span> public double[][] calculateFOV(double[][] resistanceMap, int startX, int startY, double radius, Radius radiusTechnique, double angle, double span) {<a name="line.139"></a> <span class="sourceLineNo">140</span> double rad = Math.max(1, radius);<a name="line.140"></a> <span class="sourceLineNo">141</span><a name="line.141"></a> <span class="sourceLineNo">142</span> double decay = 1.0 / rad;<a name="line.142"></a> <span class="sourceLineNo">143</span><a name="line.143"></a> <span class="sourceLineNo">144</span> double angle2 = Math.toRadians((angle &gt; 360.0 || angle &lt; 0.0)<a name="line.144"></a> <span class="sourceLineNo">145</span> ? GwtCompatibility.IEEEremainder(angle + 720.0, 360.0) : angle);<a name="line.145"></a> <span class="sourceLineNo">146</span> double span2 = Math.toRadians(span);<a name="line.146"></a> <span class="sourceLineNo">147</span> int width = resistanceMap.length;<a name="line.147"></a> <span class="sourceLineNo">148</span> int height = resistanceMap[0].length;<a name="line.148"></a> <span class="sourceLineNo">149</span><a name="line.149"></a> <span class="sourceLineNo">150</span> if (light == null)<a name="line.150"></a> <span class="sourceLineNo">151</span> light = new double[width][height];<a name="line.151"></a> <span class="sourceLineNo">152</span> else {<a name="line.152"></a> <span class="sourceLineNo">153</span> if (light.length != width || light[0].length != height)<a name="line.153"></a> <span class="sourceLineNo">154</span> light = new double[width][height];<a name="line.154"></a> <span class="sourceLineNo">155</span> else {<a name="line.155"></a> <span class="sourceLineNo">156</span> ArrayTools.fill(light, 0.0);<a name="line.156"></a> <span class="sourceLineNo">157</span> }<a name="line.157"></a> <span class="sourceLineNo">158</span> }<a name="line.158"></a> <span class="sourceLineNo">159</span> light[startX][startY] = 1;//make the starting space full power<a name="line.159"></a> <span class="sourceLineNo">160</span> maybeCache(resistanceMap);<a name="line.160"></a> <span class="sourceLineNo">161</span><a name="line.161"></a> <span class="sourceLineNo">162</span> int ctr = 0;<a name="line.162"></a> <span class="sourceLineNo">163</span> boolean started = false;<a name="line.163"></a> <span class="sourceLineNo">164</span> for (Direction d : ccw) {<a name="line.164"></a> <span class="sourceLineNo">165</span> ctr %= 4;<a name="line.165"></a> <span class="sourceLineNo">166</span> ++ctr;<a name="line.166"></a> <span class="sourceLineNo">167</span> if (angle &lt;= Math.PI / 2.0 * ctr + span / 2.0)<a name="line.167"></a> <span class="sourceLineNo">168</span> started = true;<a name="line.168"></a> <span class="sourceLineNo">169</span> if (started) {<a name="line.169"></a> <span class="sourceLineNo">170</span> if (ctr &lt; 4 &amp;&amp; angle &lt; Math.PI / 2.0 * (ctr - 1) - span / 2.0)<a name="line.170"></a> <span class="sourceLineNo">171</span> break;<a name="line.171"></a> <span class="sourceLineNo">172</span> light = shadowCastLimited(1, 1.0, 0.0, 0, d.deltaX, d.deltaY, 0, rad, startX, startY, decay, radiusTechnique, angle2, span2);<a name="line.172"></a> <span class="sourceLineNo">173</span> light = shadowCastLimited(1, 1.0, 0.0, d.deltaX, 0, 0, d.deltaY, rad, startX, startY, decay, radiusTechnique, angle2, span2);<a name="line.173"></a> <span class="sourceLineNo">174</span> }<a name="line.174"></a> <span class="sourceLineNo">175</span> }<a name="line.175"></a> <span class="sourceLineNo">176</span> return light;<a name="line.176"></a> <span class="sourceLineNo">177</span> }<a name="line.177"></a> <span class="sourceLineNo">178</span><a name="line.178"></a> <span class="sourceLineNo">179</span> /**<a name="line.179"></a> <span class="sourceLineNo">180</span> * Calculates what cells are visible from (startX,startY) using the given resistanceMap; this can be given to<a name="line.180"></a> <span class="sourceLineNo">181</span> * mixVisibleFOVs() to limit extra light sources to those visible from the starting point.<a name="line.181"></a> <span class="sourceLineNo">182</span> * @param resistanceMap the grid of cells to calculate on; the kind made by DungeonUtility.generateResistances()<a name="line.182"></a> <span class="sourceLineNo">183</span> * @param startX the center of the LOS map; typically the player's x-position<a name="line.183"></a> <span class="sourceLineNo">184</span> * @param startY the center of the LOS map; typically the player's y-position<a name="line.184"></a> <span class="sourceLineNo">185</span> * @return an LOS map with the given starting point<a name="line.185"></a> <span class="sourceLineNo">186</span> */<a name="line.186"></a> <span class="sourceLineNo">187</span> public double[][] calculateLOSMap(double[][] resistanceMap, int startX, int startY)<a name="line.187"></a> <span class="sourceLineNo">188</span> {<a name="line.188"></a> <span class="sourceLineNo">189</span> if(resistanceMap == null || resistanceMap.length == 0)<a name="line.189"></a> <span class="sourceLineNo">190</span> return new double[0][0];<a name="line.190"></a> <span class="sourceLineNo">191</span> return calculateFOV(resistanceMap, startX, startY, resistanceMap.length + resistanceMap[0].length, Radius.SQUARE);<a name="line.191"></a> <span class="sourceLineNo">192</span> }<a name="line.192"></a> <span class="sourceLineNo">193</span><a name="line.193"></a> <span class="sourceLineNo">194</span> private void maybeCache(final double[][] resistanceMap)<a name="line.194"></a> <span class="sourceLineNo">195</span> {<a name="line.195"></a> <span class="sourceLineNo">196</span> if(resMapCache != resistanceMap)<a name="line.196"></a> <span class="sourceLineNo">197</span> {<a name="line.197"></a> <span class="sourceLineNo">198</span> storeMap(resistanceMap);<a name="line.198"></a> <span class="sourceLineNo">199</span> }<a name="line.199"></a> <span class="sourceLineNo">200</span> }<a name="line.200"></a> <span class="sourceLineNo">201</span><a name="line.201"></a> <span class="sourceLineNo">202</span> /**<a name="line.202"></a> <span class="sourceLineNo">203</span> * Pre-calculates some time-intensive calculations that generally only need to be done once per map. You should pass<a name="line.203"></a> <span class="sourceLineNo">204</span> * the same exact value for resistanceMap to {@link #calculateFOV(double[][], int, int)} or its overloads if you<a name="line.204"></a> <span class="sourceLineNo">205</span> * want to avoid re-calculating this map analysis. If an element of resistanceMap changes, you should call this<a name="line.205"></a> <span class="sourceLineNo">206</span> * method again before you call calculateFOV, though it can wait until you've made all the changes you want to<a name="line.206"></a> <span class="sourceLineNo">207</span> * resistanceMap's elements. This class does not have a way to tell when the array has been modified in user code,<a name="line.207"></a> <span class="sourceLineNo">208</span> * so you should take care if you change resistanceMap to call this method.<a name="line.208"></a> <span class="sourceLineNo">209</span> * @param resistanceMap a 2D double array, as produced by {@link squidpony.squidgrid.mapping.DungeonUtility#generateResistances(char[][])}<a name="line.209"></a> <span class="sourceLineNo">210</span> */<a name="line.210"></a> <span class="sourceLineNo">211</span> public void storeMap(final double[][] resistanceMap)<a name="line.211"></a> <span class="sourceLineNo">212</span> {<a name="line.212"></a> <span class="sourceLineNo">213</span> if(resistanceMap == null || resistanceMap.length &lt;= 0 || resistanceMap[0].length &lt;= 0)<a name="line.213"></a> <span class="sourceLineNo">214</span> throw new IllegalArgumentException("resistanceMap cannot be null or empty");<a name="line.214"></a> <span class="sourceLineNo">215</span> if(resMapCache == null<a name="line.215"></a> <span class="sourceLineNo">216</span> || resMapCache.length != resistanceMap.length<a name="line.216"></a> <span class="sourceLineNo">217</span> || resMapCache[0].length != resistanceMap[0].length)<a name="line.217"></a> <span class="sourceLineNo">218</span> {<a name="line.218"></a> <span class="sourceLineNo">219</span> resMapCache = resistanceMap;<a name="line.219"></a> <span class="sourceLineNo">220</span> if(map == null)<a name="line.220"></a> <span class="sourceLineNo">221</span> map = new GreasedRegion(resistanceMap, 1.0, Double.POSITIVE_INFINITY, 3).removeCorners();<a name="line.221"></a> <span class="sourceLineNo">222</span> else<a name="line.222"></a> <span class="sourceLineNo">223</span> map.refill(resistanceMap, 1.0, Double.POSITIVE_INFINITY, 3).removeCorners();<a name="line.223"></a> <span class="sourceLineNo">224</span> }<a name="line.224"></a> <span class="sourceLineNo">225</span> else<a name="line.225"></a> <span class="sourceLineNo">226</span> {<a name="line.226"></a> <span class="sourceLineNo">227</span> for (int x = 0; x &lt; resistanceMap.length; x++) {<a name="line.227"></a> <span class="sourceLineNo">228</span> for (int y = 0; y &lt; resistanceMap[x].length; y++) {<a name="line.228"></a> <span class="sourceLineNo">229</span> if(resMapCache[x][y] != resistanceMap[x][y])<a name="line.229"></a> <span class="sourceLineNo">230</span> {<a name="line.230"></a> <span class="sourceLineNo">231</span> resMapCache = resistanceMap;<a name="line.231"></a> <span class="sourceLineNo">232</span> if(map == null)<a name="line.232"></a> <span class="sourceLineNo">233</span> map = new GreasedRegion(resistanceMap, 1.0, Double.POSITIVE_INFINITY, 3).removeCorners();<a name="line.233"></a> <span class="sourceLineNo">234</span> else<a name="line.234"></a> <span class="sourceLineNo">235</span> map.refill(resistanceMap, 1.0, Double.POSITIVE_INFINITY, 3).removeCorners();<a name="line.235"></a> <span class="sourceLineNo">236</span> return;<a name="line.236"></a> <span class="sourceLineNo">237</span> }<a name="line.237"></a> <span class="sourceLineNo">238</span> }<a name="line.238"></a> <span class="sourceLineNo">239</span> }<a name="line.239"></a> <span class="sourceLineNo">240</span> }<a name="line.240"></a> <span class="sourceLineNo">241</span> }<a name="line.241"></a> <span class="sourceLineNo">242</span><a name="line.242"></a> <span class="sourceLineNo">243</span> private double[][] shadowCast(int row, double start, double end, int xx, int xy, int yx, int yy,<a name="line.243"></a> <span class="sourceLineNo">244</span> double radius, int startx, int starty, double decay, Radius radiusStrategy) {<a name="line.244"></a> <span class="sourceLineNo">245</span> double newStart = 0;<a name="line.245"></a> <span class="sourceLineNo">246</span> if (start &lt; end) {<a name="line.246"></a> <span class="sourceLineNo">247</span> return light;<a name="line.247"></a> <span class="sourceLineNo">248</span> }<a name="line.248"></a> <span class="sourceLineNo">249</span> int width = light.length;<a name="line.249"></a> <span class="sourceLineNo">250</span> int height = light[0].length;<a name="line.250"></a> <span class="sourceLineNo">251</span><a name="line.251"></a> <span class="sourceLineNo">252</span> boolean blocked = false;<a name="line.252"></a> <span class="sourceLineNo">253</span> for (int distance = row; distance &lt;= radius &amp;&amp; distance &lt; (width + height) &amp;&amp; !blocked; distance++) {<a name="line.253"></a> <span class="sourceLineNo">254</span> int deltaY = -distance;<a name="line.254"></a> <span class="sourceLineNo">255</span> for (int deltaX = -distance; deltaX &lt;= 0; deltaX++) {<a name="line.255"></a> <span class="sourceLineNo">256</span> int currentX = startx + deltaX * xx + deltaY * xy;<a name="line.256"></a> <span class="sourceLineNo">257</span> int currentY = starty + deltaX * yx + deltaY * yy;<a name="line.257"></a> <span class="sourceLineNo">258</span> double leftSlope = (deltaX - 0.5f) / (deltaY + 0.5f);<a name="line.258"></a> <span class="sourceLineNo">259</span> double rightSlope = (deltaX + 0.5f) / (deltaY - 0.5f);<a name="line.259"></a> <span class="sourceLineNo">260</span><a name="line.260"></a> <span class="sourceLineNo">261</span> if (!(currentX &gt;= 0 &amp;&amp; currentY &gt;= 0 &amp;&amp; currentX &lt; width &amp;&amp; currentY &lt; height) || start &lt; rightSlope) {<a name="line.261"></a> <span class="sourceLineNo">262</span> continue;<a name="line.262"></a> <span class="sourceLineNo">263</span> } else if (end &gt; leftSlope) {<a name="line.263"></a> <span class="sourceLineNo">264</span> break;<a name="line.264"></a> <span class="sourceLineNo">265</span> }<a name="line.265"></a> <span class="sourceLineNo">266</span> double deltaRadius = radiusStrategy.radius(deltaX, deltaY);<a name="line.266"></a> <span class="sourceLineNo">267</span> //check if it's within the lightable area and light if needed<a name="line.267"></a> <span class="sourceLineNo">268</span> if (deltaRadius &lt;= radius) {<a name="line.268"></a> <span class="sourceLineNo">269</span> light[currentX][currentY] = 1 - decay * deltaRadius;<a name="line.269"></a> <span class="sourceLineNo">270</span> }<a name="line.270"></a> <span class="sourceLineNo">271</span><a name="line.271"></a> <span class="sourceLineNo">272</span> if (blocked) { //previous cell was a blocking one<a name="line.272"></a> <span class="sourceLineNo">273</span> if (map.contains(currentX * 3 + 1 + xx + xy, currentY * 3 + 1 + yx + yy)) { // hit a wall<a name="line.273"></a> <span class="sourceLineNo">274</span> newStart = rightSlope;<a name="line.274"></a> <span class="sourceLineNo">275</span> } else if(!map.contains(currentX * 3 + 1, currentY * 3 + 1)){<a name="line.275"></a> <span class="sourceLineNo">276</span> blocked = false;<a name="line.276"></a> <span class="sourceLineNo">277</span> start = newStart;<a name="line.277"></a> <span class="sourceLineNo">278</span> }<a name="line.278"></a> <span class="sourceLineNo">279</span> } else {<a name="line.279"></a> <span class="sourceLineNo">280</span> if (distance &lt; radius &amp;&amp; map.contains(currentX * 3 + 1, currentY * 3 + 1))<a name="line.280"></a> <span class="sourceLineNo">281</span> { // hit a wall within sight line<a name="line.281"></a> <span class="sourceLineNo">282</span> blocked = true;<a name="line.282"></a> <span class="sourceLineNo">283</span> light = shadowCast(distance + 1, start, leftSlope, xx, xy, yx, yy, radius, startx, starty, decay, radiusStrategy);<a name="line.283"></a> <span class="sourceLineNo">284</span> newStart = rightSlope;<a name="line.284"></a> <span class="sourceLineNo">285</span> }<a name="line.285"></a> <span class="sourceLineNo">286</span> }<a name="line.286"></a> <span class="sourceLineNo">287</span> }<a name="line.287"></a> <span class="sourceLineNo">288</span> }<a name="line.288"></a> <span class="sourceLineNo">289</span> return light;<a name="line.289"></a> <span class="sourceLineNo">290</span> }<a name="line.290"></a> <span class="sourceLineNo">291</span> private double[][] shadowCastLimited(int row, double start, double end, int xx, int xy, int yx, int yy,<a name="line.291"></a> <span class="sourceLineNo">292</span> double radius, int startx, int starty, double decay,<a name="line.292"></a> <span class="sourceLineNo">293</span> Radius radiusStrategy, double angle, double span) {<a name="line.293"></a> <span class="sourceLineNo">294</span> double newStart = 0;<a name="line.294"></a> <span class="sourceLineNo">295</span> if (start &lt; end) {<a name="line.295"></a> <span class="sourceLineNo">296</span> return light;<a name="line.296"></a> <span class="sourceLineNo">297</span> }<a name="line.297"></a> <span class="sourceLineNo">298</span> int width = light.length;<a name="line.298"></a> <span class="sourceLineNo">299</span> int height = light[0].length;<a name="line.299"></a> <span class="sourceLineNo">300</span><a name="line.300"></a> <span class="sourceLineNo">301</span> boolean blocked = false;<a name="line.301"></a> <span class="sourceLineNo">302</span> for (int distance = row; distance &lt;= radius &amp;&amp; distance &lt; (width + height) &amp;&amp; !blocked; distance++) {<a name="line.302"></a> <span class="sourceLineNo">303</span> int deltaY = -distance;<a name="line.303"></a> <span class="sourceLineNo">304</span> for (int deltaX = -distance; deltaX &lt;= 0; deltaX++) {<a name="line.304"></a> <span class="sourceLineNo">305</span> int currentX = startx + deltaX * xx + deltaY * xy;<a name="line.305"></a> <span class="sourceLineNo">306</span> int currentY = starty + deltaX * yx + deltaY * yy;<a name="line.306"></a> <span class="sourceLineNo">307</span> double leftSlope = (deltaX - 0.5f) / (deltaY + 0.5f);<a name="line.307"></a> <span class="sourceLineNo">308</span> double rightSlope = (deltaX + 0.5f) / (deltaY - 0.5f);<a name="line.308"></a> <span class="sourceLineNo">309</span><a name="line.309"></a> <span class="sourceLineNo">310</span> if (!(currentX &gt;= 0 &amp;&amp; currentY &gt;= 0 &amp;&amp; currentX &lt; width &amp;&amp; currentY &lt; height) || start &lt; rightSlope) {<a name="line.310"></a> <span class="sourceLineNo">311</span> continue;<a name="line.311"></a> <span class="sourceLineNo">312</span> } else if (end &gt; leftSlope) {<a name="line.312"></a> <span class="sourceLineNo">313</span> break;<a name="line.313"></a> <span class="sourceLineNo">314</span> }<a name="line.314"></a> <span class="sourceLineNo">315</span> double newAngle = Math.atan2(currentY - starty, currentX - startx) + Math.PI * 2;<a name="line.315"></a> <span class="sourceLineNo">316</span> if (Math.abs(GwtCompatibility.IEEEremainder(angle - newAngle + Math.PI * 8, Math.PI * 2)) &gt; span / 2.0)<a name="line.316"></a> <span class="sourceLineNo">317</span> continue;<a name="line.317"></a> <span class="sourceLineNo">318</span><a name="line.318"></a> <span class="sourceLineNo">319</span> double deltaRadius = radiusStrategy.radius(deltaX, deltaY);<a name="line.319"></a> <span class="sourceLineNo">320</span> //check if it's within the lightable area and light if needed<a name="line.320"></a> <span class="sourceLineNo">321</span> if (deltaRadius &lt;= radius) {<a name="line.321"></a> <span class="sourceLineNo">322</span> light[currentX][currentY] = 1 - decay * deltaRadius;<a name="line.322"></a> <span class="sourceLineNo">323</span> }<a name="line.323"></a> <span class="sourceLineNo">324</span><a name="line.324"></a> <span class="sourceLineNo">325</span> if (blocked) { //previous cell was a blocking one<a name="line.325"></a> <span class="sourceLineNo">326</span> if (map.contains(currentX * 3 + 1 + xx + xy, currentY * 3 + 1 + yx + yy)) {//hit a wall<a name="line.326"></a> <span class="sourceLineNo">327</span> newStart = rightSlope;<a name="line.327"></a> <span class="sourceLineNo">328</span> } else {<a name="line.328"></a> <span class="sourceLineNo">329</span> blocked = false;<a name="line.329"></a> <span class="sourceLineNo">330</span> start = newStart;<a name="line.330"></a> <span class="sourceLineNo">331</span> }<a name="line.331"></a> <span class="sourceLineNo">332</span> } else {<a name="line.332"></a> <span class="sourceLineNo">333</span> if (map.contains(currentX * 3 + 1 + xx + xy, currentY * 3 + 1 + yx + yy) &amp;&amp; distance &lt; radius) {//hit a wall within sight line<a name="line.333"></a> <span class="sourceLineNo">334</span> blocked = true;<a name="line.334"></a> <span class="sourceLineNo">335</span> light = shadowCastLimited(distance + 1, start, leftSlope, xx, xy, yx, yy, radius, startx, starty, decay, radiusStrategy, angle, span);<a name="line.335"></a> <span class="sourceLineNo">336</span> newStart = rightSlope;<a name="line.336"></a> <span class="sourceLineNo">337</span> }<a name="line.337"></a> <span class="sourceLineNo">338</span> }<a name="line.338"></a> <span class="sourceLineNo">339</span> }<a name="line.339"></a> <span class="sourceLineNo">340</span> }<a name="line.340"></a> <span class="sourceLineNo">341</span> return light;<a name="line.341"></a> <span class="sourceLineNo">342</span> }<a name="line.342"></a> <span class="sourceLineNo">343</span><a name="line.343"></a> <span class="sourceLineNo">344</span>}<a name="line.344"></a> </pre> </div> </body> </html>
{ "content_hash": "de9596591947913a5e4e3a7ce0ff6251", "timestamp": "", "source": "github", "line_count": 416, "max_line_length": 218, "avg_line_length": 89.0889423076923, "alnum_prop": 0.6360055044386282, "repo_name": "BenMcLean/SquidLib", "id": "caad1c342ef195a58f19a938133bb2a2ef51ef45", "size": "37061", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/squidlib-util/src-html/squidpony/squidgrid/BevelFOV.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GLSL", "bytes": "621" }, { "name": "Java", "bytes": "8736432" }, { "name": "JavaScript", "bytes": "1719127" } ], "symlink_target": "" }
package com.leetcode.test; /* * Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. * An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: 11110 11010 11000 00000 Answer: 1 Example 2: 11000 11000 00100 00011 Answer: 3 */ public class NumberofIslands { public int numIslands(char[][] grid) { if(grid==null||grid.length==0) return 0; boolean[][] visited=new boolean[grid.length][grid[0].length]; int count=0; for(int i=0;i<grid.length;i++){ for(int j=0;j<grid[0].length;j++){ if(grid[i][j]=='0'||visited[i][j]) continue; count++; dfs(grid, visited, i, j); } } return count; } private void dfs(char[][] grid,boolean[][] visited,int i,int j){ if(i<0||j<0||i>=grid.length||j>=grid[0].length) return; if(grid[i][j]=='0'||visited[i][j]) return; visited[i][j]=true; dfs(grid, visited, i-1, j); dfs(grid, visited, i+1, j); dfs(grid, visited, i, j-1); dfs(grid, visited, i, j+1); } public static void main(String[] args) { char[][] chars={"11000".toCharArray(),"11000".toCharArray(),"00100".toCharArray(),"00011".toCharArray()}; NumberofIslands islands=new NumberofIslands(); System.out.println(islands.numIslands(chars)); } }
{ "content_hash": "6ec7b50ae683eb969e55653c74d60e82", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 177, "avg_line_length": 24.517857142857142, "alnum_prop": 0.6482155863073562, "repo_name": "pengood/CodeInterview", "id": "8cdf4ecab6ca523fd05be09b8eaab1be332234b9", "size": "1373", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/leetcode/test/NumberofIslands.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "322191" } ], "symlink_target": "" }
<?php namespace Symfony\Bundle\FrameworkBundle\Templating\Asset; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Templating\Asset\PathPackage as BasePathPackage; @trigger_error('The Symfony\Bundle\FrameworkBundle\Templating\Asset\PathPackage is deprecated since version 2.7 and will be removed in 3.0. Use the Asset component instead.', E_USER_DEPRECATED); /** * The path packages adds a version and a base path to asset URLs. * * @author Kris Wallsmith <[email protected]> * * @deprecated since 2.7, will be removed in 3.0. Use the Asset component instead. */ class PathPackage extends BasePathPackage { /** * Constructor. * * @param Request $request The current request * @param string $version The version * @param string $format The version format */ public function __construct(Request $request, $version = null, $format = null) { parent::__construct($request->getBasePath(), $version, $format); } }
{ "content_hash": "25a313badccdb039e152c1c68efbe128", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 194, "avg_line_length": 32.03125, "alnum_prop": 0.6907317073170731, "repo_name": "pellu/roadtothesuccess", "id": "92151bfecfa00bfeccafc20bfdbb3e8fafa9c930", "size": "1261", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Templating/Asset/PathPackage.php", "mode": "33261", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3838" }, { "name": "Batchfile", "bytes": "397" }, { "name": "CSS", "bytes": "234899" }, { "name": "HTML", "bytes": "124940" }, { "name": "JavaScript", "bytes": "104448" }, { "name": "PHP", "bytes": "103849" }, { "name": "Shell", "bytes": "2537" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>reduction-effects: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.5.0 / reduction-effects - 0.1.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> reduction-effects <small> 0.1.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-11-24 02:35:00 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-24 02:35:00 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.5.0 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.03.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.03.0 Official 4.03.0 release ocaml-config 1 OCaml Switch Configuration # opam file: opam-version: &quot;2.0&quot; name: &quot;coq-reduction-effects&quot; version: &quot;0.1.0&quot; synopsis: &quot;A Coq plugin to add reduction side effects to some Coq reduction strategies&quot; maintainer: &quot;Yishuai Li &lt;[email protected]&gt;&quot; authors: &quot;Hugo Herbelin &lt;[email protected]&gt;&quot; license: &quot;LGPL-2.1&quot; homepage: &quot;https://github.com/coq-community/reduction-effects&quot; bug-reports: &quot;https://github.com/coq-community/reduction-effects/issues&quot; depends: [ &quot;coq&quot; { &gt;= &quot;8.7&quot; &lt; &quot;8.9~&quot; } ] build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;-j%{jobs}%&quot; &quot;install&quot;] run-test:[make &quot;-j%{jobs}%&quot; &quot;test&quot;] remove: [make &quot;-j%{jobs}%&quot; &quot;uninstall&quot;] dev-repo: &quot;git+https://github.com/coq-community/reduction-effects&quot; url { src: &quot;https://github.com/coq-community/reduction-effects/archive/v0.1.0.tar.gz&quot; checksum: &quot;md5=20becd7b8910a4f7fefd7dfc24fbc33f&quot; } flags: light-uninstall tags: [ &quot;logpath:ReductionEffect&quot; ] </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-reduction-effects.0.1.0 coq.8.5.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.5.0). The following dependencies couldn&#39;t be met: - coq-reduction-effects -&gt; coq &gt;= 8.7 -&gt; ocaml &gt;= 4.05.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-reduction-effects.0.1.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "a7d9fab96475f16477ff90775147198d", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 159, "avg_line_length": 41.544910179640716, "alnum_prop": 0.5416546555203229, "repo_name": "coq-bench/coq-bench.github.io", "id": "075d255c04acbf6ee33d4acb3e65a290369396e5", "size": "6963", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.03.0-2.0.5/released/8.5.0/reduction-effects/0.1.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
title: avn22 type: products image: /img/Screen Shot 2017-05-09 at 11.56.54 AM.png heading: n22 description: lksadjf lkasdjf lksajdf lksdaj flksadj flksa fdj main: heading: Foo Bar BAz description: |- ***This is i a thing***kjh hjk kj # Blah Blah ## Blah![undefined](undefined) ### Baah image1: alt: kkkk ---
{ "content_hash": "6ca23ce9556cc8e600a1fe12bd045c88", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 61, "avg_line_length": 22.333333333333332, "alnum_prop": 0.6656716417910448, "repo_name": "pblack/kaldi-hugo-cms-template", "id": "90c622cafb17be7347bf4447775090818cf8aaf4", "size": "339", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "site/content/pages2/avn22.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "94394" }, { "name": "HTML", "bytes": "18889" }, { "name": "JavaScript", "bytes": "10014" } ], "symlink_target": "" }
/* $NetBSD: evthread_pthread.c,v 1.1.1.1 2013/04/11 16:43:25 christos Exp $ */ /* * Copyright 2009-2012 Niels Provos and Nick Mathewson * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "event2/event-config.h" #include <sys/cdefs.h> __RCSID("$NetBSD: evthread_pthread.c,v 1.1.1.1 2013/04/11 16:43:25 christos Exp $"); /* With glibc we need to define this to get PTHREAD_MUTEX_RECURSIVE. */ #define _GNU_SOURCE #include <pthread.h> struct event_base; #include "event2/thread.h" #include <stdlib.h> #include <string.h> #include "mm-internal.h" #include "evthread-internal.h" static pthread_mutexattr_t attr_recursive; static void * evthread_posix_lock_alloc(unsigned locktype) { pthread_mutexattr_t *attr = NULL; pthread_mutex_t *lock = mm_malloc(sizeof(pthread_mutex_t)); if (!lock) return NULL; if (locktype & EVTHREAD_LOCKTYPE_RECURSIVE) attr = &attr_recursive; if (pthread_mutex_init(lock, attr)) { mm_free(lock); return NULL; } return lock; } static void evthread_posix_lock_free(void *_lock, unsigned locktype) { pthread_mutex_t *lock = _lock; pthread_mutex_destroy(lock); mm_free(lock); } static int evthread_posix_lock(unsigned mode, void *_lock) { pthread_mutex_t *lock = _lock; if (mode & EVTHREAD_TRY) return pthread_mutex_trylock(lock); else return pthread_mutex_lock(lock); } static int evthread_posix_unlock(unsigned mode, void *_lock) { pthread_mutex_t *lock = _lock; return pthread_mutex_unlock(lock); } static unsigned long evthread_posix_get_id(void) { union { pthread_t thr; #if _EVENT_SIZEOF_PTHREAD_T > _EVENT_SIZEOF_LONG ev_uint64_t id; #else unsigned long id; #endif } r; #if _EVENT_SIZEOF_PTHREAD_T < _EVENT_SIZEOF_LONG memset(&r, 0, sizeof(r)); #endif r.thr = pthread_self(); return (unsigned long)r.id; } static void * evthread_posix_cond_alloc(unsigned condflags) { pthread_cond_t *cond = mm_malloc(sizeof(pthread_cond_t)); if (!cond) return NULL; if (pthread_cond_init(cond, NULL)) { mm_free(cond); return NULL; } return cond; } static void evthread_posix_cond_free(void *_cond) { pthread_cond_t *cond = _cond; pthread_cond_destroy(cond); mm_free(cond); } static int evthread_posix_cond_signal(void *_cond, int broadcast) { pthread_cond_t *cond = _cond; int r; if (broadcast) r = pthread_cond_broadcast(cond); else r = pthread_cond_signal(cond); return r ? -1 : 0; } static int evthread_posix_cond_wait(void *_cond, void *_lock, const struct timeval *tv) { int r; pthread_cond_t *cond = _cond; pthread_mutex_t *lock = _lock; if (tv) { struct timeval now, abstime; struct timespec ts; evutil_gettimeofday(&now, NULL); evutil_timeradd(&now, tv, &abstime); ts.tv_sec = abstime.tv_sec; ts.tv_nsec = abstime.tv_usec*1000; r = pthread_cond_timedwait(cond, lock, &ts); if (r == ETIMEDOUT) return 1; else if (r) return -1; else return 0; } else { r = pthread_cond_wait(cond, lock); return r ? -1 : 0; } } int evthread_use_pthreads(void) { struct evthread_lock_callbacks cbs = { EVTHREAD_LOCK_API_VERSION, EVTHREAD_LOCKTYPE_RECURSIVE, evthread_posix_lock_alloc, evthread_posix_lock_free, evthread_posix_lock, evthread_posix_unlock }; struct evthread_condition_callbacks cond_cbs = { EVTHREAD_CONDITION_API_VERSION, evthread_posix_cond_alloc, evthread_posix_cond_free, evthread_posix_cond_signal, evthread_posix_cond_wait }; /* Set ourselves up to get recursive locks. */ if (pthread_mutexattr_init(&attr_recursive)) return -1; if (pthread_mutexattr_settype(&attr_recursive, PTHREAD_MUTEX_RECURSIVE)) return -1; evthread_set_lock_callbacks(&cbs); evthread_set_condition_callbacks(&cond_cbs); evthread_set_id_callback(evthread_posix_get_id); return 0; }
{ "content_hash": "f6069e1d9458365fb1bd0a1dc9e5ec85", "timestamp": "", "source": "github", "line_count": 192, "max_line_length": 84, "avg_line_length": 26.5, "alnum_prop": 0.7181603773584906, "repo_name": "execunix/vinos", "id": "cf399a09d48c6461b830de288715420c927b8b10", "size": "5088", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "external/bsd/libevent/dist/evthread_pthread.c", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace Tests { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> sealed partial class App : Application { /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += OnSuspending; } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } Microsoft.VisualStudio.TestPlatform.TestExecutor.UnitTestClient.CreateDefaultUI(); // Ensure the current window is active Window.Current.Activate(); Microsoft.VisualStudio.TestPlatform.TestExecutor.UnitTestClient.Run(e.Arguments); } /// <summary> /// Invoked when Navigation to a certain page fails /// </summary> /// <param name="sender">The Frame which failed navigation</param> /// <param name="e">Details about the navigation failure</param> void OnNavigationFailed(object sender, NavigationFailedEventArgs e) { throw new Exception("Failed to load Page " + e.SourcePageType.FullName); } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); //TODO: Save application state and stop any background activity deferral.Complete(); } } }
{ "content_hash": "34461ea0f633331c0c270a2c14e9bdda", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 99, "avg_line_length": 37.55882352941177, "alnum_prop": 0.6332550247977029, "repo_name": "jmservera/IoTHubDemo", "id": "fe663f4a059f24692d6573bd2532f79d58c97604", "size": "3833", "binary": false, "copies": "3", "ref": "refs/heads/vs2015update1", "path": "IoTSensors/Tests/UnitTestApp.xaml.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "56467" }, { "name": "C++", "bytes": "6475" } ], "symlink_target": "" }
package me.fumiz.android.test.http; /** * Handler used Server caught HTTP requests. * User: fumiz * Date: 11/09/26 * Time: 21:11 */ public interface TestRequestHandler { /** * called on request. * @param request request object * @return response object */ public TestResponse onRequest(TestRequest request); }
{ "content_hash": "79d7c84fe7bdfec8023942ea19abb96e", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 55, "avg_line_length": 21.5, "alnum_prop": 0.6656976744186046, "repo_name": "fumiz/AndroidHttpTester", "id": "a5e8d239c40ad72a2651f009ceaf56e8aa375c68", "size": "344", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "main/src/me/fumiz/android/test/http/TestRequestHandler.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "72311" } ], "symlink_target": "" }
<!DOCTYPE html> <html class="no-js"> <head> <!-- Google Tag Manager --> <script> (function(w, d, s, l, i) { w[l] = w[l] || []; w[l].push({ 'gtm.start': new Date().getTime(), event: 'gtm.js' }); var f = d.getElementsByTagName(s)[0], j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : ''; j.async = true; j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl; f.parentNode.insertBefore(j, f); })(window, document, 'script', 'dataLayer', 'GTM-MVB3ZMX'); </script> <!-- End Google Tag Manager --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Anthony Ng</title> <!-- ============================================== Favicons =====================`========================== --> <link rel="shortcut icon" href="http://i.embed.ly/1/display/resize?key=1e6a1a1efdb011df84894040444cdc60&url=http%3A%2F%2Ftheadvocate.com%2Fcsp%2Fmediapool%2Fsites%2FAdvocate%2Fassets%2Fimg%2Fdesignimages%2FAdvocateAppIcon300.png"> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="css/main.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css"> <script> (function(i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function() { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m) })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga'); ga('create', 'UA-51174308-1', 'auto'); ga('send', 'pageview'); </script> <script> /** * Function that tracks a click on an outbound link in Analytics. * This function takes a valid URL string as an argument, and uses that URL string * as the event label. Setting the transport method to 'beacon' lets the hit be sent * using 'navigator.sendBeacon' in browser that support it. */ var trackOutboundLink = function(url) { ga('send', 'event', 'outbound', 'click', url, { 'transport': 'beacon', 'hitCallback': function() { document.location = url; } }); } </script> </head> <body> <!-- Google Tag Manager (noscript) --> <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-MVB3ZMX" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript> <!-- End Google Tag Manager (noscript) --> <div id="wrapper"> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <!-- <a class="navbar-brand" href="/">Anthony Ng</a> --> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li class="outside_nav"><a href="/" onclick="trackOutboundLink('/'); return false;">Home</a></li> <li class="outside_nav"><a href="/about" onclick="trackOutboundLink('/about'); return false;">About</a></li> <li class="dropdown outside_nav"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Portfolio <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a href="https://github.com/anthony-ng" onclick="trackOutboundLink('https://github.com/anthony-ng'); return false;">GitHub</a></li> <li class="divider"></li> <li><a href="/ourHouse" onclick="trackOutboundLink('/ourHouse'); return false;">Our House</a></li> <li><a href="/interview_garden" onclick="trackOutboundLink('/interview_garden'); return false;">Interview Garden</a></li> <li><a href="/cinephiles" onclick="trackOutboundLink('/cinephiles'); return false;">Cinephiles</a></li> <li><a href="http://anthony-ng.com/DBCraigslist/" onclick="trackOutboundLink('http://anthony-ng.com/DBCraigslist/'); return false;">DBCraigslist</a></li> <li><a href="http://anthony-ng.com/Connect-Four/" onclick="trackOutboundLink('http://anthony-ng.com/Connect-Four/'); return false;">Connect Four</a></li> <li><a href="http://anthony-ng.com/JavaScript_Racer" onclick="trackOutboundLink('http://anthony-ng.com/JavaScript_Racer'); return false;">JavaScript Racer</a></li> <li><a href="http://anthony-ng.com/NEVERNOTE" onclick="trackOutboundLink('http://anthony-ng.com/NEVERNOTE'); return false;">Neverote</a></li> <li><a href="/lilTwitter" onclick="trackOutboundLink('/lilTwitter'); return false;">Little Twitter</a></li> <li><a href="http://anthony-ng.com/Url-Shortener" onclick="trackOutboundLink('http://anthony-ng.com/Url-Shortener'); return false;">Url Shortener</a></li> <li><a href="http://anthony-ng.com/My-Anagram" onclick="trackOutboundLink('http://anthony-ng.com/My-Anagram'); return false;">My Anagram</a></li> <li><a href="/portfolio/angular" onclick="trackOutboundLink('/portfolio/angular'); return false;">My TV Shows Library</a></li> </ul> </li> <!-- <li class="outside_nav"><a href="/asset/AnthonyNg_Resume.pdf" target="_blank" onclick="trackOutboundLink('/asset/AnthonyNg_Resume.pdf'); return false;">Resume</a></li> --> <li class="outside_nav"><a href="/blog" onclick="trackOutboundLink('/blog'); return false;">Blog</a></li> <li class="outside_nav"><a href="http://www.anthonyng.xyz/" onclick="trackOutboundLink('http://www.anthonyng.xyz/'); return false;">Photography</a></li> <li class="outside_nav"><a href="/contact" onclick="trackOutboundLink('/contact'); return false;">Contact <span class="sr-only">(current)</span></a></li> </ul> <ul class="nav navbar-nav navbar-right"> </ul> </div> <!--/.nav-collapse --> </div> </nav> <div class="modules"> <div id="about_me" class="big_module"> <a href="about.html"> <div id="about_me_text"> <h3>San Francisco, CA</h3> <h1>Anthony Ng</h1> <h3>Full Stack Software Engineer</h3> </div> </a> </div> <div class="medium_module"> <div id="portfolio_1" class="small_module"> <a href="/lilTwitter"> <div id="portfolio_1_text"> <h3>Little Twitter</h3> </div> </a> </div> <div id="portfolio_2" class="small_module"> <a href="/cinephiles"> <div id="portfolio_2_text"> <h3>Cinephiles</h3> </div> </a> </div> </div> <div id="portfolio_3" class="medium_module"> <a href="/connectFour"> <div id="portfolio_3_text"> <h3>Connect Four!</h3> </div> </a> </div> <div id="portfolio_4" class="medium_module"> <a href="/interview_garden"> <div id="portfolio_4_text"> <h3>Interview Garden</h3> </div> </a> </div> <div id="portfolio_7" class="extra_small_module"> <a href="/ourHouse"> <div id="portfolio_7_text"> <h3>Our House</h3> </div> </a> </div> <div class="medium_module"> <div id="portfolio_5" class="small_module"> <a href="http://anthony-ng.com//NEVERNOTE"> <div id="portfolio_5_text"> <h3>Nevernote</h3> </div> </a> </div> <div id="portfolio_6" class="small_module"> <a href="http://anthony-ng.com/DBCraigslist/"> <div id="portfolio_6_text"> <h3>DBCraigslist</h3> </div> </a> </div> </div> <div id="gallery" class="big_module"> <a href="http://www.anthonyng.xyz/"> <div id="gallery_text"> <h3>My Gallery</h3> </div> </a> </div> </div> </div> <!-- Add your site or application content here --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script> </body> </html>
{ "content_hash": "484039c1d14ff8ea258a31c4a3f683b3", "timestamp": "", "source": "github", "line_count": 209, "max_line_length": 234, "avg_line_length": 50.55980861244019, "alnum_prop": 0.49020535629790857, "repo_name": "anthony-ng/anthony-ng.github.io", "id": "b625df0bd038056d991506bb8bcc94477ed4c953", "size": "10567", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "106648" }, { "name": "HTML", "bytes": "151396" }, { "name": "JavaScript", "bytes": "1870" } ], "symlink_target": "" }
// Copyright 2017 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.skyframe; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.devtools.build.lib.events.ExtendedEventHandler; import com.google.devtools.build.lib.util.ResourceUsage; import com.google.devtools.build.skyframe.AbstractSkyFunctionEnvironment; import com.google.devtools.build.skyframe.BuildDriver; import com.google.devtools.build.skyframe.EvaluationResult; import com.google.devtools.build.skyframe.SkyFunction; import com.google.devtools.build.skyframe.SkyKey; import com.google.devtools.build.skyframe.SkyValue; import com.google.devtools.build.skyframe.ValueOrUntypedException; import java.util.Map; /** A skyframe environment that can be used to evaluate arbitrary skykeys for testing. */ public class SkyFunctionEnvironmentForTesting extends AbstractSkyFunctionEnvironment implements SkyFunction.Environment { private final BuildDriver buildDriver; private final ExtendedEventHandler eventHandler; private final SkyframeExecutor skyframeExecutor; /** Creates a SkyFunctionEnvironmentForTesting that uses a BuildDriver to evaluate skykeys. */ public SkyFunctionEnvironmentForTesting( BuildDriver buildDriver, ExtendedEventHandler eventHandler, SkyframeExecutor skyframeExecutor) { this.buildDriver = buildDriver; this.eventHandler = eventHandler; this.skyframeExecutor = skyframeExecutor; } @Override protected Map<SkyKey, ValueOrUntypedException> getValueOrUntypedExceptions( Iterable<? extends SkyKey> depKeys) throws InterruptedException { ImmutableMap.Builder<SkyKey, ValueOrUntypedException> resultMap = ImmutableMap.builder(); Iterable<SkyKey> keysToEvaluate = ImmutableList.copyOf(depKeys); EvaluationResult<SkyValue> evaluationResult = skyframeExecutor.evaluateSkyKeys(eventHandler, keysToEvaluate, true); buildDriver.evaluate(depKeys, true, ResourceUsage.getAvailableProcessors(), eventHandler); for (SkyKey depKey : ImmutableSet.copyOf(depKeys)) { resultMap.put(depKey, ValueOrUntypedException.ofValueUntyped(evaluationResult.get(depKey))); } return resultMap.build(); } @Override public ExtendedEventHandler getListener() { return eventHandler; } @Override public boolean inErrorBubblingForTesting() { return false; } }
{ "content_hash": "0e4510f3e82108a62c020c0b824220a5", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 98, "avg_line_length": 42.041666666666664, "alnum_prop": 0.7905517013544764, "repo_name": "dropbox/bazel", "id": "e4cd196751d1e1a26cad444aee69f407d253f4c1", "size": "3027", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/google/devtools/build/lib/skyframe/SkyFunctionEnvironmentForTesting.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "710" }, { "name": "C", "bytes": "17979" }, { "name": "C++", "bytes": "1265579" }, { "name": "Dockerfile", "bytes": "82" }, { "name": "HTML", "bytes": "20252" }, { "name": "Java", "bytes": "30899654" }, { "name": "Makefile", "bytes": "248" }, { "name": "Objective-C", "bytes": "11194" }, { "name": "Objective-C++", "bytes": "1043" }, { "name": "PowerShell", "bytes": "5536" }, { "name": "Python", "bytes": "1469925" }, { "name": "Shell", "bytes": "1251163" }, { "name": "Smarty", "bytes": "464341" } ], "symlink_target": "" }
 #pragma once #include <aws/cloudformation/CloudFormation_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/cloudformation/model/ResponseMetadata.h> #include <aws/cloudformation/model/ParameterDeclaration.h> #include <aws/cloudformation/model/Capability.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Xml { class XmlDocument; } // namespace Xml } // namespace Utils namespace CloudFormation { namespace Model { /** * <p>The output for the <a>GetTemplateSummary</a> action.</p><p><h3>See Also:</h3> * <a * href="http://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/GetTemplateSummaryOutput">AWS * API Reference</a></p> */ class AWS_CLOUDFORMATION_API GetTemplateSummaryResult { public: GetTemplateSummaryResult(); GetTemplateSummaryResult(const AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result); GetTemplateSummaryResult& operator=(const AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result); /** * <p>A list of parameter declarations that describe various properties for each * parameter.</p> */ inline const Aws::Vector<ParameterDeclaration>& GetParameters() const{ return m_parameters; } /** * <p>A list of parameter declarations that describe various properties for each * parameter.</p> */ inline void SetParameters(const Aws::Vector<ParameterDeclaration>& value) { m_parameters = value; } /** * <p>A list of parameter declarations that describe various properties for each * parameter.</p> */ inline void SetParameters(Aws::Vector<ParameterDeclaration>&& value) { m_parameters = std::move(value); } /** * <p>A list of parameter declarations that describe various properties for each * parameter.</p> */ inline GetTemplateSummaryResult& WithParameters(const Aws::Vector<ParameterDeclaration>& value) { SetParameters(value); return *this;} /** * <p>A list of parameter declarations that describe various properties for each * parameter.</p> */ inline GetTemplateSummaryResult& WithParameters(Aws::Vector<ParameterDeclaration>&& value) { SetParameters(std::move(value)); return *this;} /** * <p>A list of parameter declarations that describe various properties for each * parameter.</p> */ inline GetTemplateSummaryResult& AddParameters(const ParameterDeclaration& value) { m_parameters.push_back(value); return *this; } /** * <p>A list of parameter declarations that describe various properties for each * parameter.</p> */ inline GetTemplateSummaryResult& AddParameters(ParameterDeclaration&& value) { m_parameters.push_back(std::move(value)); return *this; } /** * <p>The value that is defined in the <code>Description</code> property of the * template.</p> */ inline const Aws::String& GetDescription() const{ return m_description; } /** * <p>The value that is defined in the <code>Description</code> property of the * template.</p> */ inline void SetDescription(const Aws::String& value) { m_description = value; } /** * <p>The value that is defined in the <code>Description</code> property of the * template.</p> */ inline void SetDescription(Aws::String&& value) { m_description = std::move(value); } /** * <p>The value that is defined in the <code>Description</code> property of the * template.</p> */ inline void SetDescription(const char* value) { m_description.assign(value); } /** * <p>The value that is defined in the <code>Description</code> property of the * template.</p> */ inline GetTemplateSummaryResult& WithDescription(const Aws::String& value) { SetDescription(value); return *this;} /** * <p>The value that is defined in the <code>Description</code> property of the * template.</p> */ inline GetTemplateSummaryResult& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;} /** * <p>The value that is defined in the <code>Description</code> property of the * template.</p> */ inline GetTemplateSummaryResult& WithDescription(const char* value) { SetDescription(value); return *this;} /** * <p>The capabilities found within the template. If your template contains IAM * resources, you must specify the CAPABILITY_IAM or CAPABILITY_NAMED_IAM value for * this parameter when you use the <a>CreateStack</a> or <a>UpdateStack</a> actions * with your template; otherwise, those actions return an InsufficientCapabilities * error.</p> <p>For more information, see <a * href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities">Acknowledging * IAM Resources in AWS CloudFormation Templates</a>.</p> */ inline const Aws::Vector<Capability>& GetCapabilities() const{ return m_capabilities; } /** * <p>The capabilities found within the template. If your template contains IAM * resources, you must specify the CAPABILITY_IAM or CAPABILITY_NAMED_IAM value for * this parameter when you use the <a>CreateStack</a> or <a>UpdateStack</a> actions * with your template; otherwise, those actions return an InsufficientCapabilities * error.</p> <p>For more information, see <a * href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities">Acknowledging * IAM Resources in AWS CloudFormation Templates</a>.</p> */ inline void SetCapabilities(const Aws::Vector<Capability>& value) { m_capabilities = value; } /** * <p>The capabilities found within the template. If your template contains IAM * resources, you must specify the CAPABILITY_IAM or CAPABILITY_NAMED_IAM value for * this parameter when you use the <a>CreateStack</a> or <a>UpdateStack</a> actions * with your template; otherwise, those actions return an InsufficientCapabilities * error.</p> <p>For more information, see <a * href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities">Acknowledging * IAM Resources in AWS CloudFormation Templates</a>.</p> */ inline void SetCapabilities(Aws::Vector<Capability>&& value) { m_capabilities = std::move(value); } /** * <p>The capabilities found within the template. If your template contains IAM * resources, you must specify the CAPABILITY_IAM or CAPABILITY_NAMED_IAM value for * this parameter when you use the <a>CreateStack</a> or <a>UpdateStack</a> actions * with your template; otherwise, those actions return an InsufficientCapabilities * error.</p> <p>For more information, see <a * href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities">Acknowledging * IAM Resources in AWS CloudFormation Templates</a>.</p> */ inline GetTemplateSummaryResult& WithCapabilities(const Aws::Vector<Capability>& value) { SetCapabilities(value); return *this;} /** * <p>The capabilities found within the template. If your template contains IAM * resources, you must specify the CAPABILITY_IAM or CAPABILITY_NAMED_IAM value for * this parameter when you use the <a>CreateStack</a> or <a>UpdateStack</a> actions * with your template; otherwise, those actions return an InsufficientCapabilities * error.</p> <p>For more information, see <a * href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities">Acknowledging * IAM Resources in AWS CloudFormation Templates</a>.</p> */ inline GetTemplateSummaryResult& WithCapabilities(Aws::Vector<Capability>&& value) { SetCapabilities(std::move(value)); return *this;} /** * <p>The capabilities found within the template. If your template contains IAM * resources, you must specify the CAPABILITY_IAM or CAPABILITY_NAMED_IAM value for * this parameter when you use the <a>CreateStack</a> or <a>UpdateStack</a> actions * with your template; otherwise, those actions return an InsufficientCapabilities * error.</p> <p>For more information, see <a * href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities">Acknowledging * IAM Resources in AWS CloudFormation Templates</a>.</p> */ inline GetTemplateSummaryResult& AddCapabilities(const Capability& value) { m_capabilities.push_back(value); return *this; } /** * <p>The capabilities found within the template. If your template contains IAM * resources, you must specify the CAPABILITY_IAM or CAPABILITY_NAMED_IAM value for * this parameter when you use the <a>CreateStack</a> or <a>UpdateStack</a> actions * with your template; otherwise, those actions return an InsufficientCapabilities * error.</p> <p>For more information, see <a * href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities">Acknowledging * IAM Resources in AWS CloudFormation Templates</a>.</p> */ inline GetTemplateSummaryResult& AddCapabilities(Capability&& value) { m_capabilities.push_back(std::move(value)); return *this; } /** * <p>The list of resources that generated the values in the * <code>Capabilities</code> response element.</p> */ inline const Aws::String& GetCapabilitiesReason() const{ return m_capabilitiesReason; } /** * <p>The list of resources that generated the values in the * <code>Capabilities</code> response element.</p> */ inline void SetCapabilitiesReason(const Aws::String& value) { m_capabilitiesReason = value; } /** * <p>The list of resources that generated the values in the * <code>Capabilities</code> response element.</p> */ inline void SetCapabilitiesReason(Aws::String&& value) { m_capabilitiesReason = std::move(value); } /** * <p>The list of resources that generated the values in the * <code>Capabilities</code> response element.</p> */ inline void SetCapabilitiesReason(const char* value) { m_capabilitiesReason.assign(value); } /** * <p>The list of resources that generated the values in the * <code>Capabilities</code> response element.</p> */ inline GetTemplateSummaryResult& WithCapabilitiesReason(const Aws::String& value) { SetCapabilitiesReason(value); return *this;} /** * <p>The list of resources that generated the values in the * <code>Capabilities</code> response element.</p> */ inline GetTemplateSummaryResult& WithCapabilitiesReason(Aws::String&& value) { SetCapabilitiesReason(std::move(value)); return *this;} /** * <p>The list of resources that generated the values in the * <code>Capabilities</code> response element.</p> */ inline GetTemplateSummaryResult& WithCapabilitiesReason(const char* value) { SetCapabilitiesReason(value); return *this;} /** * <p>A list of all the template resource types that are defined in the template, * such as <code>AWS::EC2::Instance</code>, <code>AWS::Dynamo::Table</code>, and * <code>Custom::MyCustomInstance</code>.</p> */ inline const Aws::Vector<Aws::String>& GetResourceTypes() const{ return m_resourceTypes; } /** * <p>A list of all the template resource types that are defined in the template, * such as <code>AWS::EC2::Instance</code>, <code>AWS::Dynamo::Table</code>, and * <code>Custom::MyCustomInstance</code>.</p> */ inline void SetResourceTypes(const Aws::Vector<Aws::String>& value) { m_resourceTypes = value; } /** * <p>A list of all the template resource types that are defined in the template, * such as <code>AWS::EC2::Instance</code>, <code>AWS::Dynamo::Table</code>, and * <code>Custom::MyCustomInstance</code>.</p> */ inline void SetResourceTypes(Aws::Vector<Aws::String>&& value) { m_resourceTypes = std::move(value); } /** * <p>A list of all the template resource types that are defined in the template, * such as <code>AWS::EC2::Instance</code>, <code>AWS::Dynamo::Table</code>, and * <code>Custom::MyCustomInstance</code>.</p> */ inline GetTemplateSummaryResult& WithResourceTypes(const Aws::Vector<Aws::String>& value) { SetResourceTypes(value); return *this;} /** * <p>A list of all the template resource types that are defined in the template, * such as <code>AWS::EC2::Instance</code>, <code>AWS::Dynamo::Table</code>, and * <code>Custom::MyCustomInstance</code>.</p> */ inline GetTemplateSummaryResult& WithResourceTypes(Aws::Vector<Aws::String>&& value) { SetResourceTypes(std::move(value)); return *this;} /** * <p>A list of all the template resource types that are defined in the template, * such as <code>AWS::EC2::Instance</code>, <code>AWS::Dynamo::Table</code>, and * <code>Custom::MyCustomInstance</code>.</p> */ inline GetTemplateSummaryResult& AddResourceTypes(const Aws::String& value) { m_resourceTypes.push_back(value); return *this; } /** * <p>A list of all the template resource types that are defined in the template, * such as <code>AWS::EC2::Instance</code>, <code>AWS::Dynamo::Table</code>, and * <code>Custom::MyCustomInstance</code>.</p> */ inline GetTemplateSummaryResult& AddResourceTypes(Aws::String&& value) { m_resourceTypes.push_back(std::move(value)); return *this; } /** * <p>A list of all the template resource types that are defined in the template, * such as <code>AWS::EC2::Instance</code>, <code>AWS::Dynamo::Table</code>, and * <code>Custom::MyCustomInstance</code>.</p> */ inline GetTemplateSummaryResult& AddResourceTypes(const char* value) { m_resourceTypes.push_back(value); return *this; } /** * <p>The AWS template format version, which identifies the capabilities of the * template.</p> */ inline const Aws::String& GetVersion() const{ return m_version; } /** * <p>The AWS template format version, which identifies the capabilities of the * template.</p> */ inline void SetVersion(const Aws::String& value) { m_version = value; } /** * <p>The AWS template format version, which identifies the capabilities of the * template.</p> */ inline void SetVersion(Aws::String&& value) { m_version = std::move(value); } /** * <p>The AWS template format version, which identifies the capabilities of the * template.</p> */ inline void SetVersion(const char* value) { m_version.assign(value); } /** * <p>The AWS template format version, which identifies the capabilities of the * template.</p> */ inline GetTemplateSummaryResult& WithVersion(const Aws::String& value) { SetVersion(value); return *this;} /** * <p>The AWS template format version, which identifies the capabilities of the * template.</p> */ inline GetTemplateSummaryResult& WithVersion(Aws::String&& value) { SetVersion(std::move(value)); return *this;} /** * <p>The AWS template format version, which identifies the capabilities of the * template.</p> */ inline GetTemplateSummaryResult& WithVersion(const char* value) { SetVersion(value); return *this;} /** * <p>The value that is defined for the <code>Metadata</code> property of the * template.</p> */ inline const Aws::String& GetMetadata() const{ return m_metadata; } /** * <p>The value that is defined for the <code>Metadata</code> property of the * template.</p> */ inline void SetMetadata(const Aws::String& value) { m_metadata = value; } /** * <p>The value that is defined for the <code>Metadata</code> property of the * template.</p> */ inline void SetMetadata(Aws::String&& value) { m_metadata = std::move(value); } /** * <p>The value that is defined for the <code>Metadata</code> property of the * template.</p> */ inline void SetMetadata(const char* value) { m_metadata.assign(value); } /** * <p>The value that is defined for the <code>Metadata</code> property of the * template.</p> */ inline GetTemplateSummaryResult& WithMetadata(const Aws::String& value) { SetMetadata(value); return *this;} /** * <p>The value that is defined for the <code>Metadata</code> property of the * template.</p> */ inline GetTemplateSummaryResult& WithMetadata(Aws::String&& value) { SetMetadata(std::move(value)); return *this;} /** * <p>The value that is defined for the <code>Metadata</code> property of the * template.</p> */ inline GetTemplateSummaryResult& WithMetadata(const char* value) { SetMetadata(value); return *this;} /** * <p>A list of the transforms that are declared in the template.</p> */ inline const Aws::Vector<Aws::String>& GetDeclaredTransforms() const{ return m_declaredTransforms; } /** * <p>A list of the transforms that are declared in the template.</p> */ inline void SetDeclaredTransforms(const Aws::Vector<Aws::String>& value) { m_declaredTransforms = value; } /** * <p>A list of the transforms that are declared in the template.</p> */ inline void SetDeclaredTransforms(Aws::Vector<Aws::String>&& value) { m_declaredTransforms = std::move(value); } /** * <p>A list of the transforms that are declared in the template.</p> */ inline GetTemplateSummaryResult& WithDeclaredTransforms(const Aws::Vector<Aws::String>& value) { SetDeclaredTransforms(value); return *this;} /** * <p>A list of the transforms that are declared in the template.</p> */ inline GetTemplateSummaryResult& WithDeclaredTransforms(Aws::Vector<Aws::String>&& value) { SetDeclaredTransforms(std::move(value)); return *this;} /** * <p>A list of the transforms that are declared in the template.</p> */ inline GetTemplateSummaryResult& AddDeclaredTransforms(const Aws::String& value) { m_declaredTransforms.push_back(value); return *this; } /** * <p>A list of the transforms that are declared in the template.</p> */ inline GetTemplateSummaryResult& AddDeclaredTransforms(Aws::String&& value) { m_declaredTransforms.push_back(std::move(value)); return *this; } /** * <p>A list of the transforms that are declared in the template.</p> */ inline GetTemplateSummaryResult& AddDeclaredTransforms(const char* value) { m_declaredTransforms.push_back(value); return *this; } inline const ResponseMetadata& GetResponseMetadata() const{ return m_responseMetadata; } inline void SetResponseMetadata(const ResponseMetadata& value) { m_responseMetadata = value; } inline void SetResponseMetadata(ResponseMetadata&& value) { m_responseMetadata = std::move(value); } inline GetTemplateSummaryResult& WithResponseMetadata(const ResponseMetadata& value) { SetResponseMetadata(value); return *this;} inline GetTemplateSummaryResult& WithResponseMetadata(ResponseMetadata&& value) { SetResponseMetadata(std::move(value)); return *this;} private: Aws::Vector<ParameterDeclaration> m_parameters; Aws::String m_description; Aws::Vector<Capability> m_capabilities; Aws::String m_capabilitiesReason; Aws::Vector<Aws::String> m_resourceTypes; Aws::String m_version; Aws::String m_metadata; Aws::Vector<Aws::String> m_declaredTransforms; ResponseMetadata m_responseMetadata; }; } // namespace Model } // namespace CloudFormation } // namespace Aws
{ "content_hash": "f0132f4848860e66dd3a2945ef2875a0", "timestamp": "", "source": "github", "line_count": 453, "max_line_length": 151, "avg_line_length": 43.90728476821192, "alnum_prop": 0.6871292106586224, "repo_name": "svagionitis/aws-sdk-cpp", "id": "2b566ed8d4f2bdd3b9c967cf46b1dc6a571e5d6f", "size": "20463", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "aws-cpp-sdk-cloudformation/include/aws/cloudformation/model/GetTemplateSummaryResult.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2313" }, { "name": "C++", "bytes": "104799778" }, { "name": "CMake", "bytes": "455533" }, { "name": "HTML", "bytes": "4471" }, { "name": "Java", "bytes": "243075" }, { "name": "Python", "bytes": "72896" }, { "name": "Shell", "bytes": "2803" } ], "symlink_target": "" }
pkg = value_for_platform_family( [ 'rhel', 'fedora' ] => 'php-gd', 'debian' => 'php5-gd' ) package pkg do action :install notifies(:run, "execute[/usr/sbin/php5enmod gd]", :immediately) if platform?('ubuntu') && node['platform_version'].to_f >= 12.04 end execute '/usr/sbin/php5enmod gd' do action :nothing only_if { platform?('ubuntu') && node['platform_version'].to_f >= 12.04 && ::File.exists?('/usr/sbin/php5enmod') } end
{ "content_hash": "0df222c4466d1cad67df17aeac150fbe", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 130, "avg_line_length": 31.714285714285715, "alnum_prop": 0.6396396396396397, "repo_name": "priestjim/chef-php", "id": "e7892d4671f78e5f5d54804396ee25bfdc517b83", "size": "1141", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "recipes/module_gd.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "82628" }, { "name": "Ruby", "bytes": "66136" }, { "name": "Shell", "bytes": "588" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_95) on Sat Apr 09 08:38:34 CEST 2016 --> <title>Tar.TarCompressionMethod (Apache Ant API)</title> <meta name="date" content="2016-04-09"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Tar.TarCompressionMethod (Apache Ant API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/apache/tools/ant/taskdefs/Tar.html" title="class in org.apache.tools.ant.taskdefs"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../org/apache/tools/ant/taskdefs/Tar.TarFileSet.html" title="class in org.apache.tools.ant.taskdefs"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/tools/ant/taskdefs/Tar.TarCompressionMethod.html" target="_top">Frames</a></li> <li><a href="Tar.TarCompressionMethod.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#fields_inherited_from_class_org.apache.tools.ant.types.EnumeratedAttribute">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.apache.tools.ant.taskdefs</div> <h2 title="Class Tar.TarCompressionMethod" class="title">Class Tar.TarCompressionMethod</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li><a href="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html" title="class in org.apache.tools.ant.types">org.apache.tools.ant.types.EnumeratedAttribute</a></li> <li> <ul class="inheritance"> <li>org.apache.tools.ant.taskdefs.Tar.TarCompressionMethod</li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>Enclosing class:</dt> <dd><a href="../../../../../org/apache/tools/ant/taskdefs/Tar.html" title="class in org.apache.tools.ant.taskdefs">Tar</a></dd> </dl> <hr> <br> <pre>public static final class <span class="strong">Tar.TarCompressionMethod</span> extends <a href="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html" title="class in org.apache.tools.ant.types">EnumeratedAttribute</a></pre> <div class="block">Valid Modes for Compression attribute to Tar Task</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field_summary"> <!-- --> </a> <h3>Field Summary</h3> <ul class="blockList"> <li class="blockList"><a name="fields_inherited_from_class_org.apache.tools.ant.types.EnumeratedAttribute"> <!-- --> </a> <h3>Fields inherited from class&nbsp;org.apache.tools.ant.types.<a href="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html" title="class in org.apache.tools.ant.types">EnumeratedAttribute</a></h3> <code><a href="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html#value">value</a></code></li> </ul> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../../org/apache/tools/ant/taskdefs/Tar.TarCompressionMethod.html#Tar.TarCompressionMethod()">Tar.TarCompressionMethod</a></strong>()</code> <div class="block">Default constructor</div> </td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.String[]</code></td> <td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/taskdefs/Tar.TarCompressionMethod.html#getValues()">getValues</a></strong>()</code> <div class="block">Get valid enumeration values.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_org.apache.tools.ant.types.EnumeratedAttribute"> <!-- --> </a> <h3>Methods inherited from class&nbsp;org.apache.tools.ant.types.<a href="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html" title="class in org.apache.tools.ant.types">EnumeratedAttribute</a></h3> <code><a href="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html#containsValue(java.lang.String)">containsValue</a>, <a href="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html#getIndex()">getIndex</a>, <a href="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html#getInstance(java.lang.Class,%20java.lang.String)">getInstance</a>, <a href="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html#getValue()">getValue</a>, <a href="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html#indexOfValue(java.lang.String)">indexOfValue</a>, <a href="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html#setValue(java.lang.String)">setValue</a>, <a href="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html#toString()">toString</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="Tar.TarCompressionMethod()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>Tar.TarCompressionMethod</h4> <pre>public&nbsp;Tar.TarCompressionMethod()</pre> <div class="block">Default constructor</div> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getValues()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getValues</h4> <pre>public&nbsp;java.lang.String[]&nbsp;getValues()</pre> <div class="block">Get valid enumeration values.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html#getValues()">getValues</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html" title="class in org.apache.tools.ant.types">EnumeratedAttribute</a></code></dd> <dt><span class="strong">Returns:</span></dt><dd>valid enumeration values</dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/apache/tools/ant/taskdefs/Tar.html" title="class in org.apache.tools.ant.taskdefs"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../org/apache/tools/ant/taskdefs/Tar.TarFileSet.html" title="class in org.apache.tools.ant.taskdefs"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/tools/ant/taskdefs/Tar.TarCompressionMethod.html" target="_top">Frames</a></li> <li><a href="Tar.TarCompressionMethod.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#fields_inherited_from_class_org.apache.tools.ant.types.EnumeratedAttribute">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "a076d2967e6e1b3302ae753d4511769e", "timestamp": "", "source": "github", "line_count": 296, "max_line_length": 837, "avg_line_length": 39.604729729729726, "alnum_prop": 0.6457391452699821, "repo_name": "mplaine/xformsdb", "id": "08d15597a52c6b13b25c6b732cb0df630463545a", "size": "11723", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "tools/ant/manual/api/org/apache/tools/ant/taskdefs/Tar.TarCompressionMethod.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "7542" }, { "name": "CSS", "bytes": "36155" }, { "name": "Java", "bytes": "1066946" }, { "name": "JavaScript", "bytes": "19671" }, { "name": "Shell", "bytes": "8496" }, { "name": "XQuery", "bytes": "30236" }, { "name": "XSLT", "bytes": "180854" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_enabled="true" android:state_checked="true" android:drawable="@drawable/ic_cast_on_light" /> <item android:state_enabled="true" android:state_checkable="true" android:drawable="@drawable/mr_ic_media_route_connecting_mono_light" /> <item android:state_enabled="true" android:drawable="@drawable/ic_cast_off_light" /> <item android:drawable="@drawable/ic_cast_disabled_light" /> </selector>
{ "content_hash": "cc475ad0268eb729aa9856a23712ef0a", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 141, "avg_line_length": 66.875, "alnum_prop": 0.7289719626168224, "repo_name": "ChiangC/FMTech", "id": "f3445e0fdaf589618553d303da1f552346c496ca", "size": "535", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "GooglePlus/app/src/main/res/drawable/mr_ic_media_route_mono_light.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "935" }, { "name": "CMake", "bytes": "1767" }, { "name": "HTML", "bytes": "28061" }, { "name": "Java", "bytes": "47051212" }, { "name": "JavaScript", "bytes": "1535" }, { "name": "Makefile", "bytes": "5823" } ], "symlink_target": "" }
[![npm (scoped with tag)](https://img.shields.io/npm/v/@nuxtjs/opencollective/latest.svg?style=flat-square)](https://npmjs.com/package/@nuxtjs/opencollective) [![npm](https://img.shields.io/npm/dt/@nuxtjs/opencollective.svg?style=flat-square)](https://npmjs.com/package/@nuxtjs/opencollective) [![CircleCI](https://img.shields.io/circleci/project/github/nuxt/opencollective.svg?style=flat-square)](https://circleci.com/gh/nuxt/opencollective) [![Codecov](https://img.shields.io/codecov/c/github/nuxt/opencollective.svg?style=flat-square)](https://codecov.io/gh/nuxt/opencollective) [![Dependencies](https://david-dm.org/nuxt/opencollective/status.svg?style=flat-square)](https://david-dm.org/nuxt/opencollective) [![js-standard-style](https://img.shields.io/badge/code_style-standard-brightgreen.svg?style=flat-square)](http://standardjs.com) ![Showcase](https://i.imgur.com/PZqyT3x.jpg) > [📖 **Release Notes**](./CHANGELOG.md) ## Features Displaying **opencollective** statistics and a donation URL after users install a package is important for many creators. After problems with current packages that offer similar features, we decided to spin off our one own. Our key goals are: * No interference/problems when installing packages. Never break installation because of the package * Pretty output for all information * Decent configurability * Seamless drop-in for [common](https://github.com/opencollective/opencollective-cli) [solutions](https://github.com/opencollective/opencollective-postinstall) ## Setup - Add `@nuxtjs/opencollective` dependency using yarn or npm to your project - Add the script to `postinstall` in your package.json ```js { // ... "scripts": { "postinstall": "opencollective || exit 0" }, "collective": { "url": "https://opencollective.com/nuxtjs" } // ... } ``` - Configure it ## Configuration Configuration is applied through your project's `package.json`. A full configuration looks like: ```json { "collective": { "url": "https://opencollective.com/nuxtjs", "logoUrl": "https://opencollective.com/nuxtjs/logo.txt?reverse=true&variant=variant2", "donation": { "slug": "/order/591", "amount": "50", "text": "Please donate:" } } } ``` --- | Attribute | Optional | Default | Comment | | --- | --- | --- | --- | | url | ❌ | - | The URL to your opencollective page | logo | ✅ | - | **LEGACY**: The URL to the logo that should be displayed. Please use `logoUrl` instead. | logoUrl | ✅ | - | The URL to the ASCII-logo that should be displayed. | donation.slug | ✅ | '/donate' | The slug that should be appended to `url`. Can be used to setup a specific order. | donation.amount | ✅ | - | The default amount that should be selected on the opencollective page. | donation.text | ✅ | 'Donate:' | The text that will be displayed before your donation url. ## Disable message We know the postinstall messages can be annoying when deploying in production or running a CI pipeline. That's why the message is **disabled** in those environments by default. **Enabled** when one the following environment variables is set: * `NODE_ENV=dev` * `NODE_ENV=development` * `OPENCOLLECTIVE_FORCE` **Strictly Disabled** when one the following environment variables is set: - `OC_POSTINSTALL_TEST` - `OPENCOLLECTIVE_HIDE` - `CI` - `CONTINUOUS_INTEGRATION` - `NODE_ENV` (set and **not** `dev` or `development`) - `DISABLE_OPENCOLLECTIVE` (set to any string value that is not `'false'` or `'0'`, for compatability with [opencollective-postinatall](https://github.com/opencollective/opencollective-postinstall)) ## Development - Clone this repository - Install dependencies using `yarn install` or `npm install` - Run it manually `path/to/project/root/src/index.js path/to/package/you/want/to/try` - Run tests with `npm t` or `yarn test` ## Inspiration This project is heavily inspired by [opencollective-cli](https://github.com/opencollective/opencollective-cli). ## License [MIT License](./LICENSE) Copyright (c) Alexander Lichter <[email protected]>
{ "content_hash": "0c1cd01f1f2cdfe6da1dc0d4bf8a357f", "timestamp": "", "source": "github", "line_count": 114, "max_line_length": 159, "avg_line_length": 35.59649122807018, "alnum_prop": 0.7183341547560375, "repo_name": "BigBoss424/portfolio", "id": "b77a108c7e67fa358b9f667d87e6879d02ff4a14", "size": "4147", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "v6/node_modules/@nuxt/opencollective/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
// This is a generated file. Not intended for manual editing. package com.intellij.plugins.haxe.lang.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface HaxePackageStatement extends HaxePackageStatementPsiMixin { @Nullable HaxeReferenceExpression getReferenceExpression(); }
{ "content_hash": "fcfe3d61c67a7ba2b39c865479100a92", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 76, "avg_line_length": 23.333333333333332, "alnum_prop": 0.8085714285714286, "repo_name": "TiVo/intellij-haxe-nightly-builds", "id": "d7a83296922b760d771701610285ae8c3bc7b20f", "size": "1014", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "gen/com/intellij/plugins/haxe/lang/psi/HaxePackageStatement.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "2332" }, { "name": "Haxe", "bytes": "73646" }, { "name": "JFlex", "bytes": "16860" }, { "name": "Java", "bytes": "2948804" }, { "name": "Makefile", "bytes": "538" }, { "name": "Shell", "bytes": "3228" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "e209be3a06034617819f5aba10a3806d", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "11975a4b356de02a4e22c87d80f95060ba69012b", "size": "171", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Piperales/Piperaceae/Piper/Piper subfuscum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
require 'parsers/modules/extensions' require 'parsers/modules/variables' require 'parsers/modules/optimizer' require 'parsers/modules/adding_files' require 'parsers/modules/finding_files' require 'parsers/modules/dependencies' require 'parsers/modules/replacement' require 'parsers/modules/paths' require 'parsers/modules/loading' module Hammer class Parser #TODO: Do we move dependencies into a module? attr_accessor :text attr_accessor :dependencies, :wildcard_dependencies attr_accessor :error_line, :error_file attr_accessor :path, :directory, :variables, :messages, :todos, :input_directory attr_accessor :added_files include Replacement include Extensions include Variables include AddingFiles include FindingFiles include Dependency include Paths def initialize(options={}) @path ||= options[:path] @wildcard_dependencies = {} @filenames = [] @variables = {} @directory = options[:directory] || Dir.mktmpdir() end def h(text) text # TODO: HTMLify end def filename path end def path=(new_path) raise "New path was a Pathname" if new_path.is_a? Pathname @path = new_path @filenames = Dir.glob(File.join(@path, "**/*")) end def parse(text="") return text end # Used when creating a parser, to initialize variables from the last parser. def from_hash(hash) self.variables = hash[:variables] if hash[:variables] self.messages = hash[:messages] self.wildcard_dependencies = hash[:wildcard_dependencies] self.dependencies = hash[:dependencies] self.added_files = hash[:added_files] return self end # Used to initialize the next parser when chained. def to_hash # TODO: We could probably do this more extensibly with a @data attribute. { :dependencies => @dependencies, :wildcard_dependencies => @wildcard_dependencies, :variables => @variables, :messages => @messages, :added_files => @added_files } end class << self def parse_added_file(input_directory, temporary_directory, filename, output_directory, optimized, &block) # We return a hash and some text! data = {:filename => filename} text = File.open(File.join(temporary_directory, filename), 'r').read() parsers = [Hammer::TodoParser] + Hammer::Parser.for_filename(filename) parsers.each do |parser_class| # Parser initialization parser = parser_class.new().from_hash(data) parser.directory = input_directory parser.input_directory = input_directory parser.output_directory = output_directory parser.path = Pathname.new(File.join(input_directory, filename)).relative_path_from(Pathname.new(input_directory)).to_s parser.optimized = optimized begin text = parser.parse(text) rescue RuntimeError => e # Set the error up and then get out of here! # This doesn't get saved to the parser, but that doesn't really matter. data.merge!({:error_line => parser.error_line}) if parser.error_line data.merge!({:error_file => parser.error_file}) if parser.error_file data.merge!({:error => e.to_s}) # No, we don't raise this error here. We just put it in :data. # raise e # TODO: Maybe a DEBUG would help with this! ensure data.merge!(parser.to_hash) end end block.call(text, data) end def parse_file(directory, filename, output_directory, optimized, &block) # We return a hash and some text! data = {:filename => filename} text = File.open(File.join(directory, filename), 'r').read() parsers = [Hammer::TodoParser] + Hammer::Parser.for_filename(filename) parsers.each do |parser_class| # Parser initialization parser = parser_class.new().from_hash(data) parser.directory = directory parser.input_directory = directory parser.output_directory = output_directory parser.path = Pathname.new(File.join(directory, filename)).relative_path_from(Pathname.new(directory)).to_s parser.optimized = optimized begin text = parser.parse(text) rescue RuntimeError => e # Set the error up and then get out of here! # This doesn't get saved to the parser, but that doesn't really matter. data.merge!({:error_line => parser.error_line}) if parser.error_line data.merge!({:error_file => parser.error_file}) if parser.error_file data.merge!({:error => e.to_s}) # No, we don't raise this error here. We just put it in :data. # raise e # TODO: Maybe a DEBUG would help with this! ensure data.merge!(parser.to_hash) end end block.call(text, data) end end include Optimizer end end parsers_path = File.join(File.dirname(__FILE__), '..', 'parsers', '**/*.rb') Dir[parsers_path].each {|file| require file; }
{ "content_hash": "aebe58d2d40b444c78a4c681e5ca53f7", "timestamp": "", "source": "github", "line_count": 158, "max_line_length": 141, "avg_line_length": 33.79746835443038, "alnum_prop": 0.6116104868913858, "repo_name": "RiotHQ/hammer-gem", "id": "b87eebf9a562f72957373819310e04e970cbedbc", "size": "5341", "binary": false, "copies": "1", "ref": "refs/heads/v2", "path": "lib/hammer/hammer/parser.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "15518" }, { "name": "CoffeeScript", "bytes": "19" }, { "name": "HTML", "bytes": "32618" }, { "name": "JavaScript", "bytes": "1233" }, { "name": "PHP", "bytes": "1782" }, { "name": "Ruby", "bytes": "171314" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../_static/javascripts/modernizr.js"></script> <title>statsmodels.tsa.statespace.kalman_filter.KalmanFilter.invert_cholesky &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png"> <link rel="manifest" href="../_static/icons/site.webmanifest"> <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="../_static/icons/browserconfig.xml"> <link rel="stylesheet" href="../_static/stylesheets/examples.css"> <link rel="stylesheet" href="../_static/stylesheets/deprecation.css"> <link rel="stylesheet" href="../_static/material.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/doctools.js"></script> <script src="../_static/language_data.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.tsa.statespace.kalman_filter.KalmanFilter.invert_lu" href="statsmodels.tsa.statespace.kalman_filter.KalmanFilter.invert_lu.html" /> <link rel="prev" title="statsmodels.tsa.statespace.kalman_filter.KalmanFilter.inversion_methods" href="statsmodels.tsa.statespace.kalman_filter.KalmanFilter.inversion_methods.html" /> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#generated/statsmodels.tsa.statespace.kalman_filter.KalmanFilter.invert_cholesky" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels v0.12.0</span> <span class="md-header-nav__topic"> statsmodels.tsa.statespace.kalman_filter.KalmanFilter.invert_cholesky </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../search.html" method="GET" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> <script src="../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../_static/versions.json", target_loc = "../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li> <li class="md-tabs__item"><a href="../statespace.html" class="md-tabs__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a></li> <li class="md-tabs__item"><a href="statsmodels.tsa.statespace.kalman_filter.KalmanFilter.html" class="md-tabs__link">statsmodels.tsa.statespace.kalman_filter.KalmanFilter</a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="../index.html" title="statsmodels">statsmodels v0.12.0</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="../gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="../user-guide.html" class="md-nav__link">User Guide</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../user-guide.html#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../tsa.html" class="md-nav__link">Time Series analysis <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa</span></code></a> </li> <li class="md-nav__item"> <a href="../statespace.html" class="md-nav__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a> </li> <li class="md-nav__item"> <a href="../vector_ar.html" class="md-nav__link">Vector Autoregressions <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa.vector_ar</span></code></a> </li></ul> </li> <li class="md-nav__item"> <a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a> </li></ul> </li> <li class="md-nav__item"> <a href="../examples/index.html" class="md-nav__link">Examples</a> </li> <li class="md-nav__item"> <a href="../api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <a href="../about.html" class="md-nav__link">About statsmodels</a> </li> <li class="md-nav__item"> <a href="../dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="../release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.tsa.statespace.kalman_filter.KalmanFilter.invert_cholesky.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <h1 id="generated-statsmodels-tsa-statespace-kalman-filter-kalmanfilter-invert-cholesky--page-root">statsmodels.tsa.statespace.kalman_filter.KalmanFilter.invert_cholesky<a class="headerlink" href="#generated-statsmodels-tsa-statespace-kalman-filter-kalmanfilter-invert-cholesky--page-root" title="Permalink to this headline">¶</a></h1> <dl class="py attribute"> <dt id="statsmodels.tsa.statespace.kalman_filter.KalmanFilter.invert_cholesky"> <code class="sig-prename descclassname">KalmanFilter.</code><code class="sig-name descname">invert_cholesky</code><em class="property"> = False</em><a class="headerlink" href="#statsmodels.tsa.statespace.kalman_filter.KalmanFilter.invert_cholesky" title="Permalink to this definition">¶</a></dt> <dd><p>(bool) Flag for Cholesky inversion method.</p> </dd></dl> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="statsmodels.tsa.statespace.kalman_filter.KalmanFilter.inversion_methods.html" title="statsmodels.tsa.statespace.kalman_filter.KalmanFilter.inversion_methods" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> statsmodels.tsa.statespace.kalman_filter.KalmanFilter.inversion_methods </span> </div> </a> <a href="statsmodels.tsa.statespace.kalman_filter.KalmanFilter.invert_lu.html" title="statsmodels.tsa.statespace.kalman_filter.KalmanFilter.invert_lu" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> statsmodels.tsa.statespace.kalman_filter.KalmanFilter.invert_lu </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Aug 27, 2020. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 3.2.1. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
{ "content_hash": "ae07fecf3c36051ee8bae682bdb93b8f", "timestamp": "", "source": "github", "line_count": 449, "max_line_length": 999, "avg_line_length": 40.33630289532294, "alnum_prop": 0.6072000441720501, "repo_name": "statsmodels/statsmodels.github.io", "id": "18746f173fd4aa003b84e29e0dd693ffee92d5f5", "size": "18115", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "v0.12.0/generated/statsmodels.tsa.statespace.kalman_filter.KalmanFilter.invert_cholesky.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>zx.soft</groupId> <artifactId>elasticsearch-parent</artifactId> <version>1.0.0</version> <relativePath>../elasticsearch-parent/pom.xml</relativePath> </parent> <artifactId>elasticsearch-web</artifactId> <name>ElasticSearch Web</name> <dependencies> <!-- ElasticSearch包 --> <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> </dependency> <!-- Restlet包 --> <dependency> <groupId>org.restlet.jse</groupId> <artifactId>org.restlet</artifactId> </dependency> <dependency> <groupId>org.restlet.jse</groupId> <artifactId>org.restlet.ext.simple</artifactId> </dependency> <dependency> <groupId>org.restlet.jse</groupId> <artifactId>org.restlet.ext.jackson</artifactId> </dependency> <!-- 日志包 --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-access</artifactId> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </dependency> <!-- Json包 --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> </dependency> <!-- Mybatis包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> </dependency> <!-- 依赖注入 --> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> </dependency> <!-- 测试包 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.4</version> <configuration> <excludes> <exclude>elastic_search.properties</exclude> <exclude>logback.xml</exclude> <exclude>web-server.properties</exclude> </excludes> </configuration> </plugin> <plugin> <artifactId>maven-assembly-plugin</artifactId> <configuration> <descriptors> <descriptor>src/main/assembly/distribution.xml</descriptor> </descriptors> </configuration> <executions> <execution> <id>make-assembly</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> </plugin> </plugins> <finalName>${project.artifactId}-${project.version}</finalName> </build> </project>
{ "content_hash": "3edeff8e353442ed8d4b3a7a0312a84c", "timestamp": "", "source": "github", "line_count": 143, "max_line_length": 104, "avg_line_length": 26.846153846153847, "alnum_prop": 0.6798645480593904, "repo_name": "szwork2013/elasticsearch-sentiment", "id": "8a9e1f57f07478d282e956b4ab039510b473ccbe", "size": "3867", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "elasticsearch-web/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "567518" }, { "name": "Shell", "bytes": "12866" } ], "symlink_target": "" }
/* Includes ------------------------------------------------------------------*/ #include <stdio.h> #include <string.h> #include "W7500x_gpio.h" #include "W7500x_uart.h" #include "W7500x_crg.h" #include "W7500x_wztoe.h" #include "W7500x_miim.h" #include "common.h" #include "W7500x_board.h" #include "dhcp.h" #include "dhcp_cb.h" #include "timerHandler.h" #include "uartHandler.h" #include "flashHandler.h" #include "deviceHandler.h" #include "eepromHandler.h" #include "segcp.h" #include "configData.h" /* Private typedef -----------------------------------------------------------*/ typedef void (*pFunction)(void); /* Private define ------------------------------------------------------------*/ //#define _MAIN_DEBUG_ // debugging message enable // Define for Interrupt Vector Table Remap #define BOOT_VEC_BACK_ADDR (DEVICE_APP_MAIN_ADDR - SECT_SIZE) // Define for MAC address settings #define MACSTR_SIZE 22 /* Private function prototypes -----------------------------------------------*/ void application_jump(uint32_t AppAddress); uint8_t check_mac_address(void); static void W7500x_Init(void); static void W7500x_WZTOE_Init(void); int8_t process_dhcp(void); // Debug messages void display_Dev_Info_header(void); void display_Dev_Info_dhcp(void); // Functions for Interrupt Vector Table Remap void Copy_Interrupt_VectorTable(uint32_t start_addr); void Backup_Boot_Interrupt_VectorTable(void); // Delay void delay(__IO uint32_t milliseconds); //Notice: used ioLibray void TimingDelay_Decrement(void); void delay_ms(uint32_t ms); // loop delay /* Private variables ---------------------------------------------------------*/ static __IO uint32_t TimingDelay; /* Public variables ---------------------------------------------------------*/ // Shared buffer declaration uint8_t g_send_buf[DATA_BUF_SIZE]; uint8_t g_recv_buf[DATA_BUF_SIZE]; uint8_t flag_s2e_application_running = OFF; uint8_t flag_process_dhcp_success = OFF; /** * @brief Main program * @param None * @retval None */ int main(void) { DevConfig *dev_config = get_DevConfig_pointer(); uint8_t appjump_enable = OFF; uint8_t ret = 0; //uint16_t i; //uint8_t buff[512] = {0x00, }; //////////////////////////////////////////////////////////////////////////////////////////////////// // W7500x Hardware Initialize //////////////////////////////////////////////////////////////////////////////////////////////////// /* W7500x MCU Initialization */ W7500x_Init(); // includes UART2 init code for debugging /* W7500x WZTOE (Hardwired TCP/IP stack) Initialization */ W7500x_WZTOE_Init(); /* W7500x Board Initialization */ W7500x_Board_Init(); //////////////////////////////////////////////////////////////////////////////////////////////////// // W7500x Application: Initialize part1 //////////////////////////////////////////////////////////////////////////////////////////////////// /* Load the Configuration data */ load_DevConfig_from_storage(); /* Set the device working mode: BOOT */ dev_config->network_info[0].state = ST_BOOT; //////////////////////////////////////////////////////////////////////////////////////////////////// // W7500x Application: Check the MAC address and Firmware update //////////////////////////////////////////////////////////////////////////////////////////////////// // 1. MAC address°¡ ¾ø´Â °æ¿ì -> MAC ÁÖ¼Ò ÀÔ·Â ¹× save if(check_mac_address()) appjump_enable = ON; // 2. Firmware update flag°¡ 1ÀÎ °æ¿ì -> Àüü ¿µ¿ª erase, Fwup_size¸¸Å­ fw update ¼öÇà, app backup (flash) >> app main (flash) if(dev_config->firmware_update.fwup_flag == 1) { // Firmware download has already been done at application routine. // 1. 50kB app mode: Firmware copy: [App backup] -> [App main] // 2. 100kB app mode: Firmware download and write: [Network] -> [App main] ret = device_firmware_update(STORAGE_APP_MAIN); if(ret == DEVICE_FWUP_RET_SUCCESS) { dev_config->firmware_update.fwup_flag = SEGCP_DISABLE; dev_config->firmware_update.fwup_size = 0; save_DevConfig_to_storage(); appjump_enable = ON; } } if ((*(uint32_t*)DEVICE_APP_MAIN_ADDR != 0xFFFFFFFF) && (*(uint32_t*)DEVICE_APP_BACKUP_ADDR != 0xFFFFFFFF)) { appjump_enable = ON; } /* else if (*(uint32_t*)DEVICE_APP_BACKUP_ADDR == 0xFFFFFFFF) // genarate application backup storage for device restore { device_firmware_update(STORAGE_APP_BACKUP); appjump_enable = ON; } else if (*(uint32_t*)DEVICE_APP_MAIN_ADDR == 0xFFFFFFFF) // copy the backup to application main storage { device_firmware_update(STORAGE_APP_MAIN); appjump_enable = ON; } */ //#ifdef _MAIN_DEBUG_ if (*(uint32_t*)DEVICE_APP_MAIN_ADDR == 0xFFFFFFFF) { #ifdef _MAIN_DEBUG_ printf("\r\n>> Application Main: Empty [0x%.8x], Jump Failed\r\n", DEVICE_APP_MAIN_ADDR); #endif appjump_enable = OFF; } else { #ifdef _MAIN_DEBUG_ printf("\r\n>> Application Main: Detected [0x%.8x], Jump Start\r\n", DEVICE_APP_MAIN_ADDR); #endif appjump_enable = ON; } //#endif #ifdef __USE_BOOT_ENTRY__ if(get_boot_entry_pin() == 0) appjump_enable = OFF; #endif if(appjump_enable == ON) { // Copy the application code interrupt vector to 0x00000000 //printf("\r\n copy the interrupt vector, app area [0x%.8x] ==> boot", DEVICE_APP_MAIN_ADDR); Copy_Interrupt_VectorTable(DEVICE_APP_MAIN_ADDR); application_jump(DEVICE_APP_MAIN_ADDR); } //////////////////////////////////////////////////////////////////////////////////////////////////// // W7500x Application: Initialize part2 //////////////////////////////////////////////////////////////////////////////////////////////////// if(dev_config->serial_info[0].serial_debug_en) { // Debug UART: Device information print out display_Dev_Info_header(); } //////////////////////////////////////////////////////////////////////////////////////////////////// // W7500x Application: DHCP client / DNS client handler //////////////////////////////////////////////////////////////////////////////////////////////////// /* Network Configuration - DHCP client */ // Initialize Network Information: DHCP or Static IP allocation if(dev_config->options.dhcp_use) { if(process_dhcp() == DHCP_IP_LEASED) // DHCP success { flag_process_dhcp_success = ON; } else // DHCP failed { Net_Conf(); // Set default static IP settings } } else { Net_Conf(); // Set default static IP settings } // Debug UART: Network information print out (includes DHCP IP allocation result) if(dev_config->serial_info[0].serial_debug_en) { display_Net_Info(); display_Dev_Info_dhcp(); } //////////////////////////////////////////////////////////////////////////////////////////////////// // W7500x Boot: Main Routine //////////////////////////////////////////////////////////////////////////////////////////////////// flag_s2e_application_running = ON; LED_On(LED1); while(1) // main loop { do_segcp(); if(dev_config->options.dhcp_use) DHCP_run(); // DHCP client handler for IP renewal if(flag_check_main_routine) { // Device working indicator: Boot // LEDs blink rapidly (100ms) LED_Toggle(LED1); LED_Toggle(LED2); flag_check_main_routine = 0; } } // End of application main loop } // End of main /***************************************************************************** * Private functions ****************************************************************************/ void application_jump(uint32_t AppAddress) { pFunction Jump_To_Application; uint32_t JumpAddress; JumpAddress = *( uint32_t*)(AppAddress + 0x04); Jump_To_Application = (pFunction)JumpAddress; // Initialize user application's stack pointer __set_MSP(*(__IO uint32_t *)AppAddress); // Jump to application Jump_To_Application(); } static void W7500x_Init(void) { //////////////////////////////////////////////////// // W7500x MCU Initialize //////////////////////////////////////////////////// /* Reset supervisory IC Init */ Supervisory_IC_Init(); /* Set System init */ SystemInit_User(CLOCK_SOURCE_INTERNAL, PLL_SOURCE_8MHz, SYSTEM_CLOCK_8MHz); //SystemInit(); /* Delay for working stabilize */ delay_ms(1500); // //////////////////////////////////////////////////////////////////////////////////////////////////// // W7500x ISR: Interrupt Vector Table Remap (Custom) //////////////////////////////////////////////////////////////////////////////////////////////////// if (*(uint32_t*)BOOT_VEC_BACK_ADDR == 0xFFFFFFFF) // after boot code first write { Backup_Boot_Interrupt_VectorTable(); } else { Copy_Interrupt_VectorTable(BOOT_VEC_BACK_ADDR); } /* DualTimer Initialization */ Timer_Configuration(); /* UART Initialization */ //CRG_FCLK_SourceSelect(CRG_RCLK); UART2_Configuration(); // Simple UART (UART2) for Debugging /* SysTick_Config */ SysTick_Config((GetSystemClock()/1000)); #ifdef _MAIN_DEBUG_ printf("\r\n >> W7500x MCU Clock Settings ===============\r\n"); printf(" - GetPLLSource: %s, %lu (Hz)\r\n", GetPLLSource()?"External":"Internal", PLL_SOURCE_8MHz); printf(" - SetSystemClock: %lu (Hz) \r\n", SYSTEM_CLOCK_8MHz); printf(" - GetSystemClock: %d (Hz) \r\n", GetSystemClock()); #endif } static void W7500x_WZTOE_Init(void) { //////////////////////////////////////////////////// // W7500x WZTOE (Hardwired TCP/IP core) Initialize //////////////////////////////////////////////////// /* Set Network Configuration: HW Socket Tx/Rx buffer size */ //uint8_t tx_size[8] = { 2, 2, 2, 2, 2, 2, 2, 2 }; //uint8_t rx_size[8] = { 2, 2, 2, 2, 2, 2, 2, 2 }; /* Structure for timeout control: RTR, RCR */ wiz_NetTimeout * net_timeout; /* Set WZ_100US Register */ setTIC100US((GetSystemClock()/10000)); #ifdef _MAIN_DEBUG_ printf(" GetSystemClock: %X, getTIC100US: %X, (%X) \r\n", GetSystemClock(), getTIC100US(), *(uint32_t *)WZTOE_TIC100US); // for debugging #endif /* Set TCP Timeout: retry count / timeout val */ // Retry count default: [8], Timeout val default: [2000] net_timeout->retry_cnt = 8; net_timeout->time_100us = 2500; wizchip_settimeout(net_timeout); //wizchip_gettimeout(net_timeout); // ## for debugging - check the TCP timeout settings #ifdef _MAIN_DEBUG_ printf(" Network Timeout Settings - RTR: %d, RCR: %d\r\n", net_timeout->retry_cnt, net_timeout->time_100us); #endif /* Set Network Configuration */ //wizchip_init(tx_size, rx_size); } int8_t process_dhcp(void) { uint8_t ret = 0; uint8_t dhcp_retry = 0; #ifdef _MAIN_DEBUG_ printf(" - DHCP Client running\r\n"); #endif DHCP_init(SOCK_DHCP, g_send_buf); reg_dhcp_cbfunc(w7500x_dhcp_assign, w7500x_dhcp_assign, w7500x_dhcp_conflict); while(1) { ret = DHCP_run(); if(ret == DHCP_IP_LEASED) { #ifdef _MAIN_DEBUG_ printf(" - DHCP Success\r\n"); #endif break; } else if(ret == DHCP_FAILED) { dhcp_retry++; #ifdef _MAIN_DEBUG_ if(dhcp_retry <= 3) printf(" - DHCP Timeout occurred and retry [%d]\r\n", dhcp_retry); #endif } if(dhcp_retry > 3) { #ifdef _MAIN_DEBUG_ printf(" - DHCP Failed\r\n\r\n"); #endif DHCP_stop(); break; } do_segcp(); // Process the requests of configuration tool during the DHCP client run. } return ret; } void display_Dev_Info_header(void) { DevConfig *dev_config = get_DevConfig_pointer(); printf("\r\n"); printf("%s\r\n", STR_BAR); #if (DEVICE_BOARD_NAME == WIZ750SR) printf(" WIZ750SR \r\n"); printf(" >> WIZnet Serial to Ethernet Device\r\n"); #else #ifndef __W7500P__ printf(" [W7500] Serial to Ethernet Device\r\n"); #else printf(" [W7500P] Serial to Ethernet Device\r\n"); #endif #endif printf(" >> Firmware version: Boot %d.%d.%d %s\r\n", dev_config->fw_ver[0], dev_config->fw_ver[1], dev_config->fw_ver[2], STR_VERSION_STATUS); printf("%s\r\n", STR_BAR); } void display_Dev_Info_dhcp(void) { DevConfig *dev_config = get_DevConfig_pointer(); if(dev_config->options.dhcp_use) { if(flag_process_dhcp_success == ON) printf(" # DHCP IP Leased time : %u seconds\r\n", getDHCPLeasetime()); else printf(" # DHCP Failed\r\n"); } } ////////////////////////////////////////////////////////////////////////////////// // Functions for MAC address ////////////////////////////////////////////////////////////////////////////////// uint8_t check_mac_address(void) { DevConfig *dev_config = get_DevConfig_pointer(); uint8_t i; uint8_t mac_buf[6] = {0, }; uint8_t mac_str[MACSTR_SIZE] = {0, }; uint8_t trep[MACSTR_SIZE] = {0, }; uint8_t ret = 0; if(((dev_config->network_info_common.mac[0] != 0x00) || (dev_config->network_info_common.mac[1] != 0x08) || (dev_config->network_info_common.mac[2] != 0xDC)) || ((dev_config->network_info_common.mac[0] == 0xff) && (dev_config->network_info_common.mac[1] == 0xff) && (dev_config->network_info_common.mac[2] == 0xff))) { read_storage(STORAGE_MAC, 0, mac_buf, 0); //printf("Storage MAC: %.2x:%.2x:%.2x:%.2x:%.2x:%.2x\r\n", mac_buf[0], mac_buf[1], mac_buf[2], mac_buf[3], mac_buf[4], mac_buf[5]); // Initial stage: Input the MAC address if(((mac_buf[0] != 0x00) || (mac_buf[1] != 0x08) || (mac_buf[2] != 0xDC)) || ((mac_buf[0] == 0xff) && (mac_buf[1] == 0xff) && (mac_buf[2] == 0xff))) { gSEGCPPRIVILEGE = SEGCP_PRIVILEGE_CLR; gSEGCPPRIVILEGE = (SEGCP_PRIVILEGE_SET|SEGCP_PRIVILEGE_WRITE); while(1) { printf("INPUT FIRST MAC?\r\n"); for(i = 0; i < MACSTR_SIZE-1; i++) { mac_str[i] = S_UartGetc(); //S_UartPutc(mac_str[i]); } if(!proc_SEGCP(mac_str, trep)) { // Save the MAC address to PRIVATE SPACE for MAC address only erase_storage(STORAGE_MAC); write_storage(STORAGE_MAC, 0, dev_config->network_info_common.mac, 0); // Set factory default set_DevConfig_to_factory_value(); save_DevConfig_to_storage(); ret = 1; break; } else { if(dev_config->serial_info[0].serial_debug_en) printf("%s\r\n", trep); memset(mac_str, 0x00, MACSTR_SIZE); } } } else // Lost the MAC address, MAC address restore { memcpy(dev_config->network_info_common.mac, mac_buf, 6); save_DevConfig_to_storage(); } } else { ret = 1; } return ret; } ////////////////////////////////////////////////////////////////////////////////// // Functions for Interrupt Vector Table Remap ////////////////////////////////////////////////////////////////////////////////// void Copy_Interrupt_VectorTable(uint32_t start_addr) { uint32_t i; uint8_t flash_vector_area[SECT_SIZE]; for (i = 0x00; i < 0x08; i++) flash_vector_area[i] = *(volatile uint8_t *)(0x00000000+i); for (i = 0x08; i < 0xA8; i++) flash_vector_area[i] = *(volatile uint8_t *)(start_addr+i); // Actual address range; Interrupt vector table is located here for (i = 0xA8; i < SECT_SIZE; i++) flash_vector_area[i] = *(volatile uint8_t *)(0x00000000+i); __disable_irq(); DO_IAP(IAP_ERAS_SECT, 0x00000000, 0, 0); // Erase the interrupt vector table area : Sector 0 DO_IAP(IAP_PROG, 0x00000000, flash_vector_area , SECT_SIZE); // Write the applicaion vector table to 0x00000000 __enable_irq(); } void Backup_Boot_Interrupt_VectorTable(void) { uint32_t i; uint8_t flash_vector_area[SECT_SIZE]; for (i = 0; i < SECT_SIZE; i++) { flash_vector_area[i] = *(volatile uint8_t *)(0x00000000+i); } __disable_irq(); DO_IAP(IAP_PROG, BOOT_VEC_BACK_ADDR, flash_vector_area , SECT_SIZE); __enable_irq(); } /** * @brief Inserts a delay time. * @param nTime: specifies the delay time length, in milliseconds. * @retval None */ void delay(__IO uint32_t milliseconds) { TimingDelay = milliseconds; while(TimingDelay != 0); } /** * @brief Decrements the TimingDelay variable. * @param None * @retval None */ void TimingDelay_Decrement(void) { if(TimingDelay != 0x00) { TimingDelay--; } } /** * @brief Inserts a delay time when the situation cannot use the timer interrupt. * @param ms: specifies the delay time length, in milliseconds. * @retval None */ void delay_ms(uint32_t ms) { volatile uint32_t nCount; nCount=(GetSystemClock()/10000)*ms; for (; nCount!=0; nCount--); }
{ "content_hash": "218f3ee98691d387df47430b39fb17f5", "timestamp": "", "source": "github", "line_count": 572, "max_line_length": 162, "avg_line_length": 28.21853146853147, "alnum_prop": 0.5567808685955021, "repo_name": "Wiznet/W7500x-Serial-to-Ethernet-device", "id": "f6c1802560ec9a025b4ec2de3aff8f28c4688f26", "size": "17280", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Firmware_Projects_uVision5/Projects/S2E_Boot/src/main.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "37528" }, { "name": "Batchfile", "bytes": "449" }, { "name": "C", "bytes": "1130927" }, { "name": "C++", "bytes": "98058" }, { "name": "Objective-C", "bytes": "4942" } ], "symlink_target": "" }
package at.vizu.s2n.types.symbol /** * Phil on 07.12.15. */ class AppliedTypeArgument(val appliedType: TType, genericName: String, upperBound: TType, lowerBound: TType, covariant: Boolean, contravariant: Boolean, val genericModifier: TypeArgument) extends TypeArgument(genericModifier.ctx, genericName, upperBound, lowerBound, covariant, contravariant) { override def methods: Seq[Method] = appliedType.methods override def fields: Seq[Field] = appliedType.fields override def pkg: String = appliedType.pkg override def simpleName: String = appliedType.simpleName override def hasParent(tpe: TType): Boolean = appliedType.hasParent(tpe) override def isAssignableFrom(other: TType): Boolean = getConcreteType match { case g: TypeArgument => g.isAssignableFrom(other) case _@t => other.hasParent(t) } override def findField(execCtx: TType, name: String) = appliedType.findField(execCtx, name) override def findMethod(execCtx: TType, name: String, args: Seq[TType]) = appliedType.findMethod(execCtx, name, args) override def parents = appliedType.parents override def applyType(appliedType: TType): AppliedTypeArgument = { throw new RuntimeException("AHHH") } override def isAssignableAsParam(other: TType): Boolean = other match { case a: AppliedTypeArgument => checkVariances(a) case g: TypeArgument => this == g case c: ConcreteType => appliedType == c case _ => false } override def equals(that: Any): Boolean = that match { case a: AppliedTypeArgument => a.getConcreteType == getConcreteType case g: TypeArgument => appliedType == g case c: ConcreteType => getConcreteType == c case _ => false } override def typeEquals(that: Any): Boolean = { that match { case a: AppliedTypeArgument => getConcreteType == a.getConcreteType case g: TypeArgument => getConcreteType == g case c: ConcreteType => getConcreteType == c case _ => false } } def getConcreteType: TType = { appliedType match { case a: AppliedTypeArgument => a.getConcreteType case _ => appliedType } } override def isGenericModifier: Boolean = getConcreteType match { case g: TypeArgument => true case _ => false } override def gmCovariance: Boolean = genericModifier.covariance override def gmContravariance: Boolean = genericModifier.contravariance override def baseTypeEquals(obj: TType): Boolean = getConcreteType.baseTypeEquals(obj) override def toString: String = appliedType.toString }
{ "content_hash": "a0630d60666d6f3e782acd7ae2504e3b", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 119, "avg_line_length": 32.49367088607595, "alnum_prop": 0.7117257499026101, "repo_name": "viZu/nasca", "id": "397be894183404f34f38bc67d120e595523888cd", "size": "2567", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/scala/at/vizu/s2n/types/symbol/AppliedTypeArgument.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "182" }, { "name": "C++", "bytes": "2875" }, { "name": "Protocol Buffer", "bytes": "2807" }, { "name": "Scala", "bytes": "306027" } ], "symlink_target": "" }
#ifndef ATILDEFS_H #include "AtilDefs.h" #endif #ifndef OFFSET_H #include "Offset.h" #endif #ifndef SIZE_H namespace Atil { class Size; } #endif #ifndef POINT2D_H namespace Atil { class Point2d; } #endif #ifndef BOUNDINGBOX_H #define BOUNDINGBOX_H namespace Atil { // Implements a simple bounding box; provides methods to get intersections // and unions with other BoundingBox objects. // class BoundingBox { public: BoundingBox (); BoundingBox (Offset offset, Size size); BoundingBox (Offset origin, Offset extent); // Calcualtes the minimum bounding box defined by an array of offsets and // constructs a BoundingBox object from those extents. // The arguments are: // <param name='nPoints'>the number of points in the array of offsets;</param> // <param name='aOffsets'>an array of offsets used to calculate the // bounding box extents.</param> BoundingBox (int nPoints, const Offset* aOffsets); ~BoundingBox (); void set (Offset offset, Size size); void set (Offset origin, Offset extent); void set (int nPoints, const Offset* aOffsets); void expandToInclude (Offset offset); void expandToInclude (int nPoints, const Offset* aOffsets); void getExtents (Offset& origin, Offset& extent) const; Size size () const; Offset origin () const ; bool inBounds (const Offset& offset) const; bool inBounds ( int x, int y ) const; Offset clipToBounds (const Offset& offset) const; bool contains( const BoundingBox& box ) const; bool intersects ( const BoundingBox& bbOther ) const; bool getIntersection ( const BoundingBox& bbOther, BoundingBox& bbIntersection ) const; bool getIntersection( int nPoints, const Point2d* aPolygon, BoundingBox& bbIntersection ) const; void getUnion ( const BoundingBox& bbOther, BoundingBox& bbUnion ) const; private: Offset mOrigin; Offset mExtent; }; } // end of namespace Atil #ifndef BOUNDINGBOX_INL #include <BoundingBox.inl> #endif #endif //#ifndef SIZE_H //#include <Size.h> //#endif
{ "content_hash": "fb288d10c1b3e1bd7be14e5ef8117b62", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 82, "avg_line_length": 27.628205128205128, "alnum_prop": 0.6761020881670534, "repo_name": "kevinzhwl/ObjectARXCore", "id": "e2ed7b6a116554ac2e72fc5303b8a1a5f34e4d8c", "size": "3323", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "2007/utils/Atil/Inc/BoundingBox.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "14344996" }, { "name": "C++", "bytes": "77699473" }, { "name": "Objective-C", "bytes": "2136952" } ], "symlink_target": "" }
// Copyright (c) Microsoft, All rights reserved. See License.txt in the project root for license information. ;(function (factory) { var objectTypes = { 'function': true, 'object': true }; function checkGlobal(value) { return (value && value.Object === Object) ? value : null; } var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType) ? exports : null; var freeModule = (objectTypes[typeof module] && module && !module.nodeType) ? module : null; var freeGlobal = checkGlobal(freeExports && freeModule && typeof global === 'object' && global); var freeSelf = checkGlobal(objectTypes[typeof self] && self); var freeWindow = checkGlobal(objectTypes[typeof window] && window); var moduleExports = (freeModule && freeModule.exports === freeExports) ? freeExports : null; var thisGlobal = checkGlobal(objectTypes[typeof this] && this); var root = freeGlobal || ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) || freeSelf || thisGlobal || Function('return this')(); // Because of build optimizers if (typeof define === 'function' && define.amd) { define(['./rx.lite.compat'], function (Rx, exports) { return factory(root, exports, Rx); }); } else if (typeof module === 'object' && module && module.exports === freeExports) { module.exports = factory(root, module.exports, require('rx-lite-compat')); } else { root.Rx = factory(root, {}, root.Rx); } }.call(this, function (root, exp, Rx, undefined) { // Refernces var inherits = Rx.internals.inherits, AbstractObserver = Rx.internals.AbstractObserver, Observable = Rx.Observable, observableProto = Observable.prototype, AnonymousObservable = Rx.AnonymousObservable, ObservableBase = Rx.ObservableBase, observableDefer = Observable.defer, observableEmpty = Observable.empty, observableNever = Observable.never, observableThrow = Observable['throw'], observableFromArray = Observable.fromArray, defaultScheduler = Rx.Scheduler['default'], SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, SerialDisposable = Rx.SerialDisposable, CompositeDisposable = Rx.CompositeDisposable, BinaryDisposable = Rx.BinaryDisposable, RefCountDisposable = Rx.RefCountDisposable, Subject = Rx.Subject, addRef = Rx.internals.addRef, normalizeTime = Rx.Scheduler.normalize, helpers = Rx.helpers, isPromise = helpers.isPromise, isFunction = helpers.isFunction, isScheduler = Rx.Scheduler.isScheduler, observableFromPromise = Observable.fromPromise; var errorObj = {e: {}}; function tryCatcherGen(tryCatchTarget) { return function tryCatcher() { try { return tryCatchTarget.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; } }; } var tryCatch = Rx.internals.tryCatch = function tryCatch(fn) { if (!isFunction(fn)) { throw new TypeError('fn must be a function'); } return tryCatcherGen(fn); }; function thrower(e) { throw e; } /** * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTime = observableProto.windowTime = function (timeSpan, timeShiftOrScheduler, scheduler) { var source = this, timeShift; timeShiftOrScheduler == null && (timeShift = timeSpan); isScheduler(scheduler) || (scheduler = defaultScheduler); if (typeof timeShiftOrScheduler === 'number') { timeShift = timeShiftOrScheduler; } else if (isScheduler(timeShiftOrScheduler)) { timeShift = timeSpan; scheduler = timeShiftOrScheduler; } return new AnonymousObservable(function (observer) { var groupDisposable, nextShift = timeShift, nextSpan = timeSpan, q = [], refCountDisposable, timerD = new SerialDisposable(), totalTime = 0; groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable); function createTimer () { var m = new SingleAssignmentDisposable(), isSpan = false, isShift = false; timerD.setDisposable(m); if (nextSpan === nextShift) { isSpan = true; isShift = true; } else if (nextSpan < nextShift) { isSpan = true; } else { isShift = true; } var newTotalTime = isSpan ? nextSpan : nextShift, ts = newTotalTime - totalTime; totalTime = newTotalTime; if (isSpan) { nextSpan += timeShift; } if (isShift) { nextShift += timeShift; } m.setDisposable(scheduler.scheduleFuture(null, ts, function () { if (isShift) { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } isSpan && q.shift().onCompleted(); createTimer(); })); }; q.push(new Subject()); observer.onNext(addRef(q[0], refCountDisposable)); createTimer(); groupDisposable.add(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } }, function (e) { for (var i = 0, len = q.length; i < len; i++) { q[i].onError(e); } observer.onError(e); }, function () { for (var i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }, source); }; /** * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. * @param {Number} timeSpan Maximum time length of a window. * @param {Number} count Maximum element count of a window. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTimeOrCount = observableProto.windowTimeOrCount = function (timeSpan, count, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = defaultScheduler); return new AnonymousObservable(function (observer) { var timerD = new SerialDisposable(), groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable), n = 0, windowId = 0, s = new Subject(); function createTimer(id) { var m = new SingleAssignmentDisposable(); timerD.setDisposable(m); m.setDisposable(scheduler.scheduleFuture(null, timeSpan, function () { if (id !== windowId) { return; } n = 0; var newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); createTimer(newId); })); } observer.onNext(addRef(s, refCountDisposable)); createTimer(0); groupDisposable.add(source.subscribe( function (x) { var newId = 0, newWindow = false; s.onNext(x); if (++n === count) { newWindow = true; n = 0; newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); } newWindow && createTimer(newId); }, function (e) { s.onError(e); observer.onError(e); }, function () { s.onCompleted(); observer.onCompleted(); } )); return refCountDisposable; }, source); }; function toArray(x) { return x.toArray(); } /** * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTime = observableProto.bufferTime = function (timeSpan, timeShiftOrScheduler, scheduler) { return this.windowWithTime(timeSpan, timeShiftOrScheduler, scheduler).flatMap(toArray); }; function toArray(x) { return x.toArray(); } /** * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. * @param {Number} timeSpan Maximum time length of a buffer. * @param {Number} count Maximum element count of a buffer. * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTimeOrCount = observableProto.bufferTimeOrCount = function (timeSpan, count, scheduler) { return this.windowWithTimeOrCount(timeSpan, count, scheduler).flatMap(toArray); }; var TimeIntervalObservable = (function (__super__) { inherits(TimeIntervalObservable, __super__); function TimeIntervalObservable(source, s) { this.source = source; this._s = s; __super__.call(this); } TimeIntervalObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new TimeIntervalObserver(o, this._s)); }; return TimeIntervalObservable; }(ObservableBase)); var TimeIntervalObserver = (function (__super__) { inherits(TimeIntervalObserver, __super__); function TimeIntervalObserver(o, s) { this._o = o; this._s = s; this._l = s.now(); __super__.call(this); } TimeIntervalObserver.prototype.next = function (x) { var now = this._s.now(), span = now - this._l; this._l = now; this._o.onNext({ value: x, interval: span }); }; TimeIntervalObserver.prototype.error = function (e) { this._o.onError(e); }; TimeIntervalObserver.prototype.completed = function () { this._o.onCompleted(); }; return TimeIntervalObserver; }(AbstractObserver)); /** * Records the time interval between consecutive values in an observable sequence. * * @example * 1 - res = source.timeInterval(); * 2 - res = source.timeInterval(Rx.Scheduler.timeout); * * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with time interval information on values. */ observableProto.timeInterval = function (scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); return new TimeIntervalObservable(this, scheduler); }; var GenerateAbsoluteObservable = (function (__super__) { inherits(GenerateAbsoluteObservable, __super__); function GenerateAbsoluteObservable(state, cndFn, itrFn, resFn, timeFn, s) { this._state = state; this._cndFn = cndFn; this._itrFn = itrFn; this._resFn = resFn; this._timeFn = timeFn; this._s = s; __super__.call(this); } function scheduleRecursive(state, recurse) { state.hasResult && state.o.onNext(state.result); if (state.first) { state.first = false; } else { state.newState = tryCatch(state.self._itrFn)(state.newState); if (state.newState === errorObj) { return state.o.onError(state.newState.e); } } state.hasResult = tryCatch(state.self._cndFn)(state.newState); if (state.hasResult === errorObj) { return state.o.onError(state.hasResult.e); } if (state.hasResult) { state.result = tryCatch(state.self._resFn)(state.newState); if (state.result === errorObj) { return state.o.onError(state.result.e); } var time = tryCatch(state.self._timeFn)(state.newState); if (time === errorObj) { return state.o.onError(time.e); } recurse(state, time); } else { state.o.onCompleted(); } } GenerateAbsoluteObservable.prototype.subscribeCore = function (o) { var state = { o: o, self: this, newState: this._state, first: true, hasResult: false }; return this._s.scheduleRecursiveFuture(state, new Date(this._s.now()), scheduleRecursive); }; return GenerateAbsoluteObservable; }(ObservableBase)); /** * GenerateAbsolutes an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithAbsoluteTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return new Date(); } * }); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); return new GenerateAbsoluteObservable(initialState, condition, iterate, resultSelector, timeSelector, scheduler); }; var GenerateRelativeObservable = (function (__super__) { inherits(GenerateRelativeObservable, __super__); function GenerateRelativeObservable(state, cndFn, itrFn, resFn, timeFn, s) { this._state = state; this._cndFn = cndFn; this._itrFn = itrFn; this._resFn = resFn; this._timeFn = timeFn; this._s = s; __super__.call(this); } function scheduleRecursive(state, recurse) { state.hasResult && state.o.onNext(state.result); if (state.first) { state.first = false; } else { state.newState = tryCatch(state.self._itrFn)(state.newState); if (state.newState === errorObj) { return state.o.onError(state.newState.e); } } state.hasResult = tryCatch(state.self._cndFn)(state.newState); if (state.hasResult === errorObj) { return state.o.onError(state.hasResult.e); } if (state.hasResult) { state.result = tryCatch(state.self._resFn)(state.newState); if (state.result === errorObj) { return state.o.onError(state.result.e); } var time = tryCatch(state.self._timeFn)(state.newState); if (time === errorObj) { return state.o.onError(time.e); } recurse(state, time); } else { state.o.onCompleted(); } } GenerateRelativeObservable.prototype.subscribeCore = function (o) { var state = { o: o, self: this, newState: this._state, first: true, hasResult: false }; return this._s.scheduleRecursiveFuture(state, 0, scheduleRecursive); }; return GenerateRelativeObservable; }(ObservableBase)); /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithRelativeTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return 500; } * ); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); return new GenerateRelativeObservable(initialState, condition, iterate, resultSelector, timeSelector, scheduler); }; var DelaySubscription = (function(__super__) { inherits(DelaySubscription, __super__); function DelaySubscription(source, dt, s) { this.source = source; this._dt = dt; this._s = s; __super__.call(this); } DelaySubscription.prototype.subscribeCore = function (o) { var d = new SerialDisposable(); d.setDisposable(this._s.scheduleFuture([this.source, o, d], this._dt, scheduleMethod)); return d; }; function scheduleMethod(s, state) { var source = state[0], o = state[1], d = state[2]; d.setDisposable(source.subscribe(o)); } return DelaySubscription; }(ObservableBase)); /** * Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers. * * @example * 1 - res = source.delaySubscription(5000); // 5s * 2 - res = source.delaySubscription(5000, Rx.Scheduler.default); // 5 seconds * * @param {Number} dueTime Relative or absolute time shift of the subscription. * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delaySubscription = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); return new DelaySubscription(this, dueTime, scheduler); }; var SkipLastWithTimeObservable = (function (__super__) { inherits(SkipLastWithTimeObservable, __super__); function SkipLastWithTimeObservable(source, d, s) { this.source = source; this._d = d; this._s = s; __super__.call(this); } SkipLastWithTimeObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new SkipLastWithTimeObserver(o, this)); }; return SkipLastWithTimeObservable; }(ObservableBase)); var SkipLastWithTimeObserver = (function (__super__) { inherits(SkipLastWithTimeObserver, __super__); function SkipLastWithTimeObserver(o, p) { this._o = o; this._s = p._s; this._d = p._d; this._q = []; __super__.call(this); } SkipLastWithTimeObserver.prototype.next = function (x) { var now = this._s.now(); this._q.push({ interval: now, value: x }); while (this._q.length > 0 && now - this._q[0].interval >= this._d) { this._o.onNext(this._q.shift().value); } }; SkipLastWithTimeObserver.prototype.error = function (e) { this._o.onError(e); }; SkipLastWithTimeObserver.prototype.completed = function () { var now = this._s.now(); while (this._q.length > 0 && now - this._q[0].interval >= this._d) { this._o.onNext(this._q.shift().value); } this._o.onCompleted(); }; return SkipLastWithTimeObserver; }(AbstractObserver)); /** * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for skipping elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. */ observableProto.skipLastWithTime = function (duration, scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); return new SkipLastWithTimeObservable(this, duration, scheduler); }; var TakeLastWithTimeObservable = (function (__super__) { inherits(TakeLastWithTimeObservable, __super__); function TakeLastWithTimeObservable(source, d, s) { this.source = source; this._d = d; this._s = s; __super__.call(this); } TakeLastWithTimeObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new TakeLastWithTimeObserver(o, this._d, this._s)); }; return TakeLastWithTimeObservable; }(ObservableBase)); var TakeLastWithTimeObserver = (function (__super__) { inherits(TakeLastWithTimeObserver, __super__); function TakeLastWithTimeObserver(o, d, s) { this._o = o; this._d = d; this._s = s; this._q = []; __super__.call(this); } TakeLastWithTimeObserver.prototype.next = function (x) { var now = this._s.now(); this._q.push({ interval: now, value: x }); while (this._q.length > 0 && now - this._q[0].interval >= this._d) { this._q.shift(); } }; TakeLastWithTimeObserver.prototype.error = function (e) { this._o.onError(e); }; TakeLastWithTimeObserver.prototype.completed = function () { var now = this._s.now(); while (this._q.length > 0) { var next = this._q.shift(); if (now - next.interval <= this._d) { this._o.onNext(next.value); } } this._o.onCompleted(); }; return TakeLastWithTimeObserver; }(AbstractObserver)); /** * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastWithTime = function (duration, scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); return new TakeLastWithTimeObservable(this, duration, scheduler); }; /** * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastBufferWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = defaultScheduler); return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, function (e) { o.onError(e); }, function () { var now = scheduler.now(), res = []; while (q.length > 0) { var next = q.shift(); now - next.interval <= duration && res.push(next.value); } o.onNext(res); o.onCompleted(); }); }, source); }; var TakeWithTimeObservable = (function (__super__) { inherits(TakeWithTimeObservable, __super__); function TakeWithTimeObservable(source, d, s) { this.source = source; this._d = d; this._s = s; __super__.call(this); } function scheduleMethod(s, o) { o.onCompleted(); } TakeWithTimeObservable.prototype.subscribeCore = function (o) { return new BinaryDisposable( this._s.scheduleFuture(o, this._d, scheduleMethod), this.source.subscribe(o) ); }; return TakeWithTimeObservable; }(ObservableBase)); /** * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. */ observableProto.takeWithTime = function (duration, scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); return new TakeWithTimeObservable(this, duration, scheduler); }; var SkipWithTimeObservable = (function (__super__) { inherits(SkipWithTimeObservable, __super__); function SkipWithTimeObservable(source, d, s) { this.source = source; this._d = d; this._s = s; this._open = false; __super__.call(this); } function scheduleMethod(s, self) { self._open = true; } SkipWithTimeObservable.prototype.subscribeCore = function (o) { return new BinaryDisposable( this._s.scheduleFuture(this, this._d, scheduleMethod), this.source.subscribe(new SkipWithTimeObserver(o, this)) ); }; return SkipWithTimeObservable; }(ObservableBase)); var SkipWithTimeObserver = (function (__super__) { inherits(SkipWithTimeObserver, __super__); function SkipWithTimeObserver(o, p) { this._o = o; this._p = p; __super__.call(this); } SkipWithTimeObserver.prototype.next = function (x) { this._p._open && this._o.onNext(x); }; SkipWithTimeObserver.prototype.error = function (e) { this._o.onError(e); }; SkipWithTimeObserver.prototype.completed = function () { this._o.onCompleted(); }; return SkipWithTimeObserver; }(AbstractObserver)); /** * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * @description * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded * may not execute immediately, despite the zero due time. * * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. * @param {Number} duration Duration for skipping elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. */ observableProto.skipWithTime = function (duration, scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); return new SkipWithTimeObservable(this, duration, scheduler); }; var SkipUntilWithTimeObservable = (function (__super__) { inherits(SkipUntilWithTimeObservable, __super__); function SkipUntilWithTimeObservable(source, startTime, scheduler) { this.source = source; this._st = startTime; this._s = scheduler; __super__.call(this); } function scheduleMethod(s, state) { state._open = true; } SkipUntilWithTimeObservable.prototype.subscribeCore = function (o) { this._open = false; return new BinaryDisposable( this._s.scheduleFuture(this, this._st, scheduleMethod), this.source.subscribe(new SkipUntilWithTimeObserver(o, this)) ); }; return SkipUntilWithTimeObservable; }(ObservableBase)); var SkipUntilWithTimeObserver = (function (__super__) { inherits(SkipUntilWithTimeObserver, __super__); function SkipUntilWithTimeObserver(o, p) { this._o = o; this._p = p; __super__.call(this); } SkipUntilWithTimeObserver.prototype.next = function (x) { this._p._open && this._o.onNext(x); }; SkipUntilWithTimeObserver.prototype.error = function (e) { this._o.onError(e); }; SkipUntilWithTimeObserver.prototype.completed = function () { this._o.onCompleted(); }; return SkipUntilWithTimeObserver; }(AbstractObserver)); /** * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. * * @examples * 1 - res = source.skipUntilWithTime(new Date(), [scheduler]); * 2 - res = source.skipUntilWithTime(5000, [scheduler]); * @param {Date|Number} startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped until the specified start time. */ observableProto.skipUntilWithTime = function (startTime, scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); return new SkipUntilWithTimeObservable(this, startTime, scheduler); }; /** * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. * @param {Scheduler} [scheduler] Scheduler to run the timer on. * @returns {Observable} An observable sequence with the elements taken until the specified end time. */ observableProto.takeUntilWithTime = function (endTime, scheduler) { isScheduler(scheduler) || (scheduler = defaultScheduler); var source = this; return new AnonymousObservable(function (o) { return new BinaryDisposable( scheduler.scheduleFuture(o, endTime, function (_, o) { o.onCompleted(); }), source.subscribe(o)); }, source); }; return Rx; }));
{ "content_hash": "5afce8bc3959f6c26abf57b7d1db71e5", "timestamp": "", "source": "github", "line_count": 815, "max_line_length": 296, "avg_line_length": 40.8920245398773, "alnum_prop": 0.6672367749872475, "repo_name": "pfskiev/lisbon", "id": "c9a32a6f951a75090e8ede85f2c5492ad9f1aba4", "size": "33327", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "src/static/vendor/rxjs/modules/rx-lite-time-compat/rx.lite.time.compat.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "12697" }, { "name": "HTML", "bytes": "79774" }, { "name": "Python", "bytes": "79117" } ], "symlink_target": "" }
'use strict' var test = require('tape') var through2 = require('through2') var duplexify = require('duplexify') var msgpack = require('msgpack5') var pump = require('pump') var nos = require('./') var Buffer = require('safe-buffer').Buffer function genPair () { var aIn = through2() var aOut = through2() var bIn = through2() var bOut = through2() pump(aOut, bIn) pump(bOut, aIn) return { a: duplexify.obj(aOut, aIn), b: duplexify.obj(bOut, bIn) } } test('converts a binary stream in an object stream', function (t) { t.plan(2) var pair = genPair() var first = nos(pair.a) var second = nos(pair.b) var msg1 = { hello: 'world' } var msg2 = { hello: 'matteo' } first.write(msg1) second.on('data', function (data) { t.deepEqual(data, msg1, 'msg1 matches') }) second.write(msg2) first.on('data', function (data) { t.deepEqual(data, msg2, 'msg2 matches') }) }) test('sends multiple messages', function (t) { t.plan(2) var pair = genPair() var first = nos(pair.a) var second = nos(pair.b) var msg1 = { hello: 'world' } var msg2 = { hello: 'matteo' } first.write(msg1) second.once('data', function (data) { t.deepEqual(data, msg1, 'msg1 matches') process.nextTick(first.write.bind(first, msg2)) second.once('data', function (data) { t.deepEqual(data, msg2, 'msg2 matches') }) }) }) test('supports a different codec', function (t) { t.plan(2) var pair = genPair() var first = nos(pair.a, { codec: msgpack() }) var second = nos(pair.b, { codec: msgpack() }) // Buffers can be encoded in msgpack, but not in JSON var msg1 = { hello: Buffer.from('world') } var msg2 = { hello: Buffer.from('matteo') } first.write(msg1) second.on('data', function (data) { t.deepEqual(data, msg1, 'msg1 matches') }) second.write(msg2) first.on('data', function (data) { t.deepEqual(data, msg2, 'msg2 matches') }) }) test('allows half open streams', function (t) { t.plan(2) var pair = genPair() var first = nos(pair.a) var second = nos(pair.b) var msg1 = { hello: 'world' } second.end() // let's put first on flowing mode first.on('data', function () {}) first.on('end', function () { t.pass('first ends') second.on('data', function (data) { t.deepEqual(data, msg1, 'msg1 matches') }) first.write(msg1) }) }) test('without duplexify', function (t) { t.plan(2) var channel = through2() var encoder = nos.encoder() var decoder = nos.decoder() var msg = { 'hello': 'world' } encoder.pipe(channel).pipe(decoder) encoder.end(msg) decoder.on('data', function (data) { t.deepEqual(data, msg, 'msg1 matches') }) decoder.on('end', function () { t.pass('ended') }) }) test('without streams', function (t) { t.plan(1) var channel = through2() var parser = nos.parser() var msg = { 'hello': 'world' } channel.on('data', function (buf) { parser.parse(buf) }) parser.on('message', function (data) { t.deepEqual(data, msg, 'msg1 matches') }) nos.writeToStream(msg, channel) channel.end() }) test('write to strem should accept a callback', function (t) { t.plan(2) var channel = through2() var parser = nos.parser() var msg = { 'hello': 'world' } channel.on('data', function (buf) { parser.parse(buf) }) parser.on('message', function (data) { t.deepEqual(data, msg, 'msg1 matches') }) nos.writeToStream(msg, channel, null, function () { t.pass('called') }) channel.end() })
{ "content_hash": "9cf7ac6abffe477dc69b903096c2c153", "timestamp": "", "source": "github", "line_count": 169, "max_line_length": 67, "avg_line_length": 20.893491124260354, "alnum_prop": 0.6139903709997168, "repo_name": "mcollina/net-object-stream", "id": "c4467dd3f65d219efc0011510bd430c9dfa9d1fb", "size": "3531", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "7284" } ], "symlink_target": "" }
layout: post title: "ITA Baranov's Walkthrough. Chapter 8" date: 2017-01-05 excerpt: "Linear Sorting" tag: - Sorting - Algorithms --- **Linear Sorting** {: style="text-align: center;"} The book has now introduced several algorithms that can sort n numbers in **O(nlgn)** time. Merge sort and heapsort achieve this upper bound in the worst case; quicksort achieves it on average. These algorithms share an interesting property: __the sorted order they determine is based only on comparisons between the input elements__. Thus, such sorting algorithms are called comparison sorts. By doing some math, you can prove that any comparison sort must make **Ω(nlgn)** comparisons in the worst case to sort n elements. Thus, merge sort and heapsort are asymptotically optimal, and no comparison sort exists that is faster by more than a constant factor. **Counting sort** {: style="text-align: center;"} Counting sort assumes that each of the n input elements is an integer in the range 0 to k, for some integer k. When k = O(n), the sort runs in Θ(n) time. <pre> COUNTING-SORT(A,B,k) let C[0..k] be a new array for i = 0 to k C[i] = 0 for j = 1 to A.length C[A[j]] = C[A[j]] + 1 // C[i] now contains the number of elements equal to i for i = 1 to k C[i] = C[i] + C[i - 1] // C[i] now has the number of elements less than or equal to i for j = A.length downto 1 B[C[A[j]]] = A[j] C[A[j]] = C[A[j]] - 1 </pre> Counting sort determines, for each input element x, the number of elements less than x. It uses this information to place element x directly into its position in the output array. In the code below we assume that the input is an array **A[1..n]**, and thus A.length = n. We need two other arrays: the array **B[1..n]** holds the sorted output, and the array **C[0..k]** provides temporary working storage. ![image-center](/images/countsort.png){: .align-center} How much time does counting sort require? The first for loop takes time Θ(k), second one takes time Θ(n), third - Θ(k), fourth - Θ(n). Thus, the overall time is Θ(k+n). In practice, the algorithm is used when we have k = O(n), in which case the running time is **Θ(n)**. Counting sort beats the comparison sorts' lower bound of Ω(nlgn). In fact, no comparisons between input elements occur anywhere in the code. Instead, counting sort uses the actual values of the elements to index into an array. An important property of counting sort is that it is **stable**: numbers with the same value appear in the output array in the same order as they do in the input array. This is important for our next algorithm. **Radix sort** {: style="text-align: center;"} Radix sort solves the sorting problem counterintuitively - by sorting on the **least significant digit** first. In order for it to work, the digit sorts must be stable. The code for radix sort is straightforward. The following procedure assumes that each element in the n-element array A has d digits, where digit 1 is the lowest-order digit and digit d is the highest-order digit. <pre> RADIX-SORT(A,d) for i = 1 to d use a stable sort to sort array A on digit i </pre> ![image-center](/images/radixsort.png){: .align-center} Is radix sort preferable to a comparison-based sorting algorithm, such as quicksort? Which sorting algorithm we prefer depends on the characteristics of the implementations, of the underlying machine (e.g., quicksort often uses hardware caches more effectively than radix sort), and of the input data. Moreover, the version of radix sort that uses counting sort as the intermediate stable sort does not sort in place, which many of the Θ(nlgn)-time comparison sorts do. Thus, when primary memory storage is at a premium, we might prefer an in-place algorithm such as quicksort. **Bucket sort** {: style="text-align: center;"} Bucket sort assumes that the input is drawn from a uniform distribution and has an average-case running time of **O(n)**. Like counting sort, bucket sort is fast because it assumes something about the input. Whereas counting sort assumes that the input consists of integers in a small range, bucket sort assumes that the input is **generated by a random process** that distributes elements **uniformly** and independently over the interval **[0,1)**. Bucket sort divides this interval into n equal-size subintervals, or **buckets**, and then distributes the n input numbers into the buckets. Since the inputs are uniformly and independently distributed, we don't expect many numbers to fall into each bucket. To produce the output, we simply sort the numbers in each bucket and then go through the buckets in order, listing the elements in each. <pre> BUCKET-SORT(A) n = A.length let B[0..n - 1] be a new array for i = 0 to n - 1 make B[i] an empty list for i = 1 to n insert A[i] into list B[floor(n*A[i])] for i = 0 to n - 1 sort list B[i] with insertion sort concat the lists B[0], B[1], ..., B[n - 1] together in order </pre> Even if the input is not drawn from a uniform distribution, bucket sort may still run in linear time. As long as the input has the property that the sum of the squares of the bucket sizes is linear in the total number of elements, the bucket sort will run in linear time.
{ "content_hash": "b430bb06e02beca0c6160333ad1cff78", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 659, "avg_line_length": 63.58536585365854, "alnum_prop": 0.741848868431147, "repo_name": "login-m/login-m.github.io", "id": "e92c73c4678cae14341984130c72df6be31a070e", "size": "5228", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2017-01-05-Algorithms-&-Data-Structures-8.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "31792" }, { "name": "HTML", "bytes": "204269" }, { "name": "JavaScript", "bytes": "2060" }, { "name": "Ruby", "bytes": "1442" } ], "symlink_target": "" }
package org.youtubedl.extractor; import java.io.IOException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.youtubedl.URLParser; import org.youtubedl.pojo.Error; import org.youtubedl.pojo.ResultData; import org.youtubedl.pojo.Video; /** * MGTV 视频地址解析 * * http://guid.mgtv.com/pc/distribute.do?callback=STK.$.getGUID&%5Bobject%20Object%5D=1506327096928 * */ public class Mgtv extends Common implements URLParser { private static final String apiUrl = "http://pcweb.api.mgtv.com/player/video?video_id=%s&cid=%s&keepPlay=0&vid=&watchTime=0"; private static final String GUID_URL = "http://guid.mgtv.com/pc/distribute.do"; private static final String LOGIN_USER = "http://u.api.mgtv.com/user/get_login_user?_=%s"; private String guid; private String __guid; private String stkuuid; private long actionTime; private String sessionid; private Map<String, String> cookies; @Override public ResultData parse(String url) { final ResultData resultData = new ResultData(); try { // 请求 __guid = getGUid(GUID_URL); this.stkuuid = UUID.randomUUID().toString(); if (cookies == null) { cookies = new HashMap<String, String>(); } sessionid = String.valueOf(System.currentTimeMillis()); cookies.put("__STKUUID", stkuuid); cookies.put("sessionid", sessionid); cookies.put("lastActionTime", String.valueOf(System.currentTimeMillis())); // 请求sessionid sendRequest(String.format(LOGIN_USER, String.valueOf(System.currentTimeMillis()))); String vid = matchVid(url); String cid = matchCid(url); guid = getGUid(GUID_URL); actionTime = System.currentTimeMillis(); // 拼装请求地址 String api = String.format(apiUrl, vid, cid); initCookies(); String responseJson = getResponseJson(api); JsonObject json = parserJsonObject(responseJson); JsonObject data = json.getAsJsonObject("data"); if (data != null && !data.isJsonNull()) { List<Video> videos = new ArrayList<Video>(); String domain = data.getAsJsonArray("stream_domain").get(0).getAsString(); JsonObject info = data.getAsJsonObject("info"); String title = info.get("title").getAsString(); String thumb = info.get("thumb").getAsString(); int duration = info.get("duration").getAsInt() * 1000; JsonArray stream = data.getAsJsonArray("stream"); for (JsonElement element : stream) { Video video = new Video(); video.setSrcUrl(url); video.setTitle(title); video.setLogo(thumb); video.setVideoMilliseconds(duration); JsonObject obj = element.getAsJsonObject(); video.setStreamType(obj.get("name").getAsString()); video.setHdtv(setHdtv(video.getStreamType())); String streamURL = obj.get("url").getAsString(); if (streamURL == null || "".equals(streamURL)) { continue; } String chk = UUID.randomUUID().toString().replace("-", ""); streamURL += "&ver=0.2.12943&chk=" + chk + "&ld" + sessionid; String urlData = getResponseJson(domain + streamURL); JsonObject urlJson = parserJsonObject(urlData); video.setPlayUrl(urlJson.get("info").getAsString()); videos.add(video); } sort(videos); resultData.setVideos(videos); return resultData; } else { resultData.setError(new Error(json.get("code").getAsInt(), json.get("msg").getAsString())); resultData.setVideos(null); return resultData; } } catch (Exception e) { resultData.setError(new Error(500, e.getMessage())); resultData.setVideos(null); return resultData; } } private void sendRequest(String url) throws IOException { try { Jsoup.connect(url) .headers(setHeaders()) .cookies(this.cookies) .timeout(TIMEOUT).ignoreContentType(true).execute(); } catch (IOException e) { throw e; } } /** * 请求JSON * @param url * @return */ @Override public String getResponseJson(String url) throws IOException { try { Connection.Response response = Jsoup.connect(url) .headers(setHeaders()) .cookies(cookies) .timeout(TIMEOUT).ignoreContentType(true).execute(); return response.body(); } catch (IOException e) { throw e; } } /** * cookies * __STKUUID=0df95871-eecf-4011-9441-45c5493c4089; * MQGUID=912254546565664768; * Hm_lvt_7ed5b39fd087844c0268537a47e35211=1506333377; * Hm_lpvt_7ed5b39fd087844c0268537a47e35211=1506333377; * __MQGUID=912254546477584384; * lastActionTime=1506333377729 * */ private void initCookies() { if (cookies == null) { this.cookies = new HashMap<String, String>(); } cookies.put("MQGUID", guid); cookies.put("Hm_lvt_7ed5b39fd087844c0268537a47e35211", String.valueOf(actionTime/1000)); cookies.put("Hm_lpvt_7ed5b39fd087844c0268537a47e35211", String.valueOf(actionTime/1000)); cookies.put("__MQGUID", __guid); cookies.put("lastActionTime", String.valueOf(actionTime)); } /** * 从源URL中获取 vid * @param videoUrl * @return */ private String matchVid(String videoUrl) { return videoUrl.substring(videoUrl.lastIndexOf("/") + 1, videoUrl.lastIndexOf(".")); } private String matchCid (String videoUrl) { Matcher matcher = Pattern.compile("b/(.*?)/").matcher(videoUrl); if (matcher.find()) { return matcher.group(1); } return null; } private String setHdtv(String streamType) { if ("标清".equals(streamType)) { return "h3"; } else if ("高清".equals(streamType)) { return "h2"; } else if ("超清".equals(streamType)) { return "h1"; } else { return "h3"; } } private String getGUid(String url) { try { Connection.Response response = super.getResponse(url); Map<String, String> cookies = response.cookies(); if (cookies != null && cookies.containsKey("MQGUID")) { return cookies.get("MQGUID"); } } catch (IOException e) { e.printStackTrace(); } return null; } }
{ "content_hash": "50acb7554db4b50440a8b385e8455755", "timestamp": "", "source": "github", "line_count": 210, "max_line_length": 126, "avg_line_length": 28.84285714285714, "alnum_prop": 0.6783886412415387, "repo_name": "Andy11260/youtubedl-java", "id": "ce58f93cd542bf1282703b578bc4204288cd00a6", "size": "6115", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/youtubedl/extractor/Mgtv.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "77579" } ], "symlink_target": "" }
<?php namespace Acme\DevBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class AcmeDevBundle extends Bundle { }
{ "content_hash": "0121e4bfc0151acca83b0745b6d09736", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 47, "avg_line_length": 13.555555555555555, "alnum_prop": 0.7950819672131147, "repo_name": "shacme/app", "id": "1eebe6cdd9bcd6735b5820c27827ec76d27377d0", "size": "122", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Acme/DevBundle/AcmeDevBundle.php", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(), new Symfony\Bundle\AsseticBundle\AsseticBundle(), new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(), new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), new JMS\AopBundle\JMSAopBundle(), new JMS\DiExtraBundle\JMSDiExtraBundle($this), new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(), new NilsWisiol\CreditCardBundle\NilsWisiolCreditCardBundle(), ); if (in_array($this->getEnvironment(), array('dev', 'test'))) { $bundles[] = new Acme\DemoBundle\AcmeDemoBundle(); $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(); } return $bundles; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml'); } }
{ "content_hash": "48fe720004357a44e0b9c1231a661a4c", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 89, "avg_line_length": 40.84615384615385, "alnum_prop": 0.6691776522284997, "repo_name": "nils-wisiol/creditcard", "id": "83b260ed7c01d875c1e67c1819438edbf41db1eb", "size": "1593", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/AppKernel.php", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "56264" }, { "name": "PHP", "bytes": "61733" }, { "name": "Perl", "bytes": "794" } ], "symlink_target": "" }
package com.mattunderscore.specky.generator; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import java.util.Arrays; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import com.mattunderscore.specky.model.ImplementationDesc; import com.mattunderscore.specky.model.PropertyDesc; import com.mattunderscore.specky.model.SpecDesc; import com.mattunderscore.specky.model.TypeDesc; import com.mattunderscore.specky.model.ValueDesc; import com.squareup.javapoet.TypeSpec; /** * Unit tests for {@link TypeGenerator}. * * @author Matt Champion on 07/12/2016 */ public class TypeGeneratorTest { @Mock private TypeInitialiser<ImplementationDesc> typeInitialiser; @Mock private TypeAppender<ImplementationDesc> constructionMethodAppender; @Mock private TypeAppender<TypeDesc> superTypeAppender; @Mock private TypeAppenderForProperty<ImplementationDesc> fieldGeneratorForProperty; @Mock private TypeAppenderForProperty<ImplementationDesc> methodGeneratorForProperty; @Mock private TypeAppender<ImplementationDesc> methodGeneratorForType; private final SpecDesc specDesc = SpecDesc.builder().build(); private final PropertyDesc propertyDesc = PropertyDesc.builder().build(); private final ImplementationDesc implementationDesc = ValueDesc .builder() .properties(singletonList(propertyDesc)) .build(); private final TypeSpec.Builder typeBuilder = TypeSpec.classBuilder("A"); @Before public void setUp() { initMocks(this); when(typeInitialiser.create(isA(SpecDesc.class), isA(ImplementationDesc.class))).thenReturn(typeBuilder); } @Test public void generate() { final TypeGenerator<ImplementationDesc> generator = new TypeGenerator<>( typeInitialiser, Arrays.<TypeAppender<? super ImplementationDesc>>asList( constructionMethodAppender, superTypeAppender, methodGeneratorForType), asList(fieldGeneratorForProperty, methodGeneratorForProperty)); generator.generate(specDesc, implementationDesc); verify(typeInitialiser).create(specDesc, implementationDesc); verify(constructionMethodAppender).append(typeBuilder, specDesc, implementationDesc); verify(methodGeneratorForProperty).append(typeBuilder, specDesc, implementationDesc, propertyDesc); verify(methodGeneratorForType).append(isA(TypeSpec.Builder.class), eq(specDesc), eq(implementationDesc)); } }
{ "content_hash": "e5122db6111fafe7017174a85c09f1d8", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 113, "avg_line_length": 36.33766233766234, "alnum_prop": 0.7558970693352395, "repo_name": "mattunderscorechampion/specky", "id": "b3660fff28d74cc71d3eba580c4760a3da284cbf", "size": "4298", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "code-generation/src/test/java/com/mattunderscore/specky/generator/TypeGeneratorTest.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ANTLR", "bytes": "11471" }, { "name": "Java", "bytes": "683788" }, { "name": "Python", "bytes": "45213" }, { "name": "Ruby", "bytes": "22609" } ], "symlink_target": "" }
<?php namespace app\models; use Yii; use yii\behaviors\TimestampBehavior; /** * This is the model class for table "albums". * * @property integer $id * @property integer $user_id * @property string $name * @property integer $active * @property integer $created_at * @property integer $modified_at * * @property AlbumClients[] $albumClients * @property AlbumImages[] $albumImages * @property Users $user */ class Albums extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'albums'; } /** * @inheritdoc */ public function rules() { return [ [['name'], 'required'], [['user_id', 'active'], 'integer'], [['created_at', 'modified_at'], 'safe'], [['name'], 'string', 'max' => 50], [['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => Users::className(), 'targetAttribute' => ['user_id' => 'id']], [['user_id'], 'default', 'value' => function () { return \Yii::$app->user->identity->id; }] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'user_id' => 'User ID', 'name' => 'Name', 'active' => 'Active', 'created_at' => 'Created At', 'modified_at' => 'Modified At', ]; } public function extraFields() { return ['albumImages']; } /** * @return \yii\db\ActiveQuery */ public function getAlbumClients() { return $this->hasMany(AlbumClients::className(), ['album_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getAlbumImages() { return $this->hasMany(AlbumImages::className(), ['album_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getUser() { return $this->hasOne(Users::className(), ['id' => 'user_id']); } /** * @return array */ public function behaviors() { return [ [ 'class' => TimestampBehavior::className(), 'attributes' => [ \yii\db\ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'modified_at'], \yii\db\ActiveRecord::EVENT_BEFORE_UPDATE => ['modified_at'], ], ], ]; } /** * @param $idUser * @return array */ public static function getClientAlbums($idUser) { $albums = null; $i = 0; $clientAlbums = array(); $albums = AlbumClients::find() ->select('album_id') ->where([ 'user_id' => $idUser, ]) ->asArray() ->all(); foreach ($albums as $album) { $clientAlbums[$i] = $album['album_id']; $i++; } return $clientAlbums; } /** * @param $id * @param $userId * @return array|null|\yii\db\ActiveRecord[] */ public static function getAlbumAllow($id, $userId) { $album = null; $album = AlbumClients::find() ->where([ 'user_id' => $userId, 'album_id' => $id, ]) ->all(); return $album; } }
{ "content_hash": "dd42319f39d165792b515933035525ea", "timestamp": "", "source": "github", "line_count": 153, "max_line_length": 137, "avg_line_length": 22.405228758169933, "alnum_prop": 0.4684947491248541, "repo_name": "NatalyMac/InterPhotoNew", "id": "dc7d55d912cb711cc487ab59a70c4e0e093c39ee", "size": "3428", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "models/Albums.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "1030" }, { "name": "CSS", "bytes": "11183" }, { "name": "HTML", "bytes": "458255" }, { "name": "JavaScript", "bytes": "115493" }, { "name": "PHP", "bytes": "501412" } ], "symlink_target": "" }
using System; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; using OpenQA.Selenium.Internal; namespace OpenQA.Selenium.Safari { /// <summary> /// Exposes the service provided by the native SafariDriver executable. /// </summary> public sealed class SafariDriverService : DriverService { private const string DefaultSafariDriverServiceExecutableName = "safaridriver"; private const string DefaultSafariDriverServiceExecutablePath = "/usr/bin"; private static readonly Uri SafariDriverDownloadUrl = new Uri("http://apple.com"); private bool useLegacyProtocol; /// <summary> /// Initializes a new instance of the <see cref="SafariDriverService"/> class. /// </summary> /// <param name="executablePath">The full path to the SafariDriver executable.</param> /// <param name="executableFileName">The file name of the SafariDriver executable.</param> /// <param name="port">The port on which the SafariDriver executable should listen.</param> private SafariDriverService(string executablePath, string executableFileName, int port) : base(executablePath, port, executableFileName, SafariDriverDownloadUrl) { } /// <summary> /// Gets or sets a value indicating whether to use the default open-source project /// dialect of the protocol instead of the default dialect compliant with the /// W3C WebDriver Specification. /// </summary> /// <remarks> /// This is only valid for versions of the driver for Safari that target Safari 12 /// or later, and will result in an error if used with prior versions of the driver. /// </remarks> public bool UseLegacyProtocol { get { return this.useLegacyProtocol; } set { this.useLegacyProtocol = value; } } /// <summary> /// Gets the command-line arguments for the driver service. /// </summary> protected override string CommandLineArguments { get { StringBuilder argsBuilder = new StringBuilder(base.CommandLineArguments); if (this.useLegacyProtocol) { argsBuilder.Append(" --legacy"); } return argsBuilder.ToString(); } } /// <summary> /// Gets a value indicating the time to wait for the service to terminate before forcing it to terminate. /// For the Safari driver, there is no time for termination /// </summary> protected override TimeSpan TerminationTimeout { // Use a very small timeout for terminating the Safari driver, // because the executable does not have a clean shutdown command, // which means we have to kill the process. Using a short timeout // gets us to the termination point much faster. get { return TimeSpan.FromMilliseconds(100); } } /// <summary> /// Gets a value indicating whether the service has a shutdown API that can be called to terminate /// it gracefully before forcing a termination. /// </summary> protected override bool HasShutdown { // The Safari driver executable does not have a clean shutdown command, // which means we have to kill the process. get { return false; } } /// <summary> /// Gets a value indicating whether the service is responding to HTTP requests. /// </summary> protected override bool IsInitialized { get { bool isInitialized = false; Uri serviceHealthUri = new Uri(this.ServiceUrl, new Uri("/session/FakeSessionIdForPollingPurposes", UriKind.Relative)); // Since Firefox driver won't implement the /session end point (because // the W3C spec working group stupidly decided that it isn't necessary), // we'll attempt to poll for a different URL which has no side effects. // We've chosen to poll on the "quit" URL, passing in a nonexistent // session id. using (var httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.ConnectionClose = true; httpClient.Timeout = TimeSpan.FromSeconds(5); using (var httpRequest = new HttpRequestMessage(HttpMethod.Delete, serviceHealthUri)) { try { using (var httpResponse = Task.Run(async () => await httpClient.SendAsync(httpRequest)).GetAwaiter().GetResult()) { isInitialized = (httpResponse.StatusCode == HttpStatusCode.OK || httpResponse.StatusCode == HttpStatusCode.InternalServerError || httpResponse.StatusCode == HttpStatusCode.NotFound) && httpResponse.Content.Headers.ContentType.MediaType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase); } } // Checking the response from deleting a nonexistent session. Note that we are simply // checking that the HTTP status returned is a 200 status, and that the resposne has // the correct Content-Type header. A more sophisticated check would parse the JSON // response and validate its values. At the moment we do not do this more sophisticated // check. catch (Exception ex) when (ex is HttpRequestException || ex is TaskCanceledException) { Console.WriteLine(ex); } } } return isInitialized; } } /// <summary> /// Creates a default instance of the SafariDriverService. /// </summary> /// <returns>A SafariDriverService that implements default settings.</returns> public static SafariDriverService CreateDefaultService() { return CreateDefaultService(DefaultSafariDriverServiceExecutablePath); } /// <summary> /// Creates a default instance of the SafariDriverService using a specified path to the SafariDriver executable. /// </summary> /// <param name="driverPath">The directory containing the SafariDriver executable.</param> /// <returns>A SafariDriverService using a random port.</returns> public static SafariDriverService CreateDefaultService(string driverPath) { return CreateDefaultService(driverPath, DefaultSafariDriverServiceExecutableName); } /// <summary> /// Creates a default instance of the SafariDriverService using a specified path to the SafariDriver executable with the given name. /// </summary> /// <param name="driverPath">The directory containing the SafariDriver executable.</param> /// <param name="driverExecutableFileName">The name of the SafariDriver executable file.</param> /// <returns>A SafariDriverService using a random port.</returns> public static SafariDriverService CreateDefaultService(string driverPath, string driverExecutableFileName) { return new SafariDriverService(driverPath, driverExecutableFileName, PortUtilities.FindFreePort()); } } }
{ "content_hash": "8caeeb17fe2608c77b145045003d22fa", "timestamp": "", "source": "github", "line_count": 169, "max_line_length": 157, "avg_line_length": 46.289940828402365, "alnum_prop": 0.6009203630320848, "repo_name": "titusfortner/selenium", "id": "f8ecbf9c6cb4d54d70b25bd4251efa7c71e30efe", "size": "8714", "binary": false, "copies": "3", "ref": "refs/heads/trunk", "path": "dotnet/src/webdriver/Safari/SafariDriverService.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP.NET", "bytes": "825" }, { "name": "Batchfile", "bytes": "4443" }, { "name": "C", "bytes": "82917" }, { "name": "C#", "bytes": "2989900" }, { "name": "C++", "bytes": "2285448" }, { "name": "CSS", "bytes": "1049" }, { "name": "Dockerfile", "bytes": "1737" }, { "name": "HTML", "bytes": "1379853" }, { "name": "Java", "bytes": "6305900" }, { "name": "JavaScript", "bytes": "2535570" }, { "name": "Makefile", "bytes": "4655" }, { "name": "PowerShell", "bytes": "213" }, { "name": "Python", "bytes": "987676" }, { "name": "Ragel", "bytes": "3086" }, { "name": "Ruby", "bytes": "1038887" }, { "name": "Rust", "bytes": "47487" }, { "name": "Shell", "bytes": "29996" }, { "name": "Starlark", "bytes": "399974" }, { "name": "TypeScript", "bytes": "126843" }, { "name": "XSLT", "bytes": "1047" } ], "symlink_target": "" }
[@kijuky]: https://github.com/kijuky [5962]: https://github.com/sbt/sbt/issues/5962 ### Fixes with compatibility implications - The output of the dependencyTree will not be truncated at the console width. ### Improvements - Enable the asciiGraphWidth setting in the dependencyTree tasks. ### Bug fixes
{ "content_hash": "d0c7d1dac1dfce9ef7c38762a342731c", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 78, "avg_line_length": 23.692307692307693, "alnum_prop": 0.7532467532467533, "repo_name": "xuwei-k/xsbt", "id": "93fd60d1f1a48dc5805a2d40e7c14515f2550a71", "size": "308", "binary": false, "copies": "3", "ref": "refs/heads/develop", "path": "notes/1.6.0/enable-asciiGraphWidth-in-dependencyTree.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "968" }, { "name": "C++", "bytes": "508" }, { "name": "Java", "bytes": "36685" }, { "name": "Makefile", "bytes": "4356" }, { "name": "Roff", "bytes": "4443" }, { "name": "Scala", "bytes": "2532012" }, { "name": "Shell", "bytes": "208" }, { "name": "TypeScript", "bytes": "4954" } ], "symlink_target": "" }
package openmods.igw.impl.integration.openblocks; import com.google.common.collect.Lists; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import org.apache.commons.lang3.tuple.Pair; import igwmod.gui.IReservedSpace; import igwmod.gui.LocatedTexture; import openmods.igw.prefab.handler.OpenModsWikiTab; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; /* * WARNING! * The addition of new static pages most likely requires the editing of the * search bar's position and the amount of items shown in the wiki * tab. These edits have to be performed in the methods: * pagesPerTab() (where you need to edit the amount of items shown, usually diminishing by 2 every time) * getReservedSpaces() (where the y of the located texture must be edited to allow for a design-compatible number). */ public final class OpenBlocksWikiTab extends OpenModsWikiTab { private static final int SEARCH_AND_SCROLLBAR_Y = 98; private static final int ITEM_GRID_DEFAULT_X = 40; private static final int ITEM_GRID_DEFAULT_Y = 110; private static final int ITEM_GRID_DEFAULT_SLOT_DIMENSION = 16; private static final int ITEM_GRID_DEFAULT_WIDTH = ITEM_GRID_DEFAULT_SLOT_DIMENSION * 2 + 4; private static final int ITEM_GRID_DEFAULT_HEIGHT = ITEM_GRID_DEFAULT_SLOT_DIMENSION * 6 + 12; public OpenBlocksWikiTab(final List<Pair<String, ItemStack>> stacks, final Map<String, ItemStack> allClaimedPages, final Map<String, Class<? extends Entity>> allClaimedEntities) { super(stacks, allClaimedPages, allClaimedEntities, new IItemPositionProvider() { @Override public int getX(final int entryId) { return 4 * 10 + 1 + entryId % 2 * (10 + 8); } @Override public int getY(final int entryId) { return 100 + 10 + 1 + entryId / 2 * (10 + 8); } }); this.addPageToStaticPages(createStaticPageFactory("about", this, CommonPositionProviders.STATIC_PAGES)); this.addPageToStaticPages(createStaticPageFactory("credits", this, CommonPositionProviders.STATIC_PAGES)); this.addPageToStaticPages(createStaticPageFactory("obUtils", this, CommonPositionProviders.STATIC_PAGES)); this.addPageToStaticPages(createStaticPageFactory("bKey", this, CommonPositionProviders.STATIC_PAGES)); this.addPageToStaticPages(createStaticPageFactory("enchantments", this, CommonPositionProviders.STATIC_PAGES)); this.addPageToStaticPages(createStaticPageFactory("changelog", this, CommonPositionProviders.STATIC_PAGES)); } @Override public String getTabName() { return "wiki.openblocks.tab"; } @Override public String getPageName() { return "wiki.openblocks.page"; } @Override public List<IReservedSpace> getReservedSpaces() { final List<IReservedSpace> reservedSpaces = Lists.newArrayList(); final ResourceLocation textureLocation = new ResourceLocation("openmods-igw", "textures/gui/wiki/6x2.png"); reservedSpaces.add( new LocatedTexture(textureLocation, ITEM_GRID_DEFAULT_X, ITEM_GRID_DEFAULT_Y, ITEM_GRID_DEFAULT_WIDTH, ITEM_GRID_DEFAULT_HEIGHT)); return reservedSpaces; } @Override public int getSearchBarAndScrollStartY() { return SEARCH_AND_SCROLLBAR_Y; } @Override public int pagesPerTab() { return 10 + 2; } @Override public int pagesPerScroll() { return 2; } @Nonnull @Override protected List<Block> getBlockCandidates() { return Lists.newArrayList(OpenBlocksItemHolder.FLAG, Blocks.SPONGE); } }
{ "content_hash": "cce3362e1f04fae54733e74d44deb480", "timestamp": "", "source": "github", "line_count": 106, "max_line_length": 119, "avg_line_length": 36.924528301886795, "alnum_prop": 0.6926417986714358, "repo_name": "OpenMods/OpenMods-IGW", "id": "c0780b609a40a2205ee067728e5899be943b5614", "size": "5055", "binary": false, "copies": "1", "ref": "refs/heads/1.10.2", "path": "src/main/java/openmods/igw/impl/integration/openblocks/OpenBlocksWikiTab.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "299791" }, { "name": "XSLT", "bytes": "54764" } ], "symlink_target": "" }
package com.streamsets.pipeline.stage.origin.elasticsearch; import com.google.common.base.Throwables; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonParser; import com.streamsets.pipeline.api.OnRecordError; import com.streamsets.pipeline.api.Record; import com.streamsets.pipeline.api.Stage; import com.streamsets.pipeline.api.StageException; import com.streamsets.pipeline.sdk.PushSourceRunner; import com.streamsets.pipeline.stage.config.elasticsearch.ElasticsearchSourceConfig; import com.streamsets.pipeline.stage.config.elasticsearch.Errors; import com.streamsets.pipeline.stage.elasticsearch.common.ElasticsearchBaseIT; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.elasticsearch.client.Response; import org.elasticsearch.client.RestClient; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import static com.google.gson.FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES; import static java.util.concurrent.TimeUnit.SECONDS; import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class ElasticsearchSourceIT extends ElasticsearchBaseIT { private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchSourceIT.class); private static RestClient restClient; @BeforeClass public static void setUp() throws Exception { ElasticsearchBaseIT.setUp(); // Create index and add data HttpHost host = new HttpHost("127.0.0.1", esHttpPort); restClient = RestClient.builder(host).build(); HttpEntity entity = new StringEntity( "{\"mappings\":{\"tweet\":{\"properties\":{\"message\":{\"type\":\"text\"},\"timestamp\":{\"type\":\"date\"}}}}}" ); restClient.performRequest( "PUT", "/twitter", new HashMap<>(), entity ); final int numTestDocs = 100; for (int i = 1; i <= numTestDocs; i++) { restClient.performRequest("PUT", "/twitter/tweet/" + i, new HashMap<>(), makeTweet()); } await().atMost(5, SECONDS).until(() -> dataIsAvailable(restClient, numTestDocs)); LOG.info("Finished setup"); } private static boolean dataIsAvailable(RestClient restClient, int size) { try { Response r = restClient.performRequest("GET", "/twitter/tweet/_search?size=" + size); Reader reader = new InputStreamReader(r.getEntity().getContent()); JsonArray hits = new JsonParser() .parse(reader) .getAsJsonObject() .getAsJsonObject("hits") .getAsJsonArray("hits"); return hits.size() == size; } catch (IOException ignored) { return false; } } private static HttpEntity makeTweet() { final String body = String.format( "{\"message\":\"%s\",\"timestamp\":%d}", UUID.randomUUID().toString(), System.currentTimeMillis() ); LOG.debug("Tweet: '{}'", body); return new StringEntity( body, ContentType.APPLICATION_JSON ); } @AfterClass public static void cleanUp() throws Exception { ElasticsearchBaseIT.cleanUp(); } @Test public void testBatchModeSingleBatch() throws Exception { ElasticsearchSourceConfig conf = new ElasticsearchSourceConfig(); conf.httpUris = Collections.singletonList("127.0.0.1:" + esHttpPort); conf.index = "twitter"; conf.mapping = "tweet"; ElasticsearchSource source = new ElasticsearchSource(conf); PushSourceRunner runner = new PushSourceRunner.Builder(ElasticsearchDSource.class, source) .addOutputLane("lane") .build(); runner.runInit(); try { runner.runProduce(Collections.emptyMap(), 5, output -> { runner.setStop(); assertNotEquals(null, output.getNewOffset()); List<Record> records = output.getRecords().get("lane"); assertEquals(5, records.size()); }); } finally { runner.runDestroy(); } } @Test public void testBatchModeToCompletion() throws Exception { ElasticsearchSourceConfig conf = new ElasticsearchSourceConfig(); conf.httpUris = Collections.singletonList("127.0.0.1:" + esHttpPort); conf.index = "twitter"; conf.mapping = "tweet"; conf.numSlices = 2; ElasticsearchSource source = new ElasticsearchSource(conf); PushSourceRunner runner = new PushSourceRunner.Builder(ElasticsearchDSource.class, source) .addOutputLane("lane") .build(); runner.runInit(); try { final Map<String, String> offsets = new HashMap<>(); final List<Record> records = Collections.synchronizedList(new ArrayList<>(5)); AtomicInteger batchCount = new AtomicInteger(0); runner.runProduce(offsets, 5, output -> { synchronized (records) { records.addAll(output.getRecords().get("lane")); } batchCount.incrementAndGet(); }); runner.waitOnProduce(); // Last batch is empty signaling finish assertEquals(22, batchCount.get()); assertEquals(100, records.size()); } finally { runner.runDestroy(); } } @Test public void testCursorExpiredNoDelete() throws Exception { ElasticsearchSourceConfig conf = new ElasticsearchSourceConfig(); conf.httpUris = Collections.singletonList("127.0.0.1:" + esHttpPort); conf.index = "twitter"; conf.mapping = "tweet"; conf.deleteCursor = false; ElasticsearchSource source = new ElasticsearchSource(conf); PushSourceRunner runner = new PushSourceRunner.Builder(ElasticsearchDSource.class, source) .setOnRecordError(OnRecordError.TO_ERROR) .addOutputLane("lane") .build(); runner.runInit(); try { final Map<String, String> offsets = new HashMap<>(); AtomicInteger batchCounter = new AtomicInteger(0); runner.runProduce(offsets, 5, output -> { offsets.put("0", output.getNewOffset()); int batchCount = batchCounter.incrementAndGet(); if (batchCount == 1) { deleteAllCursors(); } else if (batchCount > 1) { fail("Expected a StageException due to expired cursor"); } }); runner.waitOnProduce(); assertEquals(1, batchCounter.get()); } catch (Exception e) { List<Throwable> stageExceptions = Throwables.getCausalChain(e) .stream() .filter(t -> StageException.class.isAssignableFrom(t.getClass())) .collect(Collectors.toList()); assertEquals(1, stageExceptions.size()); assertEquals(Errors.ELASTICSEARCH_23, ((StageException) stageExceptions.get(0)).getErrorCode()); } finally { runner.runDestroy(); } } @Test public void testCursorExpiredDefault() throws Exception { ElasticsearchSourceConfig conf = new ElasticsearchSourceConfig(); conf.httpUris = Collections.singletonList("127.0.0.1:" + esHttpPort); conf.index = "twitter"; conf.mapping = "tweet"; conf.deleteCursor = true; ElasticsearchSource source = new ElasticsearchSource(conf); PushSourceRunner runner = new PushSourceRunner.Builder(ElasticsearchDSource.class, source) .addOutputLane("lane") .setOnRecordError(OnRecordError.TO_ERROR) .build(); runner.runInit(); final Map<String, String> offsets = new HashMap<>(); try { AtomicInteger batchCounter = new AtomicInteger(0); runner.runProduce(offsets, 5, output -> { offsets.put("0", output.getNewOffset()); int batch = batchCounter.incrementAndGet(); if (batch == 1) { deleteAllCursors(); // Because getNewOffset does not work. } else if (batch == 2) { assertEquals(5, output.getRecords().get("lane").size()); runner.setStop(); } }); runner.waitOnProduce(); assertEquals(2, batchCounter.get()); } finally { runner.runDestroy(); } } private void deleteAllCursors() { try { restClient.performRequest("DELETE", "/_search/scroll/_all"); } catch (IOException e) { throw Throwables.propagate(e); } } @Test public void testInvalidIncrementalQuery() throws Exception { ElasticsearchSourceConfig conf = new ElasticsearchSourceConfig(); conf.httpUris = Collections.singletonList("127.0.0.1:" + esHttpPort); conf.index = "twitter"; conf.mapping = "tweet"; conf.query = "{}"; conf.isIncrementalMode = true; conf.offsetField = "timestamp"; conf.initialOffset = "now-1d/d"; ElasticsearchSource source = new ElasticsearchSource(conf); PushSourceRunner runner = new PushSourceRunner.Builder(ElasticsearchDSource.class, source) .addOutputLane("lane") .build(); List<Stage.ConfigIssue> issues = runner.runValidateConfigs(); assertEquals(1, issues.size()); assertTrue(issues.get(0).toString().contains(Errors.ELASTICSEARCH_25.getCode())); } @Test public void testIncrementalMode() throws Exception { ElasticsearchSourceConfig conf = new ElasticsearchSourceConfig(); conf.httpUris = Collections.singletonList("127.0.0.1:" + esHttpPort); conf.index = "twitter"; conf.mapping = "tweet"; conf.query = "{\"sort\":[{\"timestamp\":{\"order\":\"asc\"}}],\"query\":{\"range\":{\"timestamp\":{\"gt\":${offset}}}}}"; conf.isIncrementalMode = true; conf.offsetField = "timestamp"; conf.initialOffset = "now-1d/d"; ElasticsearchSource source = new ElasticsearchSource(conf); PushSourceRunner runner = new PushSourceRunner.Builder(ElasticsearchDSource.class, source) .addOutputLane("lane") .build(); runner.runInit(); try { final Map<String, String> offsets = new HashMap<>(); final List<Record> records = new ArrayList<>(5); AtomicInteger batchCount = new AtomicInteger(0); AtomicInteger lastBatchRecordCount = new AtomicInteger(-1); runner.runProduce(offsets, 5, output -> { offsets.put("0", output.getNewOffset()); List<Record> list = output.getRecords().get("lane"); records.addAll(list); if (batchCount.incrementAndGet() == 21) { // No new records, but we should have made a request. // 20th batch would have finished the first query. lastBatchRecordCount.set(list.size()); runner.setStop(); } }); runner.waitOnProduce(); assertEquals(0, lastBatchRecordCount.get()); assertEquals(21, batchCount.get()); assertEquals(100, records.size()); } finally { runner.runDestroy(); } } @Test public void testIncrementalModeWithQueryInterval() throws Exception { ElasticsearchSourceConfig conf = new ElasticsearchSourceConfig(); conf.httpUris = Collections.singletonList("127.0.0.1:" + esHttpPort); conf.index = "twitter"; conf.mapping = "tweet"; conf.query = "{\"sort\":[{\"timestamp\":{\"order\":\"asc\"}}],\"query\":{\"range\":{\"timestamp\":{\"gt\":${offset}}}}}"; conf.isIncrementalMode = true; conf.offsetField = "timestamp"; conf.initialOffset = "now-1d/d"; conf.queryInterval = 5; ElasticsearchSource source = new ElasticsearchSource(conf); PushSourceRunner runner = new PushSourceRunner.Builder(ElasticsearchDSource.class, source) .addOutputLane("lane") .build(); runner.runInit(); try { final Map<String, String> offsets = new HashMap<>(); final List<Record> records = new ArrayList<>(5); AtomicInteger batchCount = new AtomicInteger(0); AtomicInteger lastBatchRecordCount = new AtomicInteger(-1); runner.runProduce(offsets, 5, output -> { offsets.put("0", output.getNewOffset()); List<Record> list = output.getRecords().get("lane"); records.addAll(list); if (batchCount.incrementAndGet() == 22) { lastBatchRecordCount.set(list.size()); runner.setStop(); } }); await().atLeast(5, SECONDS).atMost(6, SECONDS).until(() -> { try { runner.waitOnProduce(); } catch (final Exception ex) { throw new RuntimeException(ex); } }); assertEquals(22, batchCount.get()); assertEquals(0, lastBatchRecordCount.get()); assertEquals(100, records.size()); } finally { runner.runDestroy(); } } @Test public void testParallelismChanged() throws Exception { ElasticsearchSourceConfig conf = new ElasticsearchSourceConfig(); conf.httpUris = Collections.singletonList("127.0.0.1:" + esHttpPort); conf.index = "twitter"; conf.mapping = "tweet"; conf.query = "{\"sort\":[{\"timestamp\":{\"order\":\"asc\"}}],\"query\":{\"range\":{\"timestamp\":{\"gt\":${offset}}}}}"; conf.isIncrementalMode = true; conf.offsetField = "timestamp"; conf.initialOffset = "now-1d/d"; conf.numSlices = 2; ElasticsearchSource source = new ElasticsearchSource(conf); PushSourceRunner runner = new PushSourceRunner.Builder(ElasticsearchDSource.class, source) .addOutputLane("lane") .build(); runner.runInit(); try { final Map<String, String> offsets = new HashMap<>(); final Gson GSON = new GsonBuilder().setFieldNamingPolicy(LOWER_CASE_WITH_UNDERSCORES).create(); String offset = GSON.toJson(new ElasticsearchSourceOffset(null, String.valueOf(System.currentTimeMillis()))); offsets.put("0", offset); AtomicInteger batchCount = new AtomicInteger(0); runner.runProduce(offsets, 5, output -> batchCount.incrementAndGet()); runner.waitOnProduce(); assertEquals(0, batchCount.get()); } catch (Exception e) { List<Throwable> stageExceptions = Throwables.getCausalChain(e) .stream() .filter(t -> StageException.class.isAssignableFrom(t.getClass())) .collect(Collectors.toList()); assertEquals(1, stageExceptions.size()); assertEquals(Errors.ELASTICSEARCH_26, ((StageException) stageExceptions.get(0)).getErrorCode()); } finally { runner.runDestroy(); } } }
{ "content_hash": "45fe2062cdc91f6b6f96414b91b90254", "timestamp": "", "source": "github", "line_count": 426, "max_line_length": 121, "avg_line_length": 34.41079812206573, "alnum_prop": 0.6663483184391841, "repo_name": "kunickiaj/datacollector", "id": "e82abd0902a063702f2276a130b233467b067bcd", "size": "15257", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "elasticsearch-protolib/src/test/java/com/streamsets/pipeline/stage/origin/elasticsearch/ElasticsearchSourceIT.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "101291" }, { "name": "CSS", "bytes": "120603" }, { "name": "Groovy", "bytes": "11876" }, { "name": "HTML", "bytes": "529009" }, { "name": "Java", "bytes": "20332072" }, { "name": "JavaScript", "bytes": "1070828" }, { "name": "Python", "bytes": "7413" }, { "name": "Scala", "bytes": "6347" }, { "name": "Shell", "bytes": "30088" } ], "symlink_target": "" }
////////////////////////////////////////////////////////////////// // (c) Copyright 2003 by Jeongnim Kim ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// // National Center for Supercomputing Applications & // Materials Computation Center // University of Illinois, Urbana-Champaign // Urbana, IL 61801 // e-mail: [email protected] // Tel: 217-244-6319 (NCSA) 217-333-3324 (MCC) // // Supported by // National Center for Supercomputing Applications, UIUC // Materials Computation Center, UIUC ////////////////////////////////////////////////////////////////// // -*- C++ -*- #ifndef QMCPLUSPLUS_SPHERICALORBITALSET_H #define QMCPLUSPLUS_SPHERICALORBITALSET_H #include "Particle/DistanceTableData.h" #include "ParticleBase/ParticleAttribOps.h" #include "Numerics/SphericalTensor.h" #include "QMCWaveFunctions/OrbitalSetTraits.h" namespace qmcplusplus { /**Class to represent a set of spherical orbitals centered at a common origin origin. * *Each basis orbital is represented by \f[ \phi_i({\bf r_{jC}}) = R_{n_i l_i}(r_{jC}) \Re (Y_{l_i}^{m_i}({\bf \hat{r_{jC}}})) \f] Here \f${\bf r_{jC}} = {\bf r_j - R_C}\f$ denotes the position of particle \f$ j \f$ relative to the center \f$ C \f$. * The template (R)adial(O)rbital(T)ype should provide <ul> <li> evaluate(r,rinv) <li> Y <li> dY <li> d2Y </ul> The template (G)rid(T)ype should provide <ul> <li> index(r) </ul> Examples of ROT being GenericSTO and OneDimGridFunctor * Examples of GT being LogGrid, LinearGrid, LogGridZero and NumericalGrid */ template<class ROT, class GT=DummyGrid> struct SphericalOrbitalSet { typedef ROT RadialOrbital_t; typedef typename ROT::value_type value_type; typedef typename OrbitalSetTraits<value_type>::RealType RealType; typedef typename OrbitalSetTraits<value_type>::ValueType ValueType; typedef typename OrbitalSetTraits<value_type>::IndexType IndexType; typedef typename OrbitalSetTraits<value_type>::PosType PosType; typedef typename OrbitalSetTraits<value_type>::GradType GradType; typedef typename OrbitalSetTraits<value_type>::ValueVector_t ValueVector_t; typedef typename OrbitalSetTraits<value_type>::ValueMatrix_t ValueMatrix_t; typedef typename OrbitalSetTraits<value_type>::GradVector_t GradVector_t; typedef typename OrbitalSetTraits<value_type>::GradMatrix_t GradMatrix_t; typedef SphericalTensor<RealType,PosType> SphericalHarmonics_t; typedef VarRegistry<RealType> OptimizableSetType; ///size of the basis set IndexType BasisSetSize; ///index of the CurrentCenter IndexType CurrentCenter; ///offset IndexType CurrentOffset; ///reference to a DistanceTableData (ion-electron) const DistanceTableData* myTable; ///spherical tensor unique to this set of SphericalOrbitals SphericalHarmonics_t Ylm; ///index of the corresponding real Spherical Harmonic with quantum ///numbers \f$ (l,m) \f$ vector<int> LM; /**index of the corresponding radial orbital with quantum numbers \f$ (n,l) \f$ */ vector<int> NL; ///container for the radial grid vector<GT*> Grids; ///container for the radial orbitals vector<ROT*> Rnl; ///container for the quantum-numbers vector<QuantumNumberType> RnlID; ///the constructor explicit SphericalOrbitalSet(int lmax, bool addsignforM=false): Ylm(lmax,addsignforM) { } ~SphericalOrbitalSet() { } ///reset the internal values void resetParameters(OptimizableSetType& optVariables) { for(int nl=0; nl<Rnl.size(); nl++) Rnl[nl]->resetParameters(optVariables); } /** return the number of basis functions */ inline int getBasisSetSize() const { return BasisSetSize; }//=NL.size(); } /** implement a BasisSetBase virutal function * * Use the size of LM to set BasisSetSize */ inline void setBasisSetSize(int n) { BasisSetSize=LM.size(); } /** reset the target ParticleSet * * Do nothing. Leave it to a composite object which owns this */ void resetTargetParticleSet(ParticleSet& P) { } ///reset the DistanceTableData (ion-electron) inline void setTable(DistanceTableData* atable) { myTable = atable; BasisSetSize=LM.size(); } ///set the current offset inline void setCenter(int c, int offset) { CurrentCenter=c; CurrentOffset=offset; } template<class VV, class GV> inline void evaluateBasis(int c, int iat, int offset, VV& psi, GV& dpsi, VV& d2psi) { int nn = myTable->M[c]+iat; RealType r(myTable->r(nn)); RealType rinv(myTable->rinv(nn)); PosType dr(myTable->dr(nn)); Ylm.evaluateAll(dr); typename vector<ROT*>::iterator rit(Rnl.begin()), rit_end(Rnl.end()); while(rit != rit_end) { (*rit)->evaluateAll(r,rinv); ++rit; } vector<int>::iterator nlit(NL.begin()),nlit_end(NL.end()),lmit(LM.begin()); while(nlit != nlit_end) //for(int ib=0; ib<NL.size(); ib++, offset++) { { int nl(*nlit);//NL[ib]; int lm(*lmit);//LM[ib]; const ROT& rnl(*Rnl[nl]); RealType drnloverr(rinv*rnl.dY); ValueType ang(Ylm.getYlm(lm)); PosType gr_rad(drnloverr*dr); PosType gr_ang(Ylm.getGradYlm(lm)); psi[offset] = ang*rnl.Y; dpsi[offset] = ang*gr_rad+rnl.Y*gr_ang; d2psi[offset] = ang*(2.0*drnloverr+rnl.d2Y) + 2.0*dot(gr_rad,gr_ang); ++nlit; ++lmit; ++offset; } } template<class VM> inline void evaluate(int source, int iat, int offset, VM& y) { RealType r(myTable->Temp[source].r1); RealType rinv(myTable->Temp[source].rinv1); PosType dr(myTable->Temp[source].dr1); Ylm.evaluate(dr); typename vector<ROT*>::iterator rit(Rnl.begin()), rit_end(Rnl.end()); while(rit != rit_end) { (*rit)->evaluate(r,rinv); ++rit; } vector<int>::iterator nlit(NL.begin()),nlit_end(NL.end()),lmit(LM.begin()); while(nlit != nlit_end) //for(int ib=0; ib<NL.size(); ib++, offset++) { { y(0,offset++)=Ylm.getYlm(*lmit++)*Rnl[*nlit++]->Y; } } template<class VM, class GM> inline void evaluate(int source, int iat, int offset, VM& y, GM& dy, VM& d2y) { RealType r(myTable->Temp[source].r1); RealType rinv(myTable->Temp[source].rinv1); PosType dr(myTable->Temp[source].dr1); Ylm.evaluateAll(dr); typename vector<ROT*>::iterator rit(Rnl.begin()), rit_end(Rnl.end()); while(rit != rit_end) { (*rit)->evaluateAll(r,rinv); ++rit; } vector<int>::iterator nlit(NL.begin()),nlit_end(NL.end()),lmit(LM.begin()); while(nlit != nlit_end) //for(int ib=0; ib<NL.size(); ib++, offset++) { { int nl(*nlit);//NL[ib]; int lm(*lmit);//LM[ib]; const ROT& rnl(*Rnl[nl]); RealType drnloverr(rinv*rnl.dY); ValueType ang(Ylm.getYlm(lm)); PosType gr_rad(drnloverr*dr); PosType gr_ang(Ylm.getGradYlm(lm)); y(0,offset)= ang*rnl.Y; dy(0,offset) = ang*gr_rad+rnl.Y*gr_ang; d2y(0,offset)= ang*(2.0*drnloverr+rnl.d2Y) + 2.0*dot(gr_rad,gr_ang); ++nlit; ++lmit; ++offset; } } /** For the center with index (source), evaluate all the basis functions beginning with index (offset). * @param source index of the center \f$ I \f$ * @param first index of the first particle * @param nptcl number of particles * @param offset index of the first basis function * @param y return vector \f$ y[i,j] = \phi_j({\bf r_i-R_I}) \f$ * @param dy return vector \f$ dy[i,j] = {\bf \nabla}_i \phi_j({\bf r_i-R_I}) \f$ * @param d2y return vector \f$ d2y[i,j] = \nabla^2_i \phi_j({\bf r_i-R_I}) \f$ * The results are stored in the matrices: \f[ y[i,k] = \phi_k(r_{ic}) \f] \f[ dy[i,k] = {\bf \nabla}_i \phi_k(r_{ic}) \f] \f[ d2y[i,k] = \nabla_i^2 \phi_k(r_{ic}) \f] * The basis functions can be written in the form \f[ \phi({\bf R}) = F(r)G(r,\theta,\phi), \f] where \f$ F(r) = \frac{R(r)}{r^l} \f$ is related to the radial orbital and \f$ G(r,\theta,\phi) = r^lS_l^m(\theta,\phi) \f$ is related to the real spherical harmonic. Evaluating the gradient and Laplacian leads to \f[ {\bf \nabla} \phi({\bf R}) = ({\bf \nabla } F(r)) G(r,\theta,\phi) + F(r) ({\bf \nabla} G(r,\theta,\phi)) \f] \f[ {\bf \nabla} \phi({\bf R}) = \frac{dF(r)}{dr} G(r,\theta,\phi)\:{\bf \hat{r}} + F(r) {\bf \nabla} G(r,\theta,\phi) \f] and \f[ \nabla^2 \phi({\bf R}) = (\nabla^2 F) G +2 \nabla F \cdot \nabla G + F (\nabla^2 G) \f] where \f[ \nabla^2 F(r) = \frac{2}{r}\frac{dF(r)}{dr} + \frac{d^2F(r)}{dr^2} \mbox{, } \nabla F(r) = \frac{dF(r)}{dr}\:{\bf \hat{r}} \f] and \f[ \nabla^2 G(r,\theta,\phi) = \frac{1}{r^2}\frac{\partial} {\partial r} \left( r^2 \frac{\partial G}{\partial r}\right) - \frac{l(l+1)G}{r^2} = 0. \f] */ template<class VM, class GM> inline void evaluate(int source, int first, int nptcl, int offset, VM& y, GM& dy, VM& d2y) { int nn = myTable->M[source]+first;//first pair of the particle subset for(int i=0, iat=first; i<nptcl; i++, iat++, nn++) { RealType r(myTable->r(nn)); RealType rinv(myTable->rinv(nn)); PosType dr(myTable->dr(nn)); Ylm.evaluateAll(dr); typename vector<ROT*>::iterator rit(Rnl.begin()), rit_end(Rnl.end()); while(rit != rit_end) { (*rit)->evaluateAll(r,rinv); ++rit; } int bindex(offset); vector<int>::iterator nlit(NL.begin()),nlit_end(NL.end()),lmit(LM.begin()); while(nlit != nlit_end) //for(int ib=0; ib<NL.size(); ib++, offset++) { { int nl(*nlit);//NL[ib]; int lm(*lmit);//LM[ib]; const ROT& rnl(*Rnl[nl]); RealType drnloverr = rinv*rnl.dY; ValueType ang = Ylm.getYlm(lm); PosType gr_rad(drnloverr*dr); PosType gr_ang(Ylm.getGradYlm(lm)); y(iat,bindex)= ang*rnl.Y; dy(iat,bindex) = ang*gr_rad+rnl.Y*gr_ang; d2y(iat,bindex)= ang*(2.0*drnloverr+rnl.d2Y) + 2.0*dot(gr_rad,gr_ang); ++nlit; ++lmit; ++bindex; } //for(int ib=0; ib<NL.size(); ib++, bindex++) { // int nl = NL[ib]; // int lm = LM[ib]; // RealType drnloverr = rinv*Rnl[nl]->dY; // ValueType ang = Ylm.getYlm(lm); // PosType gr_rad = drnloverr*dr; // PosType gr_ang = Ylm.getGradYlm(lm); // y(iat,bindex)= ang*Rnl[nl]->Y; // dy(iat,bindex) = ang*gr_rad+Rnl[nl]->Y*gr_ang; // d2y(iat,bindex)= ang*(2.0*drnloverr+Rnl[nl]->d2Y) + 2.0*dot(gr_rad,gr_ang); //} } } }; } #endif /*************************************************************************** * $RCSfile$ $Author: jmcminis $ * $Revision: 5794 $ $Date: 2013-04-25 20:14:53 -0400 (Thu, 25 Apr 2013) $ * $Id: SphericalOrbitalSet.h 5794 2013-04-26 00:14:53Z jmcminis $ ***************************************************************************/
{ "content_hash": "3ffe4c259bb44523a974c20001a829d8", "timestamp": "", "source": "github", "line_count": 338, "max_line_length": 105, "avg_line_length": 33.133136094674555, "alnum_prop": 0.5812126082685954, "repo_name": "habanero-rice/hcpp", "id": "e468be9082ecae145f977d138a38e98f8c8712fc", "size": "11199", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/performance-regression/full-apps/qmcpack/src/QMCWaveFunctions/SphericalOrbitalSet.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "26226" }, { "name": "C", "bytes": "330261" }, { "name": "C++", "bytes": "255831" }, { "name": "Cuda", "bytes": "10347" }, { "name": "Makefile", "bytes": "7838" }, { "name": "Perl", "bytes": "1748" }, { "name": "Shell", "bytes": "16630" } ], "symlink_target": "" }
@extends('layouts.no_nav') @section('content') <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3 give_bottom_room"> @if(file_exists(base_path("/public/assets/images/logo.png"))) <img src="/assets/images/logo.png"> @else <img src="/assets/images/transparent_logo.png"> @endif </div> </div> <div class="row"> <div class="col-md-6 col-md-offset-3"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">{{trans("headers.createYourAccount")}}</h3> </div> <div class="panel-body"> <p> {{trans("register.creationDescription")}} </p> {!! Form::open(['action' => ['AuthenticationController@createAccount', 'token' => $creationToken->token], 'id' => 'createForm', 'method' => 'post']) !!} <div class="form-group"> <label for="email">{{trans("register.email")}}</label> {!! Form::email("email",null,['id' => 'email', 'class' => 'form-control', 'placeholder' => trans("register.email")]) !!} </div> <div class="form-group"> <label for="username">{{trans("register.username")}}</label> {!! Form::text("username",null,['id' => 'username', 'class' => 'form-control', 'placeholder' => trans("register.username")]) !!} </div> <div class="form-group"> <label for="password">{{trans("register.password")}}</label> {!! Form::password("password",['id' => 'password', 'class' => 'form-control', 'placeholder' => trans("register.password")]) !!} </div> <div class="form-group"> <label for="password_confirmation">{{trans("register.confirmPassword")}}</label> {!! Form::password("password_confirmation",['id' => 'password_confirmation', 'class' => 'form-control', 'placeholder' => trans("register.confirmPassword")]) !!} </div> <button type="submit" class="btn btn-primary">{{trans("actions.createAccount")}}</button> {!! Form::close() !!} </div> </div> <p> <a href="{{action("AuthenticationController@index")}}">{{trans("register.back")}}</a> </p> </div> </div> </div> @endsection @section('additionalJS') {!! JsValidator::formRequest('App\Http\Requests\AccountCreationRequest','#createForm') !!} @endsection @section('additionalCSS') <link rel="stylesheet" href="/assets/css/pages/index.css"> @endsection
{ "content_hash": "d4e6cc2c3f80425e83e1a0643f0a587d", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 188, "avg_line_length": 55, "alnum_prop": 0.4636363636363636, "repo_name": "sunithawisptools/customer_portal", "id": "2e5f71c64cda20efc274fd34e3c5203764b3e8c5", "size": "3080", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "portal/resources/views/pages/root/create.blade.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "7740" }, { "name": "HTML", "bytes": "69500" }, { "name": "JavaScript", "bytes": "8053" }, { "name": "PHP", "bytes": "183466" }, { "name": "Shell", "bytes": "842" } ], "symlink_target": "" }
HOMOTYPIC_SYNONYM #### According to Euro+Med Plantbase #### Published in null #### Original name null ### Remarks null
{ "content_hash": "19fcd4570faa59236f34fc6759496f56", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 18, "avg_line_length": 9.384615384615385, "alnum_prop": 0.6967213114754098, "repo_name": "mdoering/backbone", "id": "283fe63ddd7559c50d78ef6db991d3093fd63941", "size": "197", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Crepis/Hieracium subumbellatiforme/Crepis aurea glabrescens/ Syn. Hieracium aestivum subumbellatiforme/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
//----------------------------------------------------------------------- // <copyright file="HighContext.cs" company="Pat Inc."> // Copyright (c) Pat Inc. 2016. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace PatTuring2016.Common.ScreenModels.Conversation { public class HighContext { public string Element { get; set; } public string Value { get; set; } } }
{ "content_hash": "85a05d0b3a1a2d041f38e44c8116b194", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 74, "avg_line_length": 35.76923076923077, "alnum_prop": 0.44516129032258067, "repo_name": "AILanguages/Win-Conversation", "id": "d666a84eb11939db858d032ed6ccbf1b045db891", "size": "467", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "PatTuring2016.Common/ScreenModels/Conversation/HighContext.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "68797" } ], "symlink_target": "" }
using System; using Umbraco.Core.Exceptions; namespace Umbraco.Core.PropertyEditors { /// <summary> /// Marks a ConfigurationEditor property as a configuration field, and a class as a configuration field type. /// </summary> /// <remarks>Properties marked with this attribute are discovered as fields.</remarks> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class)] public class ConfigurationFieldAttribute : Attribute { private Type _type; /// <summary> /// Initializes a new instance of the <see cref="ConfigurationField"/> class. /// </summary> public ConfigurationFieldAttribute(Type type) { Type = type; } /// <summary> /// Initializes a new instance of the <see cref="ConfigurationField"/> class. /// </summary> /// <param name="key">The unique identifier of the field.</param> /// <param name="name">The friendly name of the field.</param> /// <param name="view">The view to use to render the field editor.</param> public ConfigurationFieldAttribute(string key, string name, string view) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullOrEmptyException(nameof(key)); Key = key; if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullOrEmptyException(nameof(name)); Name = name; if (string.IsNullOrWhiteSpace(view)) throw new ArgumentNullOrEmptyException(nameof(view)); View = view; } /// <summary> /// Initializes a new instance of the <see cref="ConfigurationField"/> class. /// </summary> /// <param name="name">The friendly name of the field.</param> /// <param name="view">The view to use to render the field editor.</param> /// <remarks>When no key is specified, the <see cref="ConfigurationEditor"/> will derive a key /// from the name of the property marked with this attribute.</remarks> public ConfigurationFieldAttribute(string name, string view) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullOrEmptyException(nameof(name)); Name = name; if (string.IsNullOrWhiteSpace(view)) throw new ArgumentNullOrEmptyException(nameof(view)); View = view; } /// <summary> /// Gets or sets the key of the field. /// </summary> /// <remarks>When null or empty, the <see cref="ConfigurationEditor"/> should derive a key /// from the name of the property marked with this attribute.</remarks> public string Key { get; } /// <summary> /// Gets the friendly name of the field. /// </summary> public string Name { get; } /// <summary> /// Gets or sets the view to use to render the field editor. /// </summary> public string View { get; } /// <summary> /// Gets or sets the description of the field. /// </summary> public string Description { get; set; } /// <summary> /// Gets or sets a value indicating whether the field editor should be displayed without its label. /// </summary> public bool HideLabel { get => HideLabelSettable.ValueOrDefault(false); set => HideLabelSettable.Set(value); } /// <summary> /// Gets the settable underlying <see cref="HideLabel"/>. /// </summary> public Settable<bool> HideLabelSettable { get; } = new Settable<bool>(); /// <summary> /// Gets or sets the type of the field. /// </summary> /// <remarks> /// <para>By default, fields are created as <see cref="ConfigurationField"/> instances, /// unless specified otherwise through this property.</para> /// <para>The specified type must inherit from <see cref="ConfigurationField"/>.</para> /// </remarks> public Type Type { get => _type; set { if (!typeof(ConfigurationField).IsAssignableFrom(value)) throw new ArgumentException("Type must inherit from ConfigurationField.", nameof(value)); _type = value; } } } }
{ "content_hash": "e246fe2c7d2b0d24c569f4331ea3c7a1", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 113, "avg_line_length": 38.964285714285715, "alnum_prop": 0.592346471127406, "repo_name": "rasmuseeg/Umbraco-CMS", "id": "d90aeef2e67088f824366e2867976553fb0f082d", "size": "4366", "binary": false, "copies": "2", "ref": "refs/heads/v8/dev", "path": "src/Umbraco.Core/PropertyEditors/ConfigurationFieldAttribute.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "2203" }, { "name": "C#", "bytes": "14127989" }, { "name": "CSS", "bytes": "463136" }, { "name": "HTML", "bytes": "996108" }, { "name": "JavaScript", "bytes": "3036766" }, { "name": "PowerShell", "bytes": "28895" }, { "name": "TSQL", "bytes": "98900" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_34) on Thu Jan 07 14:13:58 GMT 2016 --> <TITLE> org.apache.fop.fo.extensions.xmp (Apache FOP 2.1 API) </TITLE> <META NAME="date" CONTENT="2016-01-07"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <FONT size="+1" CLASS="FrameTitleFont"> <A HREF="../../../../../../org/apache/fop/fo/extensions/xmp/package-summary.html" target="classFrame">org.apache.fop.fo.extensions.xmp</A></FONT> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Classes</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="AbstractMetadataElement.html" title="class in org.apache.fop.fo.extensions.xmp" target="classFrame">AbstractMetadataElement</A> <BR> <A HREF="RDFElement.html" title="class in org.apache.fop.fo.extensions.xmp" target="classFrame">RDFElement</A> <BR> <A HREF="RDFElementMapping.html" title="class in org.apache.fop.fo.extensions.xmp" target="classFrame">RDFElementMapping</A> <BR> <A HREF="XMPContentHandlerFactory.html" title="class in org.apache.fop.fo.extensions.xmp" target="classFrame">XMPContentHandlerFactory</A> <BR> <A HREF="XMPElementMapping.html" title="class in org.apache.fop.fo.extensions.xmp" target="classFrame">XMPElementMapping</A> <BR> <A HREF="XMPMetadata.html" title="class in org.apache.fop.fo.extensions.xmp" target="classFrame">XMPMetadata</A> <BR> <A HREF="XMPMetaElement.html" title="class in org.apache.fop.fo.extensions.xmp" target="classFrame">XMPMetaElement</A></FONT></TD> </TR> </TABLE> </BODY> </HTML>
{ "content_hash": "e219b6bd6f34bca3b313a6d5d96c889d", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 145, "avg_line_length": 39.52272727272727, "alnum_prop": 0.714203565267395, "repo_name": "JollyApplez/SeCuenti", "id": "2dbfed6b28b2765c886c18523b0e2276d89cf9bb", "size": "1739", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "Resources/fop-2.1/javadocs/org/apache/fop/fo/extensions/xmp/package-frame.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "4336" }, { "name": "CSS", "bytes": "1391" }, { "name": "HTML", "bytes": "82926483" }, { "name": "Java", "bytes": "8120" }, { "name": "JavaScript", "bytes": "10503" }, { "name": "Shell", "bytes": "7681" }, { "name": "XSLT", "bytes": "1951" } ], "symlink_target": "" }
<bill session="115" type="h" number="1560" updated="2017-06-23T19:45:14Z"> <state datetime="2017-03-16">REFERRED</state> <status> <introduced datetime="2017-03-16"/> </status> <introduced datetime="2017-03-16"/> <titles> <title type="short" as="introduced">Parental Bereavement Act of 2017</title> <title type="short" as="introduced">Parental Bereavement Act of 2017</title> <title type="short" as="introduced">Sarah Grace-Farley-Kluger Act</title> <title type="short" as="introduced">Sarah Grace-Farley-Kluger Act</title> <title type="official" as="introduced">To amend the Family and Medical Leave Act of 1993 to provide leave because of the death of a son or daughter.</title> <title type="display">Sarah Grace-Farley-Kluger Act</title> </titles> <sponsor bioguide_id="G000565"/> <cosponsors> <cosponsor bioguide_id="A000374" joined="2017-05-24"/> <cosponsor bioguide_id="B001292" joined="2017-03-16"/> <cosponsor bioguide_id="C001105" joined="2017-03-16"/> <cosponsor bioguide_id="C001094" joined="2017-05-16"/> <cosponsor bioguide_id="D000216" joined="2017-05-03"/> <cosponsor bioguide_id="G000574" joined="2017-05-22"/> <cosponsor bioguide_id="M001197" joined="2017-03-16"/> <cosponsor bioguide_id="N000184" joined="2017-05-03"/> <cosponsor bioguide_id="S001190" joined="2017-03-16"/> <cosponsor bioguide_id="S000250" joined="2017-05-03"/> <cosponsor bioguide_id="S001191" joined="2017-05-24"/> <cosponsor bioguide_id="S001201" joined="2017-03-16"/> <cosponsor bioguide_id="W000806" joined="2017-05-16"/> </cosponsors> <actions> <action datetime="2017-03-16"> <text>Introduced in House</text> </action> <action datetime="2017-03-16" state="REFERRED"> <text>Referred to the Committee on Education and the Workforce, and in addition to the Committees on Oversight and Government Reform, and House Administration, for a period to be subsequently determined by the Speaker, in each case for consideration of such provisions as fall within the jurisdiction of the committee concerned.</text> </action> <action datetime="2017-03-16"> <text>Referred to House Education and the Workforce</text> </action> <action datetime="2017-03-16"> <text>Referred to House Oversight and Government Reform</text> </action> <action datetime="2017-03-16"> <text>Referred to House Administration</text> </action> </actions> <committees> <committee subcommittee="" code="HSHA" name="House Administration" activity="Referral"/> <committee subcommittee="" code="HSGO" name="House Oversight and Government Reform" activity="Referral"/> <committee subcommittee="" code="HSED" name="House Education and the Workforce" activity="Referral"/> </committees> <relatedbills> <bill type="s" session="115" relation="identical" number="528"/> </relatedbills> <subjects> <term name="Labor and employment"/> <term name="Elementary and secondary education"/> <term name="Employee leave"/> <term name="Family relationships"/> <term name="Government employee pay, benefits, personnel management"/> <term name="Teaching, teachers, curricula"/> </subjects> <amendments/> <summary date="2017-03-16T04:00:00Z" status="Introduced in House">Parental Bereavement Act of 2017 or the Sarah Grace-Farley-Kluger Act This bill amends the Family and Medical Leave Act of 1993 to entitle an eligible employee to up to 12 workweeks of leave during any 12-month period because of the death of a son or daughter. Such an employee may substitute any available paid leave for any leave without pay. The bill applies the same leave entitlement to federal employees.</summary> <committee-reports/> </bill>
{ "content_hash": "e1359e3451f050fa702cc18d0596e3c7", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 341, "avg_line_length": 51.78082191780822, "alnum_prop": 0.7097883597883597, "repo_name": "peter765/power-polls", "id": "9a1a14224b055266ab04b64222f105c4f56a08a4", "size": "3780", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/bills/hr/hr1560/data.xml", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "58567" }, { "name": "JavaScript", "bytes": "7370" }, { "name": "Python", "bytes": "22988" } ], "symlink_target": "" }
require("./app/server").launch();
{ "content_hash": "cdbf9b5180fe1d7038b422f811f54744", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 33, "avg_line_length": 34, "alnum_prop": 0.6470588235294118, "repo_name": "pythe/ham-downlink", "id": "49dacff4be5ea738e248221599f1fc0315a0c80d", "size": "34", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "index.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "4273" } ], "symlink_target": "" }
package org.mti.hip; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.DatePicker; import android.widget.EditText; import android.widget.RadioButton; import org.mti.hip.model.Visit; import org.mti.hip.utils.VisitDiagnosisListAdapter; import java.util.Calendar; import java.util.Date; public class ConsultationActivity extends SuperActivity { private Visit visit = getStorageManagerInstance().currentVisit(); private RadioButton rbMale; private RadioButton rbFemale; private RadioButton rbVisit; private RadioButton rbRevisit; private RadioButton rbNational; private RadioButton rbRefugee; private EditText opdNum; private EditText patientYears; private EditText patientMonths; private EditText patientDays; private StringBuilder errorBuilder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_consultation); displayMode(); opdNum = (EditText) findViewById(R.id.opd_number); patientYears = (EditText) findViewById(R.id.patient_years); patientMonths = (EditText) findViewById(R.id.patient_months); patientDays = (EditText) findViewById(R.id.patient_days); rbMale = (RadioButton) findViewById(R.id.rb_male); rbFemale = (RadioButton) findViewById(R.id.rb_female); rbNational = (RadioButton) findViewById(R.id.rb_national); rbRefugee = (RadioButton) findViewById(R.id.rb_refugee); rbVisit = (RadioButton) findViewById(R.id.rb_visit); rbRevisit = (RadioButton) findViewById(R.id.rb_revisit); rbRefugee = (RadioButton) findViewById(R.id.rb_refugee); findViewById(R.id.opd_tooltip).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alert.showAlert(getString(R.string.info), getString(R.string.tooltip_opd_number)); } }); findViewById(R.id.bt_next_screen).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { gotoNext(); } }); } protected void gotoNext() { errorBuilder = new StringBuilder(); if (valid()) { startDiagnosisActivity(); } else { alert.showAlert(getString(R.string.errors_found), errorBuilder.toString()); } } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); } @Override protected void onDestroy() { super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_next, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_next: gotoNext(); return true; default: return false; } } private void startDiagnosisActivity() { Intent i = new Intent(this, DiagnosisActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); startActivity(i); } private boolean valid() { boolean valid = true; if (editTextHasContent(opdNum)) { try { visit.setOPD(Long.valueOf(opdNum.getText().toString())); } catch (NumberFormatException e) { alert.showAlert("Invalid number", "Please enter a valid number."); } } // not worried about the else case since OPD# is optional if (editTextHasContent(patientYears) || editTextHasContent(patientMonths) || editTextHasContent(patientDays)) { visit.setPatientAgeYears(editTextToInt(patientYears, 0)); visit.setPatientAgeMonths(editTextToInt(patientMonths, 0)); visit.setPatientAgeDays(editTextToInt(patientDays, 0)); double ageMonths = visit.getPatientAgeMonthsLow(); if (ageMonths <= 0 | ageMonths > 150.0 * 12.0) { addErrorString(R.string.error_age_range); valid = false; } } else { // handles nothing entered scenario addErrorString(R.string.error_age); valid = false; } if (rbMale.isChecked()) { visit.setGender('M'); } else if (rbFemale.isChecked()) { visit.setGender('F'); } else { addErrorString(R.string.error_gender); valid = false; } if (rbNational.isChecked()) { visit.setBeneficiaryType(Visit.national); } else if (rbRefugee.isChecked()) { visit.setBeneficiaryType(Visit.refugee); } else { addErrorString(R.string.error_status_type); valid = false; } if (rbVisit.isChecked()) { visit.setIsRevisit(false); } else if (rbRevisit.isChecked()) { visit.setIsRevisit(true); } else { addErrorString(R.string.error_visit_type); valid = false; } return valid; } private void addErrorString(int id) { errorBuilder.append(getString(id)); errorBuilder.append("\n"); } @Override public void onBackPressed() { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setMessage(getString(R.string.ru_sure_u_wanna_delete_visit)); alert.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { VisitDiagnosisListAdapter.check_states.clear(); finish(); dialog.dismiss(); } }); alert.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alert.show(); } }
{ "content_hash": "09c199db06531356bc95110a83e7e9af", "timestamp": "", "source": "github", "line_count": 190, "max_line_length": 119, "avg_line_length": 33.59473684210526, "alnum_prop": 0.6166379445401848, "repo_name": "MedicalTeams/mti-android-app", "id": "1094f05b6d6f5314af62b0deb6c0bcaec152a79c", "size": "6383", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "HIP/app/src/main/java/org/mti/hip/ConsultationActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "177614" } ], "symlink_target": "" }
// // VideoRendererNode.h // ARPlayer // // Created by Maxim Makhun on 05/03/2019. // Copyright © 2019 Maxim Makhun. All rights reserved. // @import SceneKit; #import "ControlNode.h" NS_ASSUME_NONNULL_BEGIN /*! @class VideoRendererNode @abstract VideoRendererNode - node on frontal surface of which playback is done. */ @interface VideoRendererNode : ControlNode /*! @method initWithParentNode: @abstract Initialize node with parent node. */ - (instancetype)initWithParentNode:(SCNNode *)node; @end NS_ASSUME_NONNULL_END
{ "content_hash": "89fb4b9da3231f7cd2c53c6831674bb1", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 81, "avg_line_length": 18.551724137931036, "alnum_prop": 0.7360594795539034, "repo_name": "MaximAlien/ARPlayer", "id": "5f0432aacf578fec9030c1bfd7ed272f1b5215b7", "size": "539", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ARPlayer/Nodes/ControlNodes/VideoRendererNode.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "71274" } ], "symlink_target": "" }
restaurant_reviewer ===================
{ "content_hash": "3421996a1d6add8506cbf6153b25b4cd", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 19, "avg_line_length": 20, "alnum_prop": 0.45, "repo_name": "malcomb21/restaurant_reviewer", "id": "4805c2a8c859e28b6a675d7d0cff6d6e8ed6d6e7", "size": "40", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "7695" } ], "symlink_target": "" }
package mx.itesm.logistics.crew_tracking.task; import android.util.Log; import edu.mit.lastmite.insight_library.http.APIResponseHandler; import edu.mit.lastmite.insight_library.model.Route; import edu.mit.lastmite.insight_library.task.NetworkTask; import mx.itesm.logistics.crew_tracking.util.Preferences; public class StopRouteTask extends NetworkTask { protected Route mRoute; public StopRouteTask(Route route) { mRoute = route; } @Override public void execute(Callback callback) { mCallback = callback; updateRoute(); Log.d("AS", mRoute.buildParams().toString()); mAPIFetch.post("routes/postEnd", mRoute.buildParams(), new APIResponseHandler(mApplication, null, false) { @Override public void onFinish(boolean success) { activateCallback(success); } }); } @Override public Object getModel() { return mRoute; } protected void updateRoute() { mRoute.setId(getRouteId()); } protected long getRouteId() { return getLocalLong(Preferences.PREFERENCES_ROUTE_ID); } }
{ "content_hash": "a7c1d11e05d5ef1ba213c0074a5d0581", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 114, "avg_line_length": 26.113636363636363, "alnum_prop": 0.6631853785900783, "repo_name": "pablo-co/insight-android-crew", "id": "9467b1fc2ee7617718d9c81190dd9c618243d0ff", "size": "2273", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/mx/itesm/logistics/crew_tracking/task/StopRouteTask.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2695" }, { "name": "HTML", "bytes": "2649" }, { "name": "Java", "bytes": "241840" }, { "name": "JavaScript", "bytes": "5252" } ], "symlink_target": "" }
do -- let's ensure the required shared dictionaries are -- declared via lua_shared_dict in the Nginx conf local constants = require "kong.constants" for _, dict in ipairs(constants.DICTS) do if not ngx.shared[dict] then return error("missing shared dict '" .. dict .. "' in Nginx " .. "configuration, are you using a custom template? " .. "Make sure the 'lua_shared_dict " .. dict .. " [SIZE];' " .. "directive is defined.") end end end require("kong.core.globalpatches")() local dns = require "kong.tools.dns" local core = require "kong.core.handler" local Serf = require "kong.serf" local utils = require "kong.tools.utils" local Events = require "kong.core.events" local responses = require "kong.tools.responses" local constants = require "kong.constants" local singletons = require "kong.singletons" local DAOFactory = require "kong.dao.factory" local ngx_balancer = require "ngx.balancer" local plugins_iterator = require "kong.core.plugins_iterator" local balancer_execute = require("kong.core.balancer").execute local ipairs = ipairs local get_last_failure = ngx_balancer.get_last_failure local set_current_peer = ngx_balancer.set_current_peer local set_timeouts = ngx_balancer.set_timeouts local set_more_tries = ngx_balancer.set_more_tries local function attach_hooks(events, hooks) for k, v in pairs(hooks) do events:subscribe(k, v) end end local function load_plugins(kong_conf, dao, events) local in_db_plugins, sorted_plugins = {}, {} ngx.log(ngx.DEBUG, "Discovering used plugins") local rows, err_t = dao.plugins:find_all() if not rows then return nil, tostring(err_t) end for _, row in ipairs(rows) do in_db_plugins[row.name] = true end -- check all plugins in DB are enabled/installed for plugin in pairs(in_db_plugins) do if not kong_conf.plugins[plugin] then return nil, plugin .. " plugin is in use but not enabled" end end -- load installed plugins for plugin in pairs(kong_conf.plugins) do local ok, handler = utils.load_module_if_exists("kong.plugins." .. plugin .. ".handler") if not ok then return nil, plugin .. " plugin is enabled but not installed;\n" .. handler end local ok, schema = utils.load_module_if_exists("kong.plugins." .. plugin .. ".schema") if not ok then return nil, "no configuration schema found for plugin: " .. plugin end ngx.log(ngx.DEBUG, "Loading plugin: " .. plugin) sorted_plugins[#sorted_plugins+1] = { name = plugin, handler = handler(), schema = schema } -- Attaching hooks local ok, hooks = utils.load_module_if_exists("kong.plugins." .. plugin .. ".hooks") if ok then attach_hooks(events, hooks) end end -- sort plugins by order of execution table.sort(sorted_plugins, function(a, b) local priority_a = a.handler.PRIORITY or 0 local priority_b = b.handler.PRIORITY or 0 return priority_a > priority_b end) -- add reports plugin if not disabled if kong_conf.anonymous_reports then local reports = require "kong.core.reports" reports.toggle(true) sorted_plugins[#sorted_plugins+1] = { name = "reports", handler = reports } end return sorted_plugins end -- Kong public context handlers. -- @section kong_handlers local Kong = {} function Kong.init() local pl_path = require "pl.path" local conf_loader = require "kong.conf_loader" -- retrieve kong_config local conf_path = pl_path.join(ngx.config.prefix(), ".kong_env") local config = assert(conf_loader(conf_path)) local events = Events() -- retrieve node plugins local dao = assert(DAOFactory.new(config, events)) -- instanciate long-lived DAO assert(dao:init()) assert(dao:run_migrations()) -- migrating in case embedded in custom nginx -- populate singletons singletons.dns = dns(config) singletons.loaded_plugins = assert(load_plugins(config, dao, events)) singletons.serf = Serf.new(config, dao) singletons.dao = dao singletons.events = events singletons.configuration = config attach_hooks(events, require "kong.core.hooks") assert(core.build_router()) end function Kong.init_worker() -- special math.randomseed from kong.core.globalpatches -- not taking any argument. Must be called only once -- and in the init_worker phase, to avoid duplicated -- seeds. math.randomseed() -- init DAO local ok, err = singletons.dao:init_worker() if not ok then ngx.log(ngx.CRIT, "could not init DB: ", err) return end -- init inter-worker events local worker_events = require "resty.worker.events" local handler = function(data, event, source, pid) if data and data.collection == "apis" then assert(core.build_router()) elseif source and source == constants.CACHE.CLUSTER then singletons.events:publish(event, data) end end worker_events.register(handler) local ok, err = worker_events.configure { shm = "process_events", -- defined by "lua_shared_dict" timeout = 5, -- life time of event data in shm interval = 1, -- poll interval (seconds) wait_interval = 0.010, -- wait before retry fetching event data wait_max = 0.5, -- max wait time before discarding event } if not ok then ngx.log(ngx.CRIT, "could not start inter-worker events: ", err) return end core.init_worker.before() -- run plugins init_worker context for _, plugin in ipairs(singletons.loaded_plugins) do plugin.handler:init_worker() end end function Kong.ssl_certificate() local ctx = ngx.ctx core.certificate.before(ctx) for plugin, plugin_conf in plugins_iterator(singletons.loaded_plugins, true) do plugin.handler:certificate(plugin_conf) end end function Kong.balancer() local ctx = ngx.ctx local addr = ctx.balancer_address local tries = addr.tries local current_try = {} addr.try_count = addr.try_count + 1 tries[addr.try_count] = current_try core.balancer.before() if addr.try_count > 1 then -- only call balancer on retry, first one is done in `core.access.after` which runs -- in the ACCESS context and hence has less limitations than this BALANCER context -- where the retries are executed -- record failure data local previous_try = tries[addr.try_count - 1] previous_try.state, previous_try.code = get_last_failure() local ok, err = balancer_execute(addr) if not ok then ngx.log(ngx.ERR, "failed to retry the dns/balancer resolver for ", addr.upstream.host, "' with: ", tostring(err)) return responses.send(500) end else -- first try, so set the max number of retries local retries = addr.retries if retries > 0 then set_more_tries(retries) end end current_try.ip = addr.ip current_try.port = addr.port -- set the targets as resolved local ok, err = set_current_peer(addr.ip, addr.port) if not ok then ngx.log(ngx.ERR, "failed to set the current peer (address: ", tostring(addr.ip), " port: ", tostring(addr.port),"): ", tostring(err)) return responses.send(500) end ok, err = set_timeouts(addr.connect_timeout / 1000, addr.send_timeout / 1000, addr.read_timeout / 1000) if not ok then ngx.log(ngx.ERR, "could not set upstream timeouts: ", err) end core.balancer.after() end function Kong.rewrite() local ctx = ngx.ctx core.rewrite.before(ctx) -- we're just using the iterator, as in this rewrite phase no consumer nor -- api will have been identified, hence we'll just be executing the global -- plugins for plugin, plugin_conf in plugins_iterator(singletons.loaded_plugins, true) do plugin.handler:rewrite(plugin_conf) end core.rewrite.after(ctx) end function Kong.access() local ctx = ngx.ctx core.access.before(ctx) for plugin, plugin_conf in plugins_iterator(singletons.loaded_plugins, true) do plugin.handler:access(plugin_conf) end core.access.after(ctx) end function Kong.header_filter() local ctx = ngx.ctx core.header_filter.before(ctx) for plugin, plugin_conf in plugins_iterator(singletons.loaded_plugins) do plugin.handler:header_filter(plugin_conf) end core.header_filter.after(ctx) end function Kong.body_filter() local ctx = ngx.ctx for plugin, plugin_conf in plugins_iterator(singletons.loaded_plugins) do plugin.handler:body_filter(plugin_conf) end core.body_filter.after(ctx) end function Kong.log() local ctx = ngx.ctx for plugin, plugin_conf in plugins_iterator(singletons.loaded_plugins) do plugin.handler:log(plugin_conf) end core.log.after(ctx) end return Kong
{ "content_hash": "68f38b2f6f75c778cdc0027e2a8e6c63", "timestamp": "", "source": "github", "line_count": 314, "max_line_length": 92, "avg_line_length": 28.03184713375796, "alnum_prop": 0.6800727107475574, "repo_name": "akh00/kong", "id": "b64c60226a6e02828cbde8322d9479bf3e1f2731", "size": "9184", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "kong/kong.lua", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Lua", "bytes": "1756531" }, { "name": "Makefile", "bytes": "721" }, { "name": "Shell", "bytes": "3392" } ], "symlink_target": "" }
Говоримо "Привіт" ================= В даному розділі розглянемо як створити нову сторінку з надписом "Привіт". У процесі вирішення задачі ви створите [дію контролера](structure-controllers.md#creating-actions) і [представлення](structure-views.md): * Додаток опрацює запит і передасть управління відповідній дії, * а дія, у свою чергу, відобразить представлення з надписом "Привіт" кінцевому користувачу. В даному керівництві ви дізнаєтесь як: 1. створити [дію](structure-controllers.md#creating-actions), яка буде відповідати на запити; 2. створити [представлення](structure-views.md), щоб скомпонувати вміст відповіді; 3. додаток відправляє запити до [дії](structure-controllers.md#creating-actions). Створення дії <span id="creating-action"></span> ------------- Для нашої задачі знадобиться [дія](structure-controllers.md#creating-actions) `say`, яка зчитує параметр `message` із запиту і відображає його значення користувачу. Якщо в запиті відсутній параметр `message`, то дія буде відображати "Привіт". > Info: [Дії](structure-controllers.md#creating-actions) являються об’єктами, на які користувач може посилатись для виконання. Дії згруповані в [контролери](structure-controllers.md). Результатом виконання дії є відповідь, яку отримує користувач. Дії повинні оголошуватись в [контролерах](structure-controllers.md). Для простоти, ви можете оголосити дію `say` в уже наявному контролері `SiteController`, який визначений у файлі класу `controllers/SiteController.php`: ```php <?php namespace app\controllers; use yii\web\Controller; class SiteController extends Controller { // ...наявний код... public function actionSay($message = 'Привіт') { return $this->render('say', ['message' => $message]); } } ``` В наведеному коді дія `say` визначена як метод `actionSay` в класі `SiteController`. Yii використовує префікс `action` для того, щоб відрізняти методи-дії від звичайних методів у класі контролеру. Назва після префікса `action` вважається ідентифікатором відповідної дії. Коли черга доходить до іменування дій, слід розуміти як Yii поводиться з ідентифікаторами дій. Ідентифікатори дій можуть бути лише в нижньому регістрі. Якщо ідентифікатор складається з декількох слів, вони з’єднуються дефісами (наприклад, `create-comment`). Імена методів дій отримуються шляхом видалення дефісів з ідентифікатора, перетворення першої літери кожного слова у верхній регістр і додавання префікса `action`. Наприклад, ідентифікатор дії `create-comment` відповідає методу `actionCreateComment`. Метод дії у нашому прикладі приймає параметр `$message`, який за замовчуванням визначено як `"Привіт"` (так само, як ви звикли визначати значення за замовчуванням для аргументів функції у PHP). Коли додаток отримує запит і визначає, що дія `say` відповідає за його опрацювання, додаток призначає цьому параметру значення однойменного параметра із запиту. Іншими словами, якщо запит містить параметр `message` зі значенням `"До побачення"`, то змінній `$message` всередині дії буде призначено це значення. Всередині метода дії, для відображення [представлення](structure-views.md) з ім’ям `say`, використовується метод [[yii\web\Controller::render()|render()]]. Для того, щоб вивести повідомлення, у представлення передається параметр `message`. Результат формування повертається методом дії. Цей результат приймається додатком та відображається кінцевому користувачу в браузері (як частина цілої HTML-сторінки). Створення представлення <span id="creating-view"></span> ----------------------- [Представлення](structure-views.md) є скриптами, які використовуються для генерування вмісту відповіді. Для нашого додатку ви створите представлення `say`, яке буде виводити параметр `message`, отриманий із методу дії: ```php <?php use yii\helpers\Html; ?> <?= Html::encode($message) ?> ``` Представлення `say` мусить бути збережено у файлі `views/site/say.php`. Коли метод [[yii\web\Controller::render()|render()]] викликається в дії, він буде шукати PHP-файл з ім’ям виду `views/ControllerID/ViewName.php`. Варто зазначити, що у вищезазначеному коді параметр `message` [[yii\helpers\Html::encode()|екранується для HTML]] перед відображенням. Це обов’язково, бо параметр приходить від користувача, котрий може спробувати провести [XSS атаку](https://uk.wikipedia.org/wiki/%D0%9C%D1%96%D0%B6%D1%81%D0%B0%D0%B9%D1%82%D0%BE%D0%B2%D0%B8%D0%B9_%D1%81%D0%BA%D1%80%D0%B8%D0%BF%D1%82%D1%96%D0%BD%D0%B3), шляхом вставки небезпечного JavaScript кода. Ви можете доповнити представлення `say` HTML-тегами, текстом або кодом PHP. Фактично, представлення `say` є простим PHP-скриптом, який виконується методом [[yii\web\Controller::render()|render()]]. Вміст, який формується скриптом представлення, буде передано додатком користувачу. Спробуємо <span id="trying-it-out"></span> --------- Після створення дії і представлення, ви можете перейти на нову сторінку по наступному URL: ``` https://hostname/index.php?r=site%2Fsay&message=Привіт+світ ``` ![Привіт, світ](images/start-hello-world.png) Буде відображена сторінка з надписом "Привіт світ". Вона використовує ту ж шапку та футер, що і решта сторінок додатка. Якщо ви не вкажете параметр `message` в URL, то побачите на сторінці лише "Привіт". Це відбувається тому, що `message` передається як параметр в метод `actionSay()`, а коли він не вказаний, використовується значення за замовчуванням "Привіт". > Info: Нова сторінка використовує ту ж шапку та футер, що й решта сторінок, тому що метод [[yii\web\Controller::render()|render()]] автоматично підставляє результат формування представлення `say` в, так званий, [макет](structure-views.md#layouts), який в даному випадку розміщено у `views/layouts/main.php`. Параметр `r` у вищезазначеному URL потребує додаткових пояснень. Він вказує [маршрут](runtime-routing.md), що являє собою унікальний для додатка ідентифікатор, який вказує на дію. Його формат `ControllerID/ActionID`. Коли додаток отримує запит, він перевіряє цей параметр і, використовуючи частину `ControllerID`, визначає який контролер слід використовувати для опрацювання запиту. Потім, контролер використовує частину `ActionID`, щоб визначити яку дію використовувати для виконання реальної роботи. В нашому випадку маршрут `site/say` буде відповідати контролеру `SiteController` і його дії `say`. В результаті, для опрацювання запиту буде викликано метод `SiteController::actionSay()`. > Info: Як і дії, контролери також мають ідентифікатори, котрі однозначно визначають їх в додатку. Ідентифікатори контролерів використовують ті ж самі правила іменування, що і ідентифікатори дій. Імена класів контролерів отримуються шляхом видалення дефісів з ідентифікатора, перетворення першої літери кожного слова у верхній регістр і додавання в кінець слова `Controller`. Наприклад, ідентифікатор контролера `post-comment` відповідає імені класу контролера `PostCommentController`. Підсумок <span id="summary"></span> -------- В даному розділі ви торкнулися таких частин шаблону проектування MVC як контролери та представлення. Ви створили дію, як частину контролера, для опрацювання специфічного запиту. А також ви створили представлення для формування вмісту відповіді. В цьому процесі ніяк не використовувалась модель, оскільки в ролі даних виступає тільки простий параметр `message`. Також ви ознайомились із концепцією маршрутизації, котра є сполучною ланкою між запитом користувача і дією контролера. В наступному розділі ви дізнаєтесь як створити модель та додати нову сторінку з HTML-формою.
{ "content_hash": "ff88cfaed9dbdab1f5b8478c6468dec1", "timestamp": "", "source": "github", "line_count": 143, "max_line_length": 189, "avg_line_length": 52.46153846153846, "alnum_prop": 0.7848573713676353, "repo_name": "lubosdz/yii2", "id": "4ea3fd4825e6d8a822579d59e38861a5e62b575c", "size": "11990", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "docs/guide-uk/start-hello.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "1090" }, { "name": "CSS", "bytes": "20" }, { "name": "Dockerfile", "bytes": "3386" }, { "name": "HTML", "bytes": "13876" }, { "name": "Hack", "bytes": "4074" }, { "name": "JavaScript", "bytes": "278174" }, { "name": "PHP", "bytes": "7590159" }, { "name": "PLSQL", "bytes": "20760" }, { "name": "Shell", "bytes": "2070" }, { "name": "TSQL", "bytes": "18884" } ], "symlink_target": "" }
import { types as tt } from "./tokentype"; import { Parser } from "./state"; import { lineBreak } from "./whitespace"; const pp = Parser.prototype; // ## Parser utilities // Test whether a statement node is the string literal `"use strict"`. pp.isUseStrict = function (stmt) { return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && stmt.expression.raw.slice(1, -1) === "use strict"; }; // Predicate that tests whether the next token is of the given // type, and if yes, consumes it as a side effect. pp.eat = function (type) { if (this.type === type) { this.next(); return true; } else { return false; } }; // Tests whether parsed token is a contextual keyword. pp.isContextual = function (name) { return this.type === tt.name && this.value === name; }; // Consumes contextual keyword if possible. pp.eatContextual = function (name) { return this.value === name && this.eat(tt.name); }; // Asserts that following token is given contextual keyword. pp.expectContextual = function (name) { if (!this.eatContextual(name)) this.unexpected(); }; // Test whether a semicolon can be inserted at the current position. pp.canInsertSemicolon = function () { return this.type === tt.eof || this.type === tt.braceR || lineBreak.test(this.input.slice(this.lastTokEnd, this.start)); }; pp.insertSemicolon = function () { if (this.canInsertSemicolon()) { if (this.options.onInsertedSemicolon) this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); return true; } }; // Consume a semicolon, or, failing that, see if we are allowed to // pretend that there is a semicolon at this position. pp.semicolon = function () { if (!this.eat(tt.semi) && !this.insertSemicolon()) this.unexpected(); }; pp.afterTrailingComma = function (tokType) { if (this.type === tokType) { if (this.options.onTrailingComma) this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); this.next(); return true; } }; // Expect a token of a given type. If found, consume it, otherwise, // raise an unexpected token error. pp.expect = function (type) { return this.eat(type) || this.unexpected(); }; // Raise an unexpected token error. pp.unexpected = function (pos) { this.raise(pos != null ? pos : this.start, "Unexpected token"); };
{ "content_hash": "222727fa8be9ea845eafa1490eec8200", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 136, "avg_line_length": 26.71590909090909, "alnum_prop": 0.6801361122926415, "repo_name": "ryankanno/babel", "id": "41c6d8e79b1b0aa2d3ca5ba7f3f21eb45bd33f9b", "size": "2351", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "packages/babylon/src/parseutil.js", "mode": "33261", "license": "mit", "language": [ { "name": "HTML", "bytes": "470" }, { "name": "JavaScript", "bytes": "2370809" }, { "name": "Makefile", "bytes": "986" }, { "name": "Shell", "bytes": "2553" } ], "symlink_target": "" }
package net.peelo.kahvi.compiler.lookup.descriptor; public interface TypeDescriptorVisitor<R, P> { R visitArrayTypeDescriptor(ArrayTypeDescriptor td, P p); R visitClassTypeDescriptor(ClassTypeDescriptor td, P p); R visitPrimitiveTypeDescriptor(PrimitiveTypeDescriptor td, P p); R visitVoidTypeDescriptor(VoidTypeDescriptor td, P p); }
{ "content_hash": "09b882fdbd0f26a1538aae34b0c82ac0", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 68, "avg_line_length": 39.111111111111114, "alnum_prop": 0.7954545454545454, "repo_name": "peelonet/kahvi", "id": "62662638ec0e3925261d1c34aa2f0b92e51904b0", "size": "352", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/net/peelo/kahvi/compiler/lookup/descriptor/TypeDescriptorVisitor.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "253171" } ], "symlink_target": "" }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal abstract class SynthesizedImplementationMethod : SynthesizedInstanceMethodSymbol { //inputs private readonly MethodSymbol _interfaceMethod; private readonly NamedTypeSymbol _implementingType; private readonly bool _generateDebugInfo; private readonly PropertySymbol _associatedProperty; //computed private readonly ImmutableArray<MethodSymbol> _explicitInterfaceImplementations; private readonly ImmutableArray<TypeParameterSymbol> _typeParameters; private readonly TypeSymbol _returnType; private readonly ImmutableArray<ParameterSymbol> _parameters; private readonly string _name; public SynthesizedImplementationMethod( MethodSymbol interfaceMethod, NamedTypeSymbol implementingType, string name = null, bool generateDebugInfo = true, PropertySymbol associatedProperty = null) { //it does not make sense to add methods to substituted types Debug.Assert(implementingType.IsDefinition); _name = name ?? ExplicitInterfaceHelpers.GetMemberName(interfaceMethod.Name, interfaceMethod.ContainingType, aliasQualifierOpt: null); _interfaceMethod = interfaceMethod; _implementingType = implementingType; _generateDebugInfo = generateDebugInfo; _associatedProperty = associatedProperty; _explicitInterfaceImplementations = ImmutableArray.Create<MethodSymbol>(interfaceMethod); // alpha-rename to get the implementation's type parameters var typeMap = interfaceMethod.ContainingType.TypeSubstitution ?? TypeMap.Empty; typeMap.WithAlphaRename(interfaceMethod, this, out _typeParameters); var substitutedInterfaceMethod = interfaceMethod.ConstructIfGeneric(_typeParameters.Cast<TypeParameterSymbol, TypeSymbol>()); _returnType = substitutedInterfaceMethod.ReturnType; _parameters = SynthesizedParameterSymbol.DeriveParameters(substitutedInterfaceMethod, this); } #region Delegate to interfaceMethod public sealed override bool IsVararg { get { return _interfaceMethod.IsVararg; } } public sealed override int Arity { get { return _interfaceMethod.Arity; } } public sealed override bool ReturnsVoid { get { return _interfaceMethod.ReturnsVoid; } } internal sealed override Cci.CallingConvention CallingConvention { get { return _interfaceMethod.CallingConvention; } } public sealed override ImmutableArray<CustomModifier> ReturnTypeCustomModifiers { get { return _interfaceMethod.ReturnTypeCustomModifiers; } } #endregion internal override void AddSynthesizedAttributes(ModuleCompilationState compilationState, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(compilationState, ref attributes); var compilation = this.DeclaringCompilation; if (this.ReturnType.ContainsDynamic() && compilation.HasDynamicEmitAttributes() && compilation.CanEmitBoolean()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(this.ReturnType, this.ReturnTypeCustomModifiers.Length)); } } internal sealed override bool GenerateDebugInfo { get { return _generateDebugInfo; } } public sealed override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return _typeParameters; } } public sealed override ImmutableArray<TypeSymbol> TypeArguments { get { return _typeParameters.Cast<TypeParameterSymbol, TypeSymbol>(); } } internal override RefKind RefKind { get { return _interfaceMethod.RefKind; } } public sealed override TypeSymbol ReturnType { get { return _returnType; } } public override ImmutableArray<ParameterSymbol> Parameters { get { return _parameters; } } public override Symbol ContainingSymbol { get { return _implementingType; } } public override NamedTypeSymbol ContainingType { get { return _implementingType; } } internal override bool IsExplicitInterfaceImplementation { get { return true; } } public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations { get { return _explicitInterfaceImplementations; } } public override MethodKind MethodKind { get { return MethodKind.ExplicitInterfaceImplementation; } } public override Accessibility DeclaredAccessibility { get { return Accessibility.Private; } } public override Symbol AssociatedSymbol { get { return _associatedProperty; } } public override bool HidesBaseMethodsByName { get { return false; } } public override ImmutableArray<Location> Locations { get { return ImmutableArray<Location>.Empty; } } public override bool IsStatic { get { return false; } } public override bool IsAsync { get { return false; } } public override bool IsVirtual { get { return false; } } public override bool IsOverride { get { return false; } } public override bool IsAbstract { get { return false; } } public override bool IsSealed { get { return false; } } public override bool IsExtern { get { return false; } } public override bool IsExtensionMethod { get { return false; } } public override string Name { get { return _name; } } internal sealed override bool HasSpecialName { get { return _interfaceMethod.HasSpecialName; } } internal sealed override System.Reflection.MethodImplAttributes ImplementationAttributes { get { return default(System.Reflection.MethodImplAttributes); } } internal sealed override bool RequiresSecurityObject { get { return _interfaceMethod.RequiresSecurityObject; } } internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { return true; } internal override bool IsMetadataFinal { get { return true; } } internal sealed override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) { return true; } public override DllImportData GetDllImportData() { return null; } internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation { get { return null; } } internal override bool HasDeclarativeSecurity { get { return false; } } internal override IEnumerable<Microsoft.Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<string> GetAppliedConditionalSymbols() { return ImmutableArray<string>.Empty; } } }
{ "content_hash": "629b4123446d3dd89a54c7a057a68114", "timestamp": "", "source": "github", "line_count": 275, "max_line_length": 161, "avg_line_length": 30.265454545454546, "alnum_prop": 0.616484440706476, "repo_name": "jaredpar/roslyn", "id": "e628322b195f42a46fbf53e8c95df99fbe360e8a", "size": "8325", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedImplementationMethod.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "15099" }, { "name": "C#", "bytes": "80732271" }, { "name": "C++", "bytes": "6311" }, { "name": "F#", "bytes": "421" }, { "name": "Groovy", "bytes": "7036" }, { "name": "Makefile", "bytes": "3606" }, { "name": "PowerShell", "bytes": "25894" }, { "name": "Shell", "bytes": "7453" }, { "name": "Visual Basic", "bytes": "61232818" } ], "symlink_target": "" }
gradlew.bat clean check assemble lib:install lib:bintrayUpload cli:fatJar
{ "content_hash": "3dedc3f4a5399c56fe6ea517eec554e3", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 73, "avg_line_length": 73, "alnum_prop": 0.863013698630137, "repo_name": "raybritton/json-query", "id": "b74c4ef402d1f825d094e359650b789be0dacfca", "size": "73", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "release.bat", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "73" }, { "name": "Kotlin", "bytes": "252374" }, { "name": "Shell", "bytes": "71" } ], "symlink_target": "" }
package system.file; import java.util.*; import java.io.*; import org.xml.sax.helpers.*; import org.xml.sax.*; import system.file.xml.XMLReader; import system.*; /** * The device configuration parser class. This class performs the loading and validation of the XML device configuration file. */ public class DeviceConfigParser { /** The device configuration parser handler. */ private DeviceConfigParserHandler handler; /** The XML device configuration file (path and name). */ private String deviceconfig_file; // description section /** The version of the device module. */ private String version = ""; /** The company's device name. */ private String company = ""; /** The author name of the device module. */ private String author = ""; /** The device name. */ private String name = ""; /** The version date of the device module. */ private String date = ""; /** The observation of the device module. */ private String obs = ""; // device section /** The list of the with the registers name. */ private Vector<String> reg_class; /** The number of registers. */ private int number_registers; /** The device class name. */ private String dev_class; /** * Instantiates a new device configuration parser. */ public DeviceConfigParser() { handler = new DeviceConfigParserHandler(); reg_class = new Vector<String>(); } //----------------------------------------- // method used to load and verify xml files //----------------------------------------- /** * Loads the XML device configuration file (path and name). * * @param deviceconfig_file the XML device configuration file (path and name). * @throws DeviceConfigParserException if any error occur when loads the XML device configuration file. */ public void load(String deviceconfig_file) throws DeviceConfigParserException { XMLReader inputXml; File file; this.deviceconfig_file = deviceconfig_file; try { file = new File(deviceconfig_file); inputXml = new XMLReader(file); inputXml.read(handler); verify(); } catch(DeviceConfigParserException e) { throw new DeviceConfigParserException(e.getMessage()); } catch(IOException e) { throw new DeviceConfigParserException(e.getMessage()); } catch(SAXException e) { throw new DeviceConfigParserException(e.getMessage()); } } /** * Verifies the validation of the content of the XML cpu configuration file. * * @throws DeviceConfigParserException if any error occur when verifies the validation of the content of the XML device configuration file. */ private void verify() throws DeviceConfigParserException { int aux_a; int aux_b; try { Class.forName(Configuration.devices + "." + dev_class + "." + dev_class); } catch(ClassNotFoundException e) { throw new DeviceConfigParserException(dev_class + ", OPB Device not exist."); } if(number_registers != reg_class.size()) throw new DeviceConfigParserException(dev_class + ", OPB Device the number of registers is " + number_registers + " and the defined registers are " + reg_class.size() + "."); for(aux_a = 0;aux_a < number_registers - 1;aux_a++) for(aux_b = aux_a + 1;aux_b < number_registers;aux_b++) if(reg_class.get(aux_a).equals(reg_class.get(aux_b))) throw new DeviceConfigParserException(dev_class + ", OPB Device have two or more registers with the name " + reg_class.get(aux_a) + "."); for(aux_a = 0;aux_a < number_registers;aux_a++) if(dev_class.equals(reg_class.get(aux_a))) throw new DeviceConfigParserException(dev_class + ", OPB Device have one or more registers with the name of the device"); try { for(aux_a = 0;aux_a < number_registers;aux_a++) Class.forName(Configuration.devices + "." + dev_class + "." + reg_class.get(aux_a)); } catch(ClassNotFoundException e) { throw new DeviceConfigParserException("in the " + dev_class + ", OPB Device is missing the " + reg_class.get(aux_a) + " register."); } } //-------------------------------- // methods used for accessing data //-------------------------------- /** * Returns the device name. * * @return the device name. */ public String getDescription_name() { return name; } /** * Returns the author name of the device module. * * @return the author name of the device module. */ public String getDescription_author() { return author; } /** * Returns the company's device name. * * @return the company's device name. */ public String getDescription_company() { return company; } /** * Returns the version of the device module. * * @return the version of the device module. */ public String getDescription_version() { return version; } /** * Returns the version date of the device module. * * @return the version date of the device module. */ public String getDescription_date() { return date; } /** * Returns the observation of the device module. * * @return the observation of the device module. */ public String getDescription_obs() { return obs; } /** * Returns the number of registers of the device. * * @return the number of registers of the device. */ public int getNumber_registers() { return number_registers; } /** * Returns the device. * * @return the device. */ public String getDev_class_name() { return dev_class; } /** * Returns the list with the name of the device registers. * * @return the list with the name of the device registers. */ public Vector<String> getReg_class_names() { return reg_class; } // ---------------------------------------------- // method for displaying the contents of xml file // ---------------------------------------------- /** * Displays the content of the XML device configuration file. */ public void show() { int aux; System.out.println(""); System.out.println("OPB Device definition"); System.out.println(""); System.out.println(" File"); System.out.println(" . Name: " + deviceconfig_file); System.out.println(""); System.out.println(" Description"); System.out.println(" . Name : " + name); System.out.println(" . Version: " + version); System.out.println(" . Author : " + author); System.out.println(" . Company: " + company); System.out.println(" . Date : " + date); System.out.println(" . Obs : " + obs); System.out.println(""); System.out.println(" OPB Device"); System.out.println(" . Name: " + dev_class); System.out.println(""); System.out.println(" Registers"); System.out.println(" . Number: " + number_registers); if(reg_class.size() > 0) for(aux = 0;aux < reg_class.size();aux++) System.out.println(" . Register: " + reg_class.get(aux)); } //-------------------------------------------------------- // class used to handle xml files of the SystemConfig type //-------------------------------------------------------- /** * The device configuration parser handler class. */ private class DeviceConfigParserHandler extends DefaultHandler { /** The current element. */ private String currentElement = null; //--------------------------------- // methods used to process the tags //--------------------------------- /** * Receive notification of the beginning of an element. * * @param uri the Namespace URI, or the empty string if the element has no Namespace URI or if Namespace processing is not being performed. * @param localName the local name (without prefix), or the empty string if Namespace processing is not being performed. * @param qName the qualified name (with prefix), or the empty string if qualified names are not available. * @param attributes the attributes attached to the element. If there are no attributes, it shall be an empty Attributes object. The value of this object after startElement returns is undefined. * @throws SAXException any SAX exception, possibly wrapping another exception. * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) */ public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException { long value; try { if(qName.equalsIgnoreCase("NAME")) { currentElement = qName; } else if(qName.equalsIgnoreCase("AUTHOR")) { currentElement = qName; } else if(qName.equalsIgnoreCase("VERSION")) { currentElement = qName; } else if(qName.equalsIgnoreCase("COMPANY")) { currentElement = qName; } else if(qName.equalsIgnoreCase("DATE")) { currentElement = qName; } else if(qName.equalsIgnoreCase("OBS")) { currentElement = qName; } else if(qName.equalsIgnoreCase("DEVCLASS")) { try { if(attributes.getValue("name").length() == 0) throw new DeviceConfigParserException("the OPB Device most have a name."); dev_class = attributes.getValue("name"); value = Integer.parseInt(attributes.getValue("number"),10); number_registers = (int)value; if(value < 0) throw new DeviceConfigParserException("the number of registers is less then 0."); } catch(NumberFormatException e) { throw new SAXException("the number of registers is not a decimal number."); } catch(DeviceConfigParserException e) { throw new SAXException(e.getMessage()); } } else if(qName.equalsIgnoreCase("REG")) { currentElement = qName; } } catch(Exception e) { throw new SAXException(e.getMessage()); } } /** * Receive notification of the end of an element. * * @param namespaceURI the Namespace URI, or the empty string if the element has no Namespace URI or if Namespace processing is not being performed. * @param localName the local name (without prefix), or the empty string if Namespace processing is not being performed. * @param qName the qualified XML name (with prefix), or the empty string if qualified names are not available. * @throws SAXException any SAX exception, possibly wrapping another exception. * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String) */ public void endElement(String namespaceURI, String localName,String qName) throws SAXException { try { } catch(Exception e) { throw new SAXException(e.getMessage()); } } /** * Receive notification of character data. * * @param ch the characters from the XML document. * @param start the start position in the array. * @param length the number of characters to read from the array. * @throws SAXException any SAX exception, possibly wrapping another exception. * @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int) */ public void characters(char ch[],int start,int length) throws SAXException { String string; try { string = new String(ch,start,length); if(!string.trim().equals("")) { if(currentElement.equalsIgnoreCase("NAME")) { name = string; } else if(currentElement.equalsIgnoreCase("VERSION")) { version = string; } else if(currentElement.equalsIgnoreCase("AUTHOR")) { author = string; } else if(currentElement.equalsIgnoreCase("COMPANY")) { company = string; } else if(currentElement.equalsIgnoreCase("DATE")) { date = string; } else if(currentElement.equalsIgnoreCase("OBS")) { obs = string; } else if(currentElement.equalsIgnoreCase("REG")) { reg_class.add(string); } } } catch(Exception e) { throw new SAXException(e.getMessage()); } } //---------------------------- // methods used to deal errors //---------------------------- /** * Receive notification of a recoverable parser error. * * @param exception the error information encoded as an exception. * @throws SAXException any SAX exception, possibly wrapping another exception. * @see org.xml.sax.helpers.DefaultHandler#error(org.xml.sax.SAXParseException) */ public void error(SAXParseException exception) throws SAXException { throw new SAXException(deviceconfig_file + ",XML file don't respect the Document Type Definition."); } /** * Report a fatal XML parsing error. * * @param exception the error information encoded as an exception. * @throws SAXException any SAX exception, possibly wrapping another exception. * @see org.xml.sax.helpers.DefaultHandler#fatalError(org.xml.sax.SAXParseException) */ public void fatalError(SAXParseException exception) throws SAXException { throw new SAXException(deviceconfig_file + ",XML file fatalError."); } /** * Receive notification of a parser warning. * * @param exception the warning information encoded as an exception. * @throws SAXException any SAX exception, possibly wrapping another exception. * @see org.xml.sax.helpers.DefaultHandler#warning(org.xml.sax.SAXParseException) */ public void warning(SAXParseException exception) throws SAXException { throw new SAXException(deviceconfig_file + ",XML file warning."); } //---------------------------------------------------------- // method used when can not open o DTD in the program folder //---------------------------------------------------------- /** * Allow the application to resolve external entities. * * @param publicId the public identifier of the external entity being referenced, or null if none was supplied. * @param systemId the system identifier of the external entity being referenced. * @return an InputSource object describing the new input source, or null to request that the parser open a regular URI connection to the system identifier. * @throws SAXException any SAX exception, possibly wrapping another exception. * @see org.xml.sax.helpers.DefaultHandler#resolveEntity(java.lang.String, java.lang.String) */ public InputSource resolveEntity(String publicId, String systemId) throws SAXException { FileInputStream fis; File fl; try { fl = new File(Configuration.configuration_folder + "deviceconfig.dtd"); fis = new FileInputStream(fl); return new InputSource(fis); } catch(Exception e) { throw new SAXException("missing the file Document Type Definition."); } } } }
{ "content_hash": "c8f442a684cfd9f98baa47f7760e88c3", "timestamp": "", "source": "github", "line_count": 490, "max_line_length": 196, "avg_line_length": 29.46530612244898, "alnum_prop": 0.655007618783765, "repo_name": "hetau/cycle", "id": "7d6a4c841930b667b3f8795cb242c61f4bced420", "size": "14438", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/system/file/DeviceConfigParser.java", "mode": "33261", "license": "apache-2.0", "language": [], "symlink_target": "" }
 CKEDITOR.plugins.setLang( 'liststyle', 'th', { armenian: 'Armenian numbering', bulletedTitle: 'Bulleted List Properties', circle: 'Circle', decimal: 'Decimal (1, 2, 3, etc.)', decimalLeadingZero: 'Decimal leading zero (01, 02, 03, etc.)', disc: 'Disc', georgian: 'Georgian numbering (an, ban, gan, etc.)', lowerAlpha: 'Lower Alpha (a, b, c, d, e, etc.)', lowerGreek: 'Lower Greek (alpha, beta, gamma, etc.)', lowerRoman: 'Lower Roman (i, ii, iii, iv, v, etc.)', none: 'None', notset: '<not set>', numberedTitle: 'Numbered List Properties', square: 'Square', start: 'Start', type: 'Type', upperAlpha: 'Upper Alpha (A, B, C, D, E, etc.)', upperRoman: 'Upper Roman (I, II, III, IV, V, etc.)', validateStartNumber: 'List start number must be a whole number.' });
{ "content_hash": "590833c06f77cbf269701b5432095e1b", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 65, "avg_line_length": 36.45454545454545, "alnum_prop": 0.6334164588528678, "repo_name": "bkahlert/com.bkahlert.nebula", "id": "212aff32151e75cb6257a0e128f67ba78f67c7be", "size": "951", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "src/com/bkahlert/nebula/widgets/composer/html/plugins/liststyle/lang/th.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "509981" }, { "name": "Java", "bytes": "3235793" }, { "name": "JavaScript", "bytes": "4263220" }, { "name": "PHP", "bytes": "2219" }, { "name": "Ruby", "bytes": "578" }, { "name": "Shell", "bytes": "26" } ], "symlink_target": "" }
package ru.job4j.ioc.xml;
{ "content_hash": "43ad1ae983256b86270a272584e701c1", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 25, "avg_line_length": 25, "alnum_prop": 0.8, "repo_name": "fr3anthe/ifedorenko", "id": "f792df52318affc0f45c8dab2984ccb060b4fb73", "size": "25", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "3.2-Spring/3.2.1.1-IoC/src/main/java/ru/job4j/ioc/xml/package-info.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "6874" }, { "name": "Java", "bytes": "660982" }, { "name": "JavaScript", "bytes": "2186" }, { "name": "XSLT", "bytes": "418" } ], "symlink_target": "" }
require_relative '../print_table' require_relative '../ui/ui' module FastlaneCore # Responsible for loading configuration files class ConfigurationFile class ExceptionWhileParsingError < RuntimeError attr_reader :wrapped_exception attr_reader :recovered_options def initialize(wrapped_ex, options) @wrapped_exception = wrapped_ex @recovered_options = options end end # Available keys from the config file attr_accessor :available_keys # After loading, contains all the found options attr_accessor :options # Path to the config file represented by the current object attr_accessor :configfile_path # @param config [FastlaneCore::Configuration] is used to gather required information about the configuration # @param path [String] The path to the configuration file to use def initialize(config, path, block_for_missing, skip_printing_values = false) self.available_keys = config.all_keys self.configfile_path = path self.options = {} @block_for_missing = block_for_missing content = File.read(path) # From https://github.com/orta/danger/blob/master/lib/danger/Dangerfile.rb if content.tr!('“”‘’‛', %(""''')) UI.error("Your #{File.basename(path)} has had smart quotes sanitised. " \ 'To avoid issues in the future, you should not use ' \ 'TextEdit for editing it. If you are not using TextEdit, ' \ 'you should turn off smart quotes in your editor of choice.') end begin # rubocop:disable Security/Eval eval(content) # this is okay in this case # rubocop:enable Security/Eval print_resulting_config_values unless skip_printing_values # only on success rescue SyntaxError => ex line = ex.to_s.match(/\(eval\):(\d+)/)[1] UI.user_error!("Syntax error in your configuration file '#{path}' on line #{line}: #{ex}") rescue => ex raise ExceptionWhileParsingError.new(ex, self.options), "Error while parsing config file at #{path}" end end def print_resulting_config_values require 'terminal-table' UI.success("Successfully loaded '#{File.expand_path(self.configfile_path)}' 📄") # Show message when self.modified_values is empty if self.modified_values.empty? UI.important("No values defined in '#{self.configfile_path}'") return end rows = self.modified_values.collect do |key, value| [key, value] if value.to_s.length > 0 end.compact puts("") puts(Terminal::Table.new(rows: FastlaneCore::PrintTable.transform_output(rows), title: "Detected Values from '#{self.configfile_path}'")) puts("") end # This is used to display only the values that have changed in the summary table def modified_values @modified_values ||= {} end def method_missing(method_sym, *arguments, &block) # First, check if the key is actually available return if self.options.key?(method_sym) if self.available_keys.include?(method_sym) value = arguments.first value = yield if value.nil? && block_given? if value.nil? unless block_given? # The config file has something like this: # # clean # # without specifying a value for the method call # or a block. This is most likely a user error # So we tell the user that they can provide a value warning = ["In the config file '#{self.configfile_path}'"] warning << "you have the line #{method_sym}, but didn't provide" warning << "any value. Make sure to append a value right after the" warning << "option name. Make sure to check the docs for more information" UI.important(warning.join(" ")) end return end self.modified_values[method_sym] = value # to support frozen strings (e.g. ENV variables) too # we have to dupe the value # in < Ruby 2.4.0 `.dup` is not support by boolean values # and there is no good way to check if a class actually # responds to `dup`, so we have to rescue the exception begin value = value.dup rescue TypeError # Nothing specific to do here, if we can't dupe, we just # deal with it (boolean values can't be from env variables anyway) end self.options[method_sym] = value else # We can't set this value, maybe the tool using this configuration system has its own # way of handling this block, as this might be a special block (e.g. ipa block) that's only # executed on demand if @block_for_missing @block_for_missing.call(method_sym, arguments, block) else self.options[method_sym] = '' # important, since this will raise a good exception for free end end end # Override configuration for a specific lane. If received lane name does not # match the lane name available as environment variable, no changes will # be applied. # # @param lane_name Symbol representing a lane name. # @yield Block to run for overriding configuration values. # def for_lane(lane_name) if ENV["FASTLANE_LANE_NAME"] == lane_name.to_s with_a_clean_config_merged_when_complete do yield end end end # Override configuration for a specific platform. If received platform name # does not match the platform name available as environment variable, no # changes will be applied. # # @param platform_name Symbol representing a platform name. # @yield Block to run for overriding configuration values. # def for_platform(platform_name) if ENV["FASTLANE_PLATFORM_NAME"] == platform_name.to_s with_a_clean_config_merged_when_complete do yield end end end # Allows a configuration block (for_lane, for_platform) to get a clean # configuration for applying values, so that values can be overridden # (once) again. Those values are then merged into the surrounding # configuration as the block completes def with_a_clean_config_merged_when_complete previous_config = self.options.dup self.options = {} begin yield ensure self.options = previous_config.merge(self.options) end end end end
{ "content_hash": "7c076e68c8209fac5d4f8ac985a707b1", "timestamp": "", "source": "github", "line_count": 180, "max_line_length": 112, "avg_line_length": 36.55, "alnum_prop": 0.6350509195926433, "repo_name": "luongm/fastlane", "id": "8c60d19061fb6c31bbed9389023e0620149b8124", "size": "6592", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "fastlane_core/lib/fastlane_core/configuration/configuration_file.rb", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "45370" }, { "name": "Java", "bytes": "30810" }, { "name": "JavaScript", "bytes": "39" }, { "name": "Matlab", "bytes": "115" }, { "name": "Objective-C", "bytes": "69198" }, { "name": "Ruby", "bytes": "4031573" }, { "name": "Shell", "bytes": "45206" }, { "name": "Swift", "bytes": "441044" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_232) on Tue Sep 15 08:53:04 UTC 2020 --> <title>Uses of Class org.springframework.aop.aspectj.annotation.PrototypeAspectInstanceFactory (Spring Framework 5.1.18.RELEASE API)</title> <meta name="date" content="2020-09-15"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.springframework.aop.aspectj.annotation.PrototypeAspectInstanceFactory (Spring Framework 5.1.18.RELEASE API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/springframework/aop/aspectj/annotation/PrototypeAspectInstanceFactory.html" title="class in org.springframework.aop.aspectj.annotation">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Spring Framework</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/springframework/aop/aspectj/annotation/class-use/PrototypeAspectInstanceFactory.html" target="_top">Frames</a></li> <li><a href="PrototypeAspectInstanceFactory.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.springframework.aop.aspectj.annotation.PrototypeAspectInstanceFactory" class="title">Uses of Class<br>org.springframework.aop.aspectj.annotation.PrototypeAspectInstanceFactory</h2> </div> <div class="classUseContainer">No usage of org.springframework.aop.aspectj.annotation.PrototypeAspectInstanceFactory</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/springframework/aop/aspectj/annotation/PrototypeAspectInstanceFactory.html" title="class in org.springframework.aop.aspectj.annotation">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Spring Framework</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/springframework/aop/aspectj/annotation/class-use/PrototypeAspectInstanceFactory.html" target="_top">Frames</a></li> <li><a href="PrototypeAspectInstanceFactory.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "33306ffd799a455f179bddd21c243bb9", "timestamp": "", "source": "github", "line_count": 126, "max_line_length": 209, "avg_line_length": 40, "alnum_prop": 0.635515873015873, "repo_name": "akhr/java", "id": "037b6f779bedec608aa6bc1b5c7251e772fbfe6b", "size": "5040", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Spring/jars/spring-framework-5.1.18.RELEASE/docs/javadoc-api/org/springframework/aop/aspectj/annotation/class-use/PrototypeAspectInstanceFactory.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "93017" }, { "name": "HTML", "bytes": "203648040" }, { "name": "Java", "bytes": "1237949" }, { "name": "JavaScript", "bytes": "827" }, { "name": "Shell", "bytes": "59" } ], "symlink_target": "" }
- Feature Name: Stateless Replica Relocation - Status: completed - Start Date: 2015-08-19 - RFC PR: [#2171](https://github.com/cockroachdb/cockroach/pull/2171) - Cockroach Issue: [#620](https://github.com/cockroachdb/cockroach/issues/620) # Summary A relocation is, conceptually, the transfer of a single replica from one store to another. However, the implementation is necessarily the combination of two operations: 1. Creating a new replica for a range on a new store. 2. Removing a replica of the same range from a different store. For example, by creating a replica on store Y and then removing a replica from store X, you have in effect moved the replica from X to Y. This RFC is suggesting an overall architectural design goal: that the decision to make any individual operation (either a create or a remove) should be **stateless**. In other words, the second operation in a replica relocation should not depend on a specific invocation of the first operation. # Motivation For an assortment of reasons, Cockroach will often need to relocate the replicas of a range. Most immediately, this is needed for repair (when a store dies and its replicas are no longer usable) and rebalance (relocating replicas on overloaded stores to stores with excess capacity). A relocation must be expressed as a combination of two operations: 1. Creating a new replica for a range on a new store. 2. Removing a replica of the same range from a different store. These operations can happen in either order as long as quorum is maintained in the range's raft group after each individual operation, although one ordering may be preferred over another. Expressing a specific relocation (i.e. "move replica from store X to store Y") would require maintaining some persistent state to link the two operations involved. Storing that state presents a number of issues: where is it stored, in memory or on disk? If it's in memory, does it have to be replicated through raft or is it local to one node? If on disk, can the persistent state become stale? How do you detect conflicts between two relocation operations initiated from different places? This RFC suggests that no such relocation state should be persisted. Instead, a system that wants to initiate a relocation will perform only the first operation; a different system will later detect the need for a complementary operation and perform it. A relocation is thus completed without any state being exchanged between those two systems. By eliminating the need to persist any data about in-progress relocation operations, the overall system is dramatically simplified. # Detailed design The implementation involves a few pieces: 1. Each range must have a persisted *target replication state*. This does not prescribe specific replica locations; it specifies a required count of replicas, along with some desired attributes for the stores where they are placed. 2. The core mechanic is a stateless function which can compare the immediate replication state of a range to its target replication state; if the target state is different, this function will either create or remove a replica in order to move the range towards the target replication state. By running multiple times (adding or removing a replica each time), the target replication state will eventually be matched. 3. Any operations that wish to *relocate* a replica need only perform the first operation of the relocation (either a create or a remove). This will perturb the range's replication state away from the target; the core function will later detect that mismatch, and correct it by performing the complementary operation of the relocation (a remove or a create). The first piece is already present: each range has a zone configuration which determines the target replication state for the range. The second piece, the core mechanic, will be performed by the existing "replicate queue" which will be renamed the "*replication queue*". This queue is already used to add replicas to ranges which are under-replicated; it can be enhanced to remove replicas from over-replicated ranges, thus satisfying the basic requirements of the core mechanic. The third piece simply informs the design of systems performing relocations; for example, the upcoming repair and rebalance systems (still being planned). After identifying a relocation opportunity, these systems will perform the first operation of the relocation (add or remove) and then insert the corresponding replica into the local replication queue. The replication queue will then perform the complementary operation. The final complication is how to ensure that the replicate queue promptly identifies ranges outside of their ideal target state. As a queue it will be attached to the replica scanner, but we will also want to enqueue a replica immediately whenever we knowingly perturb the replication state. Thus, components initiating a relocation (e.g. rebalance or repair) should immediately enqueue their target replicas after changing the replication state. # Drawbacks ### Specific Move Operations A stateless model for relocation precludes the ability to request specific relocations; only the first operation can be made with specificity. For example, the verb "Move replica from X to Y" cannot be expressed with certainty; instead, only "Move replica to X from (some store)" or "Move replica to Y from (some store)" can be expressed. The replicate queue will be responsible for selecting an appropriate store for the complementary operation. It is assumed that this level of specificity is simply not needed for any relocation operations; there is no currently apparent use case where a move between a specific pair of stores is needed. Even if this was necessary, it might be possible to express by manipulating the factors behind the individual stateless decisions. ### Thrashing of complementary operation Because there is no relocation state, the possibility of "thrashing" is introduced. For example: 1. Rebalance operation adds a new replica to the range. 2. The replicate queue picks up the range and detects the need to remove a replica; however, it decides to remove the replica that was just added. This is possible if the rebalance's criteria for new replica selection are sufficiently different from the replicate queue's selection criteria for removing a replica. To reduce this risk, there must be sufficient agreement in the criteria between the operations; a Rebalance operation should avoid adding a new replica if there's a realistic chance that the replicate queue will immediately remove it. This can realized by adding a "buffer" zone between the different criteria; that is, when selecting a replica to add, the new replica should be *significantly* removed from the criteria for removing a replica, thus reducing the chances that it will be selected. When properly tuned to avoid thrashing, the stateless nature could instead be considered a positive because it can respond to changes during the interim; consider if, due to a delay, the relative health of nodes changes and the originally selected replica is no longer a good option. The stateless system will respond correctly to this situation. ### Delay in complementary operation By separating the two operations, we are possibly delaying the application of the second operation. For example, the replicate queue could be very busy, or an untimely crash could result in the range being under- or over-replicated without being in the replicate queue on any store. However, many of these concerns are allayed by the existence of repair; if the node goes down, the repair system will add the range to the replicate queue on another store. Even in an exotic failure scenario, the stateless design will eventually detect the replication anomaly through the normal operation of the replica scanner. ### Lack of non-voting replicas Our raft implementation currently lacks support for non-voting members; as a result, some types of relocation will temporarily make the effected range more fragile. When initially creating a replica, it is very far behind the current state of the range and thus needs to receive a snapshot. It may take some time before the range fully catches up and can take place in quorum commits. However, without non-voting replicas we have no choice but to add the new replica as a full member, thus changing the quorum requirements of the group. In the case of odd-numbered ranges, this will increase the quorum count by one, with the new range unable to be part of a quorum decision. This increases the chance of losing quorum until that replica is caught up, thus reducing availability. This could be mitigated somewhat without having to completely add-non voting replicas; in preparation for adding a replica, we could manually generate a snapshot and send it to the node *before* adding it to the raft configuration. This would decrease the window of time between adding the replica and having it fully catch up. "Lack of Non-voting replicas" is listed this as a drawback because going forward with relocation *without* non-voting replication introduces this fragility, regardless of how relocation decisions are made. Stateless relocation will still work correctly when non-voting replicas are implemented; there will simply be a delay in the case where a replica is added first (e.g. rebalance), with the removal not taking place until the non-voting replica catches up and is upgraded to a full group member. This is not trivial, but will still allow for stateless decisions. # Alternatives The main alternative would be some sort of stateful system, where relocation operations would be expressed explicitly (i.e. "Move replica from X to Y") and then seen to completion. For reasons outlined in the "motivation" section, this is considered sub-optimal when making distributed decisions. ### Relocation Master The ultimate expression of this would be the designation of a "Relocation master", a single node that makes all relocation decisions for the entire cluster There is enough information in gossip for a central node to make acceptable decisions about replica movement. In some ways the individual decisions would be worse, because they would be unable to consider current raft state; however, in aggregate the decisions could be much better, because the central master could consider groups of relocations together. For example, it would be able to avoid distributed pitfalls such as under-loaded nodes being suddenly inundated with requests for new replicas. It would be able to more quickly and correctly move replicas to new nodes introduced to the system. This system would also have an easier time communicating the individual relocation decisions that were made. This could be helpful for debugging or tweaking relocation criteria. However, It's important to note that a relocation master is not entirely incompatible with the "stateless" design; the relocation master could simply be the initiator of the stateless operations. You could thus get much of the improved decision making and communication of the master without having to move to a stateful design. # Unresolved questions ### Raft leader constraint The biggest unresolved issue is the requirement for relocation decisions to be constrained to the raft leader. For example, there is no firm need for a relocation operation to be initiated from a range leader; a secondary replica can safely initiate an add or remove replica, with the safety being guaranteed by a combination of raft and cockroach's transactions. However, if the criteria for an operation wants to consider raft state (such as which nodes are behind in replication), those decisions could only be made from the raft leader (which is the only node that has the full raft state). Alternatively, an interface could be provided for non-leader members to query that information from the leader.
{ "content_hash": "f08e05049e2a87247969b62a690ad4a4", "timestamp": "", "source": "github", "line_count": 230, "max_line_length": 86, "avg_line_length": 52.143478260869564, "alnum_prop": 0.8058033853080964, "repo_name": "paperstreet/cockroach", "id": "10586ead083fb468fc0ed3c47d030a1811e6dec4", "size": "11993", "binary": false, "copies": "25", "ref": "refs/heads/master", "path": "docs/RFCS/stateless_replica_relocation.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "1029" }, { "name": "C", "bytes": "6345" }, { "name": "C++", "bytes": "61409" }, { "name": "CSS", "bytes": "29259" }, { "name": "Go", "bytes": "4557679" }, { "name": "HCL", "bytes": "20417" }, { "name": "HTML", "bytes": "5083" }, { "name": "JavaScript", "bytes": "1439" }, { "name": "Makefile", "bytes": "22428" }, { "name": "Protocol Buffer", "bytes": "122526" }, { "name": "Ruby", "bytes": "1408" }, { "name": "Shell", "bytes": "40578" }, { "name": "Smarty", "bytes": "1514" }, { "name": "TypeScript", "bytes": "227222" }, { "name": "Yacc", "bytes": "102312" } ], "symlink_target": "" }
package org.apache.struts2.convention.actions.params; import org.apache.struts2.convention.annotation.Action; public class ActionParamsMethodLevelAction { private String param1; private String param2; @Action(value = "actionParam1", params = {"param1", "val1", "param2", "val2"}) public String run1() throws Exception { return null; } public String getParam1() { return param1; } public void setParam1(String param1) { this.param1 = param1; } public String getParam2() { return param2; } public void setParam2(String param2) { this.param2 = param2; } }
{ "content_hash": "38c44e14c4136cafabb31baad866a059", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 82, "avg_line_length": 21.766666666666666, "alnum_prop": 0.6462480857580398, "repo_name": "shuliangtao/struts-2.3.24", "id": "42ac1fc0716b175b772bbd8584ebd16dc7efd3b4", "size": "1470", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/plugins/convention/src/test/java/org/apache/struts2/convention/actions/params/ActionParamsMethodLevelAction.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "22970" }, { "name": "CSS", "bytes": "73781" }, { "name": "FreeMarker", "bytes": "327079" }, { "name": "HTML", "bytes": "1055902" }, { "name": "Java", "bytes": "10176206" }, { "name": "JavaScript", "bytes": "3966249" }, { "name": "XSLT", "bytes": "8112" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello World, Click Me!</string> <string name="app_name">CommunicationService.Android</string> </resources>
{ "content_hash": "2b26120872c277b21fd8a9ddd032973a", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 62, "avg_line_length": 36.4, "alnum_prop": 0.7142857142857143, "repo_name": "AlexStefan/template-app", "id": "801cc6f140a1b9598af62a880c56f19bb538cf02", "size": "184", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CommunicationService/CommunicationService.Android/Resources/values/Strings.xml", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "116115" }, { "name": "PowerShell", "bytes": "8700" } ], "symlink_target": "" }
package org.apache.camel.component.netty.http.handlers; import java.net.SocketAddress; import java.net.URI; import java.nio.channels.ClosedChannelException; import java.nio.charset.Charset; import java.util.Iterator; import javax.security.auth.Subject; import javax.security.auth.login.LoginException; import org.apache.camel.Exchange; import org.apache.camel.LoggingLevel; import org.apache.camel.component.netty.NettyConsumer; import org.apache.camel.component.netty.NettyHelper; import org.apache.camel.component.netty.handlers.ServerChannelHandler; import org.apache.camel.component.netty.http.HttpPrincipal; import org.apache.camel.component.netty.http.NettyHttpConsumer; import org.apache.camel.component.netty.http.NettyHttpSecurityConfiguration; import org.apache.camel.component.netty.http.SecurityAuthenticator; import org.apache.camel.util.CamelLogger; import org.apache.camel.util.ObjectHelper; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.handler.codec.base64.Base64; import org.jboss.netty.handler.codec.http.DefaultHttpResponse; import org.jboss.netty.handler.codec.http.HttpHeaders; import org.jboss.netty.handler.codec.http.HttpRequest; import org.jboss.netty.handler.codec.http.HttpResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.jboss.netty.handler.codec.http.HttpHeaders.is100ContinueExpected; import static org.jboss.netty.handler.codec.http.HttpHeaders.isKeepAlive; import static org.jboss.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST; import static org.jboss.netty.handler.codec.http.HttpResponseStatus.CONTINUE; import static org.jboss.netty.handler.codec.http.HttpResponseStatus.METHOD_NOT_ALLOWED; import static org.jboss.netty.handler.codec.http.HttpResponseStatus.SERVICE_UNAVAILABLE; import static org.jboss.netty.handler.codec.http.HttpResponseStatus.UNAUTHORIZED; import static org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1; /** * Netty HTTP {@link ServerChannelHandler} that handles the incoming HTTP requests and routes * the received message in Camel. */ public class HttpServerChannelHandler extends ServerChannelHandler { // use NettyHttpConsumer as logger to make it easier to read the logs as this is part of the consumer private static final Logger LOG = LoggerFactory.getLogger(NettyHttpConsumer.class); private final NettyHttpConsumer consumer; private HttpRequest request; public HttpServerChannelHandler(NettyHttpConsumer consumer) { super(consumer); this.consumer = consumer; } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent messageEvent) throws Exception { // store request, as this channel handler is created per pipeline request = (HttpRequest) messageEvent.getMessage(); LOG.debug("Message received: {}", request); if (is100ContinueExpected(request)) { // send back http 100 response to continue HttpResponse response = new DefaultHttpResponse(HTTP_1_1, CONTINUE); messageEvent.getChannel().write(response); return; } if (consumer.isSuspended()) { // are we suspended? LOG.debug("Consumer suspended, cannot service request {}", request); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, SERVICE_UNAVAILABLE); response.setChunked(false); response.setHeader(Exchange.CONTENT_TYPE, "text/plain"); response.setHeader(Exchange.CONTENT_LENGTH, 0); response.setContent(ChannelBuffers.copiedBuffer(new byte[]{})); messageEvent.getChannel().write(response); return; } if (consumer.getEndpoint().getHttpMethodRestrict() != null && !consumer.getEndpoint().getHttpMethodRestrict().contains(request.getMethod().getName())) { HttpResponse response = new DefaultHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED); response.setChunked(false); response.setHeader(Exchange.CONTENT_TYPE, "text/plain"); response.setHeader(Exchange.CONTENT_LENGTH, 0); response.setContent(ChannelBuffers.copiedBuffer(new byte[]{})); messageEvent.getChannel().write(response); return; } if ("TRACE".equals(request.getMethod().getName()) && !consumer.getEndpoint().isTraceEnabled()) { HttpResponse response = new DefaultHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED); response.setChunked(false); response.setHeader(Exchange.CONTENT_TYPE, "text/plain"); response.setHeader(Exchange.CONTENT_LENGTH, 0); response.setContent(ChannelBuffers.copiedBuffer(new byte[]{})); messageEvent.getChannel().write(response); return; } // must include HOST header as required by HTTP 1.1 if (!request.getHeaderNames().contains(HttpHeaders.Names.HOST)) { HttpResponse response = new DefaultHttpResponse(HTTP_1_1, BAD_REQUEST); response.setChunked(false); response.setHeader(Exchange.CONTENT_TYPE, "text/plain"); response.setHeader(Exchange.CONTENT_LENGTH, 0); response.setContent(ChannelBuffers.copiedBuffer(new byte[]{})); messageEvent.getChannel().write(response); return; } // is basic auth configured NettyHttpSecurityConfiguration security = consumer.getEndpoint().getSecurityConfiguration(); if (security != null && security.isAuthenticate() && "Basic".equalsIgnoreCase(security.getConstraint())) { String url = request.getUri(); // drop parameters from url if (url.contains("?")) { url = ObjectHelper.before(url, "?"); } // we need the relative path without the hostname and port URI uri = new URI(request.getUri()); String target = uri.getPath(); // strip the starting endpoint path so the target is relative to the endpoint uri String path = consumer.getConfiguration().getPath(); if (path != null && target.startsWith(path)) { target = target.substring(path.length()); } // is it a restricted resource? String roles; if (security.getSecurityConstraint() != null) { // if restricted returns null, then the resource is not restricted and we should not authenticate the user roles = security.getSecurityConstraint().restricted(target); } else { // assume any roles is valid if no security constraint has been configured roles = "*"; } if (roles != null) { // basic auth subject HttpPrincipal principal = extractBasicAuthSubject(request); // authenticate principal and check if the user is in role Subject subject = null; boolean inRole = true; if (principal != null) { subject = authenticate(security.getSecurityAuthenticator(), security.getLoginDeniedLoggingLevel(), principal); if (subject != null) { String userRoles = security.getSecurityAuthenticator().getUserRoles(subject); inRole = matchesRoles(roles, userRoles); } } if (principal == null || subject == null || !inRole) { if (principal == null) { LOG.debug("Http Basic Auth required for resource: {}", url); } else if (subject == null) { LOG.debug("Http Basic Auth not authorized for username: {}", principal.getUsername()); } else { LOG.debug("Http Basic Auth not in role for username: {}", principal.getUsername()); } // restricted resource, so send back 401 to require valid username/password HttpResponse response = new DefaultHttpResponse(HTTP_1_1, UNAUTHORIZED); response.setHeader("WWW-Authenticate", "Basic realm=\"" + security.getRealm() + "\""); response.setHeader(Exchange.CONTENT_TYPE, "text/plain"); response.setHeader(Exchange.CONTENT_LENGTH, 0); response.setContent(ChannelBuffers.copiedBuffer(new byte[]{})); messageEvent.getChannel().write(response); return; } else { LOG.debug("Http Basic Auth authorized for username: {}", principal.getUsername()); } } } // let Camel process this message super.messageReceived(ctx, messageEvent); } protected boolean matchesRoles(String roles, String userRoles) { // matches if no role restrictions or any role is accepted if (roles.equals("*")) { return true; } // see if any of the user roles is contained in the roles list Iterator it = ObjectHelper.createIterator(userRoles); while (it.hasNext()) { String userRole = it.next().toString(); if (roles.contains(userRole)) { return true; } } return false; } /** * Extracts the username and password details from the HTTP basic header Authorization. * <p/> * This requires that the <tt>Authorization</tt> HTTP header is provided, and its using Basic. * Currently Digest is <b>not</b> supported. * * @return {@link HttpPrincipal} with username and password details, or <tt>null</tt> if not possible to extract */ protected static HttpPrincipal extractBasicAuthSubject(HttpRequest request) { String auth = request.getHeader("Authorization"); if (auth != null) { String constraint = ObjectHelper.before(auth, " "); if (constraint != null) { if ("Basic".equalsIgnoreCase(constraint.trim())) { String decoded = ObjectHelper.after(auth, " "); // the decoded part is base64 encoded, so we need to decode that ChannelBuffer buf = ChannelBuffers.copiedBuffer(decoded.getBytes()); ChannelBuffer out = Base64.decode(buf); String userAndPw = out.toString(Charset.defaultCharset()); String username = ObjectHelper.before(userAndPw, ":"); String password = ObjectHelper.after(userAndPw, ":"); HttpPrincipal principal = new HttpPrincipal(username, password); LOG.debug("Extracted Basic Auth principal from HTTP header: {}", principal); return principal; } } } return null; } /** * Authenticates the http basic auth subject. * * @param authenticator the authenticator * @param principal the principal * @return <tt>true</tt> if username and password is valid, <tt>false</tt> if not */ protected Subject authenticate(SecurityAuthenticator authenticator, LoggingLevel deniedLoggingLevel, HttpPrincipal principal) { try { return authenticator.login(principal); } catch (LoginException e) { CamelLogger logger = new CamelLogger(LOG, deniedLoggingLevel); logger.log("Cannot login " + principal.getName() + " due " + e.getMessage(), e); } return null; } @Override protected void beforeProcess(Exchange exchange, MessageEvent messageEvent) { if (consumer.getConfiguration().isBridgeEndpoint()) { exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent exceptionEvent) throws Exception { // only close if we are still allowed to run if (consumer.isRunAllowed()) { if (exceptionEvent.getCause() instanceof ClosedChannelException) { LOG.debug("Channel already closed. Ignoring this exception."); } else { LOG.warn("Closing channel as an exception was thrown from Netty", exceptionEvent.getCause()); // close channel in case an exception was thrown NettyHelper.close(exceptionEvent.getChannel()); } } } @Override protected ChannelFutureListener createResponseFutureListener(NettyConsumer consumer, Exchange exchange, SocketAddress remoteAddress) { // make sure to close channel if not keep-alive if (request != null && isKeepAlive(request)) { LOG.trace("Request has Connection: keep-alive so Channel is not being closed"); return null; } else { LOG.trace("Request is not Connection: close so Channel is being closed"); return ChannelFutureListener.CLOSE; } } @Override protected Object getResponseBody(Exchange exchange) throws Exception { // use the binding if (exchange.hasOut()) { return consumer.getEndpoint().getNettyHttpBinding().toNettyResponse(exchange.getOut(), consumer.getConfiguration()); } else { return consumer.getEndpoint().getNettyHttpBinding().toNettyResponse(exchange.getIn(), consumer.getConfiguration()); } } }
{ "content_hash": "56cadeb4002acc39aba3f1046168a236", "timestamp": "", "source": "github", "line_count": 296, "max_line_length": 138, "avg_line_length": 46.73986486486486, "alnum_prop": 0.6422840621611854, "repo_name": "shuliangtao/apache-camel-2.13.0-src", "id": "71a8aec1f595567a43bb1940aae27665bcfb0cf9", "size": "14638", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/handlers/HttpServerChannelHandler.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "19954" }, { "name": "Batchfile", "bytes": "106" }, { "name": "CSS", "bytes": "221391" }, { "name": "Elm", "bytes": "5970" }, { "name": "Groovy", "bytes": "18886" }, { "name": "HTML", "bytes": "344357" }, { "name": "Java", "bytes": "36428706" }, { "name": "JavaScript", "bytes": "3695475" }, { "name": "PHP", "bytes": "88860" }, { "name": "Protocol Buffer", "bytes": "551" }, { "name": "Ruby", "bytes": "4802" }, { "name": "Scala", "bytes": "266906" }, { "name": "Shell", "bytes": "9057" }, { "name": "Tcl", "bytes": "4974" }, { "name": "XQuery", "bytes": "543" }, { "name": "XSLT", "bytes": "73707" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Bolezni rastenii 17: 86 (1928) #### Original name Botryosphaeria bondarzewii L.A. Kantsch. ### Remarks null
{ "content_hash": "272d9289ced7618af6a67838442ba4c0", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 40, "avg_line_length": 13.153846153846153, "alnum_prop": 0.7192982456140351, "repo_name": "mdoering/backbone", "id": "9b84b487735439c1e4c435e589c1886b4a94ade6", "size": "235", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Dothideomycetes/Botryosphaeriales/Botryosphaeriaceae/Botryosphaeria/Botryosphaeria bondarzewii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.fiteagle.north.sfa.aaa; import java.io.ByteArrayOutputStream; import java.io.StringReader; import java.io.StringWriter; import java.security.cert.X509Certificate; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.fiteagle.north.sfa.aaa.jaxbClasses.Credential; import org.fiteagle.north.sfa.aaa.jaxbClasses.Signatures; import org.fiteagle.north.sfa.aaa.jaxbClasses.SignedCredential; import org.fiteagle.north.sfa.util.URN; import org.xml.sax.InputSource; public class CredentialFactory { public static Credential newCredential(X509Certificate userCert, URN user, X509Certificate targetCert, URN target) throws Exception { CredentialFactoryWorker worker = new CredentialFactoryWorker(userCert,user,targetCert, target); return worker.getCredential(); } public static String signCredential(Credential credential){ SignedCredential signedCredential = new SignedCredential(); signedCredential.setCredential(credential); Signatures signatures = new Signatures(); signedCredential.setSignatures(signatures); SignatureCreator signer = new SignatureCreator(); String signedCredentialString = ""; try { String tmpsignedcredentialString = getJAXBString(signedCredential); InputSource is = new InputSource(new StringReader(tmpsignedcredentialString)); ByteArrayOutputStream bout = signer.signContent(is, credential.getId()); tmpsignedcredentialString = new String(bout.toByteArray()); signedCredentialString = SFIFix.removeNewlinesFromCertificateInsideSignature(tmpsignedcredentialString); } catch (JAXBException e) { throw new RuntimeException(e.getMessage()); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } signedCredentialString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + signedCredentialString; return signedCredentialString; } private static String getJAXBString(Object jaxbObject) throws JAXBException { JAXBContext context = JAXBContext .newInstance("org.fiteagle.north.sfa.aaa.jaxbClasses"); Marshaller marshaller = context.createMarshaller(); StringWriter stringWriter = new StringWriter(); marshaller.marshal(jaxbObject, stringWriter); return stringWriter.toString(); } public static SignedCredential buildCredential(String credential) throws JAXBException { JAXBContext context = JAXBContext.newInstance("org.fiteagle.north.sfa.aaa.jaxbClasses"); Unmarshaller unmarshaller = context.createUnmarshaller(); StringReader reader = new StringReader(credential); SignedCredential sc = (SignedCredential) unmarshaller.unmarshal(reader); return sc; } private static class SFIFix{ public static String removeNewlinesFromCertificateInsideSignature(String certificateString){ String begin = "<X509Certificate>"; String end = "</X509Certificate>"; certificateString = certificateString.replaceAll(begin+"\\n", begin); certificateString = certificateString.replaceAll("\\n" +end, end); return certificateString; } } }
{ "content_hash": "b4af597a7de8629ddb74daefaf12fcbc", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 137, "avg_line_length": 38.31868131868132, "alnum_prop": 0.6974476627473473, "repo_name": "FITeagle/sfa", "id": "7e4fd8b430342bcc5bd6822995c2c46151c37ad7", "size": "3487", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/fiteagle/north/sfa/aaa/CredentialFactory.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "340467" }, { "name": "Shell", "bytes": "8121" } ], "symlink_target": "" }
"""Prefix DAG permissions. Revision ID: 849da589634d Revises: 45ba3f1493b9 Create Date: 2020-10-01 17:25:10.006322 """ from flask_appbuilder import SQLA from flask_appbuilder.security.sqla.models import Permission, PermissionView, ViewMenu from airflow import settings from airflow.security import permissions # revision identifiers, used by Alembic. revision = '849da589634d' down_revision = '45ba3f1493b9' branch_labels = None depends_on = None def prefix_individual_dag_permissions(session): dag_perms = ['can_dag_read', 'can_dag_edit'] prefix = "DAG:" perms = ( session.query(PermissionView) .join(Permission) .filter(Permission.name.in_(dag_perms)) .join(ViewMenu) .filter(ViewMenu.name != 'all_dags') .filter(ViewMenu.name.notlike(prefix + '%')) .all() ) resource_ids = {permission.view_menu.id for permission in perms} vm_query = session.query(ViewMenu).filter(ViewMenu.id.in_(resource_ids)) vm_query.update({ViewMenu.name: prefix + ViewMenu.name}, synchronize_session=False) session.commit() def get_or_create_dag_resource(session): dag_resource = get_resource_query(session, permissions.RESOURCE_DAG).first() if dag_resource: return dag_resource dag_resource = ViewMenu() dag_resource.name = permissions.RESOURCE_DAG session.add(dag_resource) session.commit() return dag_resource def get_or_create_action(session, action_name): action = get_action_query(session, action_name).first() if action: return action action = Permission() action.name = action_name session.add(action) session.commit() return action def get_resource_query(session, resource_name): return session.query(ViewMenu).filter(ViewMenu.name == resource_name) def get_action_query(session, action_name): return session.query(Permission).filter(Permission.name == action_name) def get_permission_with_action_query(session, action): return session.query(PermissionView).filter(PermissionView.permission == action) def get_permission_with_resource_query(session, resource): return session.query(PermissionView).filter(PermissionView.view_menu_id == resource.id) def update_permission_action(session, permission_query, action): permission_query.update({PermissionView.permission_id: action.id}, synchronize_session=False) session.commit() def get_permission(session, resource, action): return ( session.query(PermissionView) .filter(PermissionView.view_menu == resource) .filter(PermissionView.permission == action) .first() ) def update_permission_resource(session, permission_query, resource): for permission in permission_query.all(): if not get_permission(session, resource, permission.permission): permission.view_menu = resource else: session.delete(permission) session.commit() def migrate_to_new_dag_permissions(db): # Prefix individual dag perms with `DAG:` prefix_individual_dag_permissions(db.session) # Update existing permissions to use `can_read` instead of `can_dag_read` can_dag_read_action = get_action_query(db.session, 'can_dag_read').first() old_can_dag_read_permissions = get_permission_with_action_query(db.session, can_dag_read_action) can_read_action = get_or_create_action(db.session, 'can_read') update_permission_action(db.session, old_can_dag_read_permissions, can_read_action) # Update existing permissions to use `can_edit` instead of `can_dag_edit` can_dag_edit_action = get_action_query(db.session, 'can_dag_edit').first() old_can_dag_edit_permissions = get_permission_with_action_query(db.session, can_dag_edit_action) can_edit_action = get_or_create_action(db.session, 'can_edit') update_permission_action(db.session, old_can_dag_edit_permissions, can_edit_action) # Update existing permissions for `all_dags` resource to use `DAGs` resource. all_dags_resource = get_resource_query(db.session, 'all_dags').first() if all_dags_resource: old_all_dags_permission = get_permission_with_resource_query(db.session, all_dags_resource) dag_resource = get_or_create_dag_resource(db.session) update_permission_resource(db.session, old_all_dags_permission, dag_resource) # Delete the `all_dags` resource db.session.delete(all_dags_resource) # Delete `can_dag_read` action if can_dag_read_action: db.session.delete(can_dag_read_action) # Delete `can_dag_edit` action if can_dag_edit_action: db.session.delete(can_dag_edit_action) db.session.commit() def upgrade(): db = SQLA() db.session = settings.Session migrate_to_new_dag_permissions(db) db.session.commit() db.session.close() def downgrade(): pass
{ "content_hash": "caed6ef651778b158e0703bd85362495", "timestamp": "", "source": "github", "line_count": 152, "max_line_length": 100, "avg_line_length": 32.046052631578945, "alnum_prop": 0.7039622254157257, "repo_name": "dhuang/incubator-airflow", "id": "fbbaa3adc3a3e809a20b8c2992463f1d35214fd1", "size": "5659", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "airflow/migrations/versions/849da589634d_prefix_dag_permissions.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "109698" }, { "name": "HTML", "bytes": "264851" }, { "name": "JavaScript", "bytes": "1988427" }, { "name": "Mako", "bytes": "1037" }, { "name": "Python", "bytes": "3357958" }, { "name": "Shell", "bytes": "34442" } ], "symlink_target": "" }
package com.aspose.cells.model; import java.util.*; import com.aspose.cells.model.Color; import com.aspose.cells.model.LinkElement; public class Worksheet { private List<Link> Links = new ArrayList<Link>(); private Boolean DisplayRightToLeft = null; private Boolean DisplayZeros = null; private Integer FirstVisibleColumn = null; private Integer FirstVisibleRow = null; private String Name = null; private Integer Index = null; private Boolean IsGridlinesVisible = null; private Boolean IsOutlineShown = null; private Boolean IsPageBreakPreview = null; private Boolean IsVisible = null; private Boolean IsProtected = null; private Boolean IsRowColumnHeadersVisible = null; private Boolean IsRulerVisible = null; private Boolean IsSelected = null; private Color TabColor = null; private Boolean TransitionEntry = null; private Boolean TransitionEvaluation = null; private String Type = null; private String ViewType = null; private String VisibilityType = null; private Integer Zoom = null; private LinkElement Cells = null; private LinkElement Charts = null; private LinkElement AutoShapes = null; private LinkElement OleObjects = null; private LinkElement Comments = null; private LinkElement Pictures = null; private LinkElement MergedCells = null; private LinkElement Validations = null; private LinkElement ConditionalFormattings = null; private LinkElement Hyperlinks = null; /** * getLinks * Gets List<Link> * @return Links */ public List<Link> getLinks() { return Links; } /** * setLinks * Sets List<Link> * @param Links List<Link> */ public void setLinks(List<Link> Links) { this.Links = Links; } /** * getDisplayRightToLeft * Gets Boolean * @return DisplayRightToLeft */ public Boolean getDisplayRightToLeft() { return DisplayRightToLeft; } /** * setDisplayRightToLeft * Sets Boolean * @param DisplayRightToLeft Boolean */ public void setDisplayRightToLeft(Boolean DisplayRightToLeft) { this.DisplayRightToLeft = DisplayRightToLeft; } /** * getDisplayZeros * Gets Boolean * @return DisplayZeros */ public Boolean getDisplayZeros() { return DisplayZeros; } /** * setDisplayZeros * Sets Boolean * @param DisplayZeros Boolean */ public void setDisplayZeros(Boolean DisplayZeros) { this.DisplayZeros = DisplayZeros; } /** * getFirstVisibleColumn * Gets Integer * @return FirstVisibleColumn */ public Integer getFirstVisibleColumn() { return FirstVisibleColumn; } /** * setFirstVisibleColumn * Sets Integer * @param FirstVisibleColumn Integer */ public void setFirstVisibleColumn(Integer FirstVisibleColumn) { this.FirstVisibleColumn = FirstVisibleColumn; } /** * getFirstVisibleRow * Gets Integer * @return FirstVisibleRow */ public Integer getFirstVisibleRow() { return FirstVisibleRow; } /** * setFirstVisibleRow * Sets Integer * @param FirstVisibleRow Integer */ public void setFirstVisibleRow(Integer FirstVisibleRow) { this.FirstVisibleRow = FirstVisibleRow; } /** * getName * Gets String * @return Name */ public String getName() { return Name; } /** * setName * Sets String * @param Name String */ public void setName(String Name) { this.Name = Name; } /** * getIndex * Gets Integer * @return Index */ public Integer getIndex() { return Index; } /** * setIndex * Sets Integer * @param Index Integer */ public void setIndex(Integer Index) { this.Index = Index; } /** * getIsGridlinesVisible * Gets Boolean * @return IsGridlinesVisible */ public Boolean getIsGridlinesVisible() { return IsGridlinesVisible; } /** * setIsGridlinesVisible * Sets Boolean * @param IsGridlinesVisible Boolean */ public void setIsGridlinesVisible(Boolean IsGridlinesVisible) { this.IsGridlinesVisible = IsGridlinesVisible; } /** * getIsOutlineShown * Gets Boolean * @return IsOutlineShown */ public Boolean getIsOutlineShown() { return IsOutlineShown; } /** * setIsOutlineShown * Sets Boolean * @param IsOutlineShown Boolean */ public void setIsOutlineShown(Boolean IsOutlineShown) { this.IsOutlineShown = IsOutlineShown; } /** * getIsPageBreakPreview * Gets Boolean * @return IsPageBreakPreview */ public Boolean getIsPageBreakPreview() { return IsPageBreakPreview; } /** * setIsPageBreakPreview * Sets Boolean * @param IsPageBreakPreview Boolean */ public void setIsPageBreakPreview(Boolean IsPageBreakPreview) { this.IsPageBreakPreview = IsPageBreakPreview; } /** * getIsVisible * Gets Boolean * @return IsVisible */ public Boolean getIsVisible() { return IsVisible; } /** * setIsVisible * Sets Boolean * @param IsVisible Boolean */ public void setIsVisible(Boolean IsVisible) { this.IsVisible = IsVisible; } /** * getIsProtected * Gets Boolean * @return IsProtected */ public Boolean getIsProtected() { return IsProtected; } /** * setIsProtected * Sets Boolean * @param IsProtected Boolean */ public void setIsProtected(Boolean IsProtected) { this.IsProtected = IsProtected; } /** * getIsRowColumnHeadersVisible * Gets Boolean * @return IsRowColumnHeadersVisible */ public Boolean getIsRowColumnHeadersVisible() { return IsRowColumnHeadersVisible; } /** * setIsRowColumnHeadersVisible * Sets Boolean * @param IsRowColumnHeadersVisible Boolean */ public void setIsRowColumnHeadersVisible(Boolean IsRowColumnHeadersVisible) { this.IsRowColumnHeadersVisible = IsRowColumnHeadersVisible; } /** * getIsRulerVisible * Gets Boolean * @return IsRulerVisible */ public Boolean getIsRulerVisible() { return IsRulerVisible; } /** * setIsRulerVisible * Sets Boolean * @param IsRulerVisible Boolean */ public void setIsRulerVisible(Boolean IsRulerVisible) { this.IsRulerVisible = IsRulerVisible; } /** * getIsSelected * Gets Boolean * @return IsSelected */ public Boolean getIsSelected() { return IsSelected; } /** * setIsSelected * Sets Boolean * @param IsSelected Boolean */ public void setIsSelected(Boolean IsSelected) { this.IsSelected = IsSelected; } /** * getTabColor * Gets Color * @return TabColor */ public Color getTabColor() { return TabColor; } /** * setTabColor * Sets Color * @param TabColor Color */ public void setTabColor(Color TabColor) { this.TabColor = TabColor; } /** * getTransitionEntry * Gets Boolean * @return TransitionEntry */ public Boolean getTransitionEntry() { return TransitionEntry; } /** * setTransitionEntry * Sets Boolean * @param TransitionEntry Boolean */ public void setTransitionEntry(Boolean TransitionEntry) { this.TransitionEntry = TransitionEntry; } /** * getTransitionEvaluation * Gets Boolean * @return TransitionEvaluation */ public Boolean getTransitionEvaluation() { return TransitionEvaluation; } /** * setTransitionEvaluation * Sets Boolean * @param TransitionEvaluation Boolean */ public void setTransitionEvaluation(Boolean TransitionEvaluation) { this.TransitionEvaluation = TransitionEvaluation; } /** * getType * Gets String * @return Type */ public String getType() { return Type; } /** * setType * Sets String * @param Type String */ public void setType(String Type) { this.Type = Type; } /** * getViewType * Gets String * @return ViewType */ public String getViewType() { return ViewType; } /** * setViewType * Sets String * @param ViewType String */ public void setViewType(String ViewType) { this.ViewType = ViewType; } /** * getVisibilityType * Gets String * @return VisibilityType */ public String getVisibilityType() { return VisibilityType; } /** * setVisibilityType * Sets String * @param VisibilityType String */ public void setVisibilityType(String VisibilityType) { this.VisibilityType = VisibilityType; } /** * getZoom * Gets Integer * @return Zoom */ public Integer getZoom() { return Zoom; } /** * setZoom * Sets Integer * @param Zoom Integer */ public void setZoom(Integer Zoom) { this.Zoom = Zoom; } /** * getCells * Gets LinkElement * @return Cells */ public LinkElement getCells() { return Cells; } /** * setCells * Sets LinkElement * @param Cells LinkElement */ public void setCells(LinkElement Cells) { this.Cells = Cells; } /** * getCharts * Gets LinkElement * @return Charts */ public LinkElement getCharts() { return Charts; } /** * setCharts * Sets LinkElement * @param Charts LinkElement */ public void setCharts(LinkElement Charts) { this.Charts = Charts; } /** * getAutoShapes * Gets LinkElement * @return AutoShapes */ public LinkElement getAutoShapes() { return AutoShapes; } /** * setAutoShapes * Sets LinkElement * @param AutoShapes LinkElement */ public void setAutoShapes(LinkElement AutoShapes) { this.AutoShapes = AutoShapes; } /** * getOleObjects * Gets LinkElement * @return OleObjects */ public LinkElement getOleObjects() { return OleObjects; } /** * setOleObjects * Sets LinkElement * @param OleObjects LinkElement */ public void setOleObjects(LinkElement OleObjects) { this.OleObjects = OleObjects; } /** * getComments * Gets LinkElement * @return Comments */ public LinkElement getComments() { return Comments; } /** * setComments * Sets LinkElement * @param Comments LinkElement */ public void setComments(LinkElement Comments) { this.Comments = Comments; } /** * getPictures * Gets LinkElement * @return Pictures */ public LinkElement getPictures() { return Pictures; } /** * setPictures * Sets LinkElement * @param Pictures LinkElement */ public void setPictures(LinkElement Pictures) { this.Pictures = Pictures; } /** * getMergedCells * Gets LinkElement * @return MergedCells */ public LinkElement getMergedCells() { return MergedCells; } /** * setMergedCells * Sets LinkElement * @param MergedCells LinkElement */ public void setMergedCells(LinkElement MergedCells) { this.MergedCells = MergedCells; } /** * getValidations * Gets LinkElement * @return Validations */ public LinkElement getValidations() { return Validations; } /** * setValidations * Sets LinkElement * @param Validations LinkElement */ public void setValidations(LinkElement Validations) { this.Validations = Validations; } /** * getConditionalFormattings * Gets LinkElement * @return ConditionalFormattings */ public LinkElement getConditionalFormattings() { return ConditionalFormattings; } /** * setConditionalFormattings * Sets LinkElement * @param ConditionalFormattings LinkElement */ public void setConditionalFormattings(LinkElement ConditionalFormattings) { this.ConditionalFormattings = ConditionalFormattings; } /** * getHyperlinks * Gets LinkElement * @return Hyperlinks */ public LinkElement getHyperlinks() { return Hyperlinks; } /** * setHyperlinks * Sets LinkElement * @param Hyperlinks LinkElement */ public void setHyperlinks(LinkElement Hyperlinks) { this.Hyperlinks = Hyperlinks; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Worksheet {\n"); sb.append(" Links: ").append(Links).append("\n"); sb.append(" DisplayRightToLeft: ").append(DisplayRightToLeft).append("\n"); sb.append(" DisplayZeros: ").append(DisplayZeros).append("\n"); sb.append(" FirstVisibleColumn: ").append(FirstVisibleColumn).append("\n"); sb.append(" FirstVisibleRow: ").append(FirstVisibleRow).append("\n"); sb.append(" Name: ").append(Name).append("\n"); sb.append(" Index: ").append(Index).append("\n"); sb.append(" IsGridlinesVisible: ").append(IsGridlinesVisible).append("\n"); sb.append(" IsOutlineShown: ").append(IsOutlineShown).append("\n"); sb.append(" IsPageBreakPreview: ").append(IsPageBreakPreview).append("\n"); sb.append(" IsVisible: ").append(IsVisible).append("\n"); sb.append(" IsProtected: ").append(IsProtected).append("\n"); sb.append(" IsRowColumnHeadersVisible: ").append(IsRowColumnHeadersVisible).append("\n"); sb.append(" IsRulerVisible: ").append(IsRulerVisible).append("\n"); sb.append(" IsSelected: ").append(IsSelected).append("\n"); sb.append(" TabColor: ").append(TabColor).append("\n"); sb.append(" TransitionEntry: ").append(TransitionEntry).append("\n"); sb.append(" TransitionEvaluation: ").append(TransitionEvaluation).append("\n"); sb.append(" Type: ").append(Type).append("\n"); sb.append(" ViewType: ").append(ViewType).append("\n"); sb.append(" VisibilityType: ").append(VisibilityType).append("\n"); sb.append(" Zoom: ").append(Zoom).append("\n"); sb.append(" Cells: ").append(Cells).append("\n"); sb.append(" Charts: ").append(Charts).append("\n"); sb.append(" AutoShapes: ").append(AutoShapes).append("\n"); sb.append(" OleObjects: ").append(OleObjects).append("\n"); sb.append(" Comments: ").append(Comments).append("\n"); sb.append(" Pictures: ").append(Pictures).append("\n"); sb.append(" MergedCells: ").append(MergedCells).append("\n"); sb.append(" Validations: ").append(Validations).append("\n"); sb.append(" ConditionalFormattings: ").append(ConditionalFormattings).append("\n"); sb.append(" Hyperlinks: ").append(Hyperlinks).append("\n"); sb.append("}\n"); return sb.toString(); } }
{ "content_hash": "34f8f4e6b3809b91f96b4f2e3b73b2ac", "timestamp": "", "source": "github", "line_count": 655, "max_line_length": 94, "avg_line_length": 21.316030534351146, "alnum_prop": 0.6773384901876522, "repo_name": "farooqsheikhpk/Aspose.Cells-for-Cloud", "id": "927abdbdd848f767f5c6976914dcbe86d8e98cc6", "size": "13962", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "SDKs/Aspose.Cells-Cloud-SDK-for-Java/src/main/java/com/aspose/cells/model/Worksheet.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "203" }, { "name": "C#", "bytes": "897367" }, { "name": "HTML", "bytes": "110" }, { "name": "Java", "bytes": "993746" }, { "name": "JavaScript", "bytes": "664643" }, { "name": "Objective-C", "bytes": "1142444" }, { "name": "PHP", "bytes": "626745" }, { "name": "Perl", "bytes": "856316" }, { "name": "Python", "bytes": "833397" }, { "name": "Ruby", "bytes": "799033" } ], "symlink_target": "" }
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #pragma once #include "IUserInfo.h" class FFriendViewModel : public TSharedFromThis<FFriendViewModel> , public IUserInfo { public: virtual ~FFriendViewModel() {} virtual void EnumerateActions(TArray<EFriendActionType::Type>& Actions, bool bFromChat = false) = 0; virtual const bool HasChatAction() const = 0; virtual void PerformAction(const EFriendActionType::Type ActionType) = 0; virtual void SetPendingAction(EFriendActionType::Type PendingAction) = 0; virtual EFriendActionType::Type GetPendingAction() = 0; virtual bool CanPerformAction(const EFriendActionType::Type ActionType) = 0; virtual FText GetJoinGameDisallowReason() const = 0; virtual FText GetFriendLocation() const = 0; virtual bool IsOnline() const = 0; virtual bool IsInGameSession() const = 0; virtual TSharedRef<class IFriendItem> GetFriendItem() const = 0; virtual const FString GetNameNoSpaces() const = 0; virtual bool IsInActiveParty() const = 0; }; /** * Creates the implementation for an FriendViewModel. * * @return the newly created FriendViewModel implementation. */ IFACTORY(TSharedRef< FFriendViewModel >, IFriendViewModel, const TSharedRef<class IFriendItem>& FriendItem); FACTORY(TSharedRef< IFriendViewModelFactory >, FFriendViewModelFactory, const TSharedRef<class FFriendsNavigationService>& NavigationService, const TSharedRef<class FFriendsAndChatManager>& FriendsAndChatManager);
{ "content_hash": "22bdbc10be9ce2eddc1dbbe0b6d3a7d2", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 101, "avg_line_length": 38.39473684210526, "alnum_prop": 0.7909527073337903, "repo_name": "PopCap/GameIdea", "id": "5392256f831852ca46f0465bdbdda4cb383ce716", "size": "1459", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Engine/Source/Developer/FriendsAndChat/Private/Layers/Presentation/FriendViewModel.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "ASP", "bytes": "238055" }, { "name": "Assembly", "bytes": "184134" }, { "name": "Batchfile", "bytes": "116983" }, { "name": "C", "bytes": "84264210" }, { "name": "C#", "bytes": "9612596" }, { "name": "C++", "bytes": "242290999" }, { "name": "CMake", "bytes": "548754" }, { "name": "CSS", "bytes": "134910" }, { "name": "GLSL", "bytes": "96780" }, { "name": "HLSL", "bytes": "124014" }, { "name": "HTML", "bytes": "4097051" }, { "name": "Java", "bytes": "757767" }, { "name": "JavaScript", "bytes": "2742822" }, { "name": "Makefile", "bytes": "1976144" }, { "name": "Objective-C", "bytes": "75778979" }, { "name": "Objective-C++", "bytes": "312592" }, { "name": "PAWN", "bytes": "2029" }, { "name": "PHP", "bytes": "10309" }, { "name": "PLSQL", "bytes": "130426" }, { "name": "Pascal", "bytes": "23662" }, { "name": "Perl", "bytes": "218656" }, { "name": "Python", "bytes": "21593012" }, { "name": "SAS", "bytes": "1847" }, { "name": "Shell", "bytes": "2889614" }, { "name": "Tcl", "bytes": "1452" } ], "symlink_target": "" }
package androidx.media3.exoplayer.drm; import static java.lang.annotation.ElementType.TYPE_USE; import android.media.DeniedByServerException; import android.media.MediaCryptoException; import android.media.MediaDrm; import android.media.MediaDrmException; import android.media.NotProvisionedException; import android.media.ResourceBusyException; import android.os.Handler; import android.os.PersistableBundle; import androidx.annotation.IntDef; import androidx.annotation.Nullable; import androidx.media3.common.C; import androidx.media3.common.DrmInitData.SchemeData; import androidx.media3.common.util.UnstableApi; import androidx.media3.decoder.CryptoConfig; import androidx.media3.exoplayer.analytics.PlayerId; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; /** * Used to obtain keys for decrypting protected media streams. * * <h2>Reference counting</h2> * * <p>Access to an instance is managed by reference counting, where {@link #acquire()} increments * the reference count and {@link #release()} decrements it. When the reference count drops to 0 * underlying resources are released, and the instance cannot be re-used. * * <p>Each new instance has an initial reference count of 1. Hence application code that creates a * new instance does not normally need to call {@link #acquire()}, and must call {@link #release()} * when the instance is no longer required. * * @see MediaDrm */ @UnstableApi public interface ExoMediaDrm { /** Provider for {@link ExoMediaDrm} instances. */ interface Provider { /** * Returns an {@link ExoMediaDrm} instance with an incremented reference count. When the caller * no longer needs the instance, it must call {@link ExoMediaDrm#release()} to decrement the * reference count. */ ExoMediaDrm acquireExoMediaDrm(UUID uuid); } /** * Provides an {@link ExoMediaDrm} instance owned by the app. * * <p>Note that when using this provider the app will have instantiated the {@link ExoMediaDrm} * instance, and remains responsible for calling {@link ExoMediaDrm#release()} on the instance * when it's no longer being used. */ final class AppManagedProvider implements Provider { private final ExoMediaDrm exoMediaDrm; /** Creates an instance that provides the given {@link ExoMediaDrm}. */ public AppManagedProvider(ExoMediaDrm exoMediaDrm) { this.exoMediaDrm = exoMediaDrm; } @Override public ExoMediaDrm acquireExoMediaDrm(UUID uuid) { exoMediaDrm.acquire(); return exoMediaDrm; } } /** Event indicating that keys need to be requested from the license server. */ @UnstableApi @SuppressWarnings("InlinedApi") int EVENT_KEY_REQUIRED = MediaDrm.EVENT_KEY_REQUIRED; /** Event indicating that keys have expired, and are no longer usable. */ @UnstableApi @SuppressWarnings("InlinedApi") int EVENT_KEY_EXPIRED = MediaDrm.EVENT_KEY_EXPIRED; /** Event indicating that a certificate needs to be requested from the provisioning server. */ @UnstableApi @SuppressWarnings("InlinedApi") int EVENT_PROVISION_REQUIRED = MediaDrm.EVENT_PROVISION_REQUIRED; /** * Key request type for keys that will be used for online use. Streaming keys will not be saved to * the device for subsequent use when the device is not connected to a network. */ @UnstableApi @SuppressWarnings("InlinedApi") int KEY_TYPE_STREAMING = MediaDrm.KEY_TYPE_STREAMING; /** * Key request type for keys that will be used for offline use. They will be saved to the device * for subsequent use when the device is not connected to a network. */ @UnstableApi @SuppressWarnings("InlinedApi") int KEY_TYPE_OFFLINE = MediaDrm.KEY_TYPE_OFFLINE; /** Key request type indicating that saved offline keys should be released. */ @UnstableApi @SuppressWarnings("InlinedApi") int KEY_TYPE_RELEASE = MediaDrm.KEY_TYPE_RELEASE; /** * Called when a DRM event occurs. * * @see MediaDrm.OnEventListener */ interface OnEventListener { /** * Called when an event occurs that requires the app to be notified * * @param mediaDrm The {@link ExoMediaDrm} object on which the event occurred. * @param sessionId The DRM session ID on which the event occurred. * @param event Indicates the event type. * @param extra A secondary error code. * @param data Optional byte array of data that may be associated with the event. */ void onEvent( ExoMediaDrm mediaDrm, @Nullable byte[] sessionId, int event, int extra, @Nullable byte[] data); } /** * Called when the keys in a DRM session change state. * * @see MediaDrm.OnKeyStatusChangeListener */ interface OnKeyStatusChangeListener { /** * Called when the keys in a session change status, such as when the license is renewed or * expires. * * @param mediaDrm The {@link ExoMediaDrm} object on which the event occurred. * @param sessionId The DRM session ID on which the event occurred. * @param exoKeyInformation A list of {@link KeyStatus} that contains key ID and status. * @param hasNewUsableKey Whether a new key became usable. */ void onKeyStatusChange( ExoMediaDrm mediaDrm, byte[] sessionId, List<KeyStatus> exoKeyInformation, boolean hasNewUsableKey); } /** * Called when a session expiration update occurs. * * @see MediaDrm.OnExpirationUpdateListener */ interface OnExpirationUpdateListener { /** * Called when a session expiration update occurs, to inform the app about the change in * expiration time. * * @param mediaDrm The {@link ExoMediaDrm} object on which the event occurred. * @param sessionId The DRM session ID on which the event occurred * @param expirationTimeMs The new expiration time for the keys in the session. The time is in * milliseconds, relative to the Unix epoch. A time of 0 indicates that the keys never * expire. */ void onExpirationUpdate(ExoMediaDrm mediaDrm, byte[] sessionId, long expirationTimeMs); } /** * Defines the status of a key. * * @see MediaDrm.KeyStatus */ final class KeyStatus { private final int statusCode; private final byte[] keyId; /** * Creates an instance. * * @param statusCode The status code of the key, as defined by {@link * MediaDrm.KeyStatus#getStatusCode()}. * @param keyId The ID of the key. */ public KeyStatus(int statusCode, byte[] keyId) { this.statusCode = statusCode; this.keyId = keyId; } /** Returns the status of the key, as defined by {@link MediaDrm.KeyStatus#getStatusCode()}. */ public int getStatusCode() { return statusCode; } /** Returns the ID of the key. */ public byte[] getKeyId() { return keyId; } } /** * Contains data used to request keys from a license server. * * @see MediaDrm.KeyRequest */ final class KeyRequest { /** * Key request types. One of {@link #REQUEST_TYPE_UNKNOWN}, {@link #REQUEST_TYPE_INITIAL}, * {@link #REQUEST_TYPE_RENEWAL}, {@link #REQUEST_TYPE_RELEASE}, {@link #REQUEST_TYPE_NONE} or * {@link #REQUEST_TYPE_UPDATE}. */ @Documented @Retention(RetentionPolicy.SOURCE) @Target(TYPE_USE) @IntDef({ REQUEST_TYPE_UNKNOWN, REQUEST_TYPE_INITIAL, REQUEST_TYPE_RENEWAL, REQUEST_TYPE_RELEASE, REQUEST_TYPE_NONE, REQUEST_TYPE_UPDATE, }) public @interface RequestType {} /** * Value returned from {@link #getRequestType()} if the underlying key request does not specify * a type. */ public static final int REQUEST_TYPE_UNKNOWN = Integer.MIN_VALUE; /** Key request type for an initial license request. */ public static final int REQUEST_TYPE_INITIAL = MediaDrm.KeyRequest.REQUEST_TYPE_INITIAL; /** Key request type for license renewal. */ public static final int REQUEST_TYPE_RENEWAL = MediaDrm.KeyRequest.REQUEST_TYPE_RENEWAL; /** Key request type for license release. */ public static final int REQUEST_TYPE_RELEASE = MediaDrm.KeyRequest.REQUEST_TYPE_RELEASE; /** * Key request type if keys are already loaded and available for use. No license request is * necessary, and no key request data is returned. */ public static final int REQUEST_TYPE_NONE = MediaDrm.KeyRequest.REQUEST_TYPE_NONE; /** * Key request type if keys have been loaded, but an additional license request is needed to * update their values. */ public static final int REQUEST_TYPE_UPDATE = MediaDrm.KeyRequest.REQUEST_TYPE_UPDATE; private final byte[] data; private final String licenseServerUrl; private final @RequestType int requestType; /** * Creates an instance with {@link #REQUEST_TYPE_UNKNOWN}. * * @param data The opaque key request data. * @param licenseServerUrl The license server URL to which the request should be made. */ public KeyRequest(byte[] data, String licenseServerUrl) { this(data, licenseServerUrl, REQUEST_TYPE_UNKNOWN); } /** * Creates an instance. * * @param data The opaque key request data. * @param licenseServerUrl The license server URL to which the request should be made. * @param requestType The type of the request, or {@link #REQUEST_TYPE_UNKNOWN}. */ public KeyRequest(byte[] data, String licenseServerUrl, @RequestType int requestType) { this.data = data; this.licenseServerUrl = licenseServerUrl; this.requestType = requestType; } /** Returns the opaque key request data. */ public byte[] getData() { return data; } /** Returns the URL of the license server to which the request should be made. */ public String getLicenseServerUrl() { return licenseServerUrl; } /** * Returns the type of the request, or {@link #REQUEST_TYPE_UNKNOWN} if the underlying key * request does not specify a type. Note that when using a platform {@link MediaDrm} instance, * key requests only specify a type on API levels 23 and above. */ public @RequestType int getRequestType() { return requestType; } } /** * Contains data to request a certificate from a provisioning server. * * @see MediaDrm.ProvisionRequest */ final class ProvisionRequest { private final byte[] data; private final String defaultUrl; /** * Creates an instance. * * @param data The opaque provisioning request data. * @param defaultUrl The default URL of the provisioning server to which the request can be * made, or the empty string if not known. */ public ProvisionRequest(byte[] data, String defaultUrl) { this.data = data; this.defaultUrl = defaultUrl; } /** Returns the opaque provisioning request data. */ public byte[] getData() { return data; } /** * Returns the default URL of the provisioning server to which the request can be made, or the * empty string if not known. */ public String getDefaultUrl() { return defaultUrl; } } /** * Sets the listener for DRM events. * * <p>This is an optional method, and some implementations may only support it on certain Android * API levels. * * @param listener The listener to receive events, or {@code null} to stop receiving events. * @throws UnsupportedOperationException if the implementation doesn't support this method. * @see MediaDrm#setOnEventListener(MediaDrm.OnEventListener) */ void setOnEventListener(@Nullable OnEventListener listener); /** * Sets the listener for key status change events. * * <p>This is an optional method, and some implementations may only support it on certain Android * API levels. * * @param listener The listener to receive events, or {@code null} to stop receiving events. * @throws UnsupportedOperationException if the implementation doesn't support this method. * @see MediaDrm#setOnKeyStatusChangeListener(MediaDrm.OnKeyStatusChangeListener, Handler) */ void setOnKeyStatusChangeListener(@Nullable OnKeyStatusChangeListener listener); /** * Sets the listener for session expiration events. * * <p>This is an optional method, and some implementations may only support it on certain Android * API levels. * * @param listener The listener to receive events, or {@code null} to stop receiving events. * @throws UnsupportedOperationException if the implementation doesn't support this method. * @see MediaDrm#setOnExpirationUpdateListener(MediaDrm.OnExpirationUpdateListener, Handler) */ void setOnExpirationUpdateListener(@Nullable OnExpirationUpdateListener listener); /** * Opens a new DRM session. A session ID is returned. * * @return The session ID. * @throws NotProvisionedException If provisioning is needed. * @throws ResourceBusyException If required resources are in use. * @throws MediaDrmException If the session could not be opened. */ byte[] openSession() throws MediaDrmException; /** * Closes a DRM session. * * @param sessionId The ID of the session to close. */ void closeSession(byte[] sessionId); /** * Sets the {@link PlayerId} of the player using a session. * * @param sessionId The ID of the session. * @param playerId The {@link PlayerId} of the player using the session. */ default void setPlayerIdForSession(byte[] sessionId, PlayerId playerId) {} /** * Generates a key request. * * @param scope If {@code keyType} is {@link #KEY_TYPE_STREAMING} or {@link #KEY_TYPE_OFFLINE}, * the ID of the session that the keys will be provided to. If {@code keyType} is {@link * #KEY_TYPE_RELEASE}, the {@code keySetId} of the keys to release. * @param schemeDatas If key type is {@link #KEY_TYPE_STREAMING} or {@link #KEY_TYPE_OFFLINE}, a * list of {@link SchemeData} instances extracted from the media. Null otherwise. * @param keyType The type of the request. Either {@link #KEY_TYPE_STREAMING} to acquire keys for * streaming, {@link #KEY_TYPE_OFFLINE} to acquire keys for offline usage, or {@link * #KEY_TYPE_RELEASE} to release acquired keys. Releasing keys invalidates them for all * sessions. * @param optionalParameters Are included in the key request message to allow a client application * to provide additional message parameters to the server. This may be {@code null} if no * additional parameters are to be sent. * @return The generated key request. * @see MediaDrm#getKeyRequest(byte[], byte[], String, int, HashMap) */ KeyRequest getKeyRequest( byte[] scope, @Nullable List<SchemeData> schemeDatas, int keyType, @Nullable HashMap<String, String> optionalParameters) throws NotProvisionedException; /** * Provides a key response for the last request to be generated using {@link #getKeyRequest}. * * @param scope If the request had type {@link #KEY_TYPE_STREAMING} or {@link #KEY_TYPE_OFFLINE}, * the ID of the session to provide the keys to. If {@code keyType} is {@link * #KEY_TYPE_RELEASE}, the {@code keySetId} of the keys being released. * @param response The response data from the server. * @return If the request had type {@link #KEY_TYPE_OFFLINE}, the {@code keySetId} for the offline * keys. An empty byte array or {@code null} may be returned for other cases. * @throws NotProvisionedException If the response indicates that provisioning is needed. * @throws DeniedByServerException If the response indicates that the server rejected the request. */ @Nullable byte[] provideKeyResponse(byte[] scope, byte[] response) throws NotProvisionedException, DeniedByServerException; /** * Generates a provisioning request. * * @return The generated provisioning request. */ ProvisionRequest getProvisionRequest(); /** * Provides a provisioning response for the last request to be generated using {@link * #getProvisionRequest()}. * * @param response The response data from the server. * @throws DeniedByServerException If the response indicates that the server rejected the request. */ void provideProvisionResponse(byte[] response) throws DeniedByServerException; /** * Returns the key status for a given session, as {name, value} pairs. Since DRM license policies * vary by vendor, the returned entries depend on the DRM plugin being used. Refer to your DRM * provider's documentation for more information. * * @param sessionId The ID of the session being queried. * @return The key status for the session. */ Map<String, String> queryKeyStatus(byte[] sessionId); /** * Returns whether the given session requires use of a secure decoder for the given MIME type. * Assumes a license policy that requires the highest level of security supported by the session. * * @param sessionId The ID of the session. * @param mimeType The content MIME type to query. */ boolean requiresSecureDecoder(byte[] sessionId, String mimeType); /** * Increments the reference count. When the caller no longer needs to use the instance, it must * call {@link #release()} to decrement the reference count. * * <p>A new instance will have an initial reference count of 1, and therefore it is not normally * necessary for application code to call this method. */ void acquire(); /** * Decrements the reference count. If the reference count drops to 0 underlying resources are * released, and the instance cannot be re-used. */ void release(); /** * Restores persisted offline keys into a session. * * @param sessionId The ID of the session into which the keys will be restored. * @param keySetId The {@code keySetId} of the keys to restore, as provided by the call to {@link * #provideKeyResponse} that persisted them. */ void restoreKeys(byte[] sessionId, byte[] keySetId); /** * Returns metrics data for this ExoMediaDrm instance, or {@code null} if metrics are unavailable. */ @Nullable PersistableBundle getMetrics(); /** * Returns the value of a string property. For standard property names, see {@link * MediaDrm#getPropertyString}. * * @param propertyName The property name. * @return The property value. * @throws IllegalArgumentException If the underlying DRM plugin does not support the property. */ String getPropertyString(String propertyName); /** * Returns the value of a byte array property. For standard property names, see {@link * MediaDrm#getPropertyByteArray}. * * @param propertyName The property name. * @return The property value. * @throws IllegalArgumentException If the underlying DRM plugin does not support the property. */ byte[] getPropertyByteArray(String propertyName); /** * Sets the value of a string property. * * @param propertyName The property name. * @param value The value. * @throws IllegalArgumentException If the underlying DRM plugin does not support the property. */ void setPropertyString(String propertyName, String value); /** * Sets the value of a byte array property. * * @param propertyName The property name. * @param value The value. * @throws IllegalArgumentException If the underlying DRM plugin does not support the property. */ void setPropertyByteArray(String propertyName, byte[] value); /** * Creates a {@link CryptoConfig} that can be passed to a compatible decoder to allow decryption * of protected content using the specified session. * * @param sessionId The ID of the session. * @return A {@link CryptoConfig} for the given session. * @throws MediaCryptoException If a {@link CryptoConfig} could not be created. */ CryptoConfig createCryptoConfig(byte[] sessionId) throws MediaCryptoException; /** * Returns the {@link C.CryptoType type} of {@link CryptoConfig} instances returned by {@link * #createCryptoConfig}. */ @C.CryptoType int getCryptoType(); }
{ "content_hash": "812ab464f8b2d4bf12780dc4d4efbb7f", "timestamp": "", "source": "github", "line_count": 564, "max_line_length": 100, "avg_line_length": 36.301418439716315, "alnum_prop": 0.7007424050014652, "repo_name": "androidx/media", "id": "115cad12bb565b54b9c0a46af3d11512f9f9de9b", "size": "21093", "binary": false, "copies": "1", "ref": "refs/heads/release", "path": "libraries/exoplayer/src/main/java/androidx/media3/exoplayer/drm/ExoMediaDrm.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AIDL", "bytes": "27206" }, { "name": "C++", "bytes": "112467" }, { "name": "CMake", "bytes": "3728" }, { "name": "GLSL", "bytes": "24923" }, { "name": "Java", "bytes": "17624240" }, { "name": "Makefile", "bytes": "11496" }, { "name": "Shell", "bytes": "24988" } ], "symlink_target": "" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_console_06.c Label Definition File: CWE761_Free_Pointer_Not_at_Start_of_Buffer.label.xml Template File: source-sinks-06.tmpl.c */ /* * @description * CWE: 761 Free Pointer not at Start of Buffer * BadSource: console Read input from the console * Sinks: * GoodSink: free() memory correctly at the start of the buffer * BadSink : free() memory not at the start of the buffer * Flow Variant: 06 Control flow: if(STATIC_CONST_FIVE==5) and if(STATIC_CONST_FIVE!=5) * * */ #include "std_testcase.h" #include <wchar.h> #define SEARCH_CHAR 'S' /* The variable below is declared "const", so a tool should be able to identify that reads of this will always give its initialized value. */ static const int STATIC_CONST_FIVE = 5; #ifndef OMITBAD void CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_console_06_bad() { char * data; data = (char *)malloc(100*sizeof(char)); if (data == NULL) {exit(-1);} data[0] = '\0'; { /* Read input from the console */ size_t dataLen = strlen(data); /* if there is room in data, read into it from the console */ if (100-dataLen > 1) { /* POTENTIAL FLAW: Read data from the console */ if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL) { /* The next few lines remove the carriage return from the string that is * inserted by fgets() */ dataLen = strlen(data); if (dataLen > 0 && data[dataLen-1] == '\n') { data[dataLen-1] = '\0'; } } else { printLine("fgets() failed"); /* Restore NUL terminator if fgets fails */ data[dataLen] = '\0'; } } } if(STATIC_CONST_FIVE==5) { /* FLAW: We are incrementing the pointer in the loop - this will cause us to free the * memory block not at the start of the buffer */ for (; *data != '\0'; data++) { if (*data == SEARCH_CHAR) { printLine("We have a match!"); break; } } free(data); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodB2G1() - use badsource and goodsink by changing STATIC_CONST_FIVE==5 to STATIC_CONST_FIVE!=5 */ static void goodB2G1() { char * data; data = (char *)malloc(100*sizeof(char)); if (data == NULL) {exit(-1);} data[0] = '\0'; { /* Read input from the console */ size_t dataLen = strlen(data); /* if there is room in data, read into it from the console */ if (100-dataLen > 1) { /* POTENTIAL FLAW: Read data from the console */ if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL) { /* The next few lines remove the carriage return from the string that is * inserted by fgets() */ dataLen = strlen(data); if (dataLen > 0 && data[dataLen-1] == '\n') { data[dataLen-1] = '\0'; } } else { printLine("fgets() failed"); /* Restore NUL terminator if fgets fails */ data[dataLen] = '\0'; } } } if(STATIC_CONST_FIVE!=5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { { size_t i; /* FIX: Use a loop variable to traverse through the string pointed to by data */ for (i=0; i < strlen(data); i++) { if (data[i] == SEARCH_CHAR) { printLine("We have a match!"); break; } } free(data); } } } /* goodB2G2() - use badsource and goodsink by reversing statements in if */ static void goodB2G2() { char * data; data = (char *)malloc(100*sizeof(char)); if (data == NULL) {exit(-1);} data[0] = '\0'; { /* Read input from the console */ size_t dataLen = strlen(data); /* if there is room in data, read into it from the console */ if (100-dataLen > 1) { /* POTENTIAL FLAW: Read data from the console */ if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL) { /* The next few lines remove the carriage return from the string that is * inserted by fgets() */ dataLen = strlen(data); if (dataLen > 0 && data[dataLen-1] == '\n') { data[dataLen-1] = '\0'; } } else { printLine("fgets() failed"); /* Restore NUL terminator if fgets fails */ data[dataLen] = '\0'; } } } if(STATIC_CONST_FIVE==5) { { size_t i; /* FIX: Use a loop variable to traverse through the string pointed to by data */ for (i=0; i < strlen(data); i++) { if (data[i] == SEARCH_CHAR) { printLine("We have a match!"); break; } } free(data); } } } void CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_console_06_good() { goodB2G1(); goodB2G2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_console_06_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_console_06_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
{ "content_hash": "8577b2eaafa6e06e9b4fa609de2ebe31", "timestamp": "", "source": "github", "line_count": 218, "max_line_length": 102, "avg_line_length": 30.80275229357798, "alnum_prop": 0.49545793000744603, "repo_name": "JianpingZeng/xcc", "id": "50a8da3ff33b918b895542a146b2f5b6ed3f0317", "size": "6715", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "xcc/test/juliet/testcases/CWE761_Free_Pointer_Not_at_Start_of_Buffer/CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_console_06.c", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <com.facebook.drawee.view.SimpleDraweeView android:id="@+id/icon" android:layout_width="80dp" android:layout_height="80dp" /> <TextView android:id="@+id/version_name" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
{ "content_hash": "cd11c5cd16a6f85a13cbaa01999bc01e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 72, "avg_line_length": 41.46153846153846, "alnum_prop": 0.6771799628942486, "repo_name": "sdgdsffdsfff/YcpTest", "id": "da8ef31965c5221cb2b45aa5937679e003729b3c", "size": "539", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/src/main/res/layout/adapter_versions.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "36449" } ], "symlink_target": "" }
 #include <aws/iot-jobs-data/model/StartNextPendingJobExecutionRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::IoTJobsDataPlane::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; StartNextPendingJobExecutionRequest::StartNextPendingJobExecutionRequest() : m_thingNameHasBeenSet(false), m_statusDetailsHasBeenSet(false), m_stepTimeoutInMinutes(0), m_stepTimeoutInMinutesHasBeenSet(false) { } Aws::String StartNextPendingJobExecutionRequest::SerializePayload() const { JsonValue payload; if(m_statusDetailsHasBeenSet) { JsonValue statusDetailsJsonMap; for(auto& statusDetailsItem : m_statusDetails) { statusDetailsJsonMap.WithString(statusDetailsItem.first, statusDetailsItem.second); } payload.WithObject("statusDetails", std::move(statusDetailsJsonMap)); } if(m_stepTimeoutInMinutesHasBeenSet) { payload.WithInt64("stepTimeoutInMinutes", m_stepTimeoutInMinutes); } return payload.View().WriteReadable(); }
{ "content_hash": "79a73fa5d14d9b08f80039ad5fbd4e57", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 88, "avg_line_length": 22.76086956521739, "alnum_prop": 0.7717287488061128, "repo_name": "JoyIfBam5/aws-sdk-cpp", "id": "42e752fa28e07b3f2565ef52c6247210abaaa117", "size": "1620", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-cpp-sdk-iot-jobs-data/source/model/StartNextPendingJobExecutionRequest.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "11868" }, { "name": "C++", "bytes": "167818064" }, { "name": "CMake", "bytes": "591577" }, { "name": "HTML", "bytes": "4471" }, { "name": "Java", "bytes": "271801" }, { "name": "Python", "bytes": "85650" }, { "name": "Shell", "bytes": "5277" } ], "symlink_target": "" }
package com.stripe.functional; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import com.stripe.BaseStripeTest; import com.stripe.exception.StripeException; import com.stripe.model.Account; import com.stripe.model.AccountCollection; import com.stripe.model.ExternalAccount; import com.stripe.model.PersonCollection; import com.stripe.net.ApiResource; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; public class AccountTest extends BaseStripeTest { public static final String ACCOUNT_ID = "acct_123"; private Account getAccountFixture() throws StripeException { final Account account = Account.retrieve(ACCOUNT_ID, null); resetNetworkSpy(); return account; } @Test public void testCreate() throws StripeException { final Map<String, Object> params = new HashMap<>(); params.put("type", "custom"); final Account account = Account.create(params); assertNotNull(account); verifyRequest(ApiResource.RequestMethod.POST, String.format("/v1/accounts"), params); } @Test public void testList() throws StripeException { final Map<String, Object> params = new HashMap<>(); params.put("limit", 1); final AccountCollection accounts = Account.list(params); assertNotNull(accounts); verifyRequest(ApiResource.RequestMethod.GET, String.format("/v1/accounts"), params); } @Test public void testRetrieve() throws StripeException { final Account account = Account.retrieve(); assertNotNull(account); verifyRequest(ApiResource.RequestMethod.GET, String.format("/v1/account")); } @Test public void testRetrieveWithId() throws StripeException { final Account account = Account.retrieve(ACCOUNT_ID, null); assertNotNull(account); verifyRequest(ApiResource.RequestMethod.GET, String.format("/v1/accounts/%s", ACCOUNT_ID)); } @Test public void testUpdate() throws StripeException { final Account account = getAccountFixture(); final Map<String, Object> params = new HashMap<>(); params.put("business_type", "individual"); final Account updatedAccount = account.update(params); assertNotNull(updatedAccount); verifyRequest( ApiResource.RequestMethod.POST, String.format("/v1/accounts/%s", account.getId()), params); } @Test public void testDelete() throws StripeException { final Account account = getAccountFixture(); final Account deletedAccount = account.delete(); assertNotNull(deletedAccount); assertTrue(deletedAccount.getDeleted()); verifyRequest( ApiResource.RequestMethod.DELETE, String.format("/v1/accounts/%s", account.getId())); } @Test public void testReject() throws StripeException { final Account account = getAccountFixture(); final Map<String, Object> params = new HashMap<>(); params.put("reason", "fraud"); Account rejectedAccount = account.reject(params); assertNotNull(rejectedAccount); verifyRequest( ApiResource.RequestMethod.POST, String.format("/v1/accounts/%s/reject", account.getId()), params); } @Test public void testAccountCreateExternalAccount() throws StripeException { final Account resource = Account.retrieve(ACCOUNT_ID, null); final Map<String, Object> params = new HashMap<>(); params.put("external_account", "tok_123"); final ExternalAccount ea = resource.getExternalAccounts().create(params); assertNotNull(ea); verifyRequest( ApiResource.RequestMethod.POST, String.format("/v1/accounts/%s/external_accounts", resource.getId()), params); } @Test public void testPersons() throws StripeException { final Account resource = Account.retrieve(ACCOUNT_ID, null); final Map<String, Object> params = new HashMap<>(); params.put("limit", 1); final PersonCollection persons = resource.persons(params); assertNotNull(persons); verifyRequest( ApiResource.RequestMethod.GET, String.format("/v1/accounts/%s/persons", resource.getId()), params); } }
{ "content_hash": "8a63edd6bc91a0d43003245e21685ef5", "timestamp": "", "source": "github", "line_count": 137, "max_line_length": 99, "avg_line_length": 30.16788321167883, "alnum_prop": 0.7164287442535688, "repo_name": "stripe/stripe-java", "id": "b957f3e58f646d0ebbc7a8f8a0d03f29e954366c", "size": "4133", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/com/stripe/functional/AccountTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "12216683" }, { "name": "Makefile", "bytes": "953" } ], "symlink_target": "" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE511_Logic_Time_Bomb__w32CompareFileTime_15.c Label Definition File: CWE511_Logic_Time_Bomb.label.xml Template File: point-flaw-15.tmpl.c */ /* * @description * CWE: 511 Logic Time Bomb * Sinks: w32CompareFileTime * GoodSink: After a certain date, do something harmless * BadSink : After a certain date, do something bad * Flow Variant: 15 Control flow: switch(6) * * */ #include "std_testcase.h" #ifdef _WIN32 #define UNLINK _unlink #else #include <unistd.h> #define UNLINK unlink #endif #include <windows.h> #ifndef OMITBAD void CWE511_Logic_Time_Bomb__w32CompareFileTime_15_bad() { switch(6) { case 6: { SYSTEMTIME setTime, currentTime; FILETIME setTimeAsFileTime, currentTimeAsFileTime; /* Jan 1, 2008 12:00:00 PM */ setTime.wYear = 2008; /* Year */ setTime.wMonth = 1; /* January */ setTime.wDayOfWeek = 0; /* Ignored */ setTime.wDay = 1; /* The first of the month */ setTime.wHour = 12; /* 12 PM */ setTime.wMinute = 0; /* 0 minutes into the hour */ setTime.wSecond = 0; /* 0 seconds into the minute */ setTime.wMilliseconds = 0; /* 0 milliseconds into the second */ GetSystemTime(&currentTime); /* Must convert to FILETIME for comparison */ SystemTimeToFileTime(&currentTime, &currentTimeAsFileTime); SystemTimeToFileTime(&setTime, &setTimeAsFileTime); /* FLAW: After a certain date, delete a file */ if (CompareFileTime(&currentTimeAsFileTime, &setTimeAsFileTime) == 1) { UNLINK("important_file.txt"); } } break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); break; } } #endif /* OMITBAD */ #ifndef OMITGOOD /* good1() changes the switch to switch(5) */ static void good1() { switch(5) { case 6: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); break; default: { SYSTEMTIME setTime, currentTime; FILETIME setTimeAsFileTime, currentTimeAsFileTime; /* Jan 1, 2008 12:00:00 PM */ setTime.wYear = 2008; /* Year */ setTime.wMonth = 1; /* January */ setTime.wDayOfWeek = 0; /* Ignored */ setTime.wDay = 1; /* The first of the month */ setTime.wHour = 12; /* 12 PM */ setTime.wMinute = 0; /* 0 minutes into the hour */ setTime.wSecond = 0; /* 0 seconds into the minute */ setTime.wMilliseconds = 0; /* 0 milliseconds into the second */ GetSystemTime(&currentTime); /* Must convert to FILETIME for comparison */ SystemTimeToFileTime(&currentTime, &currentTimeAsFileTime); SystemTimeToFileTime(&setTime, &setTimeAsFileTime); /* FIX: After a certain date, print to the console */ if (CompareFileTime(&currentTimeAsFileTime, &setTimeAsFileTime) == 1) { printLine("Happy New Year!"); } } break; } } /* good2() reverses the blocks in the switch */ static void good2() { switch(6) { case 6: { SYSTEMTIME setTime, currentTime; FILETIME setTimeAsFileTime, currentTimeAsFileTime; /* Jan 1, 2008 12:00:00 PM */ setTime.wYear = 2008; /* Year */ setTime.wMonth = 1; /* January */ setTime.wDayOfWeek = 0; /* Ignored */ setTime.wDay = 1; /* The first of the month */ setTime.wHour = 12; /* 12 PM */ setTime.wMinute = 0; /* 0 minutes into the hour */ setTime.wSecond = 0; /* 0 seconds into the minute */ setTime.wMilliseconds = 0; /* 0 milliseconds into the second */ GetSystemTime(&currentTime); /* Must convert to FILETIME for comparison */ SystemTimeToFileTime(&currentTime, &currentTimeAsFileTime); SystemTimeToFileTime(&setTime, &setTimeAsFileTime); /* FIX: After a certain date, print to the console */ if (CompareFileTime(&currentTimeAsFileTime, &setTimeAsFileTime) == 1) { printLine("Happy New Year!"); } } break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); break; } } void CWE511_Logic_Time_Bomb__w32CompareFileTime_15_good() { good1(); good2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE511_Logic_Time_Bomb__w32CompareFileTime_15_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE511_Logic_Time_Bomb__w32CompareFileTime_15_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
{ "content_hash": "7c9e6f6f240a93c447878973752b59b2", "timestamp": "", "source": "github", "line_count": 172, "max_line_length": 77, "avg_line_length": 32.69767441860465, "alnum_prop": 0.5796586059743954, "repo_name": "maurer/tiamat", "id": "c247ad9b312d08aaaf34f4f15d2092588fdcc142", "size": "5624", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "samples/Juliet/testcases/CWE511_Logic_Time_Bomb/CWE511_Logic_Time_Bomb__w32CompareFileTime_15.c", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>V8 API Reference Guide for node.js v0.4.9: Class Members - Functions</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for node.js v0.4.9 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li class="current"><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="navrow3" class="tabs2"> <ul class="tablist"> <li><a href="functions.html"><span>All</span></a></li> <li class="current"><a href="functions_func.html"><span>Functions</span></a></li> <li><a href="functions_vars.html"><span>Variables</span></a></li> <li><a href="functions_type.html"><span>Typedefs</span></a></li> <li><a href="functions_enum.html"><span>Enumerations</span></a></li> </ul> </div> <div id="navrow4" class="tabs3"> <ul class="tablist"> <li><a href="functions_func.html#index_a"><span>a</span></a></li> <li><a href="functions_func_c.html#index_c"><span>c</span></a></li> <li><a href="functions_func_d.html#index_d"><span>d</span></a></li> <li class="current"><a href="functions_func_e.html#index_e"><span>e</span></a></li> <li><a href="functions_func_f.html#index_f"><span>f</span></a></li> <li><a href="functions_func_g.html#index_g"><span>g</span></a></li> <li><a href="functions_func_h.html#index_h"><span>h</span></a></li> <li><a href="functions_func_i.html#index_i"><span>i</span></a></li> <li><a href="functions_func_l.html#index_l"><span>l</span></a></li> <li><a href="functions_func_m.html#index_m"><span>m</span></a></li> <li><a href="functions_func_n.html#index_n"><span>n</span></a></li> <li><a href="functions_func_o.html#index_o"><span>o</span></a></li> <li><a href="functions_func_p.html#index_p"><span>p</span></a></li> <li><a href="functions_func_r.html#index_r"><span>r</span></a></li> <li><a href="functions_func_s.html#index_s"><span>s</span></a></li> <li><a href="functions_func_t.html#index_t"><span>t</span></a></li> <li><a href="functions_func_u.html#index_u"><span>u</span></a></li> <li><a href="functions_func_w.html#index_w"><span>w</span></a></li> <li><a href="functions_func_~.html#index_~"><span>~</span></a></li> </ul> </div> </div><!-- top --> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> &#160; <h3><a class="anchor" id="index_e"></a>- e -</h3><ul> <li>Empty() : <a class="el" href="classv8_1_1_string.html#a148c0f01dca1c477eba42717068a2c7e">v8::String</a> </li> <li>EnableAgent() : <a class="el" href="classv8_1_1_debug.html#a78506e80b599010624c5fcde72a643a7">v8::Debug</a> </li> <li>EnableSlidingStateWindow() : <a class="el" href="classv8_1_1_v8.html#aa91df5fe1bb98b87952ef4bbf0aceb96">v8::V8</a> </li> <li>EndOfStream() : <a class="el" href="classv8_1_1_output_stream.html#a6c5c308367fc5776bcbedff0e94d6049">v8::OutputStream</a> </li> <li>Enter() : <a class="el" href="classv8_1_1_context.html#a6995c49d9897eb49053f07874b825133">v8::Context</a> </li> <li>Equals() : <a class="el" href="classv8_1_1_value.html#a643fcf5c7c6136d819b0b4927f8d1724">v8::Value</a> </li> <li>Exception() : <a class="el" href="classv8_1_1_try_catch.html#a99c425f29b3355b4294cbe762377f99b">v8::TryCatch</a> </li> <li>Exit() : <a class="el" href="classv8_1_1_context.html#a2db09d4fefb26023a40d88972a4c1599">v8::Context</a> </li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Aug 11 2015 23:47:11 for V8 API Reference Guide for node.js v0.4.9 by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
{ "content_hash": "2ecf3ebc187d4dfc5fc55ee524299336", "timestamp": "", "source": "github", "line_count": 155, "max_line_length": 154, "avg_line_length": 44.645161290322584, "alnum_prop": 0.6352601156069364, "repo_name": "v8-dox/v8-dox.github.io", "id": "03d4bf60e99fc368f037104ffec85be383f3ea75", "size": "6920", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "1e7769d/html/functions_func_e.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
#ifndef QT3D_QABSTRACTLIGHT_H #define QT3D_QABSTRACTLIGHT_H #include <Qt3DRenderer/qshaderdata.h> #include <Qt3DRenderer/qt3drenderer_global.h> #include <QVector3D> #include <QColor> QT_BEGIN_NAMESPACE namespace Qt3D { class QAbstractLightPrivate; class QT3DRENDERERSHARED_EXPORT QAbstractLight : public QShaderData { Q_OBJECT Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged) Q_PROPERTY(float intensity READ intensity WRITE setIntensity NOTIFY intensityChanged) Q_PROPERTY(QVector3D position READ position WRITE setPosition NOTIFY positionChanged) Q_PROPERTY(TransformType positionTransformed READ positionTransformed CONSTANT) public : explicit QAbstractLight(QNode *parent = 0); QColor color() const; void setColor(const QColor &color); float intensity() const; void setIntensity(float intensity); void setPosition(const QVector3D &position); QVector3D position() const; TransformType positionTransformed() const; protected : QAbstractLight(QAbstractLightPrivate &dd, QNode *parent = 0); void copy(const QNode *ref) Q_DECL_OVERRIDE; Q_SIGNALS: void colorChanged(); void intensityChanged(); void positionChanged(); private: Q_DECLARE_PRIVATE(QAbstractLight) }; } // Qt3D QT_END_NAMESPACE #endif // QT3D_LIGHT_H
{ "content_hash": "4a8f7164bb031899b36a0d9b5d755ffa", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 89, "avg_line_length": 22.913793103448278, "alnum_prop": 0.7562076749435666, "repo_name": "RikoOphorst/blowbox", "id": "c5db0e67caf42cd61e9a9dc1abdb8aeae9f14ea6", "size": "3070", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "dependencies/qt/Include/Qt3DRenderer/qabstractlight.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "836" }, { "name": "C++", "bytes": "250806" }, { "name": "CSS", "bytes": "25182" }, { "name": "HLSL", "bytes": "1209" } ], "symlink_target": "" }
 #pragma once #include <aws/managedblockchain/ManagedBlockchain_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace ManagedBlockchain { namespace Model { /** * <p>Attributes of an Ethereum node.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/managedblockchain-2018-09-24/NodeEthereumAttributes">AWS * API Reference</a></p> */ class AWS_MANAGEDBLOCKCHAIN_API NodeEthereumAttributes { public: NodeEthereumAttributes(); NodeEthereumAttributes(Aws::Utils::Json::JsonView jsonValue); NodeEthereumAttributes& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The endpoint on which the Ethereum node listens to run Ethereum API methods * over HTTP connections from a client. Use this endpoint in client code for smart * contracts when using an HTTP connection. Connections to this endpoint are * authenticated using <a * href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature * Version 4</a>.</p> */ inline const Aws::String& GetHttpEndpoint() const{ return m_httpEndpoint; } /** * <p>The endpoint on which the Ethereum node listens to run Ethereum API methods * over HTTP connections from a client. Use this endpoint in client code for smart * contracts when using an HTTP connection. Connections to this endpoint are * authenticated using <a * href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature * Version 4</a>.</p> */ inline bool HttpEndpointHasBeenSet() const { return m_httpEndpointHasBeenSet; } /** * <p>The endpoint on which the Ethereum node listens to run Ethereum API methods * over HTTP connections from a client. Use this endpoint in client code for smart * contracts when using an HTTP connection. Connections to this endpoint are * authenticated using <a * href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature * Version 4</a>.</p> */ inline void SetHttpEndpoint(const Aws::String& value) { m_httpEndpointHasBeenSet = true; m_httpEndpoint = value; } /** * <p>The endpoint on which the Ethereum node listens to run Ethereum API methods * over HTTP connections from a client. Use this endpoint in client code for smart * contracts when using an HTTP connection. Connections to this endpoint are * authenticated using <a * href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature * Version 4</a>.</p> */ inline void SetHttpEndpoint(Aws::String&& value) { m_httpEndpointHasBeenSet = true; m_httpEndpoint = std::move(value); } /** * <p>The endpoint on which the Ethereum node listens to run Ethereum API methods * over HTTP connections from a client. Use this endpoint in client code for smart * contracts when using an HTTP connection. Connections to this endpoint are * authenticated using <a * href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature * Version 4</a>.</p> */ inline void SetHttpEndpoint(const char* value) { m_httpEndpointHasBeenSet = true; m_httpEndpoint.assign(value); } /** * <p>The endpoint on which the Ethereum node listens to run Ethereum API methods * over HTTP connections from a client. Use this endpoint in client code for smart * contracts when using an HTTP connection. Connections to this endpoint are * authenticated using <a * href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature * Version 4</a>.</p> */ inline NodeEthereumAttributes& WithHttpEndpoint(const Aws::String& value) { SetHttpEndpoint(value); return *this;} /** * <p>The endpoint on which the Ethereum node listens to run Ethereum API methods * over HTTP connections from a client. Use this endpoint in client code for smart * contracts when using an HTTP connection. Connections to this endpoint are * authenticated using <a * href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature * Version 4</a>.</p> */ inline NodeEthereumAttributes& WithHttpEndpoint(Aws::String&& value) { SetHttpEndpoint(std::move(value)); return *this;} /** * <p>The endpoint on which the Ethereum node listens to run Ethereum API methods * over HTTP connections from a client. Use this endpoint in client code for smart * contracts when using an HTTP connection. Connections to this endpoint are * authenticated using <a * href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature * Version 4</a>.</p> */ inline NodeEthereumAttributes& WithHttpEndpoint(const char* value) { SetHttpEndpoint(value); return *this;} /** * <p>The endpoint on which the Ethereum node listens to run Ethereum JSON-RPC * methods over WebSocket connections from a client. Use this endpoint in client * code for smart contracts when using a WebSocket connection. Connections to this * endpoint are authenticated using <a * href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature * Version 4</a>.</p> */ inline const Aws::String& GetWebSocketEndpoint() const{ return m_webSocketEndpoint; } /** * <p>The endpoint on which the Ethereum node listens to run Ethereum JSON-RPC * methods over WebSocket connections from a client. Use this endpoint in client * code for smart contracts when using a WebSocket connection. Connections to this * endpoint are authenticated using <a * href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature * Version 4</a>.</p> */ inline bool WebSocketEndpointHasBeenSet() const { return m_webSocketEndpointHasBeenSet; } /** * <p>The endpoint on which the Ethereum node listens to run Ethereum JSON-RPC * methods over WebSocket connections from a client. Use this endpoint in client * code for smart contracts when using a WebSocket connection. Connections to this * endpoint are authenticated using <a * href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature * Version 4</a>.</p> */ inline void SetWebSocketEndpoint(const Aws::String& value) { m_webSocketEndpointHasBeenSet = true; m_webSocketEndpoint = value; } /** * <p>The endpoint on which the Ethereum node listens to run Ethereum JSON-RPC * methods over WebSocket connections from a client. Use this endpoint in client * code for smart contracts when using a WebSocket connection. Connections to this * endpoint are authenticated using <a * href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature * Version 4</a>.</p> */ inline void SetWebSocketEndpoint(Aws::String&& value) { m_webSocketEndpointHasBeenSet = true; m_webSocketEndpoint = std::move(value); } /** * <p>The endpoint on which the Ethereum node listens to run Ethereum JSON-RPC * methods over WebSocket connections from a client. Use this endpoint in client * code for smart contracts when using a WebSocket connection. Connections to this * endpoint are authenticated using <a * href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature * Version 4</a>.</p> */ inline void SetWebSocketEndpoint(const char* value) { m_webSocketEndpointHasBeenSet = true; m_webSocketEndpoint.assign(value); } /** * <p>The endpoint on which the Ethereum node listens to run Ethereum JSON-RPC * methods over WebSocket connections from a client. Use this endpoint in client * code for smart contracts when using a WebSocket connection. Connections to this * endpoint are authenticated using <a * href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature * Version 4</a>.</p> */ inline NodeEthereumAttributes& WithWebSocketEndpoint(const Aws::String& value) { SetWebSocketEndpoint(value); return *this;} /** * <p>The endpoint on which the Ethereum node listens to run Ethereum JSON-RPC * methods over WebSocket connections from a client. Use this endpoint in client * code for smart contracts when using a WebSocket connection. Connections to this * endpoint are authenticated using <a * href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature * Version 4</a>.</p> */ inline NodeEthereumAttributes& WithWebSocketEndpoint(Aws::String&& value) { SetWebSocketEndpoint(std::move(value)); return *this;} /** * <p>The endpoint on which the Ethereum node listens to run Ethereum JSON-RPC * methods over WebSocket connections from a client. Use this endpoint in client * code for smart contracts when using a WebSocket connection. Connections to this * endpoint are authenticated using <a * href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature * Version 4</a>.</p> */ inline NodeEthereumAttributes& WithWebSocketEndpoint(const char* value) { SetWebSocketEndpoint(value); return *this;} private: Aws::String m_httpEndpoint; bool m_httpEndpointHasBeenSet = false; Aws::String m_webSocketEndpoint; bool m_webSocketEndpointHasBeenSet = false; }; } // namespace Model } // namespace ManagedBlockchain } // namespace Aws
{ "content_hash": "592834b7056537029134022ee32df9ac", "timestamp": "", "source": "github", "line_count": 209, "max_line_length": 139, "avg_line_length": 46.942583732057415, "alnum_prop": 0.7099174396086025, "repo_name": "aws/aws-sdk-cpp", "id": "4377b3e4b3e4fb2c27ffe2d02f95d2c76f34db14", "size": "9930", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "aws-cpp-sdk-managedblockchain/include/aws/managedblockchain/model/NodeEthereumAttributes.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "309797" }, { "name": "C++", "bytes": "476866144" }, { "name": "CMake", "bytes": "1245180" }, { "name": "Dockerfile", "bytes": "11688" }, { "name": "HTML", "bytes": "8056" }, { "name": "Java", "bytes": "413602" }, { "name": "Python", "bytes": "79245" }, { "name": "Shell", "bytes": "9246" } ], "symlink_target": "" }
/** * Next function supports optional `ctx` replacement for following middleware. */ export type Next<T> = () => Promise<T>; /** * Middleware function pattern. */ export type Middleware<T, U> = (ctx: T, next: Next<U>) => U | Promise<U>; /** * Final function has no `next()`. */ export type Done<T, U> = (ctx: T) => U | Promise<U>; /** * Composed function signature. */ export type Composed<T, U> = (ctx: T, done: Done<T, U>) => Promise<U>; /** * Debug mode wrapper for middleware functions. */ function debugMiddleware<T, U>( middleware: Array<Middleware<T, U>> ): Composed<T, U> { if (!Array.isArray(middleware)) { throw new TypeError( `Expected middleware to be an array, got ${typeof middleware}` ); } for (const fn of middleware) { if ((typeof fn as any) !== "function") { // tslint:disable-line throw new TypeError( `Expected middleware to contain functions, but got ${typeof fn}` ); } } return function composedDebug(ctx: T, done: Done<T, U>) { if ((typeof done as any) !== "function") { // tslint:disable-line throw new TypeError( `Expected the last argument to be \`done(ctx)\`, but got ${typeof done}` ); } let index = 0; function dispatch(pos: number): Promise<U> { const fn = middleware[pos] || done; index = pos; return new Promise(resolve => { const result = fn(ctx, function next() { if (pos < index) { throw new TypeError("`next()` called multiple times"); } if (pos > middleware.length) { throw new TypeError( "Composed `done(ctx)` function should not call `next()`" ); } return dispatch(pos + 1); }); if ((result as any) === undefined) { // tslint:disable-line throw new TypeError( "Expected middleware to return `next()` or a value" ); } return resolve(result); }); } return dispatch(index); }; } /** * Production-mode middleware composition (no errors thrown). */ function composeMiddleware<T, U>( middleware: Array<Middleware<T, U>> ): Composed<T, U> { function dispatch(pos: number, ctx: T, done: Done<T, U>): Promise<U> { const fn = middleware[pos] || done; return new Promise<U>(resolve => { return resolve( fn(ctx, function next() { return dispatch(pos + 1, ctx, done); }) ); }); } return function composed(ctx, done) { return dispatch(0, ctx, done); }; } /** * Compose an array of middleware functions into a single function. */ export const compose = process.env.NODE_ENV === "production" ? composeMiddleware : debugMiddleware;
{ "content_hash": "ed24a1a7be3e6bad672cb94261356005", "timestamp": "", "source": "github", "line_count": 114, "max_line_length": 80, "avg_line_length": 24.30701754385965, "alnum_prop": 0.5738000721761097, "repo_name": "blakeembrey/throwback", "id": "f2f74046c099803dc31037bc8df96754c85e9f8d", "size": "2771", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/index.ts", "mode": "33188", "license": "mit", "language": [ { "name": "TypeScript", "bytes": "5655" } ], "symlink_target": "" }
 using System; using System.Runtime.Serialization; namespace MongoDB.Driver.Communication.Security { /// <summary> /// An exception thrown during login and privilege negotiation. /// </summary> [Serializable] public class MongoSecurityException : MongoException { /// <summary> /// Initializes a new instance of the <see cref="MongoSecurityException" /> class. /// </summary> /// <param name="message">The message.</param> public MongoSecurityException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="MongoSecurityException" /> class. /// </summary> /// <param name="message">The message.</param> /// <param name="inner">The inner.</param> public MongoSecurityException(string message, Exception inner) : base(message, inner) { } /// <summary> /// Initializes a new instance of the <see cref="MongoSecurityException" /> class. /// </summary> /// <param name="info">The info.</param> /// <param name="context">The context.</param> protected MongoSecurityException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
{ "content_hash": "586449bd260f5202f86fe38d31879348", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 90, "avg_line_length": 31.46511627906977, "alnum_prop": 0.5875831485587583, "repo_name": "antonnik/code-classifier", "id": "8870b8f9f2758fcc0d28b08ea8343e538e54bfd6", "size": "1935", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "naive_bayes/resources/c#/MongoSecurityException.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "786556" }, { "name": "C#", "bytes": "7197222" }, { "name": "C++", "bytes": "1142843" }, { "name": "HTML", "bytes": "442" }, { "name": "Java", "bytes": "1964348" }, { "name": "JavaScript", "bytes": "1817078" }, { "name": "PHP", "bytes": "180152" }, { "name": "Perl", "bytes": "236747" }, { "name": "Perl6", "bytes": "11938" }, { "name": "Python", "bytes": "1301749" }, { "name": "Ruby", "bytes": "321339" }, { "name": "Scala", "bytes": "169585" } ], "symlink_target": "" }
<?php require_once dirname(__FILE__).'/accesscheck.php'; if (isset($_GET['delete'])) { # delete the index in delete $delete = sprintf('%d',$_GET['delete']); print $GLOBALS['I18N']->get('Deleting')." $delete ...\n"; $result = Sql_query("delete from ".$tables["template"]." where id = $delete"); $result = Sql_query("delete from ".$tables["templateimage"]." where template = $delete"); print "... ".$GLOBALS['I18N']->get('Done')."<br /><hr /><br />\n"; } if (isset($_POST['defaulttemplate'])) { saveConfig('defaultmessagetemplate',sprintf('%d',$_POST['defaulttemplate'])); } if (isset($_POST['systemtemplate'])) { saveConfig('systemmessagetemplate',sprintf('%d',$_POST['systemtemplate'])); } $req = Sql_Query("select * from {$tables["template"]} order by listorder"); if (!Sql_Affected_Rows()) print '<p class="information">'.$GLOBALS['I18N']->get("No template have been defined").'</p>'; $defaulttemplate = getConfig('defaultmessagetemplate'); $systemtemplate = getConfig('systemmessagetemplate'); print formStart('name="templates" class="templatesEdit" '); $ls = new WebblerListing($GLOBALS['I18N']->get("Existing templates")); while ($row = Sql_fetch_Array($req)) { $img_template = '<img src="images/no-image-template.png" />'; if(file_exists('templates/'.$row['id'].'.jpg')){ $img_template = '<img src="templates/'.$row['id'].'.jpg" />';} $element = $row['title']; $ls->addElement($element,PageUrl2('template&amp;id='.$row['id'])); $ls->setClass($element,'row1'); $ls->addColumn($element,$GLOBALS['I18N']->get('ID'),$row['id']); $ls->addRow($element,$img_template,'<span class="button">'.PageLinkDialogOnly("viewtemplate&amp;id=".$row["id"],$GLOBALS['img_view']).'</span>'.sprintf('<span class="delete"><a class="button" href="javascript:deleteRec(\'%s\');" title="'.$GLOBALS['I18N']->get('delete').'">%s</a>',PageUrl2("templates","","delete=".$row["id"]),$GLOBALS['I18N']->get('delete'))); # $imgcount = Sql_Fetch_Row_query(sprintf('select count(*) from %s where template = %d', # $GLOBALS['tables']['templateimage'],$row['id'])); # $ls->addColumn($element,$GLOBALS['I18N']->get('# imgs'),$imgcount[0]); # $ls->addColumn($element,$GLOBALS['I18N']->get('View'),); $ls->addColumn($element,$GLOBALS['I18N']->get('Campaign Default'),sprintf('<input type=radio name="defaulttemplate" value="%d" %s onchange="document.templates.submit();">', $row['id'],$row['id'] == $defaulttemplate ? 'checked':'')); $ls->addColumn($element,$GLOBALS['I18N']->get('System'),sprintf('<input type=radio name="systemtemplate" value="%d" %s onchange="document.templates.submit();">', $row['id'],$row['id'] == $systemtemplate ? 'checked':'')); } print $ls->display(); print '</form>'; print '<p class="button">'.PageLink2("template",$GLOBALS['I18N']->get('Add new Template'))."</p>"; $exists = Sql_Fetch_Row_Query(sprintf('select * from %s where title = "System Template"',$GLOBALS['tables']['template'])); if (empty($exists[0])) { print '<p class="button">'.PageLink2("defaultsystemtemplate",$GLOBALS['I18N']->get('Add default system template'))."</p>"; }
{ "content_hash": "ee909d98faaa420ef563d8d2900807cf", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 363, "avg_line_length": 57.236363636363635, "alnum_prop": 0.6308767471410419, "repo_name": "jeromio/motr", "id": "8ed817174eefdf01cac42320c1ca13e80c80a11f", "size": "3148", "binary": false, "copies": "13", "ref": "refs/heads/master", "path": "list/admin/templates.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "6368" }, { "name": "Assembly", "bytes": "1137778" }, { "name": "Batchfile", "bytes": "66" }, { "name": "C", "bytes": "128361" }, { "name": "C++", "bytes": "46792" }, { "name": "CSS", "bytes": "3191179" }, { "name": "ColdFusion", "bytes": "7942" }, { "name": "Groff", "bytes": "155107" }, { "name": "HTML", "bytes": "20588643" }, { "name": "JavaScript", "bytes": "6870285" }, { "name": "PHP", "bytes": "36508700" }, { "name": "PLpgSQL", "bytes": "17239" }, { "name": "Perl", "bytes": "5806" }, { "name": "Shell", "bytes": "9822" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Perfon.Interfaces.Notifications; namespace Perfon.Core.Notifications { /// <summary> /// Event arg for Notification events /// </summary> public class ThreshouldNotificationEventArg:EventArgs, IThreshouldNotificationEventArg { public string Message { get; private set; } public ThreshouldNotificationEventArg(string message) { Message = message; } } }
{ "content_hash": "bd643d83f011840fdc2ef59f9307cb52", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 90, "avg_line_length": 24.772727272727273, "alnum_prop": 0.6972477064220184, "repo_name": "magsoft2/Perfon.Net", "id": "491844e87e3789f14c7ea95b166e7ea4116a0824", "size": "547", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Perfon.Core/Notifications/ThreshouldNotificationEventArg.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "206" }, { "name": "Batchfile", "bytes": "562" }, { "name": "C#", "bytes": "127094" }, { "name": "CSS", "bytes": "704" }, { "name": "HTML", "bytes": "15737" } ], "symlink_target": "" }
#import "CDVAccelerometer.h" @interface CDVAccelerometer () { } @property (readwrite, assign) BOOL isRunning; @end @implementation CDVAccelerometer @synthesize callbackId, isRunning; // defaults to 10 msec #define kAccelerometerInterval 40 // g constant: -9.81 m/s^2 #define kGravitionalConstant -9.81 - (CDVAccelerometer*) init { self = [super init]; if (self) { x = 0; y = 0; z = 0; timestamp = 0; self.callbackId = nil; self.isRunning = NO; } return self; } - (void) dealloc { [self stop:nil withDict:nil]; [super dealloc]; // pretty important. } - (void)start:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options { NSString* cbId = [arguments objectAtIndex:0]; NSTimeInterval desiredFrequency_num = kAccelerometerInterval; UIAccelerometer* pAccel = [UIAccelerometer sharedAccelerometer]; // accelerometer expects fractional seconds, but we have msecs pAccel.updateInterval = desiredFrequency_num / 1000; self.callbackId = cbId; if(!self.isRunning) { pAccel.delegate = self; self.isRunning = YES; } } - (void)stop:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options { UIAccelerometer* theAccelerometer = [UIAccelerometer sharedAccelerometer]; theAccelerometer.delegate = nil; self.isRunning = NO; } /** * Picks up accel updates from device and stores them in this class */ - (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration { if(self.isRunning) { x = acceleration.x; y = acceleration.y; z = acceleration.z; timestamp = ([[NSDate date] timeIntervalSince1970] * 1000); [self returnAccelInfo]; } } - (void)returnAccelInfo { CDVPluginResult* result = nil; NSString* jsString = nil; // Create an acceleration object NSMutableDictionary *accelProps = [NSMutableDictionary dictionaryWithCapacity:4]; [accelProps setValue:[NSNumber numberWithDouble:x*kGravitionalConstant] forKey:@"x"]; [accelProps setValue:[NSNumber numberWithDouble:y*kGravitionalConstant] forKey:@"y"]; [accelProps setValue:[NSNumber numberWithDouble:z*kGravitionalConstant] forKey:@"z"]; [accelProps setValue:[NSNumber numberWithDouble:timestamp] forKey:@"timestamp"]; result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:accelProps]; [result setKeepCallback:[NSNumber numberWithBool:YES]]; jsString = [result toSuccessCallbackString:self.callbackId]; [self writeJavascript:jsString]; } // TODO: Consider using filtering to isolate instantaneous data vs. gravity data -jm /* #define kFilteringFactor 0.1 // Use a basic low-pass filter to keep only the gravity component of each axis. grav_accelX = (acceleration.x * kFilteringFactor) + ( grav_accelX * (1.0 - kFilteringFactor)); grav_accelY = (acceleration.y * kFilteringFactor) + ( grav_accelY * (1.0 - kFilteringFactor)); grav_accelZ = (acceleration.z * kFilteringFactor) + ( grav_accelZ * (1.0 - kFilteringFactor)); // Subtract the low-pass value from the current value to get a simplified high-pass filter instant_accelX = acceleration.x - ( (acceleration.x * kFilteringFactor) + (instant_accelX * (1.0 - kFilteringFactor)) ); instant_accelY = acceleration.y - ( (acceleration.y * kFilteringFactor) + (instant_accelY * (1.0 - kFilteringFactor)) ); instant_accelZ = acceleration.z - ( (acceleration.z * kFilteringFactor) + (instant_accelZ * (1.0 - kFilteringFactor)) ); */ @end
{ "content_hash": "a1553ce98e1d4cf37d4a369d6d860dd4", "timestamp": "", "source": "github", "line_count": 114, "max_line_length": 121, "avg_line_length": 31.228070175438596, "alnum_prop": 0.7087078651685393, "repo_name": "MoodKick/App", "id": "3843babe7e957919b716ac3e3de2981bd2dc3da0", "size": "4335", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "iOS/CordovaLib/Classes/CDVAccelerometer.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "107117" }, { "name": "CSS", "bytes": "82942" }, { "name": "CoffeeScript", "bytes": "1098" }, { "name": "Java", "bytes": "55606" }, { "name": "JavaScript", "bytes": "352062" }, { "name": "Objective-C", "bytes": "1179286" }, { "name": "Perl", "bytes": "890" }, { "name": "Python", "bytes": "526736" }, { "name": "Ruby", "bytes": "1059" }, { "name": "Shell", "bytes": "8835" } ], "symlink_target": "" }
<?php namespace ATWS\AutotaskObjects; class TicketSecondaryResource extends Entity { // Required public $ResourceID; public $RoleID; public $TicketID; }
{ "content_hash": "1de2bdf5186168939dd8dbaccd3fa420", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 44, "avg_line_length": 17, "alnum_prop": 0.7176470588235294, "repo_name": "opendns/autotask-php", "id": "1660fe3b236733b9c7cb4c4dabb752417fc0f87f", "size": "170", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/AutotaskObjects/TicketSecondaryResource.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PHP", "bytes": "92938" } ], "symlink_target": "" }
module Renalware module Transplants WAITLIST_FILTERS = %w( all active suspended active_and_suspended working_up status_mismatch ).freeze def self.table_name_prefix "transplant_" end def self.cast_patient(patient) ActiveType.cast(patient, ::Renalware::Transplants::Patient) end end end
{ "content_hash": "af7cadf8dc95d2700297ba2a6675e785", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 65, "avg_line_length": 18.15, "alnum_prop": 0.6336088154269972, "repo_name": "airslie/renalware-core", "id": "f3f8b5171f6a32cd73f2e5bc80b160633dc2bf2e", "size": "394", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "app/models/renalware/transplants.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9251" }, { "name": "Dockerfile", "bytes": "4123" }, { "name": "Gherkin", "bytes": "114740" }, { "name": "HTML", "bytes": "36757" }, { "name": "JavaScript", "bytes": "1330952" }, { "name": "PLpgSQL", "bytes": "790250" }, { "name": "Procfile", "bytes": "287" }, { "name": "Rich Text Format", "bytes": "629" }, { "name": "Ruby", "bytes": "4090100" }, { "name": "SCSS", "bytes": "145750" }, { "name": "Shell", "bytes": "11142" }, { "name": "Slim", "bytes": "758115" } ], "symlink_target": "" }