text
stringlengths
2
1.04M
meta
dict
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "d58a73dcee68ff703cc6c3f6afe18815", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "f35e2f57c6f8601c6d358db9f18fb19ed89a8731", "size": "208", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Liparis/Liparis elliptica/ Syn. Stichorkis elliptica/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
#define wxMOTIF_USE_RENDER_TABLE 1 #else #define wxMOTIF_USE_RENDER_TABLE 0 #endif #define wxMOTIF_NEW_FONT_HANDLING wxMOTIF_USE_RENDER_TABLE class wxXFont; // Font class WXDLLIMPEXP_CORE wxFont : public wxFontBase { public: // ctors and such wxFont() { } wxFont(const wxFontInfo& info) { Create(info.GetPointSize(), info.GetFamily(), info.GetStyle(), info.GetWeight(), info.IsUnderlined(), info.GetFaceName(), info.GetEncoding()); if ( info.IsUsingSizeInPixels() ) SetPixelSize(info.GetPixelSize()); } wxFont(const wxNativeFontInfo& info); wxFont(int size, wxFontFamily family, wxFontStyle style, wxFontWeight weight, bool underlined = false, const wxString& face = wxEmptyString, wxFontEncoding encoding = wxFONTENCODING_DEFAULT) { Create(size, family, style, weight, underlined, face, encoding); } wxFont(const wxSize& pixelSize, wxFontFamily family, wxFontStyle style, wxFontWeight weight, bool underlined = false, const wxString& face = wxEmptyString, wxFontEncoding encoding = wxFONTENCODING_DEFAULT) { Create(10, family, style, weight, underlined, face, encoding); SetPixelSize(pixelSize); } bool Create(int size, wxFontFamily family, wxFontStyle style, wxFontWeight weight, bool underlined = false, const wxString& face = wxEmptyString, wxFontEncoding encoding = wxFONTENCODING_DEFAULT); // wxMOTIF-specific bool Create(const wxString& fontname, wxFontEncoding fontenc = wxFONTENCODING_DEFAULT); bool Create(const wxNativeFontInfo& fontinfo); virtual ~wxFont(); // implement base class pure virtuals virtual int GetPointSize() const; virtual wxFontStyle GetStyle() const; virtual wxFontWeight GetWeight() const; virtual bool GetUnderlined() const; virtual wxString GetFaceName() const; virtual wxFontEncoding GetEncoding() const; virtual const wxNativeFontInfo *GetNativeFontInfo() const; virtual void SetPointSize(int pointSize); virtual void SetFamily(wxFontFamily family); virtual void SetStyle(wxFontStyle style); virtual void SetWeight(wxFontWeight weight); virtual bool SetFaceName(const wxString& faceName); virtual void SetUnderlined(bool underlined); virtual void SetEncoding(wxFontEncoding encoding); wxDECLARE_COMMON_FONT_METHODS(); wxDEPRECATED_MSG("use wxFONT{FAMILY,STYLE,WEIGHT}_XXX constants") wxFont(int size, int family, int style, int weight, bool underlined = false, const wxString& face = wxEmptyString, wxFontEncoding encoding = wxFONTENCODING_DEFAULT) { (void)Create(size, (wxFontFamily)family, (wxFontStyle)style, (wxFontWeight)weight, underlined, face, encoding); } // Implementation // Find an existing, or create a new, XFontStruct // based on this wxFont and the given scale. Append the // font to list in the private data for future reference. // TODO This is a fairly basic implementation, that doesn't // allow for different facenames, and also doesn't do a mapping // between 'standard' facenames (e.g. Arial, Helvetica, Times Roman etc.) // and the fonts that are available on a particular system. // Maybe we need to scan the user's machine to build up a profile // of the fonts and a mapping file. // Return font struct, and optionally the Motif font list wxXFont *GetInternalFont(double scale = 1.0, WXDisplay* display = NULL) const; // These two are helper functions for convenient access of the above. #if wxMOTIF_USE_RENDER_TABLE WXFontSet GetFontSet(double scale, WXDisplay* display = NULL) const; WXRenderTable GetRenderTable(WXDisplay* display) const; #else // if !wxMOTIF_USE_RENDER_TABLE WXFontStructPtr GetFontStruct(double scale = 1.0, WXDisplay* display = NULL) const; WXFontList GetFontList(double scale = 1.0, WXDisplay* display = NULL) const; #endif // !wxMOTIF_USE_RENDER_TABLE // returns either a XmFontList or XmRenderTable, depending // on Motif version WXFontType GetFontType(WXDisplay* display) const; // like the function above but does a copy for XmFontList WXFontType GetFontTypeC(WXDisplay* display) const; static WXString GetFontTag(); protected: virtual wxGDIRefData *CreateGDIRefData() const; virtual wxGDIRefData *CloneGDIRefData(const wxGDIRefData *data) const; virtual void DoSetNativeFontInfo( const wxNativeFontInfo& info ); virtual wxFontFamily DoGetFamily() const; void Unshare(); private: DECLARE_DYNAMIC_CLASS(wxFont) }; #endif // _WX_FONT_H_
{ "content_hash": "85ec287d3a82d8edb67c34589bad92bf", "timestamp": "", "source": "github", "line_count": 149, "max_line_length": 119, "avg_line_length": 33.53020134228188, "alnum_prop": 0.66693354683747, "repo_name": "nmehost/waxe-works", "id": "300cb485b4d2f2fddb2afa78701113d41cd1b79a", "size": "5428", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "include/wx/motif/font.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "5688434" }, { "name": "C++", "bytes": "7592265" }, { "name": "Nemerle", "bytes": "24326" }, { "name": "Objective-C", "bytes": "44008" } ], "symlink_target": "" }
require 'virtus' module Libis module Services module Rosetta class OaiSet # noinspection RubyResolve include Virtus.model nullify_blank: true attribute :description, String attribute :name, String attribute :spec, String def to_hash super.cleanup end end end end end
{ "content_hash": "bb73778bd7e57f5d1b43860112df45c6", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 48, "avg_line_length": 17.142857142857142, "alnum_prop": 0.6083333333333333, "repo_name": "Kris-LIBIS/LIBIS_Services", "id": "6e197b4ef544932e226e2ce2ce7ddbe63c07e3f3", "size": "360", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/libis/services/rosetta/oai_set.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "238258" } ], "symlink_target": "" }
package com.xinxin.firstcodeutil.model; /** * Created by xinxin on 2016/5/6. */ public class ZhuangbiImage { public String description; public String image_url; }
{ "content_hash": "2b735017cf636fb091abf39141d8846d", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 39, "avg_line_length": 19.333333333333332, "alnum_prop": 0.7126436781609196, "repo_name": "zhangxx0/FirstCodeUtil", "id": "826d5e6711764648848a87a2a8fa5db983f3d590", "size": "174", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/xinxin/firstcodeutil/model/ZhuangbiImage.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "128309" } ], "symlink_target": "" }
title: Wio Link Starter Kit category: Wio bzurl: https://seeedstudio.com/Wio-Link-Starter-Kit-p-2614.html oldwikiname: Wio_Link_Starter_Kit prodimagename: Wio_Link_Starter_Kit_product_view_1200_s.jpg bzprodimageurl: http://statics3.seeedstudio.com/images/product/110020051 1.jpg surveyurl: https://www.research.net/r/Wio_Link_Starter_Kit sku: 110020051 --- ![](https://raw.githubusercontent.com/SeeedDocument/Wio_Link_Starter_Kit/master/img/Wio_Link_Starter_Kit_product_view_1200_s.jpg) This kit is aimed at novices wanting to become a maker. The functional modules included in this kit are selected especially for a beginner which all are frequently required modules, and it is cost-effective. The most amazing part of this kit is the Wio Link development board which can be utilized for various devices: without a bit programming skill required. All the actions you want your modules performed and the flashing-code operation to Wio Link could be completed with taps in a mobile app. And you can send instructions to your devices over Internet at anywhere. So Wio Link will be a perfect utility to making things around smarter for everyone. Now let's enjoy being a maker. [![](https://raw.githubusercontent.com/SeeedDocument/common/master/Get_One_Now_Banner.png)](http://www.seeedstudio.com/depot/Wio-Link-Starter-Kit-p-2614.html) Features -------- - Include common frequently-used environment-monitoring functional modules - Grove port interfaced, more practical function and less work - Completely easy to make things around you smarter and add fun to daily life. - Cost-effective - Weight: 267 g Parts list ---------- | Parts name | Quantity | |----------------------------------------------------------------------------------------------------------------------|----------| | [Grove - Button](/Grove-Button) | 1PC | | [Grove - Relay](http://www.seeedstudio.com/depot/Grove-Relay-p-769.html) | 1PC | | [Grove - Temp&Humi Sensor](http://www.seeedstudio.com/depot/Grove-TempHumi-Sensor-p-745.html?cPath=25_125) | 1PC | | [Grove - Digital Light Sensor](http://www.seeedstudio.com/depot/Grove-Digital-Light-Sensor-p-1281.html?cPath=25_128) | 1PC | | Grove - WS2812 Waterproof LED Strip - 30 LEDs 1 meter | 1PC | | [Grove - 3-Axis Digital Accelerometer(±1.5g)](/Grove-3-Axis_Digital_Accelerometer-1.5g) | 1PC | | [Wio Link](/Wio_Link) | 1PC | | [Micro USB Cable - 48cm](http://www.seeedstudio.com/depot/Micro-USB-Cable-48cm-p-1475.html?cPath=98_100) | 1PC | A simple demo ------------- This demo can used as a compilation result-indicator. ### Preliminary Guide - [Travis CI](https://travis-ci.org/) - [Wio Link](/Wio_Link) ### Prerequisites - [Wio Link APP](https://www.kickstarter.com/projects/seeed/wio-link-3-steps-5-minutes-build-your-iot-applicat) - [Wio Link](/Wio_Link) - [Grove Relay](http://www.seeedstudio.com/depot/Grove-Relay-p-769.html?cPath=39_42) × 3 - A Travis CI Account - A GitHub Account - Traffic Light ### A detailed how-to Please go to [Recipe](http://www.seeedstudio.com/recipe/1068-traffic-light-indicates-travis-ci-compiled-results.html) for the detailed manual. <!-- This Markdown file was created from http://www.seeedstudio.com/wiki/Wio_Link_Starter_Kit -->
{ "content_hash": "7a6ded7427c772567f6c3857cce064c6", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 686, "avg_line_length": 58.82539682539682, "alnum_prop": 0.6219643820831084, "repo_name": "SeeedDoc/WikiMigrationSync", "id": "838322b5eb853638fef889472d51f2dadecbed43", "size": "3712", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docs/Wio_Link_Starter_Kit.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
'use strict'; describe("ngAnimate", function() { beforeEach(module('ngAnimate')); beforeEach(module('ngAnimateMock')); it("should disable animations on bootstrap for structural animations even after the first digest has passed", function() { var hasBeenAnimated = false; module(function($animateProvider) { $animateProvider.register('.my-structrual-animation', function() { return { enter : function(element, done) { hasBeenAnimated = true; done(); }, leave : function(element, done) { hasBeenAnimated = true; done(); } } }); }); inject(function($rootScope, $compile, $animate, $rootElement, $document) { var element = $compile('<div class="my-structrual-animation">...</div>')($rootScope); $rootElement.append(element); jqLite($document[0].body).append($rootElement); $animate.enter(element, $rootElement); $rootScope.$digest(); expect(hasBeenAnimated).toBe(false); $animate.leave(element); $rootScope.$digest(); expect(hasBeenAnimated).toBe(true); }); }); //we use another describe block because the before/after operations below //are used across all animations tests and we don't want that same behavior //to be used on the root describe block at the start of the animateSpec.js file describe('', function() { var ss, body; beforeEach(module(function() { body = jqLite(document.body); return function($window, $document, $animate, $timeout, $rootScope) { ss = createMockStyleSheet($document, $window); try { $timeout.flush(); } catch(e) {} $animate.enabled(true); $rootScope.$digest(); }; })); afterEach(function(){ if(ss) { ss.destroy(); } dealoc(body); }); describe("$animate", function() { var element, $rootElement; function html(html) { body.append($rootElement); $rootElement.html(html); element = $rootElement.children().eq(0); return element; } describe("enable / disable", function() { it("should work for all animations", inject(function($animate) { expect($animate.enabled()).toBe(true); expect($animate.enabled(0)).toBe(false); expect($animate.enabled()).toBe(false); expect($animate.enabled(1)).toBe(true); expect($animate.enabled()).toBe(true); })); it('should place a hard disable on all child animations', function() { var count = 0; module(function($animateProvider) { $animateProvider.register('.animated', function() { return { addClass : function(element, className, done) { count++; done(); } } }); }); inject(function($compile, $rootScope, $animate, $sniffer, $rootElement, $timeout) { $animate.enabled(true); var elm1 = $compile('<div class="animated"></div>')($rootScope); var elm2 = $compile('<div class="animated"></div>')($rootScope); $rootElement.append(elm1); angular.element(document.body).append($rootElement); $animate.addClass(elm1, 'klass'); expect(count).toBe(1); $animate.enabled(false); $animate.addClass(elm1, 'klass2'); expect(count).toBe(1); $animate.enabled(true); elm1.append(elm2); $animate.addClass(elm2, 'klass'); expect(count).toBe(2); $animate.enabled(false, elm1); $animate.addClass(elm2, 'klass2'); expect(count).toBe(2); var root = angular.element($rootElement[0]); $rootElement.addClass('animated'); $animate.addClass(root, 'klass2'); expect(count).toBe(3); }); }); it('should skip animations if the element is attached to the $rootElement', function() { var count = 0; module(function($animateProvider) { $animateProvider.register('.animated', function() { return { addClass : function(element, className, done) { count++; done(); } } }); }); inject(function($compile, $rootScope, $animate, $sniffer, $rootElement, $timeout) { $animate.enabled(true); var elm1 = $compile('<div class="animated"></div>')($rootScope); $animate.addClass(elm1, 'klass2'); expect(count).toBe(0); }); }); it('should check enable/disable animations up until the $rootElement element', function() { var rootElm = jqLite('<div></div>'); var captured = false; module(function($provide, $animateProvider) { $provide.value('$rootElement', rootElm); $animateProvider.register('.capture-animation', function() { return { addClass : function(element, className, done) { captured = true; done(); } } }); }); inject(function($animate, $rootElement, $rootScope, $compile, $timeout) { var initialState; angular.bootstrap(rootElm, ['ngAnimate']); $animate.enabled(true); var element = $compile('<div class="capture-animation"></div>')($rootScope); rootElm.append(element); expect(captured).toBe(false); $animate.addClass(element, 'red'); expect(captured).toBe(true); captured = false; $animate.enabled(false); $animate.addClass(element, 'blue'); expect(captured).toBe(false); //clean up the mess $animate.enabled(false, rootElm); dealoc(rootElm); }); }); }); describe("with polyfill", function() { var child, after; beforeEach(function() { module(function($animateProvider) { $animateProvider.register('.custom', function() { return { start: function(element, done) { done(); } } }); $animateProvider.register('.custom-delay', function($timeout) { function animate(element, done) { done = arguments.length == 3 ? arguments[2] : done; $timeout(done, 2000, false); return function() { element.addClass('animation-cancelled'); } } return { leave : animate, addClass : animate, removeClass : animate } }); $animateProvider.register('.custom-long-delay', function($timeout) { function animate(element, done) { done = arguments.length == 3 ? arguments[2] : done; $timeout(done, 20000, false); return function(cancelled) { element.addClass(cancelled ? 'animation-cancelled' : 'animation-ended'); } } return { leave : animate, addClass : animate, removeClass : animate } }); $animateProvider.register('.setup-memo', function() { return { removeClass: function(element, className, done) { element.text('memento'); done(); } } }); return function($animate, $compile, $rootScope, $rootElement) { element = $compile('<div></div>')($rootScope); forEach(['.ng-hide-add', '.ng-hide-remove', '.ng-enter', '.ng-leave', '.ng-move'], function(selector) { ss.addRule(selector, '-webkit-transition:1s linear all;' + 'transition:1s linear all;'); }); child = $compile('<div>...</div>')($rootScope); jqLite($document[0].body).append($rootElement); element.append(child); after = $compile('<div></div>')($rootScope); $rootElement.append(element); }; }); }) it("should animate the enter animation event", inject(function($animate, $rootScope, $sniffer, $timeout) { element[0].removeChild(child[0]); expect(element.contents().length).toBe(0); $animate.enter(child, element); $rootScope.$digest(); if($sniffer.transitions) { $animate.triggerReflow(); expect(child.hasClass('ng-enter')).toBe(true); expect(child.hasClass('ng-enter-active')).toBe(true); browserTrigger(element, 'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 1 }); } expect(element.contents().length).toBe(1); })); it("should animate the leave animation event", inject(function($animate, $rootScope, $sniffer, $timeout) { expect(element.contents().length).toBe(1); $animate.leave(child); $rootScope.$digest(); if($sniffer.transitions) { $animate.triggerReflow(); expect(child.hasClass('ng-leave')).toBe(true); expect(child.hasClass('ng-leave-active')).toBe(true); browserTrigger(child,'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 1 }); } expect(element.contents().length).toBe(0); })); it("should animate the move animation event", inject(function($animate, $compile, $rootScope, $timeout, $sniffer) { $rootScope.$digest(); element.empty(); var child1 = $compile('<div>1</div>')($rootScope); var child2 = $compile('<div>2</div>')($rootScope); element.append(child1); element.append(child2); expect(element.text()).toBe('12'); $animate.move(child1, element, child2); $rootScope.$digest(); if($sniffer.transitions) { $animate.triggerReflow(); } expect(element.text()).toBe('21'); })); it("should animate the show animation event", inject(function($animate, $rootScope, $sniffer, $timeout) { $rootScope.$digest(); child.addClass('ng-hide'); expect(child).toBeHidden(); $animate.removeClass(child, 'ng-hide'); if($sniffer.transitions) { $animate.triggerReflow(); expect(child.hasClass('ng-hide-remove')).toBe(true); expect(child.hasClass('ng-hide-remove-active')).toBe(true); browserTrigger(child,'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 1 }); } expect(child.hasClass('ng-hide-remove')).toBe(false); expect(child.hasClass('ng-hide-remove-active')).toBe(false); expect(child).toBeShown(); })); it("should animate the hide animation event", inject(function($animate, $rootScope, $sniffer, $timeout) { $rootScope.$digest(); expect(child).toBeShown(); $animate.addClass(child, 'ng-hide'); if($sniffer.transitions) { $animate.triggerReflow(); expect(child.hasClass('ng-hide-add')).toBe(true); expect(child.hasClass('ng-hide-add-active')).toBe(true); browserTrigger(child,'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 1 }); } expect(child).toBeHidden(); })); it("should assign the ng-event className to all animation events when transitions/keyframes are used", inject(function($animate, $sniffer, $rootScope, $timeout) { if (!$sniffer.transitions) return; $rootScope.$digest(); element[0].removeChild(child[0]); //enter $animate.enter(child, element); $rootScope.$digest(); $animate.triggerReflow(); expect(child.attr('class')).toContain('ng-enter'); expect(child.attr('class')).toContain('ng-enter-active'); browserTrigger(child,'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 1 }); $timeout.flush(); //move element.append(after); $animate.move(child, element, after); $rootScope.$digest(); $animate.triggerReflow(); expect(child.attr('class')).toContain('ng-move'); expect(child.attr('class')).toContain('ng-move-active'); browserTrigger(child,'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 1 }); $timeout.flush(); //hide $animate.addClass(child, 'ng-hide'); $animate.triggerReflow(); expect(child.attr('class')).toContain('ng-hide-add'); expect(child.attr('class')).toContain('ng-hide-add-active'); browserTrigger(child,'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 1 }); //show $animate.removeClass(child, 'ng-hide'); $animate.triggerReflow(); expect(child.attr('class')).toContain('ng-hide-remove'); expect(child.attr('class')).toContain('ng-hide-remove-active'); browserTrigger(child,'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 1 }); //leave $animate.leave(child); $rootScope.$digest(); $animate.triggerReflow(); expect(child.attr('class')).toContain('ng-leave'); expect(child.attr('class')).toContain('ng-leave-active'); browserTrigger(child,'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 1 }); })); it("should not run if animations are disabled", inject(function($animate, $rootScope, $timeout, $sniffer) { $animate.enabled(false); $rootScope.$digest(); element.addClass('setup-memo'); element.text('123'); expect(element.text()).toBe('123'); $animate.removeClass(element, 'ng-hide'); expect(element.text()).toBe('123'); $animate.enabled(true); element.addClass('ng-hide'); $animate.removeClass(element, 'ng-hide'); if($sniffer.transitions) { $animate.triggerReflow(); } expect(element.text()).toBe('memento'); })); it("should only call done() once and right away if another animation takes place in between", inject(function($animate, $rootScope, $sniffer, $timeout) { element.append(child); child.addClass('custom-delay'); expect(element).toBeShown(); $animate.addClass(child, 'ng-hide'); if($sniffer.transitions) { expect(child).toBeShown(); } $animate.leave(child); $rootScope.$digest(); if($sniffer.transitions) { $animate.triggerReflow(); } expect(child).toBeHidden(); //hides instantly //lets change this to prove that done doesn't fire anymore for the previous hide() operation child.css('display','block'); child.removeClass('ng-hide'); if($sniffer.transitions) { expect(element.children().length).toBe(1); //still animating browserTrigger(child,'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 1 }); } $timeout.flush(2000); $timeout.flush(2000); expect(child).toBeShown(); expect(element.children().length).toBe(0); })); it("should retain existing styles of the animated element", inject(function($animate, $rootScope, $sniffer, $timeout) { element.append(child); child.attr('style', 'width: 20px'); $animate.addClass(child, 'ng-hide'); $animate.leave(child); $rootScope.$digest(); if($sniffer.transitions) { $animate.triggerReflow(); //this is to verify that the existing style is appended with a semicolon automatically expect(child.attr('style')).toMatch(/width: 20px;.+?/i); browserTrigger(child,'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 1 }); } expect(child.attr('style')).toMatch(/width: 20px/i); })); it("should call the cancel callback when another animation is called on the same element", inject(function($animate, $rootScope, $sniffer, $timeout) { element.append(child); child.addClass('custom-delay ng-hide'); $animate.removeClass(child, 'ng-hide'); if($sniffer.transitions) { $animate.triggerReflow(); browserTrigger(child,'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 1 }); } $timeout.flush(2000); $animate.addClass(child, 'ng-hide'); expect(child.hasClass('animation-cancelled')).toBe(true); })); it("should skip a class-based animation if the same element already has an ongoing structural animation", inject(function($animate, $rootScope, $sniffer, $timeout) { var completed = false; $animate.enter(child, element, null, function() { completed = true; }); $rootScope.$digest(); expect(completed).toBe(false); $animate.addClass(child, 'green'); expect(element.hasClass('green')); expect(completed).toBe(false); if($sniffer.transitions) { $animate.triggerReflow(); browserTrigger(child,'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 1 }); } $timeout.flush(); expect(completed).toBe(true); })); it("should skip class-based animations if animations are directly disabled on the same element", function() { var capture; module(function($animateProvider) { $animateProvider.register('.capture', function() { return { addClass : function(element, className, done) { capture = true; done(); } }; }); }); inject(function($animate, $rootScope, $sniffer, $timeout) { $animate.enabled(true); $animate.enabled(false, element); $animate.addClass(element, 'capture'); expect(element.hasClass('capture')).toBe(true); expect(capture).not.toBe(true); }); }); it("should fire the cancel/end function with the correct flag in the parameters", inject(function($animate, $rootScope, $sniffer, $timeout) { element.append(child); $animate.addClass(child, 'custom-delay'); $animate.addClass(child, 'custom-long-delay'); expect(child.hasClass('animation-cancelled')).toBe(true); expect(child.hasClass('animation-ended')).toBe(false); $timeout.flush(); expect(child.hasClass('animation-ended')).toBe(true); })); it("should NOT clobber all data on an element when animation is finished", inject(function($animate) { child.css('display','none'); element.data('foo', 'bar'); $animate.removeClass(element, 'ng-hide'); $animate.addClass(element, 'ng-hide'); expect(element.data('foo')).toEqual('bar'); })); it("should allow multiple JS animations which run in parallel", inject(function($animate, $rootScope, $compile, $sniffer, $timeout) { $animate.addClass(element, 'custom-delay custom-long-delay'); $timeout.flush(2000); $timeout.flush(20000); expect(element.hasClass('custom-delay')).toBe(true); expect(element.hasClass('custom-long-delay')).toBe(true); })); it("should allow both multiple JS and CSS animations which run in parallel", inject(function($animate, $rootScope, $compile, $sniffer, $timeout, _$rootElement_) { $rootElement = _$rootElement_; ss.addRule('.ng-hide-add', '-webkit-transition:1s linear all;' + 'transition:1s linear all;'); ss.addRule('.ng-hide-remove', '-webkit-transition:1s linear all;' + 'transition:1s linear all;'); element = $compile(html('<div>1</div>'))($rootScope); element.addClass('custom-delay custom-long-delay'); $rootScope.$digest(); $animate.removeClass(element, 'ng-hide'); if($sniffer.transitions) { browserTrigger(element,'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 1 }); } $timeout.flush(2000); $timeout.flush(20000); expect(element.hasClass('custom-delay')).toBe(true); expect(element.hasClass('custom-delay-add')).toBe(false); expect(element.hasClass('custom-delay-add-active')).toBe(false); expect(element.hasClass('custom-long-delay')).toBe(true); expect(element.hasClass('custom-long-delay-add')).toBe(false); expect(element.hasClass('custom-long-delay-add-active')).toBe(false); })); }); describe("with CSS3", function() { beforeEach(function() { module(function() { return function(_$rootElement_) { $rootElement = _$rootElement_; }; }) }); describe("Animations", function() { it("should properly detect and make use of CSS Animations", inject(function($animate, $rootScope, $compile, $sniffer, $timeout) { ss.addRule('.ng-hide-add', '-webkit-animation: some_animation 4s linear 0s 1 alternate;' + 'animation: some_animation 4s linear 0s 1 alternate;'); ss.addRule('.ng-hide-remove', '-webkit-animation: some_animation 4s linear 0s 1 alternate;' + 'animation: some_animation 4s linear 0s 1 alternate;'); element = $compile(html('<div>1</div>'))($rootScope); element.addClass('ng-hide'); expect(element).toBeHidden(); $animate.removeClass(element, 'ng-hide'); if ($sniffer.animations) { $animate.triggerReflow(); browserTrigger(element,'animationend', { timeStamp: Date.now() + 4000, elapsedTime: 4 }); } expect(element).toBeShown(); })); it("should properly detect and make use of CSS Animations with multiple iterations", inject(function($animate, $rootScope, $compile, $sniffer, $timeout) { var style = '-webkit-animation-duration: 2s;' + '-webkit-animation-iteration-count: 3;' + 'animation-duration: 2s;' + 'animation-iteration-count: 3;'; ss.addRule('.ng-hide-add', style); ss.addRule('.ng-hide-remove', style); element = $compile(html('<div>1</div>'))($rootScope); element.addClass('ng-hide'); expect(element).toBeHidden(); $animate.removeClass(element, 'ng-hide'); if ($sniffer.animations) { $animate.triggerReflow(); browserTrigger(element,'animationend', { timeStamp: Date.now() + 6000, elapsedTime: 6 }); } expect(element).toBeShown(); })); it("should not consider the animation delay is provided", inject(function($animate, $rootScope, $compile, $sniffer, $timeout) { var style = '-webkit-animation-duration: 2s;' + '-webkit-animation-delay: 10s;' + '-webkit-animation-iteration-count: 5;' + 'animation-duration: 2s;' + 'animation-delay: 10s;' + 'animation-iteration-count: 5;'; ss.addRule('.ng-hide-add', style); ss.addRule('.ng-hide-remove', style); element = $compile(html('<div>1</div>'))($rootScope); element.addClass('ng-hide'); expect(element).toBeHidden(); $animate.removeClass(element, 'ng-hide'); if ($sniffer.transitions) { $animate.triggerReflow(); browserTrigger(element,'animationend', { timeStamp : Date.now() + 20000, elapsedTime: 10 }); } expect(element).toBeShown(); })); it("should skip animations if disabled and run when enabled", inject(function($animate, $rootScope, $compile, $sniffer, $timeout) { $animate.enabled(false); var style = '-webkit-animation: some_animation 2s linear 0s 1 alternate;' + 'animation: some_animation 2s linear 0s 1 alternate;'; ss.addRule('.ng-hide-add', style); ss.addRule('.ng-hide-remove', style); element = $compile(html('<div>1</div>'))($rootScope); element.addClass('ng-hide'); expect(element).toBeHidden(); $animate.removeClass(element, 'ng-hide'); expect(element).toBeShown(); })); it("should finish the previous animation when a new animation is started", inject(function($animate, $rootScope, $compile, $sniffer, $timeout) { var style = '-webkit-animation: some_animation 2s linear 0s 1 alternate;' + 'animation: some_animation 2s linear 0s 1 alternate;'; ss.addRule('.ng-hide-add', style); ss.addRule('.ng-hide-remove', style); element = $compile(html('<div class="ng-hide">1</div>'))($rootScope); element.addClass('custom'); $animate.removeClass(element, 'ng-hide'); if($sniffer.animations) { $animate.triggerReflow(); expect(element.hasClass('ng-hide-remove')).toBe(true); expect(element.hasClass('ng-hide-remove-active')).toBe(true); } element.removeClass('ng-hide'); $animate.addClass(element, 'ng-hide'); expect(element.hasClass('ng-hide-remove')).toBe(false); //added right away if($sniffer.animations) { //cleanup some pending animations $animate.triggerReflow(); expect(element.hasClass('ng-hide-add')).toBe(true); expect(element.hasClass('ng-hide-add-active')).toBe(true); browserTrigger(element,'animationend', { timeStamp: Date.now() + 2000, elapsedTime: 2 }); } expect(element.hasClass('ng-hide-remove-active')).toBe(false); })); it("should stagger the items when the correct CSS class is provided", inject(function($animate, $rootScope, $compile, $sniffer, $timeout, $document, $rootElement) { if(!$sniffer.animations) return; $animate.enabled(true); ss.addRule('.real-animation.ng-enter, .real-animation.ng-leave, .real-animation-fake.ng-enter, .real-animation-fake.ng-leave', '-webkit-animation:1s my_animation;' + 'animation:1s my_animation;'); ss.addRule('.real-animation.ng-enter-stagger, .real-animation.ng-leave-stagger', '-webkit-animation-delay:0.1s;' + '-webkit-animation-duration:0s;' + 'animation-delay:0.1s;' + 'animation-duration:0s;'); ss.addRule('.fake-animation.ng-enter-stagger, .fake-animation.ng-leave-stagger', '-webkit-animation-delay:0.1s;' + '-webkit-animation-duration:1s;' + 'animation-delay:0.1s;' + 'animation-duration:1s;'); var container = $compile(html('<div></div>'))($rootScope); var elements = []; for(var i = 0; i < 5; i++) { var newScope = $rootScope.$new(); var element = $compile('<div class="real-animation"></div>')(newScope); $animate.enter(element, container); elements.push(element); }; $rootScope.$digest(); $animate.triggerReflow(); expect(elements[0].attr('style')).toBeFalsy(); expect(elements[1].attr('style')).toMatch(/animation-delay: 0\.1\d*s/); expect(elements[2].attr('style')).toMatch(/animation-delay: 0\.2\d*s/); expect(elements[3].attr('style')).toMatch(/animation-delay: 0\.3\d*s/); expect(elements[4].attr('style')).toMatch(/animation-delay: 0\.4\d*s/); for(var i = 0; i < 5; i++) { dealoc(elements[i]); var newScope = $rootScope.$new(); var element = $compile('<div class="fake-animation"></div>')(newScope); $animate.enter(element, container); elements[i] = element; }; $rootScope.$digest(); var expectFailure = true; try { $animate.triggerReflow(); expectFailure = false; } catch(e) {} expect(expectFailure).toBe(true); expect(elements[0].attr('style')).toBeFalsy(); expect(elements[1].attr('style')).not.toMatch(/animation-delay: 0\.1\d*s/); expect(elements[2].attr('style')).not.toMatch(/animation-delay: 0\.2\d*s/); expect(elements[3].attr('style')).not.toMatch(/animation-delay: 0\.3\d*s/); expect(elements[4].attr('style')).not.toMatch(/animation-delay: 0\.4\d*s/); })); it("should stagger items when multiple animation durations/delays are defined", inject(function($animate, $rootScope, $compile, $sniffer, $timeout, $document, $rootElement) { if(!$sniffer.transitions) return; $animate.enabled(true); ss.addRule('.stagger-animation.ng-enter, .stagger-animation.ng-leave', '-webkit-animation:my_animation 1s 1s, your_animation 1s 2s;' + 'animation:my_animation 1s 1s, your_animation 1s 2s;'); ss.addRule('.stagger-animation.ng-enter-stagger, .stagger-animation.ng-leave-stagger', '-webkit-animation-delay:0.1s;' + 'animation-delay:0.1s;'); var container = $compile(html('<div></div>'))($rootScope); var elements = []; for(var i = 0; i < 4; i++) { var newScope = $rootScope.$new(); var element = $compile('<div class="stagger-animation"></div>')(newScope); $animate.enter(element, container); elements.push(element); }; $rootScope.$digest(); $animate.triggerReflow(); expect(elements[0].attr('style')).toBeFalsy(); expect(elements[1].attr('style')).toMatch(/animation-delay: 1\.1\d*s,\s*2\.1\d*s/); expect(elements[2].attr('style')).toMatch(/animation-delay: 1\.2\d*s,\s*2\.2\d*s/); expect(elements[3].attr('style')).toMatch(/animation-delay: 1\.3\d*s,\s*2\.3\d*s/); })); }); describe("Transitions", function() { it("should skip transitions if disabled and run when enabled", inject(function($animate, $rootScope, $compile, $sniffer, $timeout) { var style = '-webkit-transition: 1s linear all;' + 'transition: 1s linear all;'; ss.addRule('.ng-hide-add', style); ss.addRule('.ng-hide-remove', style); $animate.enabled(false); element = $compile(html('<div>1</div>'))($rootScope); element.addClass('ng-hide'); expect(element).toBeHidden(); $animate.removeClass(element, 'ng-hide'); expect(element).toBeShown(); $animate.enabled(true); element.addClass('ng-hide'); expect(element).toBeHidden(); $animate.removeClass(element, 'ng-hide'); if ($sniffer.transitions) { $animate.triggerReflow(); browserTrigger(element,'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 1 }); } expect(element).toBeShown(); })); it("should skip animations if disabled and run when enabled picking the longest specified duration", inject(function($animate, $rootScope, $compile, $sniffer, $timeout) { var style = '-webkit-transition-duration: 1s, 2000ms, 1s;' + '-webkit-transition-property: height, left, opacity;' + 'transition-duration: 1s, 2000ms, 1s;' + 'transition-property: height, left, opacity;'; ss.addRule('.ng-hide-add', style); ss.addRule('.ng-hide-remove', style); element = $compile(html('<div>foo</div>'))($rootScope); element.addClass('ng-hide'); $animate.removeClass(element, 'ng-hide'); if ($sniffer.transitions) { $animate.triggerReflow(); var now = Date.now(); browserTrigger(element,'transitionend', { timeStamp: now + 1000, elapsedTime: 1 }); browserTrigger(element,'transitionend', { timeStamp: now + 1000, elapsedTime: 1 }); browserTrigger(element,'transitionend', { timeStamp: now + 2000, elapsedTime: 2 }); expect(element.hasClass('ng-animate')).toBe(false); } expect(element).toBeShown(); })); it("should skip animations if disabled and run when enabled picking the longest specified duration/delay combination", inject(function($animate, $rootScope, $compile, $sniffer, $timeout) { $animate.enabled(false); var style = '-webkit-transition-duration: 1s, 0s, 1s; ' + '-webkit-transition-delay: 2s, 1000ms, 2s; ' + '-webkit-transition-property: height, left, opacity;' + 'transition-duration: 1s, 0s, 1s; ' + 'transition-delay: 2s, 1000ms, 2s; ' + 'transition-property: height, left, opacity;'; ss.addRule('.ng-hide-add', style); ss.addRule('.ng-hide-remove', style); element = $compile(html('<div>foo</div>'))($rootScope); element.addClass('ng-hide'); $animate.removeClass(element, 'ng-hide'); expect(element).toBeShown(); $animate.enabled(true); element.addClass('ng-hide'); expect(element).toBeHidden(); $animate.removeClass(element, 'ng-hide'); if ($sniffer.transitions) { $animate.triggerReflow(); var now = Date.now(); browserTrigger(element,'transitionend', { timeStamp: now + 1000, elapsedTime: 1 }); browserTrigger(element,'transitionend', { timeStamp: now + 3000, elapsedTime: 3 }); browserTrigger(element,'transitionend', { timeStamp: now + 3000, elapsedTime: 3 }); } expect(element).toBeShown(); })); it("should NOT overwrite styles with outdated values when animation completes", inject(function($animate, $rootScope, $compile, $sniffer, $timeout) { if(!$sniffer.transitions) return; var style = '-webkit-transition-duration: 1s, 2000ms, 1s;' + '-webkit-transition-property: height, left, opacity;' + 'transition-duration: 1s, 2000ms, 1s;' + 'transition-property: height, left, opacity;'; ss.addRule('.ng-hide-add', style); ss.addRule('.ng-hide-remove', style); element = $compile(html('<div style="width: 100px">foo</div>'))($rootScope); element.addClass('ng-hide'); $animate.removeClass(element, 'ng-hide'); $animate.triggerReflow(); var now = Date.now(); browserTrigger(element,'transitionend', { timeStamp: now + 1000, elapsedTime: 1 }); browserTrigger(element,'transitionend', { timeStamp: now + 1000, elapsedTime: 1 }); element.css('width', '200px'); browserTrigger(element,'transitionend', { timeStamp: now + 2000, elapsedTime: 2 }); expect(element.css('width')).toBe("200px"); })); it("should animate for the highest duration", inject(function($animate, $rootScope, $compile, $sniffer, $timeout) { var style = '-webkit-transition:1s linear all 2s;' + 'transition:1s linear all 2s;' + '-webkit-animation:my_ani 10s 1s;' + 'animation:my_ani 10s 1s;'; ss.addRule('.ng-hide-add', style); ss.addRule('.ng-hide-remove', style); element = $compile(html('<div>foo</div>'))($rootScope); element.addClass('ng-hide'); expect(element).toBeHidden(); $animate.removeClass(element, 'ng-hide'); if ($sniffer.transitions) { $animate.triggerReflow(); } expect(element).toBeShown(); if ($sniffer.transitions) { expect(element.hasClass('ng-hide-remove-active')).toBe(true); browserTrigger(element,'animationend', { timeStamp: Date.now() + 11000, elapsedTime: 11 }); expect(element.hasClass('ng-hide-remove-active')).toBe(false); } })); it("should finish the previous transition when a new animation is started", inject(function($animate, $rootScope, $compile, $sniffer, $timeout) { var style = '-webkit-transition: 1s linear all;' + 'transition: 1s linear all;'; ss.addRule('.ng-hide-add', style); ss.addRule('.ng-hide-remove', style); element = $compile(html('<div>1</div>'))($rootScope); element.addClass('ng-hide'); $animate.removeClass(element, 'ng-hide'); if($sniffer.transitions) { $animate.triggerReflow(); expect(element.hasClass('ng-hide-remove')).toBe(true); expect(element.hasClass('ng-hide-remove-active')).toBe(true); browserTrigger(element,'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 1 }); } expect(element.hasClass('ng-hide-remove')).toBe(false); expect(element.hasClass('ng-hide-remove-active')).toBe(false); expect(element).toBeShown(); $animate.addClass(element, 'ng-hide'); if($sniffer.transitions) { $animate.triggerReflow(); expect(element.hasClass('ng-hide-add')).toBe(true); expect(element.hasClass('ng-hide-add-active')).toBe(true); } })); it("should stagger the items when the correct CSS class is provided", inject(function($animate, $rootScope, $compile, $sniffer, $timeout, $document, $rootElement) { if(!$sniffer.transitions) return; $animate.enabled(true); ss.addRule('.real-animation.ng-enter, .real-animation.ng-leave, .real-animation-fake.ng-enter, .real-animation-fake.ng-leave', '-webkit-transition:1s linear all;' + 'transition:1s linear all;'); ss.addRule('.real-animation.ng-enter-stagger, .real-animation.ng-leave-stagger', '-webkit-transition-delay:0.1s;' + '-webkit-transition-duration:0s;' + 'transition-delay:0.1s;' + 'transition-duration:0s;'); ss.addRule('.fake-animation.ng-enter-stagger, .fake-animation.ng-leave-stagger', '-webkit-transition-delay:0.1s;' + '-webkit-transition-duration:1s;' + 'transition-delay:0.1s;' + 'transition-duration:1s;'); var container = $compile(html('<div></div>'))($rootScope); var elements = []; for(var i = 0; i < 5; i++) { var newScope = $rootScope.$new(); var element = $compile('<div class="real-animation"></div>')(newScope); $animate.enter(element, container); elements.push(element); }; $rootScope.$digest(); $animate.triggerReflow(); expect(elements[0].attr('style')).toBeFalsy(); expect(elements[1].attr('style')).toMatch(/transition-delay: 0\.1\d*s/); expect(elements[2].attr('style')).toMatch(/transition-delay: 0\.2\d*s/); expect(elements[3].attr('style')).toMatch(/transition-delay: 0\.3\d*s/); expect(elements[4].attr('style')).toMatch(/transition-delay: 0\.4\d*s/); for(var i = 0; i < 5; i++) { dealoc(elements[i]); var newScope = $rootScope.$new(); var element = $compile('<div class="fake-animation"></div>')(newScope); $animate.enter(element, container); elements[i] = element; }; $rootScope.$digest(); var expectFailure = true; try { $animate.triggerReflow(); expectFailure = false; } catch(e) {} expect(expectFailure).toBe(true); expect(elements[0].attr('style')).toBeFalsy(); expect(elements[1].attr('style')).not.toMatch(/transition-delay: 0\.1\d*s/); expect(elements[2].attr('style')).not.toMatch(/transition-delay: 0\.2\d*s/); expect(elements[3].attr('style')).not.toMatch(/transition-delay: 0\.3\d*s/); expect(elements[4].attr('style')).not.toMatch(/transition-delay: 0\.4\d*s/); })); it("should stagger items when multiple transition durations/delays are defined", inject(function($animate, $rootScope, $compile, $sniffer, $timeout, $document, $rootElement) { if(!$sniffer.transitions) return; $animate.enabled(true); ss.addRule('.stagger-animation.ng-enter, .ani.ng-leave', '-webkit-transition:1s linear color 2s, 3s linear font-size 4s;' + 'transition:1s linear color 2s, 3s linear font-size 4s;'); ss.addRule('.stagger-animation.ng-enter-stagger, .ani.ng-leave-stagger', '-webkit-transition-delay:0.1s;' + 'transition-delay:0.1s;'); var container = $compile(html('<div></div>'))($rootScope); var elements = []; for(var i = 0; i < 4; i++) { var newScope = $rootScope.$new(); var element = $compile('<div class="stagger-animation"></div>')(newScope); $animate.enter(element, container); elements.push(element); }; $rootScope.$digest(); $animate.triggerReflow(); expect(elements[0].attr('style')).toMatch(/transition-duration: 1\d*s,\s*3\d*s;/); expect(elements[0].attr('style')).not.toContain('transition-delay'); expect(elements[1].attr('style')).toMatch(/transition-delay: 2\.1\d*s,\s*4\.1\d*s/); expect(elements[2].attr('style')).toMatch(/transition-delay: 2\.2\d*s,\s*4\.2\d*s/); expect(elements[3].attr('style')).toMatch(/transition-delay: 2\.3\d*s,\s*4\.3\d*s/); })); it("should apply a closing timeout to close all pending transitions", inject(function($animate, $rootScope, $compile, $sniffer, $timeout) { if (!$sniffer.transitions) return; ss.addRule('.animated-element', '-webkit-transition:5s linear all;' + 'transition:5s linear all;'); element = $compile(html('<div class="animated-element">foo</div>'))($rootScope); $animate.addClass(element, 'some-class'); $animate.triggerReflow(); //reflow expect(element.hasClass('some-class-add-active')).toBe(true); $timeout.flush(7500); //closing timeout expect(element.hasClass('some-class-add-active')).toBe(false); })); it("apply a closing timeout with respect to a staggering animation", inject(function($animate, $rootScope, $compile, $sniffer, $timeout) { if (!$sniffer.transitions) return; ss.addRule('.entering-element.ng-enter', '-webkit-transition:5s linear all;' + 'transition:5s linear all;'); ss.addRule('.entering-element.ng-enter-stagger', '-webkit-transition-delay:0.5s;' + 'transition-delay:0.5s;'); element = $compile(html('<div></div>'))($rootScope); var kids = []; for(var i = 0; i < 5; i++) { kids.push(angular.element('<div class="entering-element"></div>')); $animate.enter(kids[i], element); } $rootScope.$digest(); $animate.triggerReflow(); //reflow expect(element.children().length).toBe(5); for(var i = 0; i < 5; i++) { expect(kids[i].hasClass('ng-enter-active')).toBe(true); } $timeout.flush(7500); for(var i = 0; i < 5; i++) { expect(kids[i].hasClass('ng-enter-active')).toBe(true); } //(stagger * index) + (duration + delay) * 150% $timeout.flush(9500); //0.5 * 4 + 5 * 1.5 = 9500; for(var i = 0; i < 5; i++) { expect(kids[i].hasClass('ng-enter-active')).toBe(false); } })); it("should not allow the closing animation to close off a successive animation midway", inject(function($animate, $rootScope, $compile, $sniffer, $timeout) { if (!$sniffer.transitions) return; ss.addRule('.some-class-add', '-webkit-transition:5s linear all;' + 'transition:5s linear all;'); ss.addRule('.some-class-remove', '-webkit-transition:10s linear all;' + 'transition:10s linear all;'); element = $compile(html('<div>foo</div>'))($rootScope); $animate.addClass(element, 'some-class'); $animate.triggerReflow(); //reflow expect(element.hasClass('some-class-add-active')).toBe(true); $animate.removeClass(element, 'some-class'); $animate.triggerReflow(); //second reflow $timeout.flush(7500); //closing timeout for the first animation expect(element.hasClass('some-class-remove-active')).toBe(true); $timeout.flush(15000); //closing timeout for the second animation expect(element.hasClass('some-class-remove-active')).toBe(false); $timeout.verifyNoPendingTasks(); })); }); it("should apply staggering to both transitions and keyframe animations when used within the same animation", inject(function($animate, $rootScope, $compile, $sniffer, $timeout, $document, $rootElement) { if(!$sniffer.transitions) return; $animate.enabled(true); ss.addRule('.stagger-animation.ng-enter, .stagger-animation.ng-leave', '-webkit-animation:my_animation 1s 1s, your_animation 1s 2s;' + 'animation:my_animation 1s 1s, your_animation 1s 2s;' + '-webkit-transition:1s linear all 1s;' + 'transition:1s linear all 1s;'); ss.addRule('.stagger-animation.ng-enter-stagger, .stagger-animation.ng-leave-stagger', '-webkit-transition-delay:0.1s;' + 'transition-delay:0.1s;' + '-webkit-animation-delay:0.2s;' + 'animation-delay:0.2s;'); var container = $compile(html('<div></div>'))($rootScope); var elements = []; for(var i = 0; i < 3; i++) { var newScope = $rootScope.$new(); var element = $compile('<div class="stagger-animation"></div>')(newScope); $animate.enter(element, container); elements.push(element); }; $rootScope.$digest(); $animate.triggerReflow(); expect(elements[0].attr('style')).toBeFalsy(); expect(elements[1].attr('style')).toMatch(/transition-delay:\s+1.1\d*/); expect(elements[1].attr('style')).toMatch(/animation-delay: 1\.2\d*s,\s*2\.2\d*s/); expect(elements[2].attr('style')).toMatch(/transition-delay:\s+1.2\d*/); expect(elements[2].attr('style')).toMatch(/animation-delay: 1\.4\d*s,\s*2\.4\d*s/); for(var i = 0; i < 3; i++) { browserTrigger(elements[i],'transitionend', { timeStamp: Date.now() + 22000, elapsedTime: 22000 }); expect(elements[i].attr('style')).toBeFalsy(); } })); }); describe('animation evaluation', function () { it('should re-evaluate the CSS classes for an animation each time', inject(function($animate, $rootScope, $sniffer, $rootElement, $timeout, $compile) { ss.addRule('.abc.ng-enter', '-webkit-transition:22s linear all;' + 'transition:22s linear all;'); ss.addRule('.xyz.ng-enter', '-webkit-transition:11s linear all;' + 'transition:11s linear all;'); var parent = $compile('<div><span ng-class="klass"></span></div>')($rootScope); var element = parent.find('span'); $rootElement.append(parent); angular.element(document.body).append($rootElement); $rootScope.klass = 'abc'; $animate.enter(element, parent); $rootScope.$digest(); if ($sniffer.transitions) { $animate.triggerReflow(); expect(element.hasClass('abc')).toBe(true); expect(element.hasClass('ng-enter')).toBe(true); expect(element.hasClass('ng-enter-active')).toBe(true); browserTrigger(element,'transitionend', { timeStamp: Date.now() + 22000, elapsedTime: 22 }); $timeout.flush(); } expect(element.hasClass('abc')).toBe(true); $rootScope.klass = 'xyz'; $animate.enter(element, parent); $rootScope.$digest(); if ($sniffer.transitions) { $animate.triggerReflow(); expect(element.hasClass('xyz')).toBe(true); expect(element.hasClass('ng-enter')).toBe(true); expect(element.hasClass('ng-enter-active')).toBe(true); browserTrigger(element,'transitionend', { timeStamp: Date.now() + 11000, elapsedTime: 11 }); $timeout.flush(); } expect(element.hasClass('xyz')).toBe(true); })); it('should only append active to the newly append CSS className values', inject(function($animate, $rootScope, $sniffer, $rootElement, $timeout) { ss.addRule('.ng-enter', '-webkit-transition:9s linear all;' + 'transition:9s linear all;'); var parent = jqLite('<div><span></span></div>'); var element = parent.find('span'); $rootElement.append(parent); angular.element(document.body).append($rootElement); element.attr('class','one two'); $animate.enter(element, parent); $rootScope.$digest(); if($sniffer.transitions) { $animate.triggerReflow(); expect(element.hasClass('one')).toBe(true); expect(element.hasClass('two')).toBe(true); expect(element.hasClass('ng-enter')).toBe(true); expect(element.hasClass('ng-enter-active')).toBe(true); expect(element.hasClass('one-active')).toBe(false); expect(element.hasClass('two-active')).toBe(false); browserTrigger(element,'transitionend', { timeStamp: Date.now() + 3000, elapsedTime: 3 }); } expect(element.hasClass('one')).toBe(true); expect(element.hasClass('two')).toBe(true); })); }); describe("Callbacks", function() { beforeEach(function() { module(function($animateProvider) { $animateProvider.register('.custom', function($timeout) { return { removeClass : function(element, className, done) { $timeout(done, 2000); } } }); $animateProvider.register('.other', function() { return { enter : function(element, done) { $timeout(done, 10000); } } }); }) }); it("should fire the enter callback", inject(function($animate, $rootScope, $compile, $sniffer, $rootElement, $timeout) { var parent = jqLite('<div><span></span></div>'); var element = parent.find('span'); $rootElement.append(parent); body.append($rootElement); var flag = false; $animate.enter(element, parent, null, function() { flag = true; }); $rootScope.$digest(); $timeout.flush(); expect(flag).toBe(true); })); it("should fire the leave callback", inject(function($animate, $rootScope, $compile, $sniffer, $rootElement, $timeout) { var parent = jqLite('<div><span></span></div>'); var element = parent.find('span'); $rootElement.append(parent); body.append($rootElement); var flag = false; $animate.leave(element, function() { flag = true; }); $rootScope.$digest(); $timeout.flush(); expect(flag).toBe(true); })); it("should fire the move callback", inject(function($animate, $rootScope, $compile, $sniffer, $rootElement, $timeout) { var parent = jqLite('<div><span></span></div>'); var parent2 = jqLite('<div id="nice"></div>'); var element = parent.find('span'); $rootElement.append(parent); body.append($rootElement); var flag = false; $animate.move(element, parent, parent2, function() { flag = true; }); $rootScope.$digest(); $timeout.flush(); expect(flag).toBe(true); expect(element.parent().id).toBe(parent2.id); })); it("should fire the addClass/removeClass callbacks", inject(function($animate, $rootScope, $compile, $sniffer, $rootElement, $timeout) { var parent = jqLite('<div><span></span></div>'); var element = parent.find('span'); $rootElement.append(parent); body.append($rootElement); var signature = ''; $animate.addClass(element, 'on', function() { signature += 'A'; }); $animate.removeClass(element, 'on', function() { signature += 'B'; }); $timeout.flush(); expect(signature).toBe('AB'); })); it('should fire DOM callbacks on the element being animated', inject(function($animate, $rootScope, $compile, $sniffer, $rootElement, $timeout) { if(!$sniffer.transitions) return; $animate.enabled(true); ss.addRule('.klass-add', '-webkit-transition:1s linear all;' + 'transition:1s linear all;'); var element = jqLite('<div></div>'); $rootElement.append(element); body.append($rootElement); var steps = []; element.on('$animate:before', function(e, data) { steps.push(['before', data.className, data.event]); }); element.on('$animate:after', function(e, data) { steps.push(['after', data.className, data.event]); }); element.on('$animate:close', function(e, data) { steps.push(['close', data.className, data.event]); }); $animate.addClass(element, 'klass', function() { steps.push(['done', 'klass', 'addClass']); }); $timeout.flush(1); expect(steps.pop()).toEqual(['before', 'klass', 'addClass']); $animate.triggerReflow(); $timeout.flush(1); expect(steps.pop()).toEqual(['after', 'klass', 'addClass']); browserTrigger(element,'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 1 }); $timeout.flush(1); expect(steps.shift()).toEqual(['close', 'klass', 'addClass']); expect(steps.shift()).toEqual(['done', 'klass', 'addClass']); })); it('should fire the DOM callbacks even if no animation is rendered', inject(function($animate, $rootScope, $compile, $sniffer, $rootElement, $timeout) { $animate.enabled(true); var parent = jqLite('<div></div>'); var element = jqLite('<div></div>'); $rootElement.append(parent); body.append($rootElement); var steps = []; element.on('$animate:before', function(e, data) { steps.push(['before', data.className, data.event]); }); element.on('$animate:after', function(e, data) { steps.push(['after', data.className, data.event]); }); $animate.enter(element, parent); $rootScope.$digest(); $timeout.flush(1); expect(steps.shift()).toEqual(['before', 'ng-enter', 'enter']); expect(steps.shift()).toEqual(['after', 'ng-enter', 'enter']); })); it("should fire a done callback when provided with no animation", inject(function($animate, $rootScope, $compile, $sniffer, $rootElement, $timeout) { var parent = jqLite('<div><span></span></div>'); var element = parent.find('span'); $rootElement.append(parent); body.append($rootElement); var flag = false; $animate.removeClass(element, 'ng-hide', function() { flag = true; }); $timeout.flush(); expect(flag).toBe(true); })); it("should fire a done callback when provided with a css animation/transition", inject(function($animate, $rootScope, $compile, $sniffer, $rootElement, $timeout) { ss.addRule('.ng-hide-add', '-webkit-transition:1s linear all;' + 'transition:1s linear all;'); ss.addRule('.ng-hide-remove', '-webkit-transition:1s linear all;' + 'transition:1s linear all;'); var parent = jqLite('<div><span></span></div>'); $rootElement.append(parent); body.append($rootElement); var element = parent.find('span'); var flag = false; $animate.removeClass(element, 'ng-hide', function() { flag = true; }); if($sniffer.transitions) { browserTrigger(element,'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 1 }); } $timeout.flush(); expect(flag).toBe(true); })); it("should fire a done callback when provided with a JS animation", inject(function($animate, $rootScope, $compile, $sniffer, $rootElement, $timeout) { var parent = jqLite('<div><span></span></div>'); $rootElement.append(parent); body.append($rootElement); var element = parent.find('span'); element.addClass('custom'); var flag = false; $animate.removeClass(element, 'ng-hide', function() { flag = true; }); $timeout.flush(); expect(flag).toBe(true); })); it("should fire the callback right away if another animation is called right after", inject(function($animate, $rootScope, $compile, $sniffer, $rootElement, $timeout) { ss.addRule('.ng-hide-add', '-webkit-transition:9s linear all;' + 'transition:9s linear all;'); ss.addRule('.ng-hide-remove', '-webkit-transition:9s linear all;' + 'transition:9s linear all;'); var parent = jqLite('<div><span></span></div>'); $rootElement.append(parent); body.append($rootElement); var element = parent.find('span'); var signature = ''; $animate.removeClass(element, 'ng-hide', function() { signature += 'A'; }); $animate.addClass(element, 'ng-hide', function() { signature += 'B'; }); $animate.addClass(element, 'ng-hide'); //earlier animation cancelled if($sniffer.transitions) { $animate.triggerReflow(); } $timeout.flush(); expect(signature).toBe('AB'); })); }); describe("addClass / removeClass", function() { var captured; beforeEach(function() { module(function($animateProvider, $provide) { $animateProvider.register('.klassy', function($timeout) { return { addClass : function(element, className, done) { captured = 'addClass-' + className; $timeout(done, 500, false); }, removeClass : function(element, className, done) { captured = 'removeClass-' + className; $timeout(done, 3000, false); } } }); }); }); it("should not perform an animation, and the followup DOM operation, if the class is " + "already present during addClass or not present during removeClass on the element", inject(function($animate, $rootScope, $sniffer, $rootElement, $timeout) { var element = jqLite('<div class="klassy"></div>'); $rootElement.append(element); body.append($rootElement); //skipped animations captured = 'none'; $animate.removeClass(element, 'some-class'); expect(element.hasClass('some-class')).toBe(false); expect(captured).toBe('none'); element.addClass('some-class'); captured = 'nothing'; $animate.addClass(element, 'some-class'); expect(captured).toBe('nothing'); expect(element.hasClass('some-class')).toBe(true); //actual animations captured = 'none'; $animate.removeClass(element, 'some-class'); $timeout.flush(); expect(element.hasClass('some-class')).toBe(false); expect(captured).toBe('removeClass-some-class'); captured = 'nothing'; $animate.addClass(element, 'some-class'); $timeout.flush(); expect(element.hasClass('some-class')).toBe(true); expect(captured).toBe('addClass-some-class'); })); it("should add and remove CSS classes after an animation even if no animation is present", inject(function($animate, $rootScope, $sniffer, $rootElement) { var parent = jqLite('<div><span></span></div>'); $rootElement.append(parent); body.append($rootElement); var element = jqLite(parent.find('span')); $animate.addClass(element,'klass'); expect(element.hasClass('klass')).toBe(true); $animate.removeClass(element,'klass'); expect(element.hasClass('klass')).toBe(false); expect(element.hasClass('klass-remove')).toBe(false); expect(element.hasClass('klass-remove-active')).toBe(false); })); it("should add and remove CSS classes with a callback", inject(function($animate, $rootScope, $sniffer, $rootElement, $timeout) { var parent = jqLite('<div><span></span></div>'); $rootElement.append(parent); body.append($rootElement); var element = jqLite(parent.find('span')); var signature = ''; $animate.addClass(element,'klass', function() { signature += 'A'; }); expect(element.hasClass('klass')).toBe(true); $animate.removeClass(element,'klass', function() { signature += 'B'; }); $timeout.flush(); expect(element.hasClass('klass')).toBe(false); expect(signature).toBe('AB'); })); it("should end the current addClass animation, add the CSS class and then run the removeClass animation", inject(function($animate, $rootScope, $sniffer, $rootElement, $timeout) { ss.addRule('.klass-add', '-webkit-transition:3s linear all;' + 'transition:3s linear all;'); ss.addRule('.klass-remove', '-webkit-transition:3s linear all;' + 'transition:3s linear all;'); var parent = jqLite('<div><span></span></div>'); $rootElement.append(parent); body.append($rootElement); var element = jqLite(parent.find('span')); var signature = ''; $animate.addClass(element,'klass', function() { signature += '1'; }); if($sniffer.transitions) { expect(element.hasClass('klass-add')).toBe(true); $animate.triggerReflow(); expect(element.hasClass('klass')).toBe(true); expect(element.hasClass('klass-add-active')).toBe(true); browserTrigger(element,'transitionend', { timeStamp: Date.now() + 3000, elapsedTime: 3 }); } $timeout.flush(); //this cancels out the older animation $animate.removeClass(element,'klass', function() { signature += '2'; }); if($sniffer.transitions) { expect(element.hasClass('klass-remove')).toBe(true); $animate.triggerReflow(); expect(element.hasClass('klass')).toBe(false); expect(element.hasClass('klass-add')).toBe(false); expect(element.hasClass('klass-add-active')).toBe(false); browserTrigger(element,'transitionend', { timeStamp: Date.now() + 3000, elapsedTime: 3 }); } $timeout.flush(); expect(element.hasClass('klass')).toBe(false); expect(signature).toBe('12'); })); it("should properly execute JS animations and use callbacks when using addClass / removeClass", inject(function($animate, $rootScope, $sniffer, $rootElement, $timeout) { var parent = jqLite('<div><span></span></div>'); $rootElement.append(parent); body.append($rootElement); var element = jqLite(parent.find('span')); var signature = ''; $animate.addClass(element,'klassy', function() { signature += 'X'; }); $timeout.flush(500); expect(element.hasClass('klassy')).toBe(true); $animate.removeClass(element,'klassy', function() { signature += 'Y'; }); $timeout.flush(3000); expect(element.hasClass('klassy')).toBe(false); expect(signature).toBe('XY'); })); it("should properly execute CSS animations/transitions and use callbacks when using addClass / removeClass", inject(function($animate, $rootScope, $sniffer, $rootElement, $timeout) { ss.addRule('.klass-add', '-webkit-transition:11s linear all;' + 'transition:11s linear all;'); ss.addRule('.klass-remove', '-webkit-transition:11s linear all;' + 'transition:11s linear all;'); var parent = jqLite('<div><span></span></div>'); $rootElement.append(parent); body.append($rootElement); var element = jqLite(parent.find('span')); var signature = ''; $animate.addClass(element,'klass', function() { signature += 'd'; }); if($sniffer.transitions) { $animate.triggerReflow(); expect(element.hasClass('klass-add')).toBe(true); expect(element.hasClass('klass-add-active')).toBe(true); browserTrigger(element,'transitionend', { timeStamp: Date.now() + 11000, elapsedTime: 11 }); expect(element.hasClass('klass-add')).toBe(false); expect(element.hasClass('klass-add-active')).toBe(false); } $timeout.flush(); expect(element.hasClass('klass')).toBe(true); $animate.removeClass(element,'klass', function() { signature += 'b'; }); if($sniffer.transitions) { $animate.triggerReflow(); expect(element.hasClass('klass-remove')).toBe(true); expect(element.hasClass('klass-remove-active')).toBe(true); browserTrigger(element,'transitionend', { timeStamp: Date.now() + 11000, elapsedTime: 11 }); expect(element.hasClass('klass-remove')).toBe(false); expect(element.hasClass('klass-remove-active')).toBe(false); } $timeout.flush(); expect(element.hasClass('klass')).toBe(false); expect(signature).toBe('db'); })); it("should allow for multiple css classes to be animated plus a callback when added", inject(function($animate, $rootScope, $sniffer, $rootElement, $timeout) { ss.addRule('.one-add', '-webkit-transition:7s linear all;' + 'transition:7s linear all;'); ss.addRule('.two-add', '-webkit-transition:7s linear all;' + 'transition:7s linear all;'); var parent = jqLite('<div><span></span></div>'); $rootElement.append(parent); body.append($rootElement); var element = jqLite(parent.find('span')); var flag = false; $animate.addClass(element,'one two', function() { flag = true; }); if($sniffer.transitions) { $animate.triggerReflow(); expect(element.hasClass('one-add')).toBe(true); expect(element.hasClass('two-add')).toBe(true); expect(element.hasClass('one-add-active')).toBe(true); expect(element.hasClass('two-add-active')).toBe(true); browserTrigger(element,'transitionend', { timeStamp: Date.now() + 7000, elapsedTime: 7 }); expect(element.hasClass('one-add')).toBe(false); expect(element.hasClass('one-add-active')).toBe(false); expect(element.hasClass('two-add')).toBe(false); expect(element.hasClass('two-add-active')).toBe(false); } $timeout.flush(); expect(element.hasClass('one')).toBe(true); expect(element.hasClass('two')).toBe(true); expect(flag).toBe(true); })); it("should allow for multiple css classes to be animated plus a callback when removed", inject(function($animate, $rootScope, $sniffer, $rootElement, $timeout) { ss.addRule('.one-remove', '-webkit-transition:9s linear all;' + 'transition:9s linear all;'); ss.addRule('.two-remove', '-webkit-transition:9s linear all;' + 'transition:9s linear all;'); var parent = jqLite('<div><span></span></div>'); $rootElement.append(parent); body.append($rootElement); var element = jqLite(parent.find('span')); element.addClass('one two'); expect(element.hasClass('one')).toBe(true); expect(element.hasClass('two')).toBe(true); var flag = false; $animate.removeClass(element,'one two', function() { flag = true; }); if($sniffer.transitions) { $animate.triggerReflow(); expect(element.hasClass('one-remove')).toBe(true); expect(element.hasClass('two-remove')).toBe(true); expect(element.hasClass('one-remove-active')).toBe(true); expect(element.hasClass('two-remove-active')).toBe(true); browserTrigger(element,'transitionend', { timeStamp: Date.now() + 9000, elapsedTime: 9 }); expect(element.hasClass('one-remove')).toBe(false); expect(element.hasClass('one-remove-active')).toBe(false); expect(element.hasClass('two-remove')).toBe(false); expect(element.hasClass('two-remove-active')).toBe(false); } $timeout.flush(); expect(element.hasClass('one')).toBe(false); expect(element.hasClass('two')).toBe(false); expect(flag).toBe(true); })); }); }); var $rootElement, $document; beforeEach(module(function() { return function(_$rootElement_, _$document_, $animate) { $rootElement = _$rootElement_; $document = _$document_; $animate.enabled(true); } })); function html(element) { var body = jqLite($document[0].body); $rootElement.append(element); body.append($rootElement); return element; } it("should properly animate and parse CSS3 transitions", inject(function($compile, $rootScope, $animate, $sniffer, $timeout) { ss.addRule('.ng-enter', '-webkit-transition:1s linear all;' + 'transition:1s linear all;'); var element = html($compile('<div>...</div>')($rootScope)); var child = $compile('<div>...</div>')($rootScope); $animate.enter(child, element); $rootScope.$digest(); if($sniffer.transitions) { $animate.triggerReflow(); expect(child.hasClass('ng-enter')).toBe(true); expect(child.hasClass('ng-enter-active')).toBe(true); browserTrigger(child,'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 1 }); } expect(child.hasClass('ng-enter')).toBe(false); expect(child.hasClass('ng-enter-active')).toBe(false); })); it("should properly animate and parse CSS3 animations", inject(function($compile, $rootScope, $animate, $sniffer, $timeout) { ss.addRule('.ng-enter', '-webkit-animation: some_animation 4s linear 1s 2 alternate;' + 'animation: some_animation 4s linear 1s 2 alternate;'); var element = html($compile('<div>...</div>')($rootScope)); var child = $compile('<div>...</div>')($rootScope); $animate.enter(child, element); $rootScope.$digest(); if($sniffer.transitions) { $animate.triggerReflow(); expect(child.hasClass('ng-enter')).toBe(true); expect(child.hasClass('ng-enter-active')).toBe(true); browserTrigger(child,'transitionend', { timeStamp: Date.now() + 9000, elapsedTime: 9 }); } expect(child.hasClass('ng-enter')).toBe(false); expect(child.hasClass('ng-enter-active')).toBe(false); })); it("should skip animations if the browser does not support CSS3 transitions and CSS3 animations", inject(function($compile, $rootScope, $animate, $sniffer) { $sniffer.animations = false; $sniffer.transitions = false; ss.addRule('.ng-enter', '-webkit-animation: some_animation 4s linear 1s 2 alternate;' + 'animation: some_animation 4s linear 1s 2 alternate;'); var element = html($compile('<div>...</div>')($rootScope)); var child = $compile('<div>...</div>')($rootScope); expect(child.hasClass('ng-enter')).toBe(false); $animate.enter(child, element); $rootScope.$digest(); expect(child.hasClass('ng-enter')).toBe(false); })); it("should run other defined animations inline with CSS3 animations", function() { module(function($animateProvider) { $animateProvider.register('.custom', function($timeout) { return { enter : function(element, done) { element.addClass('i-was-animated'); $timeout(done, 10, false); } } }); }) inject(function($compile, $rootScope, $animate, $sniffer, $timeout) { ss.addRule('.ng-enter', '-webkit-transition: 1s linear all;' + 'transition: 1s linear all;'); var element = html($compile('<div>...</div>')($rootScope)); var child = $compile('<div>...</div>')($rootScope); expect(child.hasClass('i-was-animated')).toBe(false); child.addClass('custom'); $animate.enter(child, element); $rootScope.$digest(); if($sniffer.transitions) { $animate.triggerReflow(); browserTrigger(child,'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 1 }); } expect(child.hasClass('i-was-animated')).toBe(true); }); }); it("should properly cancel CSS transitions or animations if another animation is fired", function() { module(function($animateProvider) { $animateProvider.register('.usurper', function($timeout) { return { leave : function(element, done) { element.addClass('this-is-mine-now'); $timeout(done, 55, false); } } }); }); inject(function($compile, $rootScope, $animate, $sniffer, $timeout) { ss.addRule('.ng-enter', '-webkit-transition: 2s linear all;' + 'transition: 2s linear all;'); ss.addRule('.ng-leave', '-webkit-transition: 2s linear all;' + 'transition: 2s linear all;'); var element = html($compile('<div>...</div>')($rootScope)); var child = $compile('<div>...</div>')($rootScope); $animate.enter(child, element); $rootScope.$digest(); //this is added/removed right away otherwise if($sniffer.transitions) { $animate.triggerReflow(); expect(child.hasClass('ng-enter')).toBe(true); expect(child.hasClass('ng-enter-active')).toBe(true); } expect(child.hasClass('this-is-mine-now')).toBe(false); child.addClass('usurper'); $animate.leave(child); $rootScope.$digest(); $timeout.flush(); expect(child.hasClass('ng-enter')).toBe(false); expect(child.hasClass('ng-enter-active')).toBe(false); expect(child.hasClass('usurper')).toBe(true); expect(child.hasClass('this-is-mine-now')).toBe(true); $timeout.flush(55); }); }); it("should not perform the active class animation if the animation has been cancelled before the reflow occurs", function() { inject(function($compile, $rootScope, $animate, $sniffer, $timeout) { if(!$sniffer.transitions) return; ss.addRule('.animated.ng-enter', '-webkit-transition: 2s linear all;' + 'transition: 2s linear all;'); var element = html($compile('<div>...</div>')($rootScope)); var child = $compile('<div class="animated">...</div>')($rootScope); $animate.enter(child, element); $rootScope.$digest(); expect(child.hasClass('ng-enter')).toBe(true); $animate.leave(child); $rootScope.$digest(); $animate.triggerReflow(); expect(child.hasClass('ng-enter-active')).toBe(false); }); }); // // it("should add and remove CSS classes and perform CSS animations during the process", // inject(function($compile, $rootScope, $animate, $sniffer, $timeout) { // // ss.addRule('.on-add', '-webkit-transition: 10s linear all; ' + // 'transition: 10s linear all;'); // ss.addRule('.on-remove', '-webkit-transition: 10s linear all; ' + // 'transition: 10s linear all;'); // // var element = html($compile('<div></div>')($rootScope)); // // expect(element.hasClass('on')).toBe(false); // // $animate.addClass(element, 'on'); // // if($sniffer.transitions) { // expect(element.hasClass('on')).toBe(false); // expect(element.hasClass('on-add')).toBe(true); // $timeout.flush(); // } // // $timeout.flush(); // // expect(element.hasClass('on')).toBe(true); // expect(element.hasClass('on-add')).toBe(false); // expect(element.hasClass('on-add-active')).toBe(false); // // $animate.removeClass(element, 'on'); // if($sniffer.transitions) { // expect(element.hasClass('on')).toBe(true); // expect(element.hasClass('on-remove')).toBe(true); // $timeout.flush(10000); // } // // $timeout.flush(); // expect(element.hasClass('on')).toBe(false); // expect(element.hasClass('on-remove')).toBe(false); // expect(element.hasClass('on-remove-active')).toBe(false); // })); // // // it("should show and hide elements with CSS & JS animations being performed in the process", function() { // module(function($animateProvider) { // $animateProvider.register('.displayer', function($timeout) { // return { // removeClass : function(element, className, done) { // element.removeClass('hiding'); // element.addClass('showing'); // $timeout(done, 25, false); // }, // addClass : function(element, className, done) { // element.removeClass('showing'); // element.addClass('hiding'); // $timeout(done, 555, false); // } // } // }); // }) // inject(function($compile, $rootScope, $animate, $sniffer, $timeout) { // // ss.addRule('.ng-hide-add', '-webkit-transition: 5s linear all;' + // 'transition: 5s linear all;'); // ss.addRule('.ng-hide-remove', '-webkit-transition: 5s linear all;' + // 'transition: 5s linear all;'); // // var element = html($compile('<div></div>')($rootScope)); // // element.addClass('displayer'); // // expect(element).toBeShown(); // expect(element.hasClass('showing')).toBe(false); // expect(element.hasClass('hiding')).toBe(false); // // $animate.addClass(element, 'ng-hide'); // // if($sniffer.transitions) { // expect(element).toBeShown(); //still showing // $timeout.flush(); // expect(element).toBeShown(); // $timeout.flush(5555); // } // $timeout.flush(); // expect(element).toBeHidden(); // // expect(element.hasClass('showing')).toBe(false); // expect(element.hasClass('hiding')).toBe(true); // $animate.removeClass(element, 'ng-hide'); // // if($sniffer.transitions) { // expect(element).toBeHidden(); // $timeout.flush(); // expect(element).toBeHidden(); // $timeout.flush(5580); // } // $timeout.flush(); // expect(element).toBeShown(); // // expect(element.hasClass('showing')).toBe(true); // expect(element.hasClass('hiding')).toBe(false); // }); // }); it("should remove all the previous classes when the next animation is applied before a reflow", function() { var fn, interceptedClass; module(function($animateProvider) { $animateProvider.register('.three', function() { return { move : function(element, done) { fn = function() { done(); } return function() { interceptedClass = element.attr('class'); } } } }); }); inject(function($compile, $rootScope, $animate, $timeout) { var parent = html($compile('<div class="parent"></div>')($rootScope)); var one = $compile('<div class="one"></div>')($rootScope); var two = $compile('<div class="two"></div>')($rootScope); var three = $compile('<div class="three klass"></div>')($rootScope); parent.append(one); parent.append(two); parent.append(three); $animate.move(three, null, two); $rootScope.$digest(); $animate.move(three, null, one); $rootScope.$digest(); //this means that the former animation was cleaned up before the new one starts expect(interceptedClass.indexOf('ng-animate') >= 0).toBe(false); }); }); it("should provide the correct CSS class to the addClass and removeClass callbacks within a JS animation", function() { module(function($animateProvider) { $animateProvider.register('.classify', function() { return { removeClass : function(element, className, done) { element.data('classify','remove-' + className); done(); }, addClass : function(element, className, done) { element.data('classify','add-' + className); done(); } } }); }) inject(function($compile, $rootScope, $animate) { var element = html($compile('<div class="classify"></div>')($rootScope)); $animate.addClass(element, 'super'); expect(element.data('classify')).toBe('add-super'); $animate.removeClass(element, 'super'); expect(element.data('classify')).toBe('remove-super'); $animate.addClass(element, 'superguy'); expect(element.data('classify')).toBe('add-superguy'); }); }); it("should not skip ngAnimate animations when any pre-existing CSS transitions are present on the element", function() { inject(function($compile, $rootScope, $animate, $timeout, $sniffer) { if(!$sniffer.transitions) return; var element = html($compile('<div class="animated parent"></div>')($rootScope)); var child = html($compile('<div class="animated child"></div>')($rootScope)); ss.addRule('.animated', '-webkit-transition:1s linear all;' + 'transition:1s linear all;'); ss.addRule('.super-add', '-webkit-transition:2s linear all;' + 'transition:2s linear all;'); $rootElement.append(element); jqLite(document.body).append($rootElement); $animate.addClass(element, 'super'); var empty = true; try { $animate.triggerReflow(); empty = false; } catch(e) {} expect(empty).toBe(false); }); }); it("should wait until both the duration and delay are complete to close off the animation", inject(function($compile, $rootScope, $animate, $timeout, $sniffer) { if(!$sniffer.transitions) return; var element = html($compile('<div class="animated parent"></div>')($rootScope)); var child = html($compile('<div class="animated child"></div>')($rootScope)); ss.addRule('.animated.ng-enter', '-webkit-transition: width 1s, background 1s 1s;' + 'transition: width 1s, background 1s 1s;'); $rootElement.append(element); jqLite(document.body).append($rootElement); $animate.enter(child, element); $rootScope.$digest(); $animate.triggerReflow(); expect(child.hasClass('ng-enter')).toBe(true); expect(child.hasClass('ng-enter-active')).toBe(true); browserTrigger(child, 'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 0 }); expect(child.hasClass('ng-enter')).toBe(true); expect(child.hasClass('ng-enter-active')).toBe(true); browserTrigger(child, 'transitionend', { timeStamp: Date.now() + 2000, elapsedTime: 2 }); expect(child.hasClass('ng-enter')).toBe(false); expect(child.hasClass('ng-enter-active')).toBe(false); expect(element.contents().length).toBe(1); })); it("should cancel all child animations when a leave or move animation is triggered on a parent element", function() { var step, animationState; module(function($animateProvider) { $animateProvider.register('.animan', function($timeout) { return { enter : function(element, done) { animationState = 'enter'; step = done; return function(cancelled) { animationState = cancelled ? 'enter-cancel' : animationState; } }, addClass : function(element, className, done) { animationState = 'addClass'; step = done; return function(cancelled) { animationState = cancelled ? 'addClass-cancel' : animationState; } } }; }); }); inject(function($animate, $compile, $rootScope, $timeout, $sniffer) { var element = html($compile('<div class="parent"></div>')($rootScope)); var container = html($compile('<div class="container"></div>')($rootScope)); var child = html($compile('<div class="animan child"></div>')($rootScope)); ss.addRule('.animan.ng-enter, .animan.something-add', '-webkit-transition: width 1s, background 1s 1s;' + 'transition: width 1s, background 1s 1s;'); $rootElement.append(element); jqLite(document.body).append($rootElement); $animate.enter(child, element); $rootScope.$digest(); expect(animationState).toBe('enter'); if($sniffer.transitions) { expect(child.hasClass('ng-enter')).toBe(true); $animate.triggerReflow(); expect(child.hasClass('ng-enter-active')).toBe(true); } $animate.move(element, container); if($sniffer.transitions) { expect(child.hasClass('ng-enter')).toBe(false); expect(child.hasClass('ng-enter-active')).toBe(false); } expect(animationState).toBe('enter-cancel'); $rootScope.$digest(); $timeout.flush(); $animate.addClass(child, 'something'); if($sniffer.transitions) { $animate.triggerReflow(); } expect(animationState).toBe('addClass'); if($sniffer.transitions) { expect(child.hasClass('something-add')).toBe(true); expect(child.hasClass('something-add-active')).toBe(true); } $animate.leave(container); expect(animationState).toBe('addClass-cancel'); if($sniffer.transitions) { expect(child.hasClass('something-add')).toBe(false); expect(child.hasClass('something-add-active')).toBe(false); } }); }); it("should wait until a queue of animations are complete before performing a reflow", inject(function($rootScope, $compile, $timeout, $sniffer, $animate) { if(!$sniffer.transitions) return; $rootScope.items = [1,2,3,4,5]; var element = html($compile('<div><div class="animated" ng-repeat="item in items"></div></div>')($rootScope)); ss.addRule('.animated.ng-enter', '-webkit-transition: width 1s, background 1s 1s;' + 'transition: width 1s, background 1s 1s;'); $rootScope.$digest(); expect(element[0].querySelectorAll('.ng-enter-active').length).toBe(0); $animate.triggerReflow(); expect(element[0].querySelectorAll('.ng-enter-active').length).toBe(5); forEach(element.children(), function(kid) { browserTrigger(kid, 'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 1 }); }); expect(element[0].querySelectorAll('.ng-enter-active').length).toBe(0); })); it("should work to disable all child animations for an element", function() { var childAnimated = false, containerAnimated = false; module(function($animateProvider) { $animateProvider.register('.child', function() { return { addClass : function(element, className, done) { childAnimated = true; done(); } } }); $animateProvider.register('.container', function() { return { leave : function(element, done) { containerAnimated = true; done(); } } }); }); inject(function($compile, $rootScope, $animate, $timeout, $rootElement) { $animate.enabled(true); var element = $compile('<div class="container"></div>')($rootScope); jqLite($document[0].body).append($rootElement); $rootElement.append(element); var child = $compile('<div class="child"></div>')($rootScope); element.append(child); $animate.enabled(true, element); $animate.addClass(child, 'awesome'); expect(childAnimated).toBe(true); childAnimated = false; $animate.enabled(false, element); $animate.addClass(child, 'super'); expect(childAnimated).toBe(false); $animate.leave(element); $rootScope.$digest(); expect(containerAnimated).toBe(true); }); }); it("should disable all child animations on structural animations until the post animation timeout has passed", function() { var intercepted; module(function($animateProvider) { $animateProvider.register('.animated', function() { return { enter : ani('enter'), leave : ani('leave'), move : ani('move'), addClass : ani('addClass'), removeClass : ani('removeClass') }; function ani(type) { return function(element, className, done) { intercepted = type; (done || className)(); } } }); }); inject(function($animate, $rootScope, $sniffer, $timeout, $compile, _$rootElement_) { $rootElement = _$rootElement_; $animate.enabled(true); $rootScope.$digest(); var element = $compile('<div class="element animated">...</div>')($rootScope); var child1 = $compile('<div class="child1 animated">...</div>')($rootScope); var child2 = $compile('<div class="child2 animated">...</div>')($rootScope); var container = $compile('<div class="container">...</div>')($rootScope); jqLite($document[0].body).append($rootElement); $rootElement.append(container); element.append(child1); element.append(child2); $animate.move(element, null, container); $rootScope.$digest(); expect(intercepted).toBe('move'); $animate.addClass(child1, 'test'); expect(child1.hasClass('test')).toBe(true); expect(intercepted).toBe('move'); $animate.leave(child1); $rootScope.$digest(); expect(intercepted).toBe('move'); //reflow has passed $timeout.flush(); $animate.leave(child2); $rootScope.$digest(); expect(intercepted).toBe('leave'); }); }); it("should not disable any child animations when any parent class-based animations are run", function() { var intercepted; module(function($animateProvider) { $animateProvider.register('.animated', function() { return { enter : function(element, done) { intercepted = true; done(); } } }); }); inject(function($animate, $rootScope, $sniffer, $timeout, $compile, $document, $rootElement) { $animate.enabled(true); var element = $compile('<div ng-class="{klass:bool}"> <div ng-if="bool" class="animated">value</div></div>')($rootScope); $rootElement.append(element); jqLite($document[0].body).append($rootElement); $rootScope.bool = true; $rootScope.$digest(); expect(intercepted).toBe(true); }); }); it("should cache the response from getComputedStyle if each successive element has the same className value and parent until the first reflow hits", function() { var count = 0; module(function($provide) { $provide.value('$window', { document : jqLite(window.document), getComputedStyle: function(element) { count++; return window.getComputedStyle(element); } }); }); inject(function($animate, $rootScope, $compile, $rootElement, $timeout, $document, $sniffer) { if(!$sniffer.transitions) return; $animate.enabled(true); var element = $compile('<div></div>')($rootScope); $rootElement.append(element); jqLite($document[0].body).append($rootElement); for(var i=0;i<20;i++) { var kid = $compile('<div class="kid"></div>')($rootScope); $animate.enter(kid, element); } $rootScope.$digest(); //called three times since the classname is the same expect(count).toBe(2); dealoc(element); count = 0; for(var i=0;i<20;i++) { var kid = $compile('<div class="kid c-'+i+'"></div>')($rootScope); $animate.enter(kid, element); } $rootScope.$digest(); expect(count).toBe(20); }); }); it("should cancel an ongoing class-based animation only if the new class contains transition/animation CSS code", inject(function($compile, $rootScope, $animate, $sniffer, $timeout) { if (!$sniffer.transitions) return; ss.addRule('.green-add', '-webkit-transition:1s linear all;' + 'transition:1s linear all;'); ss.addRule('.blue-add', 'background:blue;'); ss.addRule('.red-add', '-webkit-transition:1s linear all;' + 'transition:1s linear all;'); ss.addRule('.yellow-add', '-webkit-animation: some_animation 4s linear 1s 2 alternate;' + 'animation: some_animation 4s linear 1s 2 alternate;'); var element = $compile('<div></div>')($rootScope); $rootElement.append(element); jqLite($document[0].body).append($rootElement); $animate.addClass(element, 'green'); expect(element.hasClass('green-add')).toBe(true); $animate.addClass(element, 'blue'); expect(element.hasClass('blue')).toBe(true); expect(element.hasClass('green-add')).toBe(true); //not cancelled $animate.addClass(element, 'red'); expect(element.hasClass('green-add')).toBe(false); expect(element.hasClass('red-add')).toBe(true); $animate.addClass(element, 'yellow'); expect(element.hasClass('red-add')).toBe(false); expect(element.hasClass('yellow-add')).toBe(true); })); it("should cancel and perform the dom operation only after the reflow has run", inject(function($compile, $rootScope, $animate, $sniffer, $timeout) { if (!$sniffer.transitions) return; ss.addRule('.green-add', '-webkit-transition:1s linear all;' + 'transition:1s linear all;'); ss.addRule('.red-add', '-webkit-transition:1s linear all;' + 'transition:1s linear all;'); var element = $compile('<div></div>')($rootScope); $rootElement.append(element); jqLite($document[0].body).append($rootElement); $animate.addClass(element, 'green'); expect(element.hasClass('green-add')).toBe(true); $animate.addClass(element, 'red'); expect(element.hasClass('red-add')).toBe(true); expect(element.hasClass('green')).toBe(false); expect(element.hasClass('red')).toBe(false); $animate.triggerReflow(); expect(element.hasClass('green')).toBe(true); expect(element.hasClass('red')).toBe(true); })); it("should avoid mixing up substring classes during add and remove operations", function() { var currentAnimation, currentFn; module(function($animateProvider) { $animateProvider.register('.on', function() { return { beforeAddClass : function(element, className, done) { currentAnimation = 'addClass'; currentFn = done; return function(cancelled) { currentAnimation = cancelled ? null : currentAnimation; } }, beforeRemoveClass : function(element, className, done) { currentAnimation = 'removeClass'; currentFn = done; return function(cancelled) { currentAnimation = cancelled ? null : currentAnimation; } } }; }); }); inject(function($compile, $rootScope, $animate, $sniffer, $timeout) { var element = $compile('<div class="animation-enabled only"></div>')($rootScope); $rootElement.append(element); jqLite($document[0].body).append($rootElement); $animate.addClass(element, 'on'); expect(currentAnimation).toBe('addClass'); currentFn(); currentAnimation = null; $animate.removeClass(element, 'on'); $animate.addClass(element, 'on'); expect(currentAnimation).toBe(null); }); }); it('should enable and disable animations properly on the root element', function() { var count = 0; module(function($animateProvider) { $animateProvider.register('.animated', function() { return { addClass : function(element, className, done) { count++; done(); } } }); }); inject(function($compile, $rootScope, $animate, $sniffer, $rootElement, $timeout) { $rootElement.addClass('animated'); $animate.addClass($rootElement, 'green'); expect(count).toBe(1); $animate.addClass($rootElement, 'red'); expect(count).toBe(2); }); }); it('should perform pre and post animations', function() { var steps = []; module(function($animateProvider) { $animateProvider.register('.class-animate', function() { return { beforeAddClass : function(element, className, done) { steps.push('before'); done(); }, addClass : function(element, className, done) { steps.push('after'); done(); } }; }); }); inject(function($animate, $rootScope, $compile, $rootElement, $timeout) { $animate.enabled(true); var element = $compile('<div class="class-animate"></div>')($rootScope); $rootElement.append(element); $animate.addClass(element, 'red'); expect(steps).toEqual(['before','after']); }); }); it('should treat the leave event always as a before event and discard the beforeLeave function', function() { var parentID, steps = []; module(function($animateProvider) { $animateProvider.register('.animate', function() { return { beforeLeave : function(element, done) { steps.push('before'); done(); }, leave : function(element, done) { parentID = element.parent().attr('id'); steps.push('after'); done(); } }; }); }); inject(function($animate, $rootScope, $compile, $rootElement) { $animate.enabled(true); var element = $compile('<div id="parentGuy"></div>')($rootScope); var child = $compile('<div class="animate"></div>')($rootScope); $rootElement.append(element); element.append(child); $animate.leave(child); $rootScope.$digest(); expect(steps).toEqual(['after']); expect(parentID).toEqual('parentGuy'); }); }); it('should only perform the DOM operation once', inject(function($sniffer, $compile, $rootScope, $rootElement, $animate, $timeout) { if (!$sniffer.transitions) return; ss.addRule('.base-class', '-webkit-transition:1s linear all;' + 'transition:1s linear all;'); $animate.enabled(true); var element = $compile('<div class="base-class one two"></div>')($rootScope); $rootElement.append(element); jqLite($document[0].body).append($rootElement); $animate.removeClass(element, 'base-class one two'); //still true since we're before the reflow expect(element.hasClass('base-class')).toBe(false); //this will cancel the remove animation $animate.addClass(element, 'base-class one two'); //the cancellation was a success and the class was added right away //since there was no successive animation for the after animation expect(element.hasClass('base-class')).toBe(false); //the reflow... $animate.triggerReflow(); //the reflow DOM operation was commenced but it ran before so it //shouldn't run agaun expect(element.hasClass('base-class')).toBe(true); })); it('should block and unblock transitions before the dom operation occurs', inject(function($rootScope, $compile, $rootElement, $document, $animate, $sniffer, $timeout) { if (!$sniffer.transitions) return; $animate.enabled(true); ss.addRule('.cross-animation', '-webkit-transition:1s linear all;' + 'transition:1s linear all;'); var capturedProperty = 'none'; var element = $compile('<div class="cross-animation"></div>')($rootScope); $rootElement.append(element); jqLite($document[0].body).append($rootElement); var node = element[0]; node._setAttribute = node.setAttribute; node.setAttribute = function(prop, val) { if(prop == 'class' && val.indexOf('trigger-class') >= 0) { var propertyKey = ($sniffer.vendorPrefix == 'Webkit' ? '-webkit-' : '') + 'transition-property'; capturedProperty = element.css(propertyKey); } node._setAttribute(prop, val); }; expect(capturedProperty).toBe('none'); $animate.addClass(element, 'trigger-class'); $animate.triggerReflow(); expect(capturedProperty).not.toBe('none'); })); it('should block and unblock keyframe animations around the reflow operation', inject(function($rootScope, $compile, $rootElement, $document, $animate, $sniffer, $timeout) { if (!$sniffer.animations) return; $animate.enabled(true); ss.addRule('.cross-animation', '-webkit-animation:1s my_animation;' + 'animation:1s my_animation;'); var element = $compile('<div class="cross-animation"></div>')($rootScope); $rootElement.append(element); jqLite($document[0].body).append($rootElement); var node = element[0]; var animationKey = $sniffer.vendorPrefix == 'Webkit' ? 'WebkitAnimation' : 'animation'; $animate.addClass(element, 'trigger-class'); expect(node.style[animationKey]).toContain('none'); $animate.triggerReflow(); expect(node.style[animationKey]).not.toContain('none'); })); it('should block and unblock keyframe animations before the followup JS animation occurs', function() { module(function($animateProvider) { $animateProvider.register('.special', function($sniffer, $window) { var prop = $sniffer.vendorPrefix == 'Webkit' ? 'WebkitAnimation' : 'animation'; return { beforeAddClass : function(element, className, done) { expect(element[0].style[prop]).not.toContain('none'); expect($window.getComputedStyle(element[0])[prop + 'Duration']).toBe('1s'); done(); }, addClass : function(element, className, done) { expect(element[0].style[prop]).not.toContain('none'); expect($window.getComputedStyle(element[0])[prop + 'Duration']).toBe('1s'); done(); } } }); }); inject(function($rootScope, $compile, $rootElement, $document, $animate, $sniffer, $timeout, $window) { if (!$sniffer.animations) return; $animate.enabled(true); ss.addRule('.special', '-webkit-animation:1s special_animation;' + 'animation:1s special_animation;'); var capturedProperty = 'none'; var element = $compile('<div class="special"></div>')($rootScope); $rootElement.append(element); jqLite($document[0].body).append($rootElement); $animate.addClass(element, 'some-klass'); var prop = $sniffer.vendorPrefix == 'Webkit' ? 'WebkitAnimation' : 'animation'; expect(element[0].style[prop]).toContain('none'); expect($window.getComputedStyle(element[0])[prop + 'Duration']).toBe('0s'); $animate.triggerReflow(); }); }); it('should round up long elapsedTime values to close off a CSS3 animation', inject(function($rootScope, $compile, $rootElement, $document, $animate, $sniffer, $timeout, $window) { if (!$sniffer.animations) return; ss.addRule('.millisecond-transition.ng-leave', '-webkit-transition:510ms linear all;' + 'transition:510ms linear all;'); var element = $compile('<div class="millisecond-transition"></div>')($rootScope); $rootElement.append(element); jqLite($document[0].body).append($rootElement); $animate.leave(element); $rootScope.$digest(); $animate.triggerReflow(); browserTrigger(element, 'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 0.50999999991 }); expect($rootElement.children().length).toBe(0); })); it('should properly animate elements with compound directives', function() { var capturedAnimation; module(function($animateProvider) { $animateProvider.register('.special', function() { return { enter : function(element, done) { capturedAnimation = 'enter'; done(); }, leave : function(element, done) { capturedAnimation = 'leave'; done(); } } }); }); inject(function($rootScope, $compile, $rootElement, $document, $timeout, $templateCache, $sniffer, $animate) { if(!$sniffer.transitions) return; $templateCache.put('item-template', 'item: #{{ item }} '); var element = $compile('<div>' + ' <div ng-repeat="item in items"' + ' ng-include="tpl"' + ' class="special"></div>' + '</div>')($rootScope); ss.addRule('.special', '-webkit-transition:1s linear all;' + 'transition:1s linear all;'); $rootElement.append(element); jqLite($document[0].body).append($rootElement); $rootScope.tpl = 'item-template'; $rootScope.items = [1,2,3]; $rootScope.$digest(); $animate.triggerReflow(); expect(capturedAnimation).toBe('enter'); expect(element.text()).toContain('item: #1'); forEach(element.children(), function(kid) { browserTrigger(kid, 'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 1 }); }); $timeout.flush(); $rootScope.items = []; $rootScope.$digest(); $animate.triggerReflow(); expect(capturedAnimation).toBe('leave'); }); }); it('should animate only the specified CSS className', function() { var captures = {}; module(function($animateProvider) { $animateProvider.classNameFilter(/prefixed-animation/); $animateProvider.register('.capture', function() { return { enter : buildFn('enter'), leave : buildFn('leave') }; function buildFn(key) { return function(element, className, done) { captures[key] = true; (done || className)(); } } }); }); inject(function($rootScope, $compile, $rootElement, $document, $timeout, $templateCache, $sniffer, $animate) { if(!$sniffer.transitions) return; var element = $compile('<div class="capture"></div>')($rootScope); $rootElement.append(element); jqLite($document[0].body).append($rootElement); var enterDone = false; $animate.enter(element, $rootElement, null, function() { enterDone = true; }); $rootScope.$digest(); $timeout.flush(); expect(captures['enter']).toBeUndefined(); expect(enterDone).toBe(true); element.addClass('prefixed-animation'); var leaveDone = false; $animate.leave(element, function() { leaveDone = true; }); $rootScope.$digest(); $timeout.flush(); expect(captures['leave']).toBe(true); expect(leaveDone).toBe(true); }); }); it('should respect the most relevant CSS transition property if defined in multiple classes', inject(function($sniffer, $compile, $rootScope, $rootElement, $animate, $timeout) { if (!$sniffer.transitions) return; ss.addRule('.base-class', '-webkit-transition:1s linear all;' + 'transition:1s linear all;'); ss.addRule('.base-class.on', '-webkit-transition:5s linear all;' + 'transition:5s linear all;'); $animate.enabled(true); var element = $compile('<div class="base-class"></div>')($rootScope); $rootElement.append(element); jqLite($document[0].body).append($rootElement); var ready = false; $animate.addClass(element, 'on', function() { ready = true; }); $animate.triggerReflow(); browserTrigger(element, 'transitionend', { timeStamp: Date.now(), elapsedTime: 1 }); $timeout.flush(1); expect(ready).toBe(false); browserTrigger(element, 'transitionend', { timeStamp: Date.now(), elapsedTime: 5 }); $timeout.flush(1); expect(ready).toBe(true); ready = false; $animate.removeClass(element, 'on', function() { ready = true; }); $animate.triggerReflow(); browserTrigger(element, 'transitionend', { timeStamp: Date.now(), elapsedTime: 1 }); $timeout.flush(1); expect(ready).toBe(true); })); it('should not apply a transition upon removal of a class that has a transition', inject(function($sniffer, $compile, $rootScope, $rootElement, $animate, $timeout) { if (!$sniffer.transitions) return; ss.addRule('.base-class.on', '-webkit-transition:5s linear all;' + 'transition:5s linear all;'); $animate.enabled(true); var element = $compile('<div class="base-class on"></div>')($rootScope); $rootElement.append(element); jqLite($document[0].body).append($rootElement); var ready = false; $animate.removeClass(element, 'on', function() { ready = true; }); $timeout.flush(1); expect(ready).toBe(true); })); it('should avoid skip animations if the same CSS class is added / removed synchronously before the reflow kicks in', inject(function($sniffer, $compile, $rootScope, $rootElement, $animate, $timeout) { if (!$sniffer.transitions) return; ss.addRule('.water-class', '-webkit-transition:2s linear all;' + 'transition:2s linear all;'); $animate.enabled(true); var element = $compile('<div class="water-class on"></div>')($rootScope); $rootElement.append(element); jqLite($document[0].body).append($rootElement); var signature = ''; $animate.removeClass(element, 'on', function() { signature += 'A'; }); $animate.addClass(element, 'on', function() { signature += 'B'; }); $timeout.flush(1); expect(signature).toBe('AB'); signature = ''; $animate.removeClass(element, 'on', function() { signature += 'A'; }); $animate.addClass(element, 'on', function() { signature += 'B'; }); $animate.removeClass(element, 'on', function() { signature += 'C'; }); $timeout.flush(1); expect(signature).toBe('AB'); $animate.triggerReflow(); browserTrigger(element, 'transitionend', { timeStamp: Date.now(), elapsedTime: 2000 }); $timeout.flush(1); expect(signature).toBe('ABC'); })); }); });
{ "content_hash": "0ccb96c40f1556bdef4e90a7c6ed7f2b", "timestamp": "", "source": "github", "line_count": 3270, "max_line_length": 165, "avg_line_length": 36.38654434250765, "alnum_prop": 0.5469727022120622, "repo_name": "sahat/angular.js", "id": "d626d60eeaafddb4e04f07c03fef8a7b2edafee1", "size": "118984", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "test/ngAnimate/animateSpec.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package com.jmv.utp.service.entity; public class HoraAcademica { private long id; }
{ "content_hash": "e47850804b9c14c4bf0f1d35b6e06d16", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 35, "avg_line_length": 15.5, "alnum_prop": 0.7096774193548387, "repo_name": "jmv-se/utp-mobile-webservice", "id": "ec875c4fc663bfd7eee66a4bca3c122e595e8342", "size": "93", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web-service/src/com/jmv/utp/service/entity/HoraAcademica.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
@interface SelectPlaceService () @end @implementation SelectPlaceService - (void)viewDidLoad { [super viewDidLoad]; self.navigationItem.title = @"Select Service"; // Do any additional setup after loading the view, typically from a nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark - UITableViewDelegate & UITableViewDatasource -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 2; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ; } if (indexPath.row == 0) { cell.textLabel.text = @"Nearby Search"; }else if (indexPath.row == 1) { cell.textLabel.text = @"Text Search"; } return cell; } -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { if (indexPath.row == 0) { NearbyPlaceSearchController *objNearBy =[self.storyboard instantiateViewControllerWithIdentifier:@"NearbyPlaceSearchController"]; [self.navigationController pushViewController:objNearBy animated:YES]; }else if(indexPath.row == 1) { TextSearchController *objTextBy =[self.storyboard instantiateViewControllerWithIdentifier:@"TextSearchController"]; [self.navigationController pushViewController:objTextBy animated:YES]; } } @end
{ "content_hash": "42b789288fc64719a6bf393e58180c6b", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 137, "avg_line_length": 27.55072463768116, "alnum_prop": 0.6959495002630195, "repo_name": "pchauhan/GPlaceAPI", "id": "3949316334696c8aa2ebaf8cecba7a9dd891cf35", "size": "2159", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "GPlaceAPIExample/GPlaceAPIExample/SelectPlaceService.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2211" }, { "name": "Objective-C", "bytes": "615973" }, { "name": "Ruby", "bytes": "1472" }, { "name": "Shell", "bytes": "4681" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name Podocarpus gaussenii Woltz ### Remarks null
{ "content_hash": "8ec7a3b99ac95ca651e097559ef51824", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 11.384615384615385, "alnum_prop": 0.7364864864864865, "repo_name": "mdoering/backbone", "id": "e3e366ad0ca04dcdee73b4fb1f29fd9e97ea12a3", "size": "215", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Pinophyta/Pinopsida/Pinales/Podocarpaceae/Nageia/Nageia falcata/Nageia falcata gaussenii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
""" 39. Testing using the Test Client The test client is a class that can act like a simple browser for testing purposes. It allows the user to compose GET and POST requests, and obtain the response that the server gave to those requests. The server Response objects are annotated with the details of the contexts and templates that were rendered during the process of serving the request. ``Client`` objects are stateful - they will retain cookie (and thus session) details for the lifetime of the ``Client`` instance. This is not intended as a replacement for Twill, Selenium, or other browser automation frameworks - it is here to allow testing against the contexts and templates produced by a view, rather than the HTML rendered to the end-user. """ from __future__ import absolute_import, unicode_literals from django.conf import settings from django.core import mail from django.test import Client, TestCase, RequestFactory from django.test.utils import override_settings from .views import get_view @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class ClientTest(TestCase): fixtures = ['testdata.json'] def test_get_view(self): "GET a view" # The data is ignored, but let's check it doesn't crash the system # anyway. data = {'var': '\xf2'} response = self.client.get('/test_client/get_view/', data) # Check some response details self.assertContains(response, 'This is a test') self.assertEqual(response.context['var'], '\xf2') self.assertEqual(response.templates[0].name, 'GET Template') def test_get_post_view(self): "GET a view that normally expects POSTs" response = self.client.get('/test_client/post_view/', {}) # Check some response details self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, 'Empty GET Template') self.assertTemplateUsed(response, 'Empty GET Template') self.assertTemplateNotUsed(response, 'Empty POST Template') def test_empty_post(self): "POST an empty dictionary to a view" response = self.client.post('/test_client/post_view/', {}) # Check some response details self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, 'Empty POST Template') self.assertTemplateNotUsed(response, 'Empty GET Template') self.assertTemplateUsed(response, 'Empty POST Template') def test_post(self): "POST some data to a view" post_data = { 'value': 37 } response = self.client.post('/test_client/post_view/', post_data) # Check some response details self.assertEqual(response.status_code, 200) self.assertEqual(response.context['data'], '37') self.assertEqual(response.templates[0].name, 'POST Template') self.assertContains(response, 'Data received') def test_response_headers(self): "Check the value of HTTP headers returned in a response" response = self.client.get("/test_client/header_view/") self.assertEqual(response['X-DJANGO-TEST'], 'Slartibartfast') def test_raw_post(self): "POST raw data (with a content type) to a view" test_doc = """<?xml version="1.0" encoding="utf-8"?><library><book><title>Blink</title><author>Malcolm Gladwell</author></book></library>""" response = self.client.post("/test_client/raw_post_view/", test_doc, content_type="text/xml") self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, "Book template") self.assertEqual(response.content, b"Blink - Malcolm Gladwell") def test_redirect(self): "GET a URL that redirects elsewhere" response = self.client.get('/test_client/redirect_view/') # Check that the response was a 302 (redirect) and that # assertRedirect() understands to put an implicit http://testserver/ in # front of non-absolute URLs. self.assertRedirects(response, '/test_client/get_view/') host = 'django.testserver' client_providing_host = Client(HTTP_HOST=host) response = client_providing_host.get('/test_client/redirect_view/') # Check that the response was a 302 (redirect) with absolute URI self.assertRedirects(response, '/test_client/get_view/', host=host) def test_redirect_with_query(self): "GET a URL that redirects with given GET parameters" response = self.client.get('/test_client/redirect_view/', {'var': 'value'}) # Check if parameters are intact self.assertRedirects(response, 'http://testserver/test_client/get_view/?var=value') def test_permanent_redirect(self): "GET a URL that redirects permanently elsewhere" response = self.client.get('/test_client/permanent_redirect_view/') # Check that the response was a 301 (permanent redirect) self.assertRedirects(response, 'http://testserver/test_client/get_view/', status_code=301) client_providing_host = Client(HTTP_HOST='django.testserver') response = client_providing_host.get('/test_client/permanent_redirect_view/') # Check that the response was a 301 (permanent redirect) with absolute URI self.assertRedirects(response, 'http://django.testserver/test_client/get_view/', status_code=301) def test_temporary_redirect(self): "GET a URL that does a non-permanent redirect" response = self.client.get('/test_client/temporary_redirect_view/') # Check that the response was a 302 (non-permanent redirect) self.assertRedirects(response, 'http://testserver/test_client/get_view/', status_code=302) def test_redirect_to_strange_location(self): "GET a URL that redirects to a non-200 page" response = self.client.get('/test_client/double_redirect_view/') # Check that the response was a 302, and that # the attempt to get the redirection location returned 301 when retrieved self.assertRedirects(response, 'http://testserver/test_client/permanent_redirect_view/', target_status_code=301) def test_follow_redirect(self): "A URL that redirects can be followed to termination." response = self.client.get('/test_client/double_redirect_view/', follow=True) self.assertRedirects(response, 'http://testserver/test_client/get_view/', status_code=302, target_status_code=200) self.assertEqual(len(response.redirect_chain), 2) def test_redirect_http(self): "GET a URL that redirects to an http URI" response = self.client.get('/test_client/http_redirect_view/',follow=True) self.assertFalse(response.test_was_secure_request) def test_redirect_https(self): "GET a URL that redirects to an https URI" response = self.client.get('/test_client/https_redirect_view/',follow=True) self.assertTrue(response.test_was_secure_request) def test_notfound_response(self): "GET a URL that responds as '404:Not Found'" response = self.client.get('/test_client/bad_view/') # Check that the response was a 404, and that the content contains MAGIC self.assertContains(response, 'MAGIC', status_code=404) def test_valid_form(self): "POST valid data to a form" post_data = { 'text': 'Hello World', 'email': 'foo@example.com', 'value': 37, 'single': 'b', 'multi': ('b','c','e') } response = self.client.post('/test_client/form_view/', post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Valid POST Template") def test_valid_form_with_hints(self): "GET a form, providing hints in the GET data" hints = { 'text': 'Hello World', 'multi': ('b','c','e') } response = self.client.get('/test_client/form_view/', data=hints) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Form GET Template") # Check that the multi-value data has been rolled out ok self.assertContains(response, 'Select a valid choice.', 0) def test_incomplete_data_form(self): "POST incomplete data to a form" post_data = { 'text': 'Hello World', 'value': 37 } response = self.client.post('/test_client/form_view/', post_data) self.assertContains(response, 'This field is required.', 3) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Invalid POST Template") self.assertFormError(response, 'form', 'email', 'This field is required.') self.assertFormError(response, 'form', 'single', 'This field is required.') self.assertFormError(response, 'form', 'multi', 'This field is required.') def test_form_error(self): "POST erroneous data to a form" post_data = { 'text': 'Hello World', 'email': 'not an email address', 'value': 37, 'single': 'b', 'multi': ('b','c','e') } response = self.client.post('/test_client/form_view/', post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Invalid POST Template") self.assertFormError(response, 'form', 'email', 'Enter a valid e-mail address.') def test_valid_form_with_template(self): "POST valid data to a form using multiple templates" post_data = { 'text': 'Hello World', 'email': 'foo@example.com', 'value': 37, 'single': 'b', 'multi': ('b','c','e') } response = self.client.post('/test_client/form_view_with_template/', post_data) self.assertContains(response, 'POST data OK') self.assertTemplateUsed(response, "form_view.html") self.assertTemplateUsed(response, 'base.html') self.assertTemplateNotUsed(response, "Valid POST Template") def test_incomplete_data_form_with_template(self): "POST incomplete data to a form using multiple templates" post_data = { 'text': 'Hello World', 'value': 37 } response = self.client.post('/test_client/form_view_with_template/', post_data) self.assertContains(response, 'POST data has errors') self.assertTemplateUsed(response, 'form_view.html') self.assertTemplateUsed(response, 'base.html') self.assertTemplateNotUsed(response, "Invalid POST Template") self.assertFormError(response, 'form', 'email', 'This field is required.') self.assertFormError(response, 'form', 'single', 'This field is required.') self.assertFormError(response, 'form', 'multi', 'This field is required.') def test_form_error_with_template(self): "POST erroneous data to a form using multiple templates" post_data = { 'text': 'Hello World', 'email': 'not an email address', 'value': 37, 'single': 'b', 'multi': ('b','c','e') } response = self.client.post('/test_client/form_view_with_template/', post_data) self.assertContains(response, 'POST data has errors') self.assertTemplateUsed(response, "form_view.html") self.assertTemplateUsed(response, 'base.html') self.assertTemplateNotUsed(response, "Invalid POST Template") self.assertFormError(response, 'form', 'email', 'Enter a valid e-mail address.') def test_unknown_page(self): "GET an invalid URL" response = self.client.get('/test_client/unknown_view/') # Check that the response was a 404 self.assertEqual(response.status_code, 404) def test_url_parameters(self): "Make sure that URL ;-parameters are not stripped." response = self.client.get('/test_client/unknown_view/;some-parameter') # Check that the path in the response includes it (ignore that it's a 404) self.assertEqual(response.request['PATH_INFO'], '/test_client/unknown_view/;some-parameter') def test_view_with_login(self): "Request a page that is protected with @login_required" # Get the page without logging in. Should result in 302. response = self.client.get('/test_client/login_protected_view/') self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/login_protected_view/') # Log in login = self.client.login(username='testclient', password='password') self.assertTrue(login, 'Could not log in') # Request a page that requires a login response = self.client.get('/test_client/login_protected_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') def test_view_with_method_login(self): "Request a page that is protected with a @login_required method" # Get the page without logging in. Should result in 302. response = self.client.get('/test_client/login_protected_method_view/') self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/login_protected_method_view/') # Log in login = self.client.login(username='testclient', password='password') self.assertTrue(login, 'Could not log in') # Request a page that requires a login response = self.client.get('/test_client/login_protected_method_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') def test_view_with_login_and_custom_redirect(self): "Request a page that is protected with @login_required(redirect_field_name='redirect_to')" # Get the page without logging in. Should result in 302. response = self.client.get('/test_client/login_protected_view_custom_redirect/') self.assertRedirects(response, 'http://testserver/accounts/login/?redirect_to=/test_client/login_protected_view_custom_redirect/') # Log in login = self.client.login(username='testclient', password='password') self.assertTrue(login, 'Could not log in') # Request a page that requires a login response = self.client.get('/test_client/login_protected_view_custom_redirect/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') def test_view_with_bad_login(self): "Request a page that is protected with @login, but use bad credentials" login = self.client.login(username='otheruser', password='nopassword') self.assertFalse(login) def test_view_with_inactive_login(self): "Request a page that is protected with @login, but use an inactive login" login = self.client.login(username='inactive', password='password') self.assertFalse(login) def test_logout(self): "Request a logout after logging in" # Log in self.client.login(username='testclient', password='password') # Request a page that requires a login response = self.client.get('/test_client/login_protected_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') # Log out self.client.logout() # Request a page that requires a login response = self.client.get('/test_client/login_protected_view/') self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/login_protected_view/') def test_view_with_permissions(self): "Request a page that is protected with @permission_required" # Get the page without logging in. Should result in 302. response = self.client.get('/test_client/permission_protected_view/') self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/permission_protected_view/') # Log in login = self.client.login(username='testclient', password='password') self.assertTrue(login, 'Could not log in') # Log in with wrong permissions. Should result in 302. response = self.client.get('/test_client/permission_protected_view/') self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/permission_protected_view/') # TODO: Log in with right permissions and request the page again def test_view_with_permissions_exception(self): "Request a page that is protected with @permission_required but raises a exception" # Get the page without logging in. Should result in 403. response = self.client.get('/test_client/permission_protected_view_exception/') self.assertEqual(response.status_code, 403) # Log in login = self.client.login(username='testclient', password='password') self.assertTrue(login, 'Could not log in') # Log in with wrong permissions. Should result in 403. response = self.client.get('/test_client/permission_protected_view_exception/') self.assertEqual(response.status_code, 403) def test_view_with_method_permissions(self): "Request a page that is protected with a @permission_required method" # Get the page without logging in. Should result in 302. response = self.client.get('/test_client/permission_protected_method_view/') self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/permission_protected_method_view/') # Log in login = self.client.login(username='testclient', password='password') self.assertTrue(login, 'Could not log in') # Log in with wrong permissions. Should result in 302. response = self.client.get('/test_client/permission_protected_method_view/') self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/permission_protected_method_view/') # TODO: Log in with right permissions and request the page again def test_session_modifying_view(self): "Request a page that modifies the session" # Session value isn't set initially try: self.client.session['tobacconist'] self.fail("Shouldn't have a session value") except KeyError: pass from django.contrib.sessions.models import Session response = self.client.post('/test_client/session_view/') # Check that the session was modified self.assertEqual(self.client.session['tobacconist'], 'hovercraft') def test_view_with_exception(self): "Request a page that is known to throw an error" self.assertRaises(KeyError, self.client.get, "/test_client/broken_view/") #Try the same assertion, a different way try: self.client.get('/test_client/broken_view/') self.fail('Should raise an error') except KeyError: pass def test_mail_sending(self): "Test that mail is redirected to a dummy outbox during test setup" response = self.client.get('/test_client/mail_sending_view/') self.assertEqual(response.status_code, 200) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, 'Test message') self.assertEqual(mail.outbox[0].body, 'This is a test email') self.assertEqual(mail.outbox[0].from_email, 'from@example.com') self.assertEqual(mail.outbox[0].to[0], 'first@example.com') self.assertEqual(mail.outbox[0].to[1], 'second@example.com') def test_mass_mail_sending(self): "Test that mass mail is redirected to a dummy outbox during test setup" response = self.client.get('/test_client/mass_mail_sending_view/') self.assertEqual(response.status_code, 200) self.assertEqual(len(mail.outbox), 2) self.assertEqual(mail.outbox[0].subject, 'First Test message') self.assertEqual(mail.outbox[0].body, 'This is the first test email') self.assertEqual(mail.outbox[0].from_email, 'from@example.com') self.assertEqual(mail.outbox[0].to[0], 'first@example.com') self.assertEqual(mail.outbox[0].to[1], 'second@example.com') self.assertEqual(mail.outbox[1].subject, 'Second Test message') self.assertEqual(mail.outbox[1].body, 'This is the second test email') self.assertEqual(mail.outbox[1].from_email, 'from@example.com') self.assertEqual(mail.outbox[1].to[0], 'second@example.com') self.assertEqual(mail.outbox[1].to[1], 'third@example.com') class CSRFEnabledClientTests(TestCase): def setUp(self): # Enable the CSRF middleware for this test self.old_MIDDLEWARE_CLASSES = settings.MIDDLEWARE_CLASSES csrf_middleware_class = 'django.middleware.csrf.CsrfViewMiddleware' if csrf_middleware_class not in settings.MIDDLEWARE_CLASSES: settings.MIDDLEWARE_CLASSES += (csrf_middleware_class,) def tearDown(self): settings.MIDDLEWARE_CLASSES = self.old_MIDDLEWARE_CLASSES def test_csrf_enabled_client(self): "A client can be instantiated with CSRF checks enabled" csrf_client = Client(enforce_csrf_checks=True) # The normal client allows the post response = self.client.post('/test_client/post_view/', {}) self.assertEqual(response.status_code, 200) # The CSRF-enabled client rejects it response = csrf_client.post('/test_client/post_view/', {}) self.assertEqual(response.status_code, 403) class CustomTestClient(Client): i_am_customized = "Yes" class CustomTestClientTest(TestCase): client_class = CustomTestClient def test_custom_test_client(self): """A test case can specify a custom class for self.client.""" self.assertEqual(hasattr(self.client, "i_am_customized"), True) class RequestFactoryTest(TestCase): def test_request_factory(self): factory = RequestFactory() request = factory.get('/somewhere/') response = get_view(request) self.assertEqual(response.status_code, 200) self.assertContains(response, 'This is a test')
{ "content_hash": "6216dfef691e7af10aa82778de6f9e7f", "timestamp": "", "source": "github", "line_count": 507, "max_line_length": 148, "avg_line_length": 44.44181459566075, "alnum_prop": 0.6615924019172732, "repo_name": "vsajip/django", "id": "1d9c999f21b0c0bc6279a5cca1a712c16f7f25bb", "size": "22548", "binary": false, "copies": "1", "ref": "refs/heads/django3", "path": "tests/modeltests/test_client/models.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "89078" }, { "name": "Python", "bytes": "8200429" }, { "name": "Shell", "bytes": "4241" } ], "symlink_target": "" }
package net.kuujo.copycat.io.serializer; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation for indicating which classes a serializer serializes. * * @author <a href="http://github.com/kuujo">Jordan Halterman</a> */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Serialize { /** * A list of classes the serializer serializes. */ Type[] value(); /** * Serialize type. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @interface Type { /** * The serialization ID. */ int id() default -1; /** * The type to serialize. */ Class<?> type(); } }
{ "content_hash": "b828ad01e97fae1b9f3676948ba54216", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 67, "avg_line_length": 19.24390243902439, "alnum_prop": 0.6717363751584284, "repo_name": "aruanruan/copycat", "id": "0affb4b9f07e96332c86ead06daaf9a9bfca4bf6", "size": "1399", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "io/src/main/java/net/kuujo/copycat/io/serializer/Serialize.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1349656" }, { "name": "Shell", "bytes": "321" } ], "symlink_target": "" }
from __future__ import unicode_literals import os from django.core.wsgi import get_wsgi_application # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.production" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. application = get_wsgi_application()
{ "content_hash": "35928ef686b573b72d4d4229717e873e", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 78, "avg_line_length": 45.86666666666667, "alnum_prop": 0.7834302325581395, "repo_name": "Swappsco/koalixerp", "id": "dd179b1aa72659606dd4d3a6f97c8b28731107cb", "size": "688", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/wsgi.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "58508" }, { "name": "HTML", "bytes": "208636" }, { "name": "JavaScript", "bytes": "200359" }, { "name": "Python", "bytes": "289012" }, { "name": "Shell", "bytes": "159" } ], "symlink_target": "" }
// MESSAGE ALTITUDE support class #pragma once namespace mavlink { namespace common { namespace msg { /** * @brief ALTITUDE message * * The current system altitude. */ struct ALTITUDE : mavlink::Message { static constexpr msgid_t MSG_ID = 141; static constexpr size_t LENGTH = 32; static constexpr size_t MIN_LENGTH = 32; static constexpr uint8_t CRC_EXTRA = 47; static constexpr auto NAME = "ALTITUDE"; uint64_t time_usec; /*< Timestamp (micros since boot or Unix epoch) */ float altitude_monotonic; /*< This altitude measure is initialized on system boot and monotonic (it is never reset, but represents the local altitude change). The only guarantee on this field is that it will never be reset and is consistent within a flight. The recommended value for this field is the uncorrected barometric altitude at boot time. This altitude will also drift and vary between flights. */ float altitude_amsl; /*< This altitude measure is strictly above mean sea level and might be non-monotonic (it might reset on events like GPS lock or when a new QNH value is set). It should be the altitude to which global altitude waypoints are compared to. Note that it is *not* the GPS altitude, however, most GPS modules already output AMSL by default and not the WGS84 altitude. */ float altitude_local; /*< This is the local altitude in the local coordinate frame. It is not the altitude above home, but in reference to the coordinate origin (0, 0, 0). It is up-positive. */ float altitude_relative; /*< This is the altitude above the home position. It resets on each change of the current home position. */ float altitude_terrain; /*< This is the altitude above terrain. It might be fed by a terrain database or an altimeter. Values smaller than -1000 should be interpreted as unknown. */ float bottom_clearance; /*< This is not the altitude, but the clear space below the system according to the fused clearance estimate. It generally should max out at the maximum range of e.g. the laser altimeter. It is generally a moving target. A negative value indicates no measurement available. */ inline std::string get_name(void) const override { return NAME; } inline Info get_message_info(void) const override { return { MSG_ID, LENGTH, MIN_LENGTH, CRC_EXTRA }; } inline std::string to_yaml(void) const override { std::stringstream ss; ss << NAME << ":" << std::endl; ss << " time_usec: " << time_usec << std::endl; ss << " altitude_monotonic: " << altitude_monotonic << std::endl; ss << " altitude_amsl: " << altitude_amsl << std::endl; ss << " altitude_local: " << altitude_local << std::endl; ss << " altitude_relative: " << altitude_relative << std::endl; ss << " altitude_terrain: " << altitude_terrain << std::endl; ss << " bottom_clearance: " << bottom_clearance << std::endl; return ss.str(); } inline void serialize(mavlink::MsgMap &map) const override { map.reset(MSG_ID, LENGTH); map << time_usec; // offset: 0 map << altitude_monotonic; // offset: 8 map << altitude_amsl; // offset: 12 map << altitude_local; // offset: 16 map << altitude_relative; // offset: 20 map << altitude_terrain; // offset: 24 map << bottom_clearance; // offset: 28 } inline void deserialize(mavlink::MsgMap &map) override { map >> time_usec; // offset: 0 map >> altitude_monotonic; // offset: 8 map >> altitude_amsl; // offset: 12 map >> altitude_local; // offset: 16 map >> altitude_relative; // offset: 20 map >> altitude_terrain; // offset: 24 map >> bottom_clearance; // offset: 28 } }; } // namespace msg } // namespace common } // namespace mavlink
{ "content_hash": "d8600815bfae95cafd0edae33c7b97f3", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 410, "avg_line_length": 49.63095238095238, "alnum_prop": 0.614056128568002, "repo_name": "YKSamgo/AR-Drone", "id": "5edc30f1eb75b274315b7c48690a5a333950c1de", "size": "4169", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ARDrone/ARDrone/include/common/mavlink_msg_altitude.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "3513604" }, { "name": "C++", "bytes": "1233420" } ], "symlink_target": "" }
package com.heatonresearch.aifh.examples.regression; import com.heatonresearch.aifh.examples.learning.SimpleLearn; import com.heatonresearch.aifh.general.data.BasicData; import com.heatonresearch.aifh.general.fns.link.LogitLinkFunction; import com.heatonresearch.aifh.normalize.DataSet; import com.heatonresearch.aifh.regression.MultipleLinearRegression; import com.heatonresearch.aifh.regression.TrainReweightLeastSquares; import java.io.InputStream; import java.util.List; /** * Example that uses a GLM to predict the probability of breast cancer. */ public class GLMExample extends SimpleLearn { /** * Run the example. */ public void process() { try { final InputStream istream = this.getClass().getResourceAsStream("/breast-cancer-wisconsin.csv"); if( istream==null ) { System.out.println("Cannot access data set, make sure the resources are available."); System.exit(1); } final DataSet ds = DataSet.load(istream); istream.close(); ds.deleteUnknowns(); ds.deleteColumn(0); ds.replaceColumn(9, 4, 1, 0); final List<BasicData> trainingData = ds.extractSupervised(0, 9, 9, 1); final MultipleLinearRegression reg = new MultipleLinearRegression(9); reg.setLinkFunction(new LogitLinkFunction()); final TrainReweightLeastSquares train = new TrainReweightLeastSquares(reg, trainingData); int iteration = 0; do { iteration++; train.iteration(); System.out.println("Iteration #" + iteration + ", Error: " + train.getError()); } while (iteration < 1000 && train.getError() > 0.01); query(reg, trainingData); System.out.println("Error: " + train.getError()); } catch (Throwable t) { t.printStackTrace(); } } /** * The main method. * * @param args Not used. */ public static void main(final String[] args) { final GLMExample prg = new GLMExample(); prg.process(); } }
{ "content_hash": "5db4db05d134cdd38a467638e333f30c", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 108, "avg_line_length": 31.405797101449274, "alnum_prop": 0.6211352099676973, "repo_name": "PeterLauris/aifh", "id": "6a0f230d21a5cc30f4dee4805d830c1793c1c519", "size": "3103", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "vol1/java-examples/src/main/java/com/heatonresearch/aifh/examples/regression/GLMExample.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "256539" }, { "name": "C#", "bytes": "1168093" }, { "name": "CMake", "bytes": "964" }, { "name": "Java", "bytes": "1452420" }, { "name": "Makefile", "bytes": "2018" }, { "name": "Python", "bytes": "459018" }, { "name": "R", "bytes": "35707" }, { "name": "Scala", "bytes": "906268" } ], "symlink_target": "" }
package io.renren.common.xss; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import javax.servlet.ReadListener; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; import java.util.Map; /** * XSS过滤处理 * * @author Mark sunlightcs@gmail.com * @since 1.0.0 */ public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper { HttpServletRequest orgRequest; public XssHttpServletRequestWrapper(HttpServletRequest request) { super(request); orgRequest = request; } @Override public ServletInputStream getInputStream() throws IOException { //非json类型,直接返回 if(!MediaType.APPLICATION_JSON_VALUE.contains(super.getHeader(HttpHeaders.CONTENT_TYPE))){ return super.getInputStream(); } //为空,直接返回 String json = IOUtils.toString(super.getInputStream(), StandardCharsets.UTF_8); if (StringUtils.isBlank(json)) { return super.getInputStream(); } //xss过滤 json = xssEncode(json); final ByteArrayInputStream bis = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)); return new ServletInputStream() { @Override public boolean isFinished() { return true; } @Override public boolean isReady() { return true; } @Override public void setReadListener(ReadListener readListener) { } @Override public int read() { return bis.read(); } }; } @Override public String getParameter(String name) { String value = super.getParameter(xssEncode(name)); if (StringUtils.isNotBlank(value)) { value = xssEncode(value); } return value; } @Override public String[] getParameterValues(String name) { String[] parameters = super.getParameterValues(name); if (parameters == null || parameters.length == 0) { return null; } for (int i = 0; i < parameters.length; i++) { parameters[i] = xssEncode(parameters[i]); } return parameters; } @Override public Map<String,String[]> getParameterMap() { Map<String,String[]> map = new LinkedHashMap<>(); Map<String,String[]> parameters = super.getParameterMap(); for (String key : parameters.keySet()) { String[] values = parameters.get(key); for (int i = 0; i < values.length; i++) { values[i] = xssEncode(values[i]); } map.put(key, values); } return map; } @Override public String getHeader(String name) { String value = super.getHeader(xssEncode(name)); if (StringUtils.isNotBlank(value)) { value = xssEncode(value); } return value; } private String xssEncode(String input) { return XssUtils.filter(input); } /** * 获取最原始的request */ public HttpServletRequest getOrgRequest() { return orgRequest; } /** * 获取最原始的request */ public static HttpServletRequest getOrgRequest(HttpServletRequest request) { if (request instanceof XssHttpServletRequestWrapper) { return ((XssHttpServletRequestWrapper) request).getOrgRequest(); } return request; } }
{ "content_hash": "023a6106fd210d4fdd983b21e15ee923", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 105, "avg_line_length": 26.99290780141844, "alnum_prop": 0.6127167630057804, "repo_name": "renrenio/renren-security", "id": "ef9a6adf9450e7627f718dd8beafa1993f335b0d", "size": "4000", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "renren-common/src/main/java/io/renren/common/xss/XssHttpServletRequestWrapper.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "37575" }, { "name": "Dockerfile", "bytes": "266" }, { "name": "HTML", "bytes": "7507" }, { "name": "Java", "bytes": "441813" }, { "name": "JavaScript", "bytes": "38543" }, { "name": "TSQL", "bytes": "36860" } ], "symlink_target": "" }
package org.dcm4chex.archive.mbean; import java.io.IOException; import java.rmi.RemoteException; import java.sql.SQLException; import java.sql.Timestamp; import java.util.Calendar; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.ejb.FinderException; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.ObjectName; import org.apache.log4j.Logger; import org.dcm4che.data.Command; import org.dcm4che.data.Dataset; import org.dcm4che.data.DcmObjectFactory; import org.dcm4che.dict.Tags; import org.dcm4che.dict.UIDs; import org.dcm4che.net.ActiveAssociation; import org.dcm4che.net.AssociationFactory; import org.dcm4che.net.DcmServiceException; import org.dcm4che.net.Dimse; import org.dcm4che.net.FutureRSP; import org.dcm4chex.archive.config.RetryIntervalls; import org.dcm4chex.archive.dcm.AbstractScuService; import org.dcm4chex.archive.ejb.interfaces.StudyReconciliation; import org.dcm4chex.archive.ejb.interfaces.StudyReconciliationHome; import org.dcm4chex.archive.ejb.jdbc.QueryCmd; import org.dcm4chex.archive.util.EJBHomeFactory; /** * @author franz.willer@gwi-ag.com * @version $Revision: 14910 $ $Date: 2011-02-17 00:02:15 +0800 (周四, 17 2月 2011) $ * @since Juli 2006 * */ public class StudyReconciliationService extends AbstractScuService { private final SchedulerDelegate scheduler = new SchedulerDelegate(this); private long taskInterval = 0L; private boolean isRunning; private int disabledStartHour; private int disabledEndHour; private int limitNumberOfStudiesPerTask; private long minStudyAge; private int scheduledStatus = 1; private int successStatus = 0; private int failureStatus = -1; private String calledAET = "TIANI_ARCHIVE"; private boolean keepPriorPatientAfterMerge = true; private Integer listenerID; private final static AssociationFactory af = AssociationFactory .getInstance(); private final static DcmObjectFactory dof = DcmObjectFactory.getInstance(); private final static int PCID_FIND = 1; private int priority = Command.MEDIUM; private int fetchSize; private String timerIDCheckStudyReconciliation = "CheckStudyReconciliation"; private static final int[] UPDATE_ATTRIBUTES = new int[] { Tags.OtherPatientIDs, Tags.OtherPatientNames, Tags.StudyDescription, Tags.StudyID, Tags.AccessionNumber, Tags.StudyDate, Tags.StudyTime, Tags.ReferringPhysicianName, Tags.SeriesDescription, Tags.SeriesNumber, Tags.Modality, Tags.BodyPartExamined, Tags.SeriesDate, Tags.SeriesTime, Tags.Laterality, Tags.PerformingPhysicianName }; private static final Logger log = Logger .getLogger(StudyReconciliationService.class); private final NotificationListener updateCheckListener = new NotificationListener() { public void handleNotification(Notification notif, Object handback) { Calendar cal = Calendar.getInstance(); int hour = cal.get(Calendar.HOUR_OF_DAY); if (isDisabled(hour)) { if (log.isDebugEnabled()) log.debug("Study Reconciliation ignored in time between " + disabledStartHour + " and " + disabledEndHour + " !"); } else { new Thread(new Runnable() { public void run() { try { log.info(check()); } catch (Exception e) { log.error("Study Reconciliation failed!", e); } } }).start(); } } }; public ObjectName getSchedulerServiceName() { return scheduler.getSchedulerServiceName(); } public void setSchedulerServiceName(ObjectName schedulerServiceName) { scheduler.setSchedulerServiceName(schedulerServiceName); } public String getCalledAET() { return calledAET; } public void setCalledAET(String calledAET) { this.calledAET = calledAET; } public final String getTaskInterval() { String s = RetryIntervalls.formatIntervalZeroAsNever(taskInterval); return (disabledEndHour == -1) ? s : s + "!" + disabledStartHour + "-" + disabledEndHour; } public void setTaskInterval(String interval) throws Exception { long oldInterval = taskInterval; int pos = interval.indexOf('!'); if (pos == -1) { taskInterval = RetryIntervalls.parseIntervalOrNever(interval); disabledEndHour = -1; } else { taskInterval = RetryIntervalls.parseIntervalOrNever(interval .substring(0, pos)); int pos1 = interval.indexOf('-', pos); disabledStartHour = Integer.parseInt(interval.substring(pos + 1, pos1)); disabledEndHour = Integer.parseInt(interval.substring(pos1 + 1)); } if (getState() == STARTED && oldInterval != taskInterval) { scheduler.stopScheduler(timerIDCheckStudyReconciliation, listenerID, updateCheckListener); listenerID = scheduler.startScheduler( timerIDCheckStudyReconciliation, taskInterval, updateCheckListener); } } public boolean isRunning() { return isRunning; } /** * Getter for minStudyAge. * <p> * This value is used to ensure that consistent check is not performed on * studies that are not completed (store is not completed). * * @return Returns ##w (in weeks), ##d (in days), ##h (in hours). */ public String getMinStudyAge() { return RetryIntervalls.formatInterval(minStudyAge); } /** * Setter for minStudyAge. * <p> * This value is used to ensure that consistent check is not performed on * studies that are not completed (store is not completed). * * @param age * ##w (in weeks), ##d (in days), ##h (in hours). */ public void setMinStudyAge(String age) { this.minStudyAge = RetryIntervalls.parseInterval(age); } public int getLimitNumberOfStudiesPerTask() { return limitNumberOfStudiesPerTask; } public void setLimitNumberOfStudiesPerTask(int limit) { this.limitNumberOfStudiesPerTask = limit; } public int getScheduledStatus() { return scheduledStatus; } public void setScheduledStatus(int status) { this.scheduledStatus = status; } public int getSuccessStatus() { return successStatus; } public void setSuccessStatus(int status) { this.successStatus = status; } public int getFailureStatus() { return failureStatus; } public void setFailureStatus(int failureStatus) { this.failureStatus = failureStatus; } public boolean isKeepPriorPatientAfterMerge() { return keepPriorPatientAfterMerge; } public void setKeepPriorPatientAfterMerge(boolean keepPriorPatientAfterMerge) { this.keepPriorPatientAfterMerge = keepPriorPatientAfterMerge; } public int getFetchSize() { return fetchSize; } public void setFetchSize(int fetchSize) { this.fetchSize = fetchSize; } public String check() throws Exception { synchronized(this) { if (isRunning) { String msg = "SyncFileStatus is already running!"; log.info(msg); return msg; } isRunning = true; } try { long start = System.currentTimeMillis(); StudyReconciliation studyReconciliation = newStudyReconciliation(); Timestamp createdBefore = new Timestamp(System.currentTimeMillis() - this.minStudyAge); Collection col = studyReconciliation.getStudyIuidsWithStatus( scheduledStatus, createdBefore, limitNumberOfStudiesPerTask); log.info("Check " + col.size() + " Studies for Reconcilitiation (status:" + this.scheduledStatus + ")"); if (col.isEmpty()) { log.debug("No Studies with status " + scheduledStatus + " found for Reconcilitiation!"); return "Nothing to do!"; } Map archiveStudy; Dataset qrSeriesDS = getSeriesQueryDS(); Dataset qrInstanceDS = getInstanceQueryDS(); ActiveAssociation aa = openAssociation(calledAET, UIDs.StudyRootQueryRetrieveInformationModelFIND); int numPatUpdt = 0, numPatMerge = 0, numFailures = 0; try { String studyIuid; for (Iterator iter = col.iterator(); iter.hasNext();) { studyIuid = (String) iter.next(); qrSeriesDS.putUI(Tags.StudyInstanceUID, studyIuid); archiveStudy = query(aa, qrSeriesDS, Tags.SeriesInstanceUID); Dataset patDS = checkStudy(qrSeriesDS, qrInstanceDS, archiveStudy, aa); if (patDS != null) { log.debug("check Patient info of study " + studyIuid); Dataset origPatDS = (Dataset) archiveStudy.values().iterator().next(); if (compare(patDS, origPatDS, Tags.PatientID) && compare(patDS, origPatDS, Tags.IssuerOfPatientID)) { if (!compare(patDS, origPatDS, Tags.PatientName) || !compare(patDS, origPatDS, Tags.PatientBirthDate) || !compare(patDS, origPatDS, Tags.PatientSex)) { log.info("UPDATE patient: " + origPatDS.getString(Tags.PatientID)); studyReconciliation.updatePatient(origPatDS); numPatUpdt++; } } else { log.info("MERGE patient: " + patDS.getString(Tags.PatientID) + " with " + origPatDS.getString(Tags.PatientID)); studyReconciliation.mergePatient(origPatDS, patDS, keepPriorPatientAfterMerge); numPatMerge++; } studyReconciliation.updateStudyAndSeries(studyIuid, successStatus, archiveStudy); } else { numFailures++; studyReconciliation.updateStatus(studyIuid, failureStatus); } } } finally { try { aa.release(true); } catch (Exception e) { log.warn( "Failed to release association " + aa.getAssociation(), e); } } StringBuffer sb = new StringBuffer(); sb.append(col.size()).append( " studies checked for Reconciliation!(updt:") .append(numPatUpdt); sb.append(";merged:").append(numPatMerge).append(";failed:").append( numFailures); sb.append(") in ").append(System.currentTimeMillis() - start).append( " ms"); return sb.toString(); } finally { isRunning = false; } } /** * @param ds1 * @param ds2 * @param tag * @return */ private boolean compare(Dataset ds1, Dataset ds2, int tag) { String s1 = ds1.getString(tag); String s2 = ds2.getString(tag); if (log.isDebugEnabled()) log.debug("compare '" + s1 + "'=?'" + s2 + "'"); return s1 == null ? s2 == null : s1.equals(s2); } /** * @return */ private Dataset getSeriesQueryDS() { Dataset qrDS = dof.newDataset(); qrDS.putCS(Tags.QueryRetrieveLevel, "SERIES"); qrDS.putUI(Tags.SeriesInstanceUID); qrDS.putLO(Tags.PatientID); qrDS.putPN(Tags.IssuerOfPatientID); qrDS.putPN(Tags.PatientName); qrDS.putPN(Tags.PatientBirthDate); qrDS.putPN(Tags.PatientSex); for (int i = 0; i < UPDATE_ATTRIBUTES.length; i++) { if (!qrDS.contains(UPDATE_ATTRIBUTES[i])) qrDS.putXX(UPDATE_ATTRIBUTES[i]); } return qrDS; } private Dataset getInstanceQueryDS() { Dataset qrDS = dof.newDataset(); qrDS.putCS(Tags.QueryRetrieveLevel, "IMAGE"); qrDS.putUI(Tags.SOPInstanceUID); return qrDS; } /** * @param string * @return * @throws IOException * @throws InterruptedException */ private Map query(ActiveAssociation aassoc, Dataset keys, int tag) throws InterruptedException, IOException { if (aassoc == null) { throw new IllegalStateException("No Association established"); } Command rqCmd = dof.newCommand(); rqCmd.initCFindRQ(aassoc.getAssociation().nextMsgID(), UIDs.StudyRootQueryRetrieveInformationModelFIND, priority); Dimse findRq = af.newDimse(PCID_FIND, rqCmd, keys); FutureRSP future = aassoc.invoke(findRq); Dimse findRsp = future.get(); List findRspList = future.listPending(); String iuid; Dataset ds; Map map = new HashMap(findRspList.size()); for (int i = 0, len = findRspList.size(); i < len; i++) { ds = ((Dimse) findRspList.get(i)).getDataset(); iuid = ds.getString(tag); removeEmptyUpdateAttributes(ds); if (map.put(iuid, ds) != null) { throw new IllegalArgumentException( "C-FIND contains two items with same uid (" + Tags.toString(tag) + ") ! :" + iuid); } } return map; } /** * @param ds */ private void removeEmptyUpdateAttributes(Dataset ds) { String value; for (int i = 0; i < UPDATE_ATTRIBUTES.length; i++) { value = ds.getString(UPDATE_ATTRIBUTES[i]); if (value == null || value.length() < 1) { log.info("remove empty update attribute:" + UPDATE_ATTRIBUTES[i]); ds.remove(UPDATE_ATTRIBUTES[i]); } } } /** * @param qrSeriesDS * @param archiveStudy * @param aa * @throws SQLException * @throws IOException * @throws InterruptedException */ private Dataset checkStudy(Dataset qrSeriesDS, Dataset qrInstanceDS, Map archiveStudy, ActiveAssociation aa) throws Exception { QueryCmd queryCmd = QueryCmd.create(qrSeriesDS, null, false, false, false, false, null); Map map = new HashMap(); try { queryCmd.setFetchSize(fetchSize).execute(); Dataset ds = null; String seriesIUID = null; while (queryCmd.next()) { try { ds = queryCmd.getDataset(); seriesIUID = ds.getString(Tags.SeriesInstanceUID); if (archiveStudy.get(seriesIUID) == null) { log .warn("Study Reconciliation failed! Series " + seriesIUID + " not available at reference FIND SCP! study:" + qrSeriesDS .getString(Tags.StudyInstanceUID)); return null; } if (map.put(seriesIUID, ds) != null) { log .error("Local result contains two series with same iuid! :" + seriesIUID); return null; } } catch (Exception x) { log.error("Study Reconciliation failed! (study:" + qrSeriesDS.getString(Tags.StudyInstanceUID) + ")! Internal error:" + x.getMessage(), x); return null; } } if (archiveStudy.size() != map.size()) { log .warn("Study Reconciliation failed! Number of Series mismatch! study:" + qrSeriesDS.getString(Tags.StudyInstanceUID)); return null; } boolean checked = true; qrInstanceDS.putUI(Tags.StudyInstanceUID, qrSeriesDS .getString(Tags.StudyInstanceUID)); for (Iterator iter = archiveStudy.keySet().iterator(); iter .hasNext() && checked;) { qrInstanceDS .putUI(Tags.SeriesInstanceUID, (String) iter.next()); checked = checkSeries(qrInstanceDS, aa); } return checked ? ds : null; } finally { queryCmd.close(); } } /** * @param map * @param qrInstanceDS * @param aa * @return * @throws IOException * @throws InterruptedException * @throws SQLException */ private boolean checkSeries(Dataset qrInstanceDS, ActiveAssociation aa) throws Exception { Map archiveSeries = query(aa, qrInstanceDS, Tags.SOPInstanceUID); QueryCmd queryCmd = QueryCmd.create(qrInstanceDS, null, false, false, false, false, null); try { queryCmd.execute(); Dataset ds; String iuid = null; Map map = new HashMap(); while (queryCmd.next()) { try { ds = queryCmd.getDataset(); iuid = ds.getString(Tags.SOPInstanceUID); if (archiveSeries.get(iuid) == null) { log .warn("Study Reconciliation failed! Instance " + iuid + " not available at reference FIND SCP! study:" + qrInstanceDS .getString(Tags.StudyInstanceUID) + " series:" + qrInstanceDS .getString(Tags.SeriesInstanceUID)); return false; } if (map.put(iuid, ds) != null) { log .error("Local result contains two instances with same iuid! :" + iuid); return false; } } catch (Exception x) { log.error("Study Reconciliation failed! (Series IUID:" + qrInstanceDS.getString(Tags.SeriesInstanceUID) + ")! Internal error:" + x.getMessage(), x); return false; } } if (archiveSeries.size() != map.size()) { log .warn("Study Reconciliation failed! Number of Instances mismatch! study:" + qrInstanceDS.getString(Tags.StudyInstanceUID) + " series:" + qrInstanceDS .getString(Tags.SeriesInstanceUID)); return false; } } finally { queryCmd.close(); } return true; } public String reschedule() throws RemoteException, FinderException, DcmServiceException { StudyReconciliation studyReconciliation = newStudyReconciliation(); Timestamp createdBefore = new Timestamp(System.currentTimeMillis()); int total = 0; Collection col; while (true) { col = studyReconciliation.getStudyIuidsWithStatus(failureStatus, createdBefore, limitNumberOfStudiesPerTask); if (col.isEmpty()) break; studyReconciliation.updateStatus(col, scheduledStatus); total += col.size(); } return total + " studies rescheduled for Reconciliation!"; } private boolean isDisabled(int hour) { if (disabledEndHour == -1) return false; boolean sameday = disabledStartHour <= disabledEndHour; boolean inside = hour >= disabledStartHour && hour < disabledEndHour; return sameday ? inside : !inside; } protected void startService() throws Exception { listenerID = scheduler.startScheduler(timerIDCheckStudyReconciliation, taskInterval, updateCheckListener); } protected void stopService() throws Exception { scheduler.stopScheduler(timerIDCheckStudyReconciliation, listenerID, updateCheckListener); super.stopService(); } private StudyReconciliation newStudyReconciliation() { try { StudyReconciliationHome home = (StudyReconciliationHome) EJBHomeFactory .getFactory().lookup(StudyReconciliationHome.class, StudyReconciliationHome.JNDI_NAME); return home.create(); } catch (Exception e) { throw new RuntimeException( "Failed to access Study Reconciliation SessionBean:", e); } } public String getTimerIDCheckStudyReconciliation() { return timerIDCheckStudyReconciliation; } public void setTimerIDCheckStudyReconciliation( String timerIDCheckStudyReconciliation) { this.timerIDCheckStudyReconciliation = timerIDCheckStudyReconciliation; } }
{ "content_hash": "fa134df9e820f08504db6e95d388b932", "timestamp": "", "source": "github", "line_count": 607, "max_line_length": 107, "avg_line_length": 37.47611202635915, "alnum_prop": 0.5444874274661509, "repo_name": "medicayun/medicayundicom", "id": "48dab08f39de606da6cbddfb19ed65a24ebcdd52", "size": "24630", "binary": false, "copies": "15", "ref": "refs/heads/master", "path": "dcm4jboss-all/tags/DCM4CHEE_2_18_3/dcm4jboss-sar/src/java/org/dcm4chex/archive/mbean/StudyReconciliationService.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.zstack.test.deployer.schema; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import java.util.ArrayList; import java.util.List; /** * <p>Java class for L2NetworkUnion complex type. * <p> * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;complexType name="L2NetworkUnion"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="l2NoVlanNetwork" type="{http://zstack.org/schema/zstack}L2NoVlanNetworkConfig" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="l2VlanNetwork" type="{http://zstack.org/schema/zstack}L2VlanNetworkConfig" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "L2NetworkUnion", propOrder = { "l2NoVlanNetwork", "l2VlanNetwork" }) public class L2NetworkUnion { protected List<L2NoVlanNetworkConfig> l2NoVlanNetwork; protected List<L2VlanNetworkConfig> l2VlanNetwork; /** * Gets the value of the l2NoVlanNetwork property. * <p> * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the l2NoVlanNetwork property. * <p> * <p> * For example, to add a new item, do as follows: * <pre> * getL2NoVlanNetwork().add(newItem); * </pre> * <p> * <p> * <p> * Objects of the following type(s) are allowed in the list * {@link L2NoVlanNetworkConfig } */ public List<L2NoVlanNetworkConfig> getL2NoVlanNetwork() { if (l2NoVlanNetwork == null) { l2NoVlanNetwork = new ArrayList<L2NoVlanNetworkConfig>(); } return this.l2NoVlanNetwork; } /** * Gets the value of the l2VlanNetwork property. * <p> * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the l2VlanNetwork property. * <p> * <p> * For example, to add a new item, do as follows: * <pre> * getL2VlanNetwork().add(newItem); * </pre> * <p> * <p> * <p> * Objects of the following type(s) are allowed in the list * {@link L2VlanNetworkConfig } */ public List<L2VlanNetworkConfig> getL2VlanNetwork() { if (l2VlanNetwork == null) { l2VlanNetwork = new ArrayList<L2VlanNetworkConfig>(); } return this.l2VlanNetwork; } }
{ "content_hash": "24a8ceafd125e5c219a89bbcb293cbd7", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 145, "avg_line_length": 32.70652173913044, "alnum_prop": 0.6467264872050515, "repo_name": "AlanJinTS/zstack", "id": "3aa27ae11018f8f3f7e38cf2d57ef3eaaa061029", "size": "3009", "binary": false, "copies": "16", "ref": "refs/heads/master", "path": "test/src/test/java/org/zstack/test/deployer/schema/L2NetworkUnion.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "59340" }, { "name": "Batchfile", "bytes": "1132" }, { "name": "Groovy", "bytes": "3029828" }, { "name": "Java", "bytes": "16304308" }, { "name": "Python", "bytes": "1055353" }, { "name": "Shell", "bytes": "155960" } ], "symlink_target": "" }
// Sets up common environment for Shay Green's libraries. // To change configuration options, modify blargg_config.h, not this file. // $package #ifndef BLARGG_COMMON_H #define BLARGG_COMMON_H #include <stdlib.h> #include <assert.h> #include <limits.h> typedef const char* blargg_err_t; // 0 on success, otherwise error string // Success; no error blargg_err_t const blargg_ok = 0; // BLARGG_RESTRICT: equivalent to C99's restrict, where supported #if __GNUC__ >= 3 || _MSC_VER >= 1100 #define BLARGG_RESTRICT __restrict #else #define BLARGG_RESTRICT #endif #if __cplusplus >= 199711 #define BLARGG_MUTABLE mutable #else #define BLARGG_MUTABLE #endif /* BLARGG_4CHAR('a','b','c','d') = 'abcd' (four character integer constant). I don't just use 'abcd' because that's implementation-dependent. */ #define BLARGG_4CHAR( a, b, c, d ) \ ((a&0xFF)*0x1000000 + (b&0xFF)*0x10000 + (c&0xFF)*0x100 + (d&0xFF)) /* BLARGG_STATIC_ASSERT( expr ): Generates compile error if expr is 0. Can be used at file, function, or class scope. */ #ifdef _MSC_VER // MSVC6 (_MSC_VER < 1300) __LINE__ fails when /Zl is specified #define BLARGG_STATIC_ASSERT( expr ) \ void blargg_failed_( int (*arg) [2 / (int) !!(expr) - 1] ) #else // Others fail when declaring same function multiple times in class, // so differentiate them by line #define BLARGG_STATIC_ASSERT( expr ) \ void blargg_failed_( int (*arg) [2 / !!(expr) - 1] [__LINE__] ) #endif /* Pure virtual functions cause a vtable entry to a "called pure virtual" error handler, requiring linkage to the C++ runtime library. This macro is used in place of the "= 0", and simply expands to its argument. During development, it expands to "= 0", allowing detection of missing overrides. */ #define BLARGG_PURE( def ) def /* My code depends on ASCII anywhere a character or string constant is compared with data read from a file, and anywhere file data is read and treated as a string. */ #if '\n'!=0x0A || ' '!=0x20 || '0'!=0x30 || 'A'!=0x41 || 'a'!=0x61 #error "ASCII character set required" #endif /* My code depends on int being at least 32 bits. Almost everything these days uses at least 32-bit ints, so it's hard to even find a system with 16-bit ints to test with. The issue can't be gotten around by using a suitable blargg_int everywhere either, because int is often converted to implicitly when doing arithmetic on smaller types. */ #if UINT_MAX < 0xFFFFFFFF #error "int must be at least 32 bits" #endif // In case compiler doesn't support these properly. Used rarely. #define STATIC_CAST(T,expr) static_cast<T> (expr) #define CONST_CAST( T,expr) const_cast<T> (expr) // User configuration can override the above macros if necessary #include "blargg_config.h" #ifdef BLARGG_NAMESPACE #define BLARGG_NAMESPACE_BEGIN namespace BLARGG_NAMESPACE { #define BLARGG_NAMESPACE_END } BLARGG_NAMESPACE_BEGIN BLARGG_NAMESPACE_END using namespace BLARGG_NAMESPACE; #else #define BLARGG_NAMESPACE_BEGIN #define BLARGG_NAMESPACE_END #endif BLARGG_NAMESPACE_BEGIN /* BLARGG_DEPRECATED [_TEXT] for any declarations/text to be removed in a future version. In GCC, we can let the compiler warn. In other compilers, we strip it out unless BLARGG_LEGACY is true. */ #if BLARGG_LEGACY // Allow old client code to work without warnings #define BLARGG_DEPRECATED_TEXT( text ) text #define BLARGG_DEPRECATED( text ) text #elif __GNUC__ >= 4 // In GCC, we can mark declarations and let the compiler warn #define BLARGG_DEPRECATED_TEXT( text ) text #define BLARGG_DEPRECATED( text ) __attribute__ ((deprecated)) text #else // By default, deprecated items are removed, to avoid use in new code #define BLARGG_DEPRECATED_TEXT( text ) #define BLARGG_DEPRECATED( text ) #endif /* BOOST::int8_t, BOOST::int32_t, etc. I used BOOST since I originally was going to allow use of the boost library for prividing the definitions. If I'm defining them, they must be scoped or else they could conflict with the standard ones at global scope. Even if HAVE_STDINT_H isn't defined, I can't assume the typedefs won't exist at global scope already. */ #if defined (HAVE_STDINT_H) || \ UCHAR_MAX != 0xFF || USHRT_MAX != 0xFFFF || UINT_MAX != 0xFFFFFFFF #include <stdint.h> #define BOOST #else struct BOOST { typedef signed char int8_t; typedef unsigned char uint8_t; typedef short int16_t; typedef unsigned short uint16_t; typedef int int32_t; typedef unsigned int uint32_t; typedef __int64 int64_t; typedef unsigned __int64 uint64_t; }; #endif /* My code is not written with exceptions in mind, so either uses new (nothrow) OR overrides operator new in my classes. The former is best since clients creating objects will get standard exceptions on failure, but that causes it to require the standard C++ library. So, when the client is using the C interface, I override operator new to use malloc. */ // BLARGG_DISABLE_NOTHROW is put inside classes #ifndef BLARGG_DISABLE_NOTHROW // throw spec mandatory in ISO C++ if NULL can be returned #if __cplusplus >= 199711 || __GNUC__ >= 3 || _MSC_VER >= 1300 #define BLARGG_THROWS_NOTHING throw () #else #define BLARGG_THROWS_NOTHING #endif #define BLARGG_DISABLE_NOTHROW \ void* operator new ( size_t s ) BLARGG_THROWS_NOTHING { return malloc( s ); }\ void operator delete( void* p ) BLARGG_THROWS_NOTHING { free( p ); } #define BLARGG_NEW new #else // BLARGG_NEW is used in place of new in library code #include <new> #define BLARGG_NEW new (std::nothrow) #endif class blargg_vector_ { protected: void* begin_; size_t size_; void init(); blargg_err_t resize_( size_t n, size_t elem_size ); public: size_t size() const { return size_; } void clear(); }; // Very lightweight vector for POD types (no constructor/destructor) template<class T> class blargg_vector : public blargg_vector_ { union T_must_be_pod { T t; }; // fails if T is not POD public: blargg_vector() { init(); } ~blargg_vector() { clear(); } blargg_err_t resize( size_t n ) { return resize_( n, sizeof (T) ); } T* begin() { return static_cast<T*> (begin_); } const T* begin() const { return static_cast<T*> (begin_); } T* end() { return static_cast<T*> (begin_) + size_; } const T* end() const { return static_cast<T*> (begin_) + size_; } T& operator [] ( size_t n ) { assert( n < size_ ); return static_cast<T*> (begin_) [n]; } const T& operator [] ( size_t n ) const { assert( n < size_ ); return static_cast<T*> (begin_) [n]; } }; // Callback function with user data. // blargg_callback<T> set_callback; // for user, this acts like... // void set_callback( T func, void* user_data = NULL ); // ...this // To call function, do set_callback.f( .. set_callback.data ... ); template<class T> struct blargg_callback { T f; void* data; blargg_callback() { f = NULL; } void operator () ( T callback, void* user_data = NULL ) { f = callback; data = user_data; } }; #ifndef _WIN32 // Not supported on any other platforms #undef BLARGG_UTF8_PATHS #endif BLARGG_DEPRECATED( typedef signed int blargg_long; ) BLARGG_DEPRECATED( typedef unsigned int blargg_ulong; ) #if BLARGG_LEGACY #define BOOST_STATIC_ASSERT BLARGG_STATIC_ASSERT #endif #ifdef _WIN32 typedef wchar_t blargg_wchar_t; #elif defined(HAVE_STDINT_H) #include <stdint.h> typedef uint16_t blargg_wchar_t; #else typedef unsigned short blargg_wchar_t; #endif inline size_t blargg_wcslen( const blargg_wchar_t* str ) { size_t length = 0; while ( *str++ ) length++; return length; } char* blargg_to_utf8( const blargg_wchar_t* ); blargg_wchar_t* blargg_to_wide( const char* ); BLARGG_NAMESPACE_END #endif
{ "content_hash": "c4a28b5547db4e3b5878a8bc8bb0f520", "timestamp": "", "source": "github", "line_count": 243, "max_line_length": 92, "avg_line_length": 31.85185185185185, "alnum_prop": 0.6928940568475452, "repo_name": "onnerby/musikcube", "id": "79fd28b2990cf1fc77c56a4229c61072536ace07", "size": "7740", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/plugins/gmedecoder/gme/blargg_common.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "1025" }, { "name": "C", "bytes": "3983072" }, { "name": "C++", "bytes": "4635120" }, { "name": "CMake", "bytes": "56752" }, { "name": "CSS", "bytes": "9169" }, { "name": "HTML", "bytes": "1512" }, { "name": "M4", "bytes": "7003" }, { "name": "Makefile", "bytes": "150277" }, { "name": "Objective-C", "bytes": "86364" }, { "name": "Perl", "bytes": "3982" }, { "name": "Shell", "bytes": "219091" }, { "name": "XSLT", "bytes": "12276" } ], "symlink_target": "" }
Imports System Imports System.Reflection Imports 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. ' Review the values of the assembly attributes <Assembly: AssemblyTitle("MuntuGUI")> <Assembly: AssemblyDescription("A modern Graphical User Interface by Raisy Leone")> <Assembly: AssemblyCompany("RAISY")> <Assembly: AssemblyProduct("LIBGUI")> <Assembly: AssemblyCopyright("Copyright © RAISY 2017")> <Assembly: AssemblyTrademark("Muntu GUI")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("56d60438-3116-4798-a0ae-8610db712bf4")> ' 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": "83f6c35d790dabd620fab18594aac6d5", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 84, "avg_line_length": 35.17142857142857, "alnum_prop": 0.7303005686433793, "repo_name": "RaisyClutch/Beautiful-GUI-Controls-vb.net-c-Muntu", "id": "004d2b99b8300925ed68c4226e6a4947e4dddef4", "size": "1234", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "My Project/AssemblyInfo.vb", "mode": "33188", "license": "mit", "language": [ { "name": "Visual Basic", "bytes": "370186" } ], "symlink_target": "" }
/* * LoadMenu.cpp * * Created on: 2014-3-26 * Author: toms1 */ #include "LoadMenu.h" USING_NS_CC; CCScene* LoadMenu::scene() { // 'scene' is an autorelease object CCScene *scene = CCScene::create(); // 'layer' is an autorelease object LoadMenu *layer = LoadMenu::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } bool LoadMenu::init() { ////////////////////////////// // 1. super init first if (!CCLayer::init()) { return false; } CCSize winSize = CCDirector::sharedDirector()->getWinSizeInPixels(); //»ñµÃÆÁÄ»³ß´ç£¬ÕâÀïÒª»­¸öºÍÆÁÄ»µÈ´óµÄ¾²Ì¬±³¾° CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize(); CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin(); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object CCMenuItemImage *pCloseItem = CCMenuItemImage::create("Close.png", "Closeed.png", this, menu_selector(LoadMenu::menuCloseCallback)); pCloseItem->setPosition( ccp(origin.x + visibleSize.width - pCloseItem->getContentSize().width/2 -10 , origin.y + pCloseItem->getContentSize().height/2 + 10)); CCDictionary *strings = CCDictionary::createWithContentsOfFile( "stringscn.xml"); //¶ÁÈ¡Hello¼üÖеÄÖµ objectForKey¸ù¾Ýkey£¬»ñÈ¡¶ÔÓ¦µÄstring const char *menuTitle = ((CCString*) strings->objectForKey("MenuTitle"))->m_sString.c_str(); CCLabelTTF *label = CCLabelTTF::create(menuTitle, "Arial", 63); label->setPosition( ccp(visibleSize.width/2,visibleSize.height-label->getContentSize().height)); this->addChild(label); CCMenuItemImage* item1 = CCMenuItemImage::create("btn-play-normal.png", "btn-play-selected.png", this, menu_selector(LoadMenu::menuCallback)); CCMenuItemImage* item2 = CCMenuItemImage::create( "btn-highscores-normal.png", "btn-highscores-selected.png", this, menu_selector(LoadMenu::menuCallbackHighScores)); CCMenuItemImage* item3 = CCMenuItemImage::create("btn-about-normal.png", "btn-about-selected.png", this, menu_selector(LoadMenu::menuCallbackAbout)); item1->setPosition( ccp(visibleSize.width/2,visibleSize.height-item1->getContentSize().height*5)); item2->setPosition( ccp(visibleSize.width/2,visibleSize.height-item1->getContentSize().height*9)); item3->setPosition( ccp(visibleSize.width/2,visibleSize.height-item1->getContentSize().height*13)); item1->setScaleX(3.0f); item2->setScaleX(3.0f); item3->setScaleX(3.0f); item1->setScaleY(3.0f); item2->setScaleY(3.0f); item3->setScaleY(3.0f); // create menu, it's an autorelease object CCMenu* pMenu = CCMenu::create(pCloseItem,item1,item2,item3, NULL); pMenu->setPosition(CCPointZero); this->addChild(pMenu, 1); return true; } void LoadMenu::menuCallback(CCObject* pSender) { CCDirector* pDirector = CCDirector::sharedDirector(); CCScene *pScene = HelloWorld::scene(); pDirector->replaceScene(CCTransitionFade::create(2, pScene)); //pScene->release(); } void LoadMenu::menuCallbackHighScores(CCObject* pSender){ } void LoadMenu::menuCallbackAbout(CCObject* pSender){ } void LoadMenu::menuCloseCallback(CCObject* pSender) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) CCMessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert"); #else CCDirector::sharedDirector()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); #endif #endif }
{ "content_hash": "c3eedeba3efe701716a712e5a9c95bd6", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 116, "avg_line_length": 31.58407079646018, "alnum_prop": 0.711123564023536, "repo_name": "zaowei21/linktoy", "id": "e42e7d38a4e9f00f00fb1fad98552946ae2fcee1", "size": "3569", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Classes/LoadMenu.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "23668" }, { "name": "D", "bytes": "5063509" }, { "name": "Java", "bytes": "2499" }, { "name": "Shell", "bytes": "1543" } ], "symlink_target": "" }
""" The :mod:`sklearn.feature_extraction.text` submodule gathers utilities to build feature vectors from text documents. """ from __future__ import unicode_literals import array from collections import Mapping, defaultdict import numbers from operator import itemgetter import re import unicodedata import numpy as np import scipy.sparse as sp from ..base import BaseEstimator, TransformerMixin from ..externals.six.moves import xrange from ..preprocessing import normalize from .hashing import FeatureHasher from .stop_words import ENGLISH_STOP_WORDS from sklearn.externals import six __all__ = ['CountVectorizer', 'ENGLISH_STOP_WORDS', 'TfidfTransformer', 'TfidfVectorizer', 'strip_accents_ascii', 'strip_accents_unicode', 'strip_tags'] def strip_accents_unicode(s): """Transform accentuated unicode symbols into their simple counterpart Warning: the python-level loop and join operations make this implementation 20 times slower than the strip_accents_ascii basic normalization. See also -------- strip_accents_ascii Remove accentuated char for any unicode symbol that has a direct ASCII equivalent. """ return ''.join([c for c in unicodedata.normalize('NFKD', s) if not unicodedata.combining(c)]) def strip_accents_ascii(s): """Transform accentuated unicode symbols into ascii or nothing Warning: this solution is only suited for languages that have a direct transliteration to ASCII symbols. See also -------- strip_accents_unicode Remove accentuated char for any unicode symbol. """ nkfd_form = unicodedata.normalize('NFKD', s) return nkfd_form.encode('ASCII', 'ignore').decode('ASCII') def strip_tags(s): """Basic regexp based HTML / XML tag stripper function For serious HTML/XML preprocessing you should rather use an external library such as lxml or BeautifulSoup. """ return re.compile(r"<([^>]+)>", flags=re.UNICODE).sub(" ", s) def _check_stop_list(stop): if stop == "english": return ENGLISH_STOP_WORDS elif isinstance(stop, six.string_types): raise ValueError("not a built-in stop list: %s" % stop) else: # assume it's a collection return stop class VectorizerMixin(object): """Provides common code for text vectorizers (tokenization logic).""" _white_spaces = re.compile(r"\s\s+") def decode(self, doc): """Decode the input into a string of unicode symbols The decoding strategy depends on the vectorizer parameters. """ if self.input == 'filename': with open(doc, 'rb') as fh: doc = fh.read() elif self.input == 'file': doc = doc.read() if isinstance(doc, bytes): doc = doc.decode(self.encoding, self.decode_error) if doc is np.nan: raise ValueError("np.nan is an invalid document, expected byte or " "unicode string.") return doc def _word_ngrams(self, tokens, stop_words=None): """Turn tokens into a sequence of n-grams after stop words filtering""" # handle stop words if stop_words is not None: tokens = [w for w in tokens if w not in stop_words] # handle token n-grams min_n, max_n = self.ngram_range if max_n != 1: original_tokens = tokens tokens = [] n_original_tokens = len(original_tokens) for n in xrange(min_n, min(max_n + 1, n_original_tokens + 1)): for i in xrange(n_original_tokens - n + 1): tokens.append(" ".join(original_tokens[i: i + n])) return tokens def _char_ngrams(self, text_document): """Tokenize text_document into a sequence of character n-grams""" # normalize white spaces text_document = self._white_spaces.sub(" ", text_document) text_len = len(text_document) ngrams = [] min_n, max_n = self.ngram_range for n in xrange(min_n, min(max_n + 1, text_len + 1)): for i in xrange(text_len - n + 1): ngrams.append(text_document[i: i + n]) return ngrams def _char_wb_ngrams(self, text_document): """Whitespace sensitive char-n-gram tokenization. Tokenize text_document into a sequence of character n-grams excluding any whitespace (operating only inside word boundaries)""" # normalize white spaces text_document = self._white_spaces.sub(" ", text_document) min_n, max_n = self.ngram_range ngrams = [] for w in text_document.split(): w = ' ' + w + ' ' w_len = len(w) for n in xrange(min_n, max_n + 1): offset = 0 ngrams.append(w[offset:offset + n]) while offset + n < w_len: offset += 1 ngrams.append(w[offset:offset + n]) if offset == 0: # count a short word (w_len < n) only once break return ngrams def build_preprocessor(self): """Return a function to preprocess the text before tokenization""" if self.preprocessor is not None: return self.preprocessor # unfortunately python functools package does not have an efficient # `compose` function that would have allowed us to chain a dynamic # number of functions. However the cost of a lambda call is a few # hundreds of nanoseconds which is negligible when compared to the # cost of tokenizing a string of 1000 chars for instance. noop = lambda x: x # accent stripping if not self.strip_accents: strip_accents = noop elif callable(self.strip_accents): strip_accents = self.strip_accents elif self.strip_accents == 'ascii': strip_accents = strip_accents_ascii elif self.strip_accents == 'unicode': strip_accents = strip_accents_unicode else: raise ValueError('Invalid value for "strip_accents": %s' % self.strip_accents) if self.lowercase: return lambda x: strip_accents(x.lower()) else: return strip_accents def build_tokenizer(self): """Return a function that splits a string into a sequence of tokens""" if self.tokenizer is not None: return self.tokenizer token_pattern = re.compile(self.token_pattern) return lambda doc: token_pattern.findall(doc) def get_stop_words(self): """Build or fetch the effective stop words list""" return _check_stop_list(self.stop_words) def build_analyzer(self): """Return a callable that handles preprocessing and tokenization""" if callable(self.analyzer): return self.analyzer preprocess = self.build_preprocessor() if self.analyzer == 'char': return lambda doc: self._char_ngrams(preprocess(self.decode(doc))) elif self.analyzer == 'char_wb': return lambda doc: self._char_wb_ngrams( preprocess(self.decode(doc))) elif self.analyzer == 'word': stop_words = self.get_stop_words() tokenize = self.build_tokenizer() return lambda doc: self._word_ngrams( tokenize(preprocess(self.decode(doc))), stop_words) else: raise ValueError('%s is not a valid tokenization scheme/analyzer' % self.analyzer) class HashingVectorizer(BaseEstimator, VectorizerMixin): """Convert a collection of text documents to a matrix of token occurrences It turns a collection of text documents into a scipy.sparse matrix holding token occurrence counts (or binary occurrence information), possibly normalized as token frequencies if norm='l1' or projected on the euclidean unit sphere if norm='l2'. This text vectorizer implementation uses the hashing trick to find the token string name to feature integer index mapping. This strategy has several advantages: - it is very low memory scalable to large datasets as there is no need to store a vocabulary dictionary in memory - it is fast to pickle and un-pickle as it holds no state besides the constructor parameters - it can be used in a streaming (partial fit) or parallel pipeline as there is no state computed during fit. There are also a couple of cons (vs using a CountVectorizer with an in-memory vocabulary): - there is no way to compute the inverse transform (from feature indices to string feature names) which can be a problem when trying to introspect which features are most important to a model. - there can be collisions: distinct tokens can be mapped to the same feature index. However in practice this is rarely an issue if n_features is large enough (e.g. 2 ** 18 for text classification problems). - no IDF weighting as this would render the transformer stateful. The hash function employed is the signed 32-bit version of Murmurhash3. Parameters ---------- input: string {'filename', 'file', 'content'} If 'filename', the sequence passed as an argument to fit is expected to be a list of filenames that need reading to fetch the raw content to analyze. If 'file', the sequence items must have a 'read' method (file-like object) that is called to fetch the bytes in memory. Otherwise the input is expected to be the sequence strings or bytes items are expected to be analyzed directly. encoding : string, 'utf-8' by default. If bytes or files are given to analyze, this encoding is used to decode. decode_error : {'strict', 'ignore', 'replace'} Instruction on what to do if a byte sequence is given to analyze that contains characters not of the given `encoding`. By default, it is 'strict', meaning that a UnicodeDecodeError will be raised. Other values are 'ignore' and 'replace'. strip_accents: {'ascii', 'unicode', None} Remove accents during the preprocessing step. 'ascii' is a fast method that only works on characters that have an direct ASCII mapping. 'unicode' is a slightly slower method that works on any characters. None (default) does nothing. analyzer: string, {'word', 'char', 'char_wb'} or callable Whether the feature should be made of word or character n-grams. Option 'char_wb' creates character n-grams only from text inside word boundaries. If a callable is passed it is used to extract the sequence of features out of the raw, unprocessed input. preprocessor: callable or None (default) Override the preprocessing (string transformation) stage while preserving the tokenizing and n-grams generation steps. tokenizer: callable or None (default) Override the string tokenization step while preserving the preprocessing and n-grams generation steps. ngram_range: tuple (min_n, max_n) The lower and upper boundary of the range of n-values for different n-grams to be extracted. All values of n such that min_n <= n <= max_n will be used. stop_words: string {'english'}, list, or None (default) If a string, it is passed to _check_stop_list and the appropriate stop list is returned. 'english' is currently the only supported string value. If a list, that list is assumed to contain stop words, all of which will be removed from the resulting tokens. lowercase: boolean, default True Convert all characters to lowercase before tokenizing. token_pattern: string Regular expression denoting what constitutes a "token", only used if `analyzer == 'word'`. The default regexp selects tokens of 2 or more alphanumeric characters (punctuation is completely ignored and always treated as a token separator). n_features : integer, optional, (2 ** 20) by default The number of features (columns) in the output matrices. Small numbers of features are likely to cause hash collisions, but large numbers will cause larger coefficient dimensions in linear learners. norm : 'l1', 'l2' or None, optional Norm used to normalize term vectors. None for no normalization. binary: boolean, False by default. If True, all non zero counts are set to 1. This is useful for discrete probabilistic models that model binary events rather than integer counts. dtype: type, optional Type of the matrix returned by fit_transform() or transform(). non_negative : boolean, optional Whether output matrices should contain non-negative values only; effectively calls abs on the matrix prior to returning it. When True, output values can be interpreted as frequencies. When False, output values will have expected value zero. See also -------- CountVectorizer, TfidfVectorizer """ def __init__(self, input='content', encoding='utf-8', decode_error='strict', strip_accents=None, lowercase=True, preprocessor=None, tokenizer=None, stop_words=None, token_pattern=r"(?u)\b\w\w+\b", ngram_range=(1, 1), analyzer='word', n_features=(2 ** 20), binary=False, norm='l2', non_negative=False, dtype=np.float64): self.input = input self.encoding = encoding self.decode_error = decode_error self.strip_accents = strip_accents self.preprocessor = preprocessor self.tokenizer = tokenizer self.analyzer = analyzer self.lowercase = lowercase self.token_pattern = token_pattern self.stop_words = stop_words self.n_features = n_features self.ngram_range = ngram_range self.binary = binary self.norm = norm self.non_negative = non_negative self.dtype = dtype def partial_fit(self, X, y=None): """Does nothing: this transformer is stateless. This method is just there to mark the fact that this transformer can work in a streaming setup. """ return self def fit(self, X, y=None): """Does nothing: this transformer is stateless.""" # triggers a parameter validation self._get_hasher().fit(X, y=y) return self def transform(self, X, y=None): """Transform a sequence of documents to a document-term matrix. Parameters ---------- X : iterable over raw text documents, length = n_samples Samples. Each sample must be a text document (either bytes or unicode strings, file name or file object depending on the constructor argument) which will be tokenized and hashed. y : (ignored) Returns ------- X : scipy.sparse matrix, shape = (n_samples, self.n_features) Document-term matrix. """ analyzer = self.build_analyzer() X = self._get_hasher().transform(analyzer(doc) for doc in X) if self.binary: X.data.fill(1) if self.norm is not None: X = normalize(X, norm=self.norm, copy=False) return X # Alias transform to fit_transform for convenience fit_transform = transform def _get_hasher(self): return FeatureHasher(n_features=self.n_features, input_type='string', dtype=self.dtype, non_negative=self.non_negative) def _document_frequency(X): """Count the number of non-zero values for each feature in sparse X.""" if sp.isspmatrix_csr(X): return np.bincount(X.indices, minlength=X.shape[1]) else: return np.diff(sp.csc_matrix(X, copy=False).indptr) class CountVectorizer(BaseEstimator, VectorizerMixin): """Convert a collection of text documents to a matrix of token counts This implementation produces a sparse representation of the counts using scipy.sparse.coo_matrix. If you do not provide an a-priori dictionary and you do not use an analyzer that does some kind of feature selection then the number of features will be equal to the vocabulary size found by analyzing the data. Parameters ---------- input : string {'filename', 'file', 'content'} If 'filename', the sequence passed as an argument to fit is expected to be a list of filenames that need reading to fetch the raw content to analyze. If 'file', the sequence items must have a 'read' method (file-like object) that is called to fetch the bytes in memory. Otherwise the input is expected to be the sequence strings or bytes items are expected to be analyzed directly. encoding : string, 'utf-8' by default. If bytes or files are given to analyze, this encoding is used to decode. decode_error : {'strict', 'ignore', 'replace'} Instruction on what to do if a byte sequence is given to analyze that contains characters not of the given `encoding`. By default, it is 'strict', meaning that a UnicodeDecodeError will be raised. Other values are 'ignore' and 'replace'. strip_accents : {'ascii', 'unicode', None} Remove accents during the preprocessing step. 'ascii' is a fast method that only works on characters that have an direct ASCII mapping. 'unicode' is a slightly slower method that works on any characters. None (default) does nothing. analyzer : string, {'word', 'char', 'char_wb'} or callable Whether the feature should be made of word or character n-grams. Option 'char_wb' creates character n-grams only from text inside word boundaries. If a callable is passed it is used to extract the sequence of features out of the raw, unprocessed input. preprocessor : callable or None (default) Override the preprocessing (string transformation) stage while preserving the tokenizing and n-grams generation steps. tokenizer : callable or None (default) Override the string tokenization step while preserving the preprocessing and n-grams generation steps. ngram_range : tuple (min_n, max_n) The lower and upper boundary of the range of n-values for different n-grams to be extracted. All values of n such that min_n <= n <= max_n will be used. stop_words : string {'english'}, list, or None (default) If a string, it is passed to _check_stop_list and the appropriate stop list is returned. 'english' is currently the only supported string value. If a list, that list is assumed to contain stop words, all of which will be removed from the resulting tokens. If None, no stop words will be used. max_df can be set to a value in the range [0.7, 1.0) to automatically detect and filter stop words based on intra corpus document frequency of terms. lowercase : boolean, True by default Convert all characters to lowercase before tokenizing. token_pattern : string Regular expression denoting what constitutes a "token", only used if `tokenize == 'word'`. The default regexp select tokens of 2 or more alphanumeric characters (punctuation is completely ignored and always treated as a token separator). max_df : float in range [0.0, 1.0] or int, optional, 1.0 by default When building the vocabulary ignore terms that have a document frequency strictly higher than the given threshold (corpus-specific stop words). If float, the parameter represents a proportion of documents, integer absolute counts. This parameter is ignored if vocabulary is not None. min_df : float in range [0.0, 1.0] or int, optional, 1 by default When building the vocabulary ignore terms that have a document frequency strictly lower than the given threshold. This value is also called cut-off in the literature. If float, the parameter represents a proportion of documents, integer absolute counts. This parameter is ignored if vocabulary is not None. max_features : optional, None by default If not None, build a vocabulary that only consider the top max_features ordered by term frequency across the corpus. This parameter is ignored if vocabulary is not None. vocabulary : Mapping or iterable, optional Either a Mapping (e.g., a dict) where keys are terms and values are indices in the feature matrix, or an iterable over terms. If not given, a vocabulary is determined from the input documents. Indices in the mapping should not be repeated and should not have any gap between 0 and the largest index. binary : boolean, False by default. If True, all non zero counts are set to 1. This is useful for discrete probabilistic models that model binary events rather than integer counts. dtype : type, optional Type of the matrix returned by fit_transform() or transform(). Attributes ---------- vocabulary_ : dict A mapping of terms to feature indices. stop_words_ : set Terms that were ignored because they occurred in either too many (`max_df`) or in too few (`min_df`) documents. This is only available if no vocabulary was given. See also -------- HashingVectorizer, TfidfVectorizer """ def __init__(self, input='content', encoding='utf-8', decode_error='strict', strip_accents=None, lowercase=True, preprocessor=None, tokenizer=None, stop_words=None, token_pattern=r"(?u)\b\w\w+\b", ngram_range=(1, 1), analyzer='word', max_df=1.0, min_df=1, max_features=None, vocabulary=None, binary=False, dtype=np.int64): self.input = input self.encoding = encoding self.decode_error = decode_error self.strip_accents = strip_accents self.preprocessor = preprocessor self.tokenizer = tokenizer self.analyzer = analyzer self.lowercase = lowercase self.token_pattern = token_pattern self.stop_words = stop_words self.max_df = max_df self.min_df = min_df if max_df < 0 or min_df < 0: raise ValueError("negative value for max_df of min_df") self.max_features = max_features if max_features is not None: if (not isinstance(max_features, numbers.Integral) or max_features <= 0): raise ValueError( "max_features=%r, neither a positive integer nor None" % max_features) self.ngram_range = ngram_range if vocabulary is not None: if not isinstance(vocabulary, Mapping): vocab = {} for i, t in enumerate(vocabulary): if vocab.setdefault(t, i) != i: msg = "Duplicate term in vocabulary: %r" % t raise ValueError(msg) vocabulary = vocab else: indices = set(six.itervalues(vocabulary)) if len(indices) != len(vocabulary): raise ValueError("Vocabulary contains repeated indices.") for i in xrange(len(vocabulary)): if i not in indices: msg = ("Vocabulary of size %d doesn't contain index " "%d." % (len(vocabulary), i)) raise ValueError(msg) if not vocabulary: raise ValueError("empty vocabulary passed to fit") self.fixed_vocabulary = True self.vocabulary_ = dict(vocabulary) else: self.fixed_vocabulary = False self.binary = binary self.dtype = dtype def _sort_features(self, X, vocabulary): """Sort features by name Returns a reordered matrix and modifies the vocabulary in place """ sorted_features = sorted(six.iteritems(vocabulary)) map_index = np.empty(len(sorted_features), dtype=np.int32) for new_val, (term, old_val) in enumerate(sorted_features): map_index[new_val] = old_val vocabulary[term] = new_val return X[:, map_index] def _limit_features(self, X, vocabulary, high=None, low=None, limit=None): """Remove too rare or too common features. Prune features that are non zero in more samples than high or less documents than low, modifying the vocabulary, and restricting it to at most the limit most frequent. This does not prune samples with zero features. """ if high is None and low is None and limit is None: return X, set() # Calculate a mask based on document frequencies dfs = _document_frequency(X) tfs = np.asarray(X.sum(axis=0)).ravel() mask = np.ones(len(dfs), dtype=bool) if high is not None: mask &= dfs <= high if low is not None: mask &= dfs >= low if limit is not None and mask.sum() > limit: mask_inds = (-tfs[mask]).argsort()[:limit] new_mask = np.zeros(len(dfs), dtype=bool) new_mask[np.where(mask)[0][mask_inds]] = True mask = new_mask new_indices = np.cumsum(mask) - 1 # maps old indices to new removed_terms = set() for term, old_index in list(six.iteritems(vocabulary)): if mask[old_index]: vocabulary[term] = new_indices[old_index] else: del vocabulary[term] removed_terms.add(term) kept_indices = np.where(mask)[0] if len(kept_indices) == 0: raise ValueError("After pruning, no terms remain. Try a lower" " min_df or a higher max_df.") return X[:, kept_indices], removed_terms def _count_vocab(self, raw_documents, fixed_vocab): """Create sparse feature matrix, and vocabulary where fixed_vocab=False """ if fixed_vocab: vocabulary = self.vocabulary_ else: # Add a new value when a new vocabulary item is seen vocabulary = defaultdict() vocabulary.default_factory = vocabulary.__len__ analyze = self.build_analyzer() j_indices = _make_int_array() indptr = _make_int_array() indptr.append(0) for doc in raw_documents: for feature in analyze(doc): try: j_indices.append(vocabulary[feature]) except KeyError: # Ignore out-of-vocabulary items for fixed_vocab=True continue indptr.append(len(j_indices)) if not fixed_vocab: # disable defaultdict behaviour vocabulary = dict(vocabulary) if not vocabulary: raise ValueError("empty vocabulary; perhaps the documents only" " contain stop words") # some Python/Scipy versions won't accept an array.array: if j_indices: j_indices = np.frombuffer(j_indices, dtype=np.intc) else: j_indices = np.array([], dtype=np.int32) indptr = np.frombuffer(indptr, dtype=np.intc) values = np.ones(len(j_indices)) X = sp.csr_matrix((values, j_indices, indptr), shape=(len(indptr) - 1, len(vocabulary)), dtype=self.dtype) X.sum_duplicates() return vocabulary, X def fit(self, raw_documents, y=None): """Learn a vocabulary dictionary of all tokens in the raw documents. Parameters ---------- raw_documents : iterable An iterable which yields either str, unicode or file objects. Returns ------- self """ self.fit_transform(raw_documents) return self def fit_transform(self, raw_documents, y=None): """Learn the vocabulary dictionary and return term-document matrix. This is equivalent to fit followed by transform, but more efficiently implemented. Parameters ---------- raw_documents : iterable An iterable which yields either str, unicode or file objects. Returns ------- X : array, [n_samples, n_features] Document-term matrix. """ # We intentionally don't call the transform method to make # fit_transform overridable without unwanted side effects in # TfidfVectorizer. max_df = self.max_df min_df = self.min_df max_features = self.max_features vocabulary, X = self._count_vocab(raw_documents, self.fixed_vocabulary) if self.binary: X.data.fill(1) if not self.fixed_vocabulary: X = self._sort_features(X, vocabulary) n_doc = X.shape[0] max_doc_count = (max_df if isinstance(max_df, numbers.Integral) else max_df * n_doc) min_doc_count = (min_df if isinstance(min_df, numbers.Integral) else min_df * n_doc) if max_doc_count < min_doc_count: raise ValueError( "max_df corresponds to < documents than min_df") X, self.stop_words_ = self._limit_features(X, vocabulary, max_doc_count, min_doc_count, max_features) self.vocabulary_ = vocabulary return X def transform(self, raw_documents): """Transform documents to document-term matrix. Extract token counts out of raw text documents using the vocabulary fitted with fit or the one provided to the constructor. Parameters ---------- raw_documents : iterable An iterable which yields either str, unicode or file objects. Returns ------- X : sparse matrix, [n_samples, n_features] Document-term matrix. """ if not hasattr(self, 'vocabulary_') or len(self.vocabulary_) == 0: raise ValueError("Vocabulary wasn't fitted or is empty!") # use the same matrix-building strategy as fit_transform _, X = self._count_vocab(raw_documents, fixed_vocab=True) if self.binary: X.data.fill(1) return X def inverse_transform(self, X): """Return terms per document with nonzero entries in X. Parameters ---------- X : {array, sparse matrix}, shape = [n_samples, n_features] Returns ------- X_inv : list of arrays, len = n_samples List of arrays of terms. """ if sp.issparse(X): # We need CSR format for fast row manipulations. X = X.tocsr() else: # We need to convert X to a matrix, so that the indexing # returns 2D objects X = np.asmatrix(X) n_samples = X.shape[0] terms = np.array(list(self.vocabulary_.keys())) indices = np.array(list(self.vocabulary_.values())) inverse_vocabulary = terms[np.argsort(indices)] return [inverse_vocabulary[X[i, :].nonzero()[1]].ravel() for i in range(n_samples)] def get_feature_names(self): """Array mapping from feature integer indices to feature name""" if not hasattr(self, 'vocabulary_') or len(self.vocabulary_) == 0: raise ValueError("Vocabulary wasn't fitted or is empty!") return [t for t, i in sorted(six.iteritems(self.vocabulary_), key=itemgetter(1))] def _make_int_array(): """Construct an array.array of a type suitable for scipy.sparse indices.""" return array.array(str("i")) class TfidfTransformer(BaseEstimator, TransformerMixin): """Transform a count matrix to a normalized tf or tf-idf representation Tf means term-frequency while tf-idf means term-frequency times inverse document-frequency. This is a common term weighting scheme in information retrieval, that has also found good use in document classification. The goal of using tf-idf instead of the raw frequencies of occurrence of a token in a given document is to scale down the impact of tokens that occur very frequently in a given corpus and that are hence empirically less informative than features that occur in a small fraction of the training corpus. The actual formula used for tf-idf is tf * (idf + 1) = tf + tf * idf, instead of tf * idf. The effect of this is that terms with zero idf, i.e. that occur in all documents of a training set, will not be entirely ignored. The formulas used to compute tf and idf depend on parameter settings that correspond to the SMART notation used in IR, as follows: Tf is "n" (natural) by default, "l" (logarithmic) when sublinear_tf=True. Idf is "t" when use_idf is given, "n" (none) otherwise. Normalization is "c" (cosine) when norm='l2', "n" (none) when norm=None. Parameters ---------- norm : 'l1', 'l2' or None, optional Norm used to normalize term vectors. None for no normalization. use_idf : boolean, optional Enable inverse-document-frequency reweighting. smooth_idf : boolean, optional Smooth idf weights by adding one to document frequencies, as if an extra document was seen containing every term in the collection exactly once. Prevents zero divisions. sublinear_tf : boolean, optional Apply sublinear tf scaling, i.e. replace tf with 1 + log(tf). References ---------- .. [Yates2011] `R. Baeza-Yates and B. Ribeiro-Neto (2011). Modern Information Retrieval. Addison Wesley, pp. 68-74.` .. [MRS2008] `C.D. Manning, P. Raghavan and H. Schuetze (2008). Introduction to Information Retrieval. Cambridge University Press, pp. 118-120.` """ def __init__(self, norm='l2', use_idf=True, smooth_idf=True, sublinear_tf=False): self.norm = norm self.use_idf = use_idf self.smooth_idf = smooth_idf self.sublinear_tf = sublinear_tf def fit(self, X, y=None): """Learn the idf vector (global term weights) Parameters ---------- X : sparse matrix, [n_samples, n_features] a matrix of term/token counts """ if not sp.issparse(X): X = sp.csc_matrix(X) if self.use_idf: n_samples, n_features = X.shape df = _document_frequency(X) # perform idf smoothing if required df += int(self.smooth_idf) n_samples += int(self.smooth_idf) # log1p instead of log makes sure terms with zero idf don't get # suppressed entirely idf = np.log(float(n_samples) / df) + 1.0 self._idf_diag = sp.spdiags(idf, diags=0, m=n_features, n=n_features) return self def transform(self, X, copy=True): """Transform a count matrix to a tf or tf-idf representation Parameters ---------- X : sparse matrix, [n_samples, n_features] a matrix of term/token counts Returns ------- vectors : sparse matrix, [n_samples, n_features] """ if hasattr(X, 'dtype') and np.issubdtype(X.dtype, np.float): # preserve float family dtype X = sp.csr_matrix(X, copy=copy) else: # convert counts or binary occurrences to floats X = sp.csr_matrix(X, dtype=np.float64, copy=copy) n_samples, n_features = X.shape if self.sublinear_tf: np.log(X.data, X.data) X.data += 1 if self.use_idf: if not hasattr(self, "_idf_diag"): raise ValueError("idf vector not fitted") expected_n_features = self._idf_diag.shape[0] if n_features != expected_n_features: raise ValueError("Input has n_features=%d while the model" " has been trained with n_features=%d" % ( n_features, expected_n_features)) # *= doesn't work X = X * self._idf_diag if self.norm: X = normalize(X, norm=self.norm, copy=False) return X @property def idf_(self): if hasattr(self, "_idf_diag"): return np.ravel(self._idf_diag.sum(axis=0)) else: return None class TfidfVectorizer(CountVectorizer): """Convert a collection of raw documents to a matrix of TF-IDF features. Equivalent to CountVectorizer followed by TfidfTransformer. Parameters ---------- input : string {'filename', 'file', 'content'} If 'filename', the sequence passed as an argument to fit is expected to be a list of filenames that need reading to fetch the raw content to analyze. If 'file', the sequence items must have a 'read' method (file-like object) that is called to fetch the bytes in memory. Otherwise the input is expected to be the sequence strings or bytes items are expected to be analyzed directly. encoding : string, 'utf-8' by default. If bytes or files are given to analyze, this encoding is used to decode. decode_error : {'strict', 'ignore', 'replace'} Instruction on what to do if a byte sequence is given to analyze that contains characters not of the given `encoding`. By default, it is 'strict', meaning that a UnicodeDecodeError will be raised. Other values are 'ignore' and 'replace'. strip_accents : {'ascii', 'unicode', None} Remove accents during the preprocessing step. 'ascii' is a fast method that only works on characters that have an direct ASCII mapping. 'unicode' is a slightly slower method that works on any characters. None (default) does nothing. analyzer : string, {'word', 'char'} or callable Whether the feature should be made of word or character n-grams. If a callable is passed it is used to extract the sequence of features out of the raw, unprocessed input. preprocessor : callable or None (default) Override the preprocessing (string transformation) stage while preserving the tokenizing and n-grams generation steps. tokenizer : callable or None (default) Override the string tokenization step while preserving the preprocessing and n-grams generation steps. ngram_range : tuple (min_n, max_n) The lower and upper boundary of the range of n-values for different n-grams to be extracted. All values of n such that min_n <= n <= max_n will be used. stop_words : string {'english'}, list, or None (default) If a string, it is passed to _check_stop_list and the appropriate stop list is returned. 'english' is currently the only supported string value. If a list, that list is assumed to contain stop words, all of which will be removed from the resulting tokens. If None, no stop words will be used. max_df can be set to a value in the range [0.7, 1.0) to automatically detect and filter stop words based on intra corpus document frequency of terms. lowercase : boolean, default True Convert all characters to lowercase before tokenizing. token_pattern : string Regular expression denoting what constitutes a "token", only used if `analyzer == 'word'`. The default regexp selects tokens of 2 or more alphanumeric characters (punctuation is completely ignored and always treated as a token separator). max_df : float in range [0.0, 1.0] or int, optional, 1.0 by default When building the vocabulary ignore terms that have a term frequency strictly higher than the given threshold (corpus specific stop words). If float, the parameter represents a proportion of documents, integer absolute counts. This parameter is ignored if vocabulary is not None. min_df : float in range [0.0, 1.0] or int, optional, 1 by default When building the vocabulary ignore terms that have a term frequency strictly lower than the given threshold. This value is also called cut-off in the literature. If float, the parameter represents a proportion of documents, integer absolute counts. This parameter is ignored if vocabulary is not None. max_features : optional, None by default If not None, build a vocabulary that only consider the top max_features ordered by term frequency across the corpus. This parameter is ignored if vocabulary is not None. vocabulary : Mapping or iterable, optional Either a Mapping (e.g., a dict) where keys are terms and values are indices in the feature matrix, or an iterable over terms. If not given, a vocabulary is determined from the input documents. binary : boolean, False by default. If True, all non-zero term counts are set to 1. This does not mean outputs will have only 0/1 values, only that the tf term in tf-idf is binary. (Set idf and normalization to False to get 0/1 outputs.) dtype : type, optional Type of the matrix returned by fit_transform() or transform(). norm : 'l1', 'l2' or None, optional Norm used to normalize term vectors. None for no normalization. use_idf : boolean, optional Enable inverse-document-frequency reweighting. smooth_idf : boolean, optional Smooth idf weights by adding one to document frequencies, as if an extra document was seen containing every term in the collection exactly once. Prevents zero divisions. sublinear_tf : boolean, optional Apply sublinear tf scaling, i.e. replace tf with 1 + log(tf). Attributes ---------- idf_ : array, shape = [n_features], or None The learned idf vector (global term weights) when ``use_idf`` is set to True, None otherwise. See also -------- CountVectorizer Tokenize the documents and count the occurrences of token and return them as a sparse matrix TfidfTransformer Apply Term Frequency Inverse Document Frequency normalization to a sparse matrix of occurrence counts. """ def __init__(self, input='content', encoding='utf-8', decode_error='strict', strip_accents=None, lowercase=True, preprocessor=None, tokenizer=None, analyzer='word', stop_words=None, token_pattern=r"(?u)\b\w\w+\b", ngram_range=(1, 1), max_df=1.0, min_df=1, max_features=None, vocabulary=None, binary=False, dtype=np.int64, norm='l2', use_idf=True, smooth_idf=True, sublinear_tf=False): super(TfidfVectorizer, self).__init__( input=input, encoding=encoding, decode_error=decode_error, strip_accents=strip_accents, lowercase=lowercase, preprocessor=preprocessor, tokenizer=tokenizer, analyzer=analyzer, stop_words=stop_words, token_pattern=token_pattern, ngram_range=ngram_range, max_df=max_df, min_df=min_df, max_features=max_features, vocabulary=vocabulary, binary=binary, dtype=dtype) self._tfidf = TfidfTransformer(norm=norm, use_idf=use_idf, smooth_idf=smooth_idf, sublinear_tf=sublinear_tf) # Broadcast the TF-IDF parameters to the underlying transformer instance # for easy grid search and repr @property def norm(self): return self._tfidf.norm @norm.setter def norm(self, value): self._tfidf.norm = value @property def use_idf(self): return self._tfidf.use_idf @use_idf.setter def use_idf(self, value): self._tfidf.use_idf = value @property def smooth_idf(self): return self._tfidf.smooth_idf @smooth_idf.setter def smooth_idf(self, value): self._tfidf.smooth_idf = value @property def sublinear_tf(self): return self._tfidf.sublinear_tf @sublinear_tf.setter def sublinear_tf(self, value): self._tfidf.sublinear_tf = value @property def idf_(self): return self._tfidf.idf_ def fit(self, raw_documents, y=None): """Learn vocabulary and idf from training set. Parameters ---------- raw_documents : iterable an iterable which yields either str, unicode or file objects Returns ------- self : TfidfVectorizer """ X = super(TfidfVectorizer, self).fit_transform(raw_documents) self._tfidf.fit(X) return self def fit_transform(self, raw_documents, y=None): """Learn vocabulary and idf, return term-document matrix. This is equivalent to fit followed by transform, but more efficiently implemented. Parameters ---------- raw_documents : iterable an iterable which yields either str, unicode or file objects Returns ------- X : sparse matrix, [n_samples, n_features] Tf-idf-weighted document-term matrix. """ X = super(TfidfVectorizer, self).fit_transform(raw_documents) self._tfidf.fit(X) # X is already a transformed view of raw_documents so # we set copy to False return self._tfidf.transform(X, copy=False) def transform(self, raw_documents, copy=True): """Transform documents to document-term matrix. Uses the vocabulary and document frequencies (df) learned by fit (or fit_transform). Parameters ---------- raw_documents : iterable an iterable which yields either str, unicode or file objects Returns ------- X : sparse matrix, [n_samples, n_features] Tf-idf-weighted document-term matrix. """ X = super(TfidfVectorizer, self).transform(raw_documents) return self._tfidf.transform(X, copy=False)
{ "content_hash": "6e55c7317190b2e2e0444240f304b4c3", "timestamp": "", "source": "github", "line_count": 1254, "max_line_length": 79, "avg_line_length": 37.91866028708134, "alnum_prop": 0.6154574132492113, "repo_name": "RPGOne/Skynet", "id": "d5590f06040672f581c38aec49ba5e6220c0b20a", "size": "47905", "binary": false, "copies": "2", "ref": "refs/heads/Miho", "path": "scikit-learn-c604ac39ad0e5b066d964df3e8f31ba7ebda1e0e/sklearn/feature_extraction/text.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "1C Enterprise", "bytes": "36" }, { "name": "Ada", "bytes": "89079" }, { "name": "Assembly", "bytes": "11425802" }, { "name": "Batchfile", "bytes": "123467" }, { "name": "C", "bytes": "34703955" }, { "name": "C#", "bytes": "55955" }, { "name": "C++", "bytes": "84647314" }, { "name": "CMake", "bytes": "220849" }, { "name": "CSS", "bytes": "39257" }, { "name": "Cuda", "bytes": "1344541" }, { "name": "DIGITAL Command Language", "bytes": "349320" }, { "name": "DTrace", "bytes": "37428" }, { "name": "Emacs Lisp", "bytes": "19654" }, { "name": "Erlang", "bytes": "39438" }, { "name": "Fortran", "bytes": "16914" }, { "name": "HTML", "bytes": "929759" }, { "name": "Java", "bytes": "112658" }, { "name": "JavaScript", "bytes": "32806873" }, { "name": "Jupyter Notebook", "bytes": "1616334" }, { "name": "Lua", "bytes": "22549" }, { "name": "M4", "bytes": "64967" }, { "name": "Makefile", "bytes": "1046428" }, { "name": "Matlab", "bytes": "888" }, { "name": "Module Management System", "bytes": "1545" }, { "name": "NSIS", "bytes": "2860" }, { "name": "Objective-C", "bytes": "131433" }, { "name": "PHP", "bytes": "750783" }, { "name": "Pascal", "bytes": "75208" }, { "name": "Perl", "bytes": "626627" }, { "name": "Perl 6", "bytes": "2495926" }, { "name": "PowerShell", "bytes": "38374" }, { "name": "Prolog", "bytes": "300018" }, { "name": "Python", "bytes": "26363074" }, { "name": "R", "bytes": "236175" }, { "name": "Rebol", "bytes": "217" }, { "name": "Roff", "bytes": "328366" }, { "name": "SAS", "bytes": "1847" }, { "name": "Scala", "bytes": "248902" }, { "name": "Scheme", "bytes": "14853" }, { "name": "Shell", "bytes": "360815" }, { "name": "TeX", "bytes": "105346" }, { "name": "Vim script", "bytes": "6101" }, { "name": "XS", "bytes": "4319" }, { "name": "eC", "bytes": "5158" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Copyright 2005-2015 The Kuali Foundation Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php 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. --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="ConfigurationTestView-Quickfinder-Page" parent="Uif-Page" p:headerText="Quickfinders"> <property name="items"> <list> <ref bean="ConfigurationTestView-Quickfinder-Section1"/> <ref bean="ConfigurationTestView-Suggest"/> </list> </property> </bean> <bean id="ConfigurationTestView-Quickfinder-Section1" parent="Uif-Disclosure-VerticalBoxSection" p:layoutManager.orientation="VERTICAL"> <property name="headerText" value="Quickfinders"/> <property name="instructionalText" value="Quickfinders on same view with different lookup configurations"/> <property name="items"> <list> <bean parent="GenericTextField" p:label="Lookup" p:instructionalText="TravelAccounts lookup (account number should be read only)" p:propertyName="field60"> <property name="quickfinder"> <bean parent="Uif-QuickFinder" p:dataObjectClassName="edu.sampleu.travel.bo.TravelAccount" p:fieldConversions="number:field60" p:readOnlyLookupFields="number"/> </property> </bean> <bean parent="GenericTextField" p:label="Lookup" p:instructionalText="TravelAccounts lookup (account number should NOT be read only)" p:propertyName="field90"> <property name="quickfinder"> <bean parent="Uif-QuickFinder" p:dataObjectClassName="edu.sampleu.travel.bo.TravelAccount" p:fieldConversions="number:field90"/> </property> </bean> </list> </property> </bean> <bean id="ConfigurationTestView-Suggest" parent="Uif-Disclosure-VerticalBoxSection"> <property name="headerText" value="Suggest Widgets"/> <property name="instructionalText" value="Various configurations for the suggest widget"/> <property name="items"> <list> <bean parent="Uif-InputField" p:label="Suggest" p:instructionalText="auto-query configuration, type a1 or a2 for suggestions" p:propertyName="field61"> <property name="suggest"> <bean parent="Uif-Suggest" p:render="true" p:valuePropertyName="number" p:suggestQuery.dataObjectClassName="edu.sampleu.travel.bo.TravelAccount"/> </property> </bean> <bean parent="Uif-InputField" p:label="Suggest 2" p:instructionalText="view helper method configuration, type a1 or a2 for suggestions" p:propertyName="field62"> <property name="suggest"> <bean parent="Uif-Suggest" p:render="true" p:valuePropertyName="number"> <property name="suggestQuery"> <bean parent="Uif-AttributeQueryConfig" p:queryMethodToCall="retrieveTravelAccounts"/> </property> </bean> </property> </bean> <bean parent="Uif-HorizontalFieldGroup" p:label="Suggest 3" p:group.instructionalText="view helper method with additional arguments, subaccount is used in query"> <property name="items"> <list> <bean parent="Uif-InputField" p:label="Sub-Account" p:instructionalText="type a6-sub" p:propertyName="field63"/> <bean parent="Uif-InputField" p:label="Account" p:instructionalText="type a for suggestions" p:propertyName="field64"> <property name="suggest"> <bean parent="Uif-Suggest" p:render="true" p:valuePropertyName="number"> <property name="suggestQuery"> <bean parent="Uif-AttributeQueryConfig" p:queryMethodToCall="retrieveTravelAccountsBySubAcctAndTerm" p:queryMethodArgumentFieldList="field63"/> </property> <property name="templateOptions"> <map merge="true"> <entry key="minLength" value="1"/> </map> </property> </bean> </property> </bean> </list> </property> </bean> <bean parent="Uif-InputField" p:label="Suggest 4" p:instructionalText="static method and query result suggestions option, type a or c for suggestions" p:propertyName="field65"> <property name="suggest"> <bean parent="Uif-Suggest" p:render="true"> <property name="suggestQuery"> <bean parent="Uif-AttributeQueryConfig" p:queryMethodInvokerConfig.staticMethod= "edu.sampleu.demo.TestSuggestClass.getLanguages"/> </property> <property name="templateOptions"> <map merge="true"> <entry key="minLength" value="0"/> </map> </property> </bean> </property> </bean> <bean parent="Uif-InputField" p:label="Suggest 5" p:instructionalText="service method and sorting configuration, type sub for suggestions" p:propertyName="field66"> <property name="suggest"> <bean parent="Uif-Suggest" p:render="true" p:valuePropertyName="subAccountName"> <property name="suggestQuery"> <bean parent="Uif-AttributeQueryConfig" p:queryMethodToCall="retrieveTravelAccounts" p:sortPropertyNames="subAccountName"> <property name="queryMethodInvokerConfig.targetObject"> <bean class="org.kuali.rice.core.framework.resourceloader.GlobalResourceLoaderServiceFactoryBean"> <property name="serviceName" value="testSuggestService"/> </bean> </property> </bean> </property> </bean> </property> </bean> <bean parent="Uif-InputField" p:label="Suggest 6" p:instructionalText="local suggest options, press arrow down for all options or type c" p:propertyName="field67"> <property name="suggest"> <bean parent="Uif-Suggest" p:render="true" p:retrieveAllSuggestions="true"> <property name="suggestQuery"> <bean parent="Uif-AttributeQueryConfig" p:queryMethodInvokerConfig.staticMethod= "edu.sampleu.demo.TestSuggestClass.getAllLanguages"/> </property> <property name="templateOptions"> <map> <entry key="minLength" value="0"/> <entry key="delay" value="0"/> </map> </property> </bean> </property> </bean> <bean parent="Uif-InputField" p:label="Suggest 7" p:instructionalText="rich suggest options, press arrow down for all options or type r" p:propertyName="field68"> <property name="suggest"> <bean parent="Uif-Suggest" p:render="true" p:retrieveAllSuggestions="true"> <property name="suggestQuery"> <bean parent="Uif-AttributeQueryConfig" p:queryMethodInvokerConfig.staticMethod= "edu.sampleu.demo.TestSuggestClass.getRichOptions"/> </property> <property name="templateOptions"> <map> <entry key="minLength" value="0"/> <entry key="delay" value="0"/> <entry key="html" value="true"/> </map> </property> </bean> </property> </bean> <bean parent="Uif-InputField" p:label="Location Suggest" p:instructionalText="type google, kuali, jira - navigates on selection" p:propertyName="field61"> <property name="suggest"> <bean parent="Uif-LocationSuggest" p:render="true" p:retrieveAllSuggestions="true"> <property name="suggestQuery"> <bean parent="Uif-AttributeQueryConfig" p:queryMethodInvokerConfig.staticMethod= "edu.sampleu.demo.TestSuggestClass.getLocationOptions"/> </property> <property name="templateOptions"> <map> <entry key="minLength" value="0"/> <entry key="delay" value="0"/> </map> </property> </bean> </property> </bean> <bean parent="Uif-InputField" p:label="Location Suggest - Views" p:instructionalText="Pointing to same controller, each option provides a different view, type u, c, r" p:propertyName="field63"> <property name="suggest"> <bean parent="Uif-LocationSuggest" p:render="true" p:retrieveAllSuggestions="true" p:baseUrl="@{#ConfigProperties['krad.url']}/uicomponents"> <property name="additionalRequestParameters"> <map> <entry key="methodToCall" value="start"/> </map> </property> <property name="requestParameterPropertyNames"> <map> <entry key="viewId" value="id"/> </map> </property> <property name="suggestQuery"> <bean parent="Uif-AttributeQueryConfig" p:queryMethodInvokerConfig.staticMethod= "edu.sampleu.demo.TestSuggestClass.getViewOptions"/> </property> <property name="templateOptions"> <map> <entry key="minLength" value="0"/> <entry key="delay" value="0"/> <entry key="html" value="true"/> </map> </property> </bean> </property> </bean> <bean parent="Uif-InputField" p:label="Object Options" p:instructionalText="Retrieving a custom object using namePropertyName and labelPropertyName, enter anything" p:propertyName="field62"> <property name="suggest"> <bean parent="Uif-Suggest" p:render="true" p:returnFullQueryObject="true" p:labelPropertyName="name" p:valuePropertyName="val"> <property name="suggestQuery"> <bean parent="Uif-AttributeQueryConfig" p:queryMethodInvokerConfig.staticMethod= "edu.sampleu.demo.TestSuggestClass.getObjectOptions"/> </property> <property name="templateOptions"> <map> <entry key="minLength" value="0"/> <entry key="delay" value="0"/> <entry key="html" value="true"/> </map> </property> </bean> </property> </bean> <bean parent="Uif-InputField" p:label="Suggest 8" p:instructionalText="configured suggest options, press arrow down for all options or type c" p:propertyName="field69"> <property name="suggest"> <bean parent="Uif-Suggest" p:render="true" p:retrieveAllSuggestions="true"> <property name="suggestOptions"> <list> <value>ActionScript</value> <value>AppleScript</value> <value>Asp</value> <value>BASIC</value> <value>C</value> <value>C++</value> <value>Clojure</value> <value>COBOL</value> <value>ColdFusion</value> <value>Erlang</value> <value>Fortran</value> <value>Groovy</value> <value>Haskell</value> <value>Java</value> <value>JavaScript</value> <value>Lisp</value> <value>Perl</value> <value>PHP</value> <value>Python</value> <value>Ruby</value> <value>Scala</value> <value>Scheme</value> </list> </property> <property name="templateOptions"> <map> <entry key="minLength" value="0"/> <entry key="delay" value="0"/> </map> </property> </bean> </property> </bean> <bean parent="Uif-InputField" p:label="Suggest 9" p:instructionalText="custom selection (sets hidden, input, and info), press arrow down for all options or type c" p:propertyName="field70" p:additionalHiddenPropertyNames="field71" p:propertyNamesForAdditionalDisplay="field72"> <property name="suggest"> <bean parent="Uif-Suggest" p:render="true" p:retrieveAllSuggestions="true"> <property name="suggestQuery"> <bean parent="Uif-AttributeQueryConfig" p:queryMethodInvokerConfig.staticMethod= "edu.sampleu.demo.TestSuggestClass.getComplexOptions"/> </property> <property name="templateOptions"> <map> <entry key="minLength" value="0"/> <entry key="delay" value="0"/> <entry key="select"> <value> function( event, ui ) { jQuery( "input[name='field71']" ).val( ui.item.value ); jQuery( "input[name='field70']" ).val( ui.item.label ); jQuery( "span[id$='_info_field72']").html( ui.item.description ); return false; } </value> </entry> </map> </property> </bean> </property> </bean> </list> </property> </bean> </beans>
{ "content_hash": "ddce12591655814ab5973272929b6baf", "timestamp": "", "source": "github", "line_count": 337, "max_line_length": 127, "avg_line_length": 45.602373887240354, "alnum_prop": 0.5383914627798022, "repo_name": "bhutchinson/rice", "id": "e05e6b7e19c95fab26f87b6527238673d4e8377e", "size": "15368", "binary": false, "copies": "16", "ref": "refs/heads/master", "path": "rice-middleware/sampleapp/src/main/resources/edu/sampleu/demo/kitchensink/ConfigurationTestView-Quickfinder.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "578462" }, { "name": "Groovy", "bytes": "2247167" }, { "name": "HTML", "bytes": "3141277" }, { "name": "Java", "bytes": "36230588" }, { "name": "JavaScript", "bytes": "2676255" }, { "name": "PHP", "bytes": "12488" }, { "name": "PLSQL", "bytes": "322989" }, { "name": "SQLPL", "bytes": "32403" }, { "name": "Shell", "bytes": "13217" }, { "name": "XSLT", "bytes": "107818" } ], "symlink_target": "" }
CREATE TABLE category ( id BIGINT GENERATED BY DEFAULT AS IDENTITY, name varchar(255) not null, active boolean not null default true ); insert into category(id, name) values (1, 'Electronics'); insert into category(id, name) values (2, 'Books');
{ "content_hash": "134ae66feebdcdfe4f243d826946ebda", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 57, "avg_line_length": 31.125, "alnum_prop": 0.7429718875502008, "repo_name": "TW-Bootcamp/tradeaway-svc", "id": "0c6a438438e9bcf63ee77cf42364072e9b4a9038", "size": "250", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/resources/db/migration/h2/V3__category_setup.sql", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "79142" }, { "name": "Shell", "bytes": "84" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <mule xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:stdio="http://www.mulesoft.org/schema/mule/stdio" xmlns:vm="http://www.mulesoft.org/schema/mule/vm" xmlns:smooks="http://www.muleforge.org/smooks/schema/mule-module-smooks" xmlns:file="http://www.mulesoft.org/schema/mule/file" xsi:schemaLocation=" http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/3.1/mule.xsd http://www.mulesoft.org/schema/mule/stdio http://www.mulesoft.org/schema/mule/stdio/3.1/mule-stdio.xsd http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/3.1/mule-file.xsd http://www.mulesoft.org/schema/mule/vm http://www.mulesoft.org/schema/mule/vm/3.1/mule-vm.xsd http://www.muleforge.org/smooks/schema/mule-module-smooks http://dist.muleforge.org/smooks/schema/mule-module-smooks/1.3/mule-module-smooks.xsd" > <description> This example demonstrates transforming an XML message with the Smooks Transformer </description> <!-- Defines the Mule transformer configFile: Defines where the Smooks configuration is located resultType: Defines which result type is required. STRING is the default value. This property is just here for the illustration because it is so important in case when you need a different result type. reportPath: Defines that a execution report needs to be written. Take a look at the Smooks report. It shows how Smooks processes the message. Warning: Don't set this in a production environment. It costs a lot of performance! --> <smooks:transformer name="BasicXSLTTransformation" configFile="/transforms/smooks-config.xml" resultType="STRING" reportPath="target/smooks-report/report.html" /> <model name="BasicModel"> <service name="BasicService"> <inbound> <file:inbound-endpoint path="./data/in" pollingFrequency="1000" moveToDirectory="./data/out" transformer-refs="BasicXSLTTransformation" > <file:filename-wildcard-filter pattern="*.xml"/> </file:inbound-endpoint> <!-- For unit-test --> <vm:inbound-endpoint path="BasicProcessor" transformer-refs="BasicXSLTTransformation" exchange-pattern="request-response" /> </inbound> <outbound> <pass-through-router> <stdio:outbound-endpoint system="OUT" exchange-pattern="request-response" /> </pass-through-router> </outbound> </service> </model> </mule>
{ "content_hash": "4efe3a7edc842441ffad9792886093fe", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 146, "avg_line_length": 44.77777777777778, "alnum_prop": 0.6476426799007444, "repo_name": "muleforge/Smooks-for-Mule", "id": "0073812b0cfbeeed2ecafa39d9038280212c0009", "size": "2821", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mule3/examples/basic-transformation/src/main/app/mule-config.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "496297" }, { "name": "JavaScript", "bytes": "77744" }, { "name": "Shell", "bytes": "4400" } ], "symlink_target": "" }
Currently, Cray Chapel syntax highlighting and some basic snippets for Sublime Text editor. More snippets, and Chapel compiler (`chpl`) build scenarios could be easily added. PR's will be accepted, because I won't be working on this full time. The syntax description is taken from the now official @chapel-lang 's chapel-tmbundle (https://github.com/chapel-lang/chapel-tmbundle) which is keeping (only) the textmate syntax description up-to-date. Currently, this syntax description from https://github.com/chapel-lang/chapel-tmbundle/commit/8e8f4f6e8b4c2a126181ea64fb6f181650a97dac
{ "content_hash": "2bef3e51f340430416274a136dea4761", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 202, "avg_line_length": 73.25, "alnum_prop": 0.8088737201365188, "repo_name": "acrosby/sublimetext-chapel", "id": "15b9caf9453da020dbf50bb274243f854d65416b", "size": "607", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
module.exports = function (grunt) { // table for fany display of tasks var table = require('text-table'); // lodash for easier code var _ = require('lodash'); // get all tasks var tasks = grunt.config('tasks'); // get their keys var keys = Object.keys(tasks); // simple execution wrapper for a meta task, depending on the arguments var executeMetaTask = function executeMetaTask(target, param1, param2) { grunt.task.run('meta:' + target + (!!param1 ? ':' + param1 : '') + (!!param2 ? ':' + param2 : '')); }; // builds the tasklist to be executed var buildTasklist = function buildTasklist(tasks, target, targets, param1, options) { // empty array first, pretty simple var tasklist = []; // are there any defined pre-tasks? if(!!options && !!options.preTasks) { // yep, there are some - add them to the array first preTasks = _.map(options.preTasks, function(t) { return t + ':' + param1; }); tasklist.push.apply(tasklist, preTasks); } // is there no param? if(!param1) { // yep, are there any options? if (!options) { // nope, just get the tasks task = tasks[target]; } else { // yep, get the default task task = [[target,options.default].join(':')]; } // run the default task! grunt.log.writeln('[META] Running default task: ' + task); tasklist.push.apply(tasklist, task); } else { // there is a param! V needs to be documented V _.forEach(targets[param1], function(n, key) { if (typeof n === 'object' && n.length > 0) { for (var i = 0; i < n.length; i++) { targets[param1].splice(key + i, i === 0 ? 1 : 0, n[i]); } } }); if(typeof targets[param1] === 'string') { targets[param1] = [targets[param1]]; } // add them to the tasklist tasklist.push.apply(tasklist, targets[param1]); } // do we have any post-tasks? if(!!options && !!options.postTasks) { // we do, add them! postTasks = _.map(options.postTasks, function(t) { return t + ':' + param1; }); tasklist.push.apply(tasklist, postTasks); } // return the complete task list return tasklist; }; // part where the default tasks get registered - so that the user knows what to do (and grunt as well) for (var i = 0; i < keys.length; i++) { // check if there are any options per target if (typeof tasks[keys[i]] === 'object' && keys[i] !== 'options') { var currentKey = keys[i]; var subtasks = tasks[currentKey]; var subkeys = Object.keys(subtasks); if (currentKey === 'default') { // register the very default grunt task grunt.registerTask('default', subtasks); } else { // register the other tasks as an alias for this very meta task grunt.registerTask(currentKey, 'Alias for "meta:' + currentKey + '" task.', function(param1, param2) { executeMetaTask(this.name, param1, param2); }); } } } // finally register the meta task grunt.registerTask('meta', 'Takes care of the meta tasks and executes them correctly', function(target, param1, param2) { var task, tasklist = []; var options = tasks[target].options; var targets = _.omit(tasks[target], 'options'); // build the tasklist so this task knows what to do tasklist = buildTasklist(tasks, target, targets, param1, options); //... and do it! grunt.log.writeln('[META] Run those tasks:', tasklist); grunt.task.run(tasklist); }); // registers the fany tasklist task task task. task. grunt.registerTask('tasks', 'Shows a list of available tasks for use', function() { grunt.log.writeln('Available tasks:'); for (var i = 0; i < keys.length; i++) { // remove the option key, so that it doens't get mistaken for a target if (typeof tasks[keys[i]] !== 'object' || keys[i] === 'options') { continue; } var currentKey = keys[i]; var tableRows = []; var options = tasks[currentKey].options; var subtasks = options ? _.omit(tasks[currentKey], 'options') : tasks[currentKey]; grunt.log.writeln('- ' + currentKey + (subtasks.length ? ' [' + subtasks.join(', ') + ']':'')); for (var st = 0; st < Object.keys(subtasks).length; st++) { // remove the option key, so that it doens't get mistaken for a target if (subtasks.length || currentKey === 'options') { continue; } tasklist = buildTasklist(tasks, currentKey, subtasks, Object.keys(subtasks)[st], options); tableRows.push([' :' + Object.keys(subtasks)[st], '[' + tasklist.join(', ') + ']']); } grunt.log.writeln(table(tableRows, { align: ['l', 'l'] })); // actually doesn't much more than outputting a build tasklist - in a sexy table layout. } }); };
{ "content_hash": "6546a4bcee36567697906fe67103fc29", "timestamp": "", "source": "github", "line_count": 151, "max_line_length": 125, "avg_line_length": 36.90066225165563, "alnum_prop": 0.5213567839195979, "repo_name": "JPeer264/photomeet", "id": "3ada29ea9f55df431dd2c096ddea7b43f4e5ff75", "size": "5572", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "public/config/grunt/tasks/meta.js", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "412" }, { "name": "CSS", "bytes": "7871" }, { "name": "HTML", "bytes": "12059" }, { "name": "JavaScript", "bytes": "58700" }, { "name": "PHP", "bytes": "91656" } ], "symlink_target": "" }
title: MIMIC documentation linktitle: Docs description: > This website contains documentation for the MIMIC database. Multiple versions of MIMIC have been released over the years. This website includes information on versions II, III, and IV. cascade: - type: "docs" _target: path: "/**" menu: main: weight: 10 --- Some of the information applies across all versions of MIMIC. Information specific to a given version can be found under that version in the navigation to the left.
{ "content_hash": "c8c7fb7952c3513448da7fae647aecf0", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 187, "avg_line_length": 27.88888888888889, "alnum_prop": 0.7470119521912351, "repo_name": "MIT-LCP/mimic-website", "id": "b716a1e43acd64c26208f43abfefe6dc927ddef6", "size": "506", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "content/en/docs/_index.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "57516" }, { "name": "HTML", "bytes": "22858" }, { "name": "JavaScript", "bytes": "41633" }, { "name": "Python", "bytes": "2281" }, { "name": "SCSS", "bytes": "104" } ], "symlink_target": "" }
var ValueTransformer = function () { this.displayName = "Random Boolean value"; this.shortDescription = "Generate true values with 50% of chance."; this.isEditingDisabled = true; this.infoUrl = "https://github.com/SmartJSONEditor/PublicDocuments/wiki/ValueTransformer-RandomBoolean"; this.transform = function (inputValue, jsonValue, arrayIndex, parameters, info) { var chance = (Math.random() * 100); return (chance <= 50); }; } function sjeClass() { return new ValueTransformer(); }
{ "content_hash": "1d8f23238fdb31db66b1c137b8c062c1", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 108, "avg_line_length": 33.5, "alnum_prop": 0.6828358208955224, "repo_name": "SmartJSONEditor/PublicDocuments", "id": "c7aae172881299956c140c33e78e7c323b962bc3", "size": "536", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "JSON/ValueTransformer.randombool.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "7039" }, { "name": "JavaScript", "bytes": "1751540" } ], "symlink_target": "" }
package javax.swing.text; import java.text.BreakIterator; import java.text.CharacterIterator; import java.text.StringCharacterIterator; import java.util.Arrays; /** * A simple whitespace-based BreakIterator implementation. * * @author Sergey Groznyh */ class WhitespaceBasedBreakIterator extends BreakIterator { private char[] text = new char[0]; private int[] breaks = new int[] { 0 } ; private int pos = 0; /** * Calculate break positions eagerly parallel to reading text. */ public void setText(CharacterIterator ci) { int begin = ci.getBeginIndex(); text = new char[ci.getEndIndex() - begin]; int[] breaks0 = new int[text.length + 1]; int brIx = 0; breaks0[brIx++] = begin; int charIx = 0; boolean inWs = false; for (char c = ci.first(); c != CharacterIterator.DONE; c = ci.next()) { text[charIx] = c; boolean ws = Character.isWhitespace(c); if (inWs && !ws) { breaks0[brIx++] = charIx + begin; } inWs = ws; charIx++; } if (text.length > 0) { breaks0[brIx++] = text.length + begin; } System.arraycopy(breaks0, 0, breaks = new int[brIx], 0, brIx); } public CharacterIterator getText() { return new StringCharacterIterator(new String(text)); } public int first() { return breaks[pos = 0]; } public int last() { return breaks[pos = breaks.length - 1]; } public int current() { return breaks[pos]; } public int next() { return (pos == breaks.length - 1 ? DONE : breaks[++pos]); } public int previous() { return (pos == 0 ? DONE : breaks[--pos]); } public int next(int n) { return checkhit(pos + n); } public int following(int n) { return adjacent(n, 1); } public int preceding(int n) { return adjacent(n, -1); } private int checkhit(int hit) { if ((hit < 0) || (hit >= breaks.length)) { return DONE; } else { return breaks[pos = hit]; } } private int adjacent(int n, int bias) { int hit = Arrays.binarySearch(breaks, n); int offset = (hit < 0 ? (bias < 0 ? -1 : -2) : 0); return checkhit(Math.abs(hit) + bias + offset); } }
{ "content_hash": "2e62f631ff835320f2db42c30568d52c", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 79, "avg_line_length": 25.072916666666668, "alnum_prop": 0.5450768591607811, "repo_name": "Java8-CNAPI-Team/Java8CN", "id": "18965b9c50dc7d3d6ce3d798290718d5c3624d14", "size": "2616", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "javax/swing/text/WhitespaceBasedBreakIterator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "55246870" } ], "symlink_target": "" }
package io.netty.handler.codec.http.websocketx; import io.netty.buffer.Unpooled; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpHeaders.Names; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseDecoder; import io.netty.handler.codec.http.HttpResponseEncoder; import io.netty.handler.codec.http.LastHttpContent; import io.netty.util.CharsetUtil; import org.junit.Assert; import org.junit.Test; import static io.netty.handler.codec.http.HttpHeaders.Values.*; import static io.netty.handler.codec.http.HttpVersion.*; public class WebSocketServerHandshaker00Test { @Test public void testPerformOpeningHandshake() { testPerformOpeningHandshake0(true); } @Test public void testPerformOpeningHandshakeSubProtocolNotSupported() { testPerformOpeningHandshake0(false); } private static void testPerformOpeningHandshake0(boolean subProtocol) { EmbeddedChannel ch = new EmbeddedChannel( new HttpObjectAggregator(42), new HttpRequestDecoder(), new HttpResponseEncoder()); FullHttpRequest req = new DefaultFullHttpRequest( HTTP_1_1, HttpMethod.GET, "/chat", Unpooled.copiedBuffer("^n:ds[4U", CharsetUtil.US_ASCII)); req.headers().set(Names.HOST, "server.example.com"); req.headers().set(Names.UPGRADE, WEBSOCKET.toLowerCase()); req.headers().set(Names.CONNECTION, "Upgrade"); req.headers().set(Names.ORIGIN, "http://example.com"); req.headers().set(Names.SEC_WEBSOCKET_KEY1, "4 @1 46546xW%0l 1 5"); req.headers().set(Names.SEC_WEBSOCKET_KEY2, "12998 5 Y3 1 .P00"); req.headers().set(Names.SEC_WEBSOCKET_PROTOCOL, "chat, superchat"); if (subProtocol) { new WebSocketServerHandshaker00( "ws://example.com/chat", "chat", Integer.MAX_VALUE).handshake(ch, req); } else { new WebSocketServerHandshaker00( "ws://example.com/chat", null, Integer.MAX_VALUE).handshake(ch, req); } EmbeddedChannel ch2 = new EmbeddedChannel(new HttpResponseDecoder()); ch2.writeInbound(ch.readOutbound()); HttpResponse res = (HttpResponse) ch2.readInbound(); Assert.assertEquals("ws://example.com/chat", res.headers().get(Names.SEC_WEBSOCKET_LOCATION)); if (subProtocol) { Assert.assertEquals("chat", res.headers().get(Names.SEC_WEBSOCKET_PROTOCOL)); } else { Assert.assertNull(res.headers().get(Names.SEC_WEBSOCKET_PROTOCOL)); } LastHttpContent content = (LastHttpContent) ch2.readInbound(); Assert.assertEquals("8jKS'y:G*Co,Wxa-", content.content().toString(CharsetUtil.US_ASCII)); content.release(); req.release(); } }
{ "content_hash": "e9eab793d6cc4a26a430109320a253a8", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 108, "avg_line_length": 41.945945945945944, "alnum_prop": 0.698131443298969, "repo_name": "chanakaudaya/netty", "id": "481b033e4bee77d486fd5832c63a184af25ffd0f", "size": "3738", "binary": false, "copies": "3", "ref": "refs/heads/4.0", "path": "codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshaker00Test.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "77842" }, { "name": "C++", "bytes": "1947" }, { "name": "CSS", "bytes": "49" }, { "name": "Groovy", "bytes": "1755" }, { "name": "HTML", "bytes": "1466" }, { "name": "Java", "bytes": "10523144" }, { "name": "Protocol Buffer", "bytes": "1712" }, { "name": "Shell", "bytes": "3972" } ], "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/html; charset=utf-8" /> <title>INTERFACE_COMPILE_DEFINITIONS &mdash; CMake 3.8.1 Documentation</title> <link rel="stylesheet" href="../_static/cmake.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '3.8.1', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true, SOURCELINK_SUFFIX: '.txt' }; </script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <link rel="shortcut icon" href="../_static/cmake-favicon.ico"/> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="INTERFACE_COMPILE_FEATURES" href="INTERFACE_COMPILE_FEATURES.html" /> <link rel="prev" title="INTERFACE_AUTOUIC_OPTIONS" href="INTERFACE_AUTOUIC_OPTIONS.html" /> </head> <body role="document"> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="INTERFACE_COMPILE_FEATURES.html" title="INTERFACE_COMPILE_FEATURES" accesskey="N">next</a> |</li> <li class="right" > <a href="INTERFACE_AUTOUIC_OPTIONS.html" title="INTERFACE_AUTOUIC_OPTIONS" accesskey="P">previous</a> |</li> <li> <img src="../_static/cmake-logo-16.png" alt="" style="vertical-align: middle; margin-top: -2px" /> </li> <li> <a href="https://cmake.org/">CMake</a> &#187; </li> <li> <a href="../index.html">3.8.1 Documentation</a> &#187; </li> <li class="nav-item nav-item-1"><a href="../manual/cmake-properties.7.html" accesskey="U">cmake-properties(7)</a> &#187;</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="interface-compile-definitions"> <span id="prop_tgt:INTERFACE_COMPILE_DEFINITIONS"></span><h1>INTERFACE_COMPILE_DEFINITIONS<a class="headerlink" href="#interface-compile-definitions" title="Permalink to this headline">¶</a></h1> <p>List of public compile definitions requirements for a library.</p> <p>Targets may populate this property to publish the compile definitions required to compile against the headers for the target. The <span class="target" id="index-1-command:target_compile_definitions"></span><a class="reference internal" href="../command/target_compile_definitions.html#command:target_compile_definitions" title="target_compile_definitions"><code class="xref cmake cmake-command docutils literal"><span class="pre">target_compile_definitions()</span></code></a> command populates this property with values given to the <code class="docutils literal"><span class="pre">PUBLIC</span></code> and <code class="docutils literal"><span class="pre">INTERFACE</span></code> keywords. Projects may also get and set the property directly.</p> <p>When target dependencies are specified using <span class="target" id="index-0-command:target_link_libraries"></span><a class="reference internal" href="../command/target_link_libraries.html#command:target_link_libraries" title="target_link_libraries"><code class="xref cmake cmake-command docutils literal"><span class="pre">target_link_libraries()</span></code></a>, CMake will read this property from all target dependencies to determine the build properties of the consumer.</p> <p>Contents of <code class="docutils literal"><span class="pre">INTERFACE_COMPILE_DEFINITIONS</span></code> may use &#8220;generator expressions&#8221; with the syntax <code class="docutils literal"><span class="pre">$&lt;...&gt;</span></code>. See the <span class="target" id="index-0-manual:cmake-generator-expressions(7)"></span><a class="reference internal" href="../manual/cmake-generator-expressions.7.html#manual:cmake-generator-expressions(7)" title="cmake-generator-expressions(7)"><code class="xref cmake cmake-manual docutils literal"><span class="pre">cmake-generator-expressions(7)</span></code></a> manual for available expressions. See the <span class="target" id="index-0-manual:cmake-buildsystem(7)"></span><a class="reference internal" href="../manual/cmake-buildsystem.7.html#manual:cmake-buildsystem(7)" title="cmake-buildsystem(7)"><code class="xref cmake cmake-manual docutils literal"><span class="pre">cmake-buildsystem(7)</span></code></a> -manual for more on defining buildsystem properties.</p> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h4>Previous topic</h4> <p class="topless"><a href="INTERFACE_AUTOUIC_OPTIONS.html" title="previous chapter">INTERFACE_AUTOUIC_OPTIONS</a></p> <h4>Next topic</h4> <p class="topless"><a href="INTERFACE_COMPILE_FEATURES.html" title="next chapter">INTERFACE_COMPILE_FEATURES</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/prop_tgt/INTERFACE_COMPILE_DEFINITIONS.rst.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <form class="search" action="../search.html" method="get"> <div><input type="text" name="q" /></div> <div><input type="submit" value="Go" /></div> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="INTERFACE_COMPILE_FEATURES.html" title="INTERFACE_COMPILE_FEATURES" >next</a> |</li> <li class="right" > <a href="INTERFACE_AUTOUIC_OPTIONS.html" title="INTERFACE_AUTOUIC_OPTIONS" >previous</a> |</li> <li> <img src="../_static/cmake-logo-16.png" alt="" style="vertical-align: middle; margin-top: -2px" /> </li> <li> <a href="https://cmake.org/">CMake</a> &#187; </li> <li> <a href="../index.html">3.8.1 Documentation</a> &#187; </li> <li class="nav-item nav-item-1"><a href="../manual/cmake-properties.7.html" >cmake-properties(7)</a> &#187;</li> </ul> </div> <div class="footer" role="contentinfo"> &#169; Copyright 2000-2017 Kitware, Inc. and Contributors. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.5.2. </div> </body> </html>
{ "content_hash": "db03c568ff901798ddfa58e21150ca03", "timestamp": "", "source": "github", "line_count": 147, "max_line_length": 461, "avg_line_length": 51.91156462585034, "alnum_prop": 0.645655877342419, "repo_name": "pipou/rae", "id": "f500d175adf436e29d4a940f9e379b93f81ede18", "size": "7632", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "builder/cmake/windows/doc/cmake/html/prop_tgt/INTERFACE_COMPILE_DEFINITIONS.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2544" }, { "name": "C", "bytes": "48544" }, { "name": "C++", "bytes": "6334" }, { "name": "CMake", "bytes": "8152333" }, { "name": "CSS", "bytes": "56991" }, { "name": "Cuda", "bytes": "901" }, { "name": "Emacs Lisp", "bytes": "44259" }, { "name": "Fortran", "bytes": "6400" }, { "name": "HTML", "bytes": "36295522" }, { "name": "JavaScript", "bytes": "296574" }, { "name": "M4", "bytes": "4433" }, { "name": "Roff", "bytes": "4627932" }, { "name": "Shell", "bytes": "59955" }, { "name": "Vim script", "bytes": "140497" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <title>Lesson 10</title> <meta charset="utf-8"> <meta name="description" content="Lesson 10"> <meta name="author" content="Andrew Do"> <meta name="generator" content="slidify" /> <meta name="apple-mobile-web-app-capable" content="yes"> <meta http-equiv="X-UA-Compatible" content="chrome=1"> <link rel="stylesheet" href="libraries/frameworks/io2012/css/default.css" media="all" > <link rel="stylesheet" href="libraries/frameworks/io2012/css/phone.css" media="only screen and (max-device-width: 480px)" > <link rel="stylesheet" href="libraries/frameworks/io2012/css/slidify.css" > <link rel="stylesheet" href="libraries/highlighters/highlight.js/css/tomorrow.css" /> <base target="_blank"> <!-- This amazingness opens all links in a new tab. --> <link rel=stylesheet href="./assets/css/ribbons.css"></link> <!-- Grab CDN jQuery, fall back to local if offline --> <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.min.js"></script> <script>window.jQuery || document.write('<script src="libraries/widgets/quiz/js/jquery.js"><\/script>')</script> <script data-main="libraries/frameworks/io2012/js/slides" src="libraries/frameworks/io2012/js/require-1.0.8.min.js"> </script> </head> <body style="opacity: 0"> <slides class="layout-widescreen"> <!-- LOGO SLIDE --> <slide class="title-slide segue nobackground"> <hgroup class="auto-fadein"> <h1>Lesson 10</h1> <h2>Tidy Data</h2> <p>Andrew Do<br/></p> </hgroup> <article></article> </slide> <!-- SLIDES --> <slide class="" id="slide-1" style="background:;"> <hgroup> <h2>Motivation</h2> </hgroup> <article data-timings=""> <h3>How many variables are represented in this table? What are they?</h3> <p><img src="img/3var1.png" width="600"></p> </article> <!-- Presenter Notes --> </slide> <slide class="" id="slide-2" style="background:;"> <hgroup> <h2>Motivation</h2> </hgroup> <article data-timings=""> <h3>In the language of data wrangling, we convert the table from <strong>wide format</strong> to <strong>long format</strong>.</h3> <p><img src="img/3var2.png" width="600"></p> </article> <!-- Presenter Notes --> </slide> <slide class="" id="slide-3" style="background:;"> <hgroup> <h2>Tidy Data</h2> </hgroup> <article data-timings=""> <h3>A data set is said to be <strong>tidy</strong> if:</h3> <ol> <li><strong>Observations</strong> or <strong>cases</strong> are in the rows</li> <li><strong>Variables</strong> are in the columns</li> <li>Everything is contained in a single <strong>dataset</strong></li> </ol> <p><strong>Messy data</strong> is any other arrangement of data.</p> <h3>Advantages of tidy data:</h3> <ol> <li>Standard structure allows for standard wrangling and analysis tools</li> <li>Ordering often makes sense</li> <li>Easy to read off individual cases/variables used</li> </ol> </article> <!-- Presenter Notes --> </slide> <slide class="" id="slide-4" style="background:;"> <hgroup> <h2>Common Problems of Messy Data Sets</h2> </hgroup> <article data-timings=""> <h3>Column headers contain values instead of variable names</h3> <h3>Multiple variables are stored in one column</h3> <h3>Variables stored in both rows and columns</h3> <h3>Multiple types of observational units stored in the same table</h3> <h3>Single observational unit stored in multiple tables</h3> </article> <!-- Presenter Notes --> </slide> <slide class="" id="slide-5" style="background:;"> <hgroup> <h2>Tidying Verbs</h2> </hgroup> <article data-timings=""> <p>Just like with wrangling, we can formalize a good amount of the most common tidying actions in a few verbs:</p> <table><thead> <tr> <th>Tidying verb</th> <th>Description</th> </tr> </thead><tbody> <tr> <td>gather</td> <td>Take columns and collapse into key-value pairs</td> </tr> <tr> <td>spread</td> <td>Take key-value pair and lay it over multiple columns</td> </tr> <tr> <td>separate</td> <td>Turn a single character column into multiple columns</td> </tr> <tr> <td>unite</td> <td>Turn multiple character columns into one</td> </tr> </tbody></table> </article> <!-- Presenter Notes --> </slide> <slide class="" id="slide-6" style="background:;"> <hgroup> <h2>Gather</h2> </hgroup> <article data-timings=""> <p><strong>Gathering</strong> the <strong>keys</strong> <code>A</code> and <code>B</code> into a single column called <code>Treatment</code> and their <strong>values</strong> into a column <code>Blood_Pressure</code>:</p> <pre><code>## names A B ## 1 John 121 166 ## 2 Mary 110 145 ## 3 Sue 130 141 </code></pre> <pre><code class="r">gather(data = df, key = Treatment, value = Blood_Pressure, A, B) </code></pre> <pre><code>## names Treatment Blood_Pressure ## 1 John A 121 ## 2 Mary A 110 ## 3 Sue A 130 ## 4 John B 166 ## 5 Mary B 145 ## 6 Sue B 141 </code></pre> </article> <!-- Presenter Notes --> </slide> <slide class="" id="slide-7" style="background:;"> <hgroup> <h2>Spread</h2> </hgroup> <article data-timings=""> <p><strong>Gathering</strong> the <strong>key-value pair</strong> <code>Treatment</code> and <code>Blood_Pressure</code> across multiple columns:</p> <pre><code>## names Treatment Blood_Pressure ## 1 John A 121 ## 2 Mary A 110 ## 3 Sue A 130 ## 4 John B 166 ## 5 Mary B 145 ## 6 Sue B 141 </code></pre> <pre><code class="r">spread(data = df, key = Treatment, value = Blood_Pressure) </code></pre> <pre><code>## names A B ## 1 John 121 166 ## 2 Mary 110 145 ## 3 Sue 130 141 </code></pre> </article> <!-- Presenter Notes --> </slide> <slide class="" id="slide-8" style="background:;"> <hgroup> <h2>Separate</h2> </hgroup> <article data-timings=""> <p><strong>Separating</strong> <code>x</code> into <code>first</code> and <code>second</code>, which were <strong>separated</strong> by <code>&quot;.&quot;</code></p> <pre><code>## x y ## 1 &lt;NA&gt; 1 ## 2 a.b 2 ## 3 a.d 3 ## 4 b.c 4 </code></pre> <pre><code class="r">separate(data = df, col = x, into = c(&quot;first&quot;, &quot;second&quot;), sep = &quot;\\.&quot;) </code></pre> <pre><code>## first second y ## 1 &lt;NA&gt; &lt;NA&gt; 1 ## 2 a b 2 ## 3 a d 3 ## 4 b c 4 </code></pre> </article> <!-- Presenter Notes --> </slide> <slide class="" id="slide-9" style="background:;"> <hgroup> <h2>Column headers contain values and not variables</h2> </hgroup> <article data-timings=""> <h3>Income distribution within US religious groups</h3> <ul> <li>Survey that examines relationship between income and religious affiliation</li> <li>Collected by the Pew Forum on Religious and Public Life <a href="http://pewforum.org/Income-Distribution-Within-US-Religious-Groups.aspx">LINK</a></li> <li>Data is in the <code>data</code> folder for lesson 10</li> </ul> <pre><code class="r">library(readr) df &lt;- read_tsv(&quot;../data/pew.txt&quot;) </code></pre> <h3>Discuss:</h3> <ul> <li>What are the variables in this table?</li> <li>Is this data tidy? If not, which verb would you use to fix it?</li> </ul> </article> <!-- Presenter Notes --> </slide> <slide class="" id="slide-10" style="background:;"> <hgroup> <h2>Fixing the data</h2> </hgroup> <article data-timings=""> <p>Using <code>gather</code> from <code>tidyr</code>, we can fix this data. Notice that the <code>-</code> means &quot;don&#39;t gather this column&quot;.</p> <pre><code class="r">longdf &lt;- gather(df, key = income, value = n, -religion) head(longdf, 5) </code></pre> <pre><code>## Source: local data frame [5 x 3] ## ## religion income n ## &lt;chr&gt; &lt;chr&gt; &lt;int&gt; ## 1 Agnostic &lt;$10k 27 ## 2 Atheist &lt;$10k 12 ## 3 Buddhist &lt;$10k 27 ## 4 Catholic &lt;$10k 418 ## 5 Don&lt;U+0092&gt;t know/refused &lt;$10k 15 </code></pre> </article> <!-- Presenter Notes --> </slide> <slide class="" id="slide-11" style="background:;"> <hgroup> <h2>Multiple Variables in One Column</h2> </hgroup> <article data-timings=""> <h3>WHO Tuberculosis study</h3> <pre><code class="r">df &lt;- read_csv(&quot;../data/tb.csv&quot;) %&gt;% select(-new_sp) names(df) &lt;- str_replace(names(df), &quot;new_sp_&quot;, &quot;&quot;) </code></pre> <h3>Discuss</h3> <ul> <li>What are the variables in this study? Hint: <code>f=female</code> and <code>1524=15-24</code>.</li> </ul> </article> <!-- Presenter Notes --> </slide> <slide class="" id="slide-12" style="background:;"> <hgroup> <h2>You try it</h2> </hgroup> <article data-timings=""> <h3>Tidy up the WHO data set</h3> <p>Some things you might want to think about:</p> <ul> <li>Gather the appropriate columns (<code>gather</code>)</li> <li>Separate gender and age into two columns <ul> <li>Maybe modify the string so you can use <code>separate</code></li> </ul></li> <li>Change <code>m</code> and <code>f</code> to <code>male</code> and <code>female</code> (<code>mutate</code>)</li> <li>Make <code>age</code> more readable, e.g. &quot;04&quot; should be &quot;0-4&quot; (<code>mutate</code>)</li> </ul> </article> <!-- Presenter Notes --> </slide> <slide class="" id="slide-13" style="background:;"> <hgroup> <h2>You try it</h2> </hgroup> <article data-timings=""> <pre><code class="r">age_ranges &lt;- c(&quot;04&quot; = &quot;0-4&quot;, &quot;514&quot; = &quot;5-14&quot;, &quot;014&quot; = &quot;0-14&quot;, &quot;1524&quot; = &quot;15-24&quot;, &quot;2534&quot; = &quot;25-34&quot;, &quot;3544&quot; = &quot;35-44&quot;, &quot;4554&quot; = &quot;45-54&quot;, &quot;5564&quot; = &quot;55-64&quot;, &quot;65&quot; = &quot;65+&quot;, &quot;u&quot; = &quot;unknown&quot;) gender_values &lt;- c(&quot;m&quot; = &quot;male&quot;, &quot;f&quot; = &quot;female&quot;) tidydf &lt;- gather(df, gender, n, -iso2, -year) %&gt;% separate(gender, c(&quot;gender&quot;, &quot;age&quot;), 1) %&gt;% mutate(age = str_replace_all(age, age_ranges), gender = str_replace_all(gender, gender_values)) %&gt;% na.omit </code></pre> </article> <!-- Presenter Notes --> </slide> <slide class="" id="slide-14" style="background:;"> <hgroup> <h2>Variables in Row Names and Columns</h2> </hgroup> <article data-timings=""> <h3>Weather data in Cuernavaca, Mexico in 2010</h3> <pre><code class="r">df &lt;- read_tsv(&quot;../data/weather.txt&quot;) </code></pre> <h3>Inspect the data:</h3> <ul> <li>What are the variables in this data set?</li> <li><code>tmin</code> = minimum temperature</li> <li><code>id</code> = weather station identifier</li> </ul> <p>Is the data tidy? If not, then what needs to be done?</p> </article> <!-- Presenter Notes --> </slide> <slide class="" id="slide-15" style="background:;"> <hgroup> <h2>Your turn</h2> </hgroup> <article data-timings=""> <h2>Tidy up the data. Discuss with those around you to figure out what needs to be done.</h2> </article> <!-- Presenter Notes --> </slide> <slide class="" id="slide-16" style="background:;"> <hgroup> <h2>Possible tidying procedure</h2> </hgroup> <article data-timings=""> <pre><code class="r">tidydf &lt;- df %&gt;% gather(day, temperature, -id, -year, -month, -element) %&gt;% mutate(day = str_replace(day, &quot;d&quot;, &quot;&quot;), element = str_to_lower(element)) %&gt;% select(id, year, month, day, element, temperature) %&gt;% mutate(day = as.integer(day), temperature = as.numeric(str_replace_all(temperature, &quot;(.*)(.)$&quot;, &quot;\\1\\.\\2&quot;))) %&gt;% na.omit </code></pre> </article> <!-- Presenter Notes --> </slide> <slide class="" id="slide-17" style="background:;"> <hgroup> <h2>Multiple Data Types in One Table</h2> </hgroup> <article data-timings=""> <pre><code class="r">df &lt;- read_csv(&quot;../data/billboard.csv&quot;) </code></pre> <h3>Try it yourself without guidance</h3> </article> <!-- Presenter Notes --> </slide> <slide class="" id="slide-18" style="background:;"> <hgroup> <h2>Multiple Data Types in One Table</h2> </hgroup> <article data-timings=""> <pre><code class="r">tidydf &lt;- df %&gt;% gather(Week, Rank, -year, -artist.inverted, -track, -time, -genre, -date.entered, - date.peaked) </code></pre> <p>Do you notice anything undesirable about this &quot;tidy&quot; form?</p> </article> <!-- Presenter Notes --> </slide> <slide class="" id="slide-19" style="background:;"> <hgroup> <h2>Multiple Data Types in One Table</h2> </hgroup> <article data-timings=""> <p>Each fact about a song is repeated many many times. Sign that multiple types of experimental unit stored in the same table. We can store our data more efficiently by separating it into different tables for each type of unit.</p> <p>Need to separate out into song and rank tables.</p> </article> <!-- Presenter Notes --> </slide> <slide class="" id="slide-20" style="background:;"> <hgroup> <h2>Multiple Data Types in One Table</h2> </hgroup> <article data-timings=""> <pre><code class="r">Rankings &lt;- tidydf %&gt;% select(-Week, -Rank, -date.entered, -date.peaked) %&gt;% unique %&gt;% mutate(Song_ID = row_number()) </code></pre> </article> <!-- Presenter Notes --> </slide> <slide class="" id="slide-21" style="background:;"> <hgroup> <h2>One Data Type in Multiple Tables</h2> </hgroup> <article data-timings=""> <h2>You&#39;ll see an example of this in the last problem of the homework.</h2> <hr> <h2>Further reading</h2> <p>For a complete discussion on tidy data, please read the following paper:</p> <p><a href="http://vita.had.co.nz/papers/tidy-data.pdf">Tidy Data by Hadley Wickham</a></p> </article> <!-- Presenter Notes --> </slide> <slide class="backdrop"></slide> </slides> <div class="pagination pagination-small" id='io2012-ptoc' style="display:none;"> <ul> <li> <a href="#" target="_self" rel='tooltip' data-slide=1 title='Motivation'> 1 </a> </li> <li> <a href="#" target="_self" rel='tooltip' data-slide=2 title='Motivation'> 2 </a> </li> <li> <a href="#" target="_self" rel='tooltip' data-slide=3 title='Tidy Data'> 3 </a> </li> <li> <a href="#" target="_self" rel='tooltip' data-slide=4 title='Common Problems of Messy Data Sets'> 4 </a> </li> <li> <a href="#" target="_self" rel='tooltip' data-slide=5 title='Tidying Verbs'> 5 </a> </li> <li> <a href="#" target="_self" rel='tooltip' data-slide=6 title='Gather'> 6 </a> </li> <li> <a href="#" target="_self" rel='tooltip' data-slide=7 title='Spread'> 7 </a> </li> <li> <a href="#" target="_self" rel='tooltip' data-slide=8 title='Separate'> 8 </a> </li> <li> <a href="#" target="_self" rel='tooltip' data-slide=9 title='Column headers contain values and not variables'> 9 </a> </li> <li> <a href="#" target="_self" rel='tooltip' data-slide=10 title='Fixing the data'> 10 </a> </li> <li> <a href="#" target="_self" rel='tooltip' data-slide=11 title='Multiple Variables in One Column'> 11 </a> </li> <li> <a href="#" target="_self" rel='tooltip' data-slide=12 title='You try it'> 12 </a> </li> <li> <a href="#" target="_self" rel='tooltip' data-slide=13 title='You try it'> 13 </a> </li> <li> <a href="#" target="_self" rel='tooltip' data-slide=14 title='Variables in Row Names and Columns'> 14 </a> </li> <li> <a href="#" target="_self" rel='tooltip' data-slide=15 title='Your turn'> 15 </a> </li> <li> <a href="#" target="_self" rel='tooltip' data-slide=16 title='Possible tidying procedure'> 16 </a> </li> <li> <a href="#" target="_self" rel='tooltip' data-slide=17 title='Multiple Data Types in One Table'> 17 </a> </li> <li> <a href="#" target="_self" rel='tooltip' data-slide=18 title='Multiple Data Types in One Table'> 18 </a> </li> <li> <a href="#" target="_self" rel='tooltip' data-slide=19 title='Multiple Data Types in One Table'> 19 </a> </li> <li> <a href="#" target="_self" rel='tooltip' data-slide=20 title='Multiple Data Types in One Table'> 20 </a> </li> <li> <a href="#" target="_self" rel='tooltip' data-slide=21 title='One Data Type in Multiple Tables'> 21 </a> </li> </ul> </div> <!--[if IE]> <script src="http://ajax.googleapis.com/ajax/libs/chrome-frame/1/CFInstall.min.js"> </script> <script>CFInstall.check({mode: 'overlay'});</script> <![endif]--> </body> <!-- Load Javascripts for Widgets --> <!-- LOAD HIGHLIGHTER JS FILES --> <script src="libraries/highlighters/highlight.js/highlight.pack.js"></script> <script>hljs.initHighlightingOnLoad();</script> <!-- DONE LOADING HIGHLIGHTER JS FILES --> </html>
{ "content_hash": "389e66d1a4b337aa2074c6d9135fee91", "timestamp": "", "source": "github", "line_count": 636, "max_line_length": 225, "avg_line_length": 29.072327044025158, "alnum_prop": 0.5740941049215792, "repo_name": "STAT133-Summer2016/CourseMaterials", "id": "e64fc764923fc489c196315c27822b0796d257aa", "size": "18490", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "10-lesson-tidying/slides/index.html", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "1199831" }, { "name": "HTML", "bytes": "43161716" }, { "name": "JavaScript", "bytes": "976212" }, { "name": "R", "bytes": "24508" }, { "name": "TeX", "bytes": "28899" } ], "symlink_target": "" }
{-| Copyright : (c) Dave Laing, 2017 License : BSD3 Maintainer : dave.laing.80@gmail.com Stability : experimental Portability : non-portable -} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DataKinds #-} module Rules.Type.Infer.Offline ( UnifyT , ITOffline ) where import Control.Monad (unless) import Data.Functor.Identity (Identity(..)) import Data.List (tails) import Data.Proxy (Proxy(..)) import Bound (Bound) import Control.Lens (review) import Control.Lens.Wrapped (_Wrapped, _Unwrapped) import Control.Monad.Except (MonadError) import Control.Monad.Writer (MonadWriter(..), WriterT, execWriterT, runWriterT) import Data.List.NonEmpty (NonEmpty(..)) import qualified Data.List.NonEmpty as N import qualified Data.Map as M import Data.Bitransversable import Data.Functor.Rec import Ast.Type import Ast.Term import Ast.Error.Common import Rules.Unification import Rules.Type.Infer.Common type UnifyT ki ty a = WriterT [UConstraint (TyAst ki ty) (TyAstVar a)] mkInferType' :: (Ord a, UnificationContext e m (TyAst ki ty) (TyAstVar a), MonadError e m, AsUnknownTypeError e) => (Term ki ty pt tm a -> UnifyT ki ty a m (Type ki ty a)) -> ([UConstraint (TyAst ki ty) (TyAstVar a)] -> m (M.Map (TyAstVar a) (TyAst ki ty (TyAstVar a)))) -> Term ki ty pt tm a -> m (Type ki ty a) mkInferType' go unifyFn x = do (ty, cs) <- runWriterT $ go x let ty' = review _Unwrapped ty s <- unifyFn cs let ty'' = mapSubst _TyAstVar s ty' return $ review _Wrapped ty'' data ITOffline mkCheck' :: MkInferTypeConstraint e w s r m ki ty a ITOffline => Proxy (MonadProxy e w s r m) -> (Term ki ty pt tm a -> UnifyT ki ty a m (Type ki ty a)) -> ([UConstraint (TyAst ki ty) (TyAstVar a)] -> m (M.Map (TyAstVar a) (TyAst ki ty (TyAstVar a)))) -> Term ki ty pt tm a -> Type ki ty a -> m () mkCheck' m inferFn unifyFn x y = do cs <- execWriterT $ (mkCheckType m (Proxy :: Proxy ITOffline) inferFn) x y _ <- unifyFn cs return () fixupNormalize :: (Type ki ty a -> Type ki ty a) -> TyAst ki ty (TyAstVar a) -> TyAst ki ty (TyAstVar a) fixupNormalize fn = review _Unwrapped . fn . review _Wrapped fixupUnify :: Monad m => ([UConstraint (TyAst ki ty) (TyAstVar a)] -> m (M.Map (TyAstVar a) (TyAst ki ty (TyAstVar a)))) -> [UConstraint (Type ki ty) a] -> m (M.Map a (Type ki ty a)) fixupUnify u = let fixConstraint (UCEq a1 a2) = UCEq (review _Unwrapped a1) (review _Unwrapped a2) fixMap = undefined in fmap fixMap . u . fmap fixConstraint instance MkInferType ITOffline where type MkInferTypeConstraint e w s r m ki ty a ITOffline = ( Ord a , OrdRec ki , OrdRec (ty ki) , MonadError e m , AsUnknownTypeError e , AsOccursError e (TyAst ki ty) (TyAstVar a) , AsUnificationMismatch e (TyAst ki ty) (TyAstVar a) , AsUnificationExpectedEq e (TyAst ki ty) (TyAstVar a) , Bound ki , Bound (ty ki) , Bitransversable ki , Bitransversable (ty ki) ) type InferTypeMonad m ki ty a ITOffline = UnifyT ki ty a m type MkInferTypeErrorList ki ty pt tm a ITOffline = '[ ErrOccursError (TyAst ki ty) (TyAstVar a) , ErrUnificationMismatch (TyAst ki ty) (TyAstVar a) , ErrUnificationExpectedEq (TyAst ki ty) (TyAstVar a) ] type MkInferTypeWarningList ki ty pt tm a ITOffline = '[] mkCheckType m i = mkCheckType' (expectType m i) expectType _ _ (ExpectedType ty1) (ActualType ty2) = unless (ty1 == ty2) $ tell [UCEq (review _Unwrapped ty1) (review _Unwrapped ty2)] expectTypeEq _ _ ty1 ty2 = unless (ty1 == ty2) $ tell [UCEq (review _Unwrapped ty1) (review _Unwrapped ty2)] expectTypeAllEq _ _ n@(ty :| tys) = do unless (all (== ty) tys ) $ let xss = tails . N.toList $ n f [] = [] f (x : xs) = fmap (UCEq (review _Unwrapped x)) (fmap (review _Unwrapped) xs) ws = xss >>= f in tell ws return ty prepareInferType pm pi inferKindFn normalizeFn ii = let n = fixupNormalize normalizeFn u = mkUnify _TyAstVar n . iiUnifyRules $ ii u' = fixupUnify u pc = mkPCheck . iiPCheckRules $ ii i = mkInferType inferKindFn normalizeFn pc . iiInferTypeRules $ ii i' = mkInferType' i u c = mkCheck' pm i u in InferTypeOutput u' i' c
{ "content_hash": "6715e9fef7b043332e56310532d23475", "timestamp": "", "source": "github", "line_count": 152, "max_line_length": 112, "avg_line_length": 30.026315789473685, "alnum_prop": 0.637817703768624, "repo_name": "dalaing/type-systems", "id": "8dda6bb2248b12ad35a0b80bcd10aead8fc65253", "size": "4564", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Rules/Type/Infer/Offline.hs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Haskell", "bytes": "583646" }, { "name": "Nix", "bytes": "1660" } ], "symlink_target": "" }
layout: post title: My 18yo neice posed in the snow in her bikini, so I thought I would replicate the scene for her. date: 2014-06-11 15:31:19 summary: categories: jekyll pixyll --- <a href="https://twitter.com/share" class="twitter-share-button" data-size="large" data-hashtags="5econd">Tweet</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script> <img id="myImg" style="text-align:center" width="100%" height="auto" src="https://raw.githubusercontent.com/fivesecondlaugh/fivesecondlaugh.github.io/master/images/G852Z8D.jpg" /> <script> var x = document.getElementById("myImg"); x.onload=setTimeout(function () { window.location.href = "http://fivesecondlaugh.github.io/jekyll/pixyll/2014/06/11/1438478085/"; //will redirect to your blog page (an ex: blog.html) }, 5000); </script>
{ "content_hash": "184778917a03d66d978f1f3e6f5418f3", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 295, "avg_line_length": 48.18181818181818, "alnum_prop": 0.7141509433962264, "repo_name": "fivesecondlaugh/fivesecondlaugh.github.io", "id": "1e2b0d4fd4c24941971df763f23a796420f79c84", "size": "1064", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2014-06-11-1438478080.markdown", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "22776" }, { "name": "HTML", "bytes": "14742" } ], "symlink_target": "" }
#include <stdlib.h> #include <string.h> #include <stddef.h> #include "wgl_custom.h" #if defined(__APPLE__) #include <mach-o/dyld.h> static void* AppleGLGetProcAddress (const GLubyte *name) { static const struct mach_header* image = NULL; NSSymbol symbol; char* symbolName; if (NULL == image) { image = NSAddImage("/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL", NSADDIMAGE_OPTION_RETURN_ON_ERROR); } /* prepend a '_' for the Unix C symbol mangling convention */ symbolName = malloc(strlen((const char*)name) + 2); strcpy(symbolName+1, (const char*)name); symbolName[0] = '_'; symbol = NULL; /* if (NSIsSymbolNameDefined(symbolName)) symbol = NSLookupAndBindSymbol(symbolName); */ symbol = image ? NSLookupSymbolInImage(image, symbolName, NSLOOKUPSYMBOLINIMAGE_OPTION_BIND | NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR) : NULL; free(symbolName); return symbol ? NSAddressOfSymbol(symbol) : NULL; } #endif /* __APPLE__ */ #if defined(__sgi) || defined (__sun) #include <dlfcn.h> #include <stdio.h> static void* SunGetProcAddress (const GLubyte* name) { static void* h = NULL; static void* gpa; if (h == NULL) { if ((h = dlopen(NULL, RTLD_LAZY | RTLD_LOCAL)) == NULL) return NULL; gpa = dlsym(h, "glXGetProcAddress"); } if (gpa != NULL) return ((void*(*)(const GLubyte*))gpa)(name); else return dlsym(h, (const char*)name); } #endif /* __sgi || __sun */ #if defined(_WIN32) #ifdef _MSC_VER #pragma warning(disable: 4055) #pragma warning(disable: 4054) #endif static int TestPointer(const PROC pTest) { ptrdiff_t iTest; if(!pTest) return 0; iTest = (ptrdiff_t)pTest; if(iTest == 1 || iTest == 2 || iTest == 3 || iTest == -1) return 0; return 1; } static PROC WinGetProcAddress(const char *name) { HMODULE glMod = NULL; PROC pFunc = wglGetProcAddress((LPCSTR)name); if(TestPointer(pFunc)) { return pFunc; } glMod = GetModuleHandleA("OpenGL32.dll"); return (PROC)GetProcAddress(glMod, (LPCSTR)name); } #define IntGetProcAddress(name) WinGetProcAddress(name) #else #if defined(__APPLE__) #define IntGetProcAddress(name) AppleGLGetProcAddress(name) #else #if defined(__sgi) || defined(__sun) #define IntGetProcAddress(name) SunGetProcAddress(name) #else /* GLX */ #include <GL/glx.h> #define IntGetProcAddress(name) (*glXGetProcAddressARB)((const GLubyte*)name) #endif #endif #endif int wgl_ext_NV_present_video = wgl_LOAD_FAILED; int wgl_ext_NV_video_output = wgl_LOAD_FAILED; int wgl_ext_NV_gpu_affinity = wgl_LOAD_FAILED; int wgl_ext_NV_video_capture = wgl_LOAD_FAILED; int wgl_ext_NV_copy_image = wgl_LOAD_FAILED; int wgl_ext_NV_multisample_coverage = wgl_LOAD_FAILED; int wgl_ext_NV_DX_interop = wgl_LOAD_FAILED; int wgl_ext_NV_DX_interop2 = wgl_LOAD_FAILED; BOOL (CODEGEN_FUNCPTR *_ptrc_wglBindVideoDeviceNV)(HDC, unsigned int, HVIDEOOUTPUTDEVICENV, const int *) = NULL; int (CODEGEN_FUNCPTR *_ptrc_wglEnumerateVideoDevicesNV)(HDC, HVIDEOOUTPUTDEVICENV *) = NULL; BOOL (CODEGEN_FUNCPTR *_ptrc_wglQueryCurrentContextNV)(int, int *) = NULL; static int Load_NV_present_video() { int numFailed = 0; _ptrc_wglBindVideoDeviceNV = (BOOL (CODEGEN_FUNCPTR *)(HDC, unsigned int, HVIDEOOUTPUTDEVICENV, const int *))IntGetProcAddress("wglBindVideoDeviceNV"); if(!_ptrc_wglBindVideoDeviceNV) numFailed++; _ptrc_wglEnumerateVideoDevicesNV = (int (CODEGEN_FUNCPTR *)(HDC, HVIDEOOUTPUTDEVICENV *))IntGetProcAddress("wglEnumerateVideoDevicesNV"); if(!_ptrc_wglEnumerateVideoDevicesNV) numFailed++; _ptrc_wglQueryCurrentContextNV = (BOOL (CODEGEN_FUNCPTR *)(int, int *))IntGetProcAddress("wglQueryCurrentContextNV"); if(!_ptrc_wglQueryCurrentContextNV) numFailed++; return numFailed; } BOOL (CODEGEN_FUNCPTR *_ptrc_wglBindVideoImageNV)(HPVIDEODEV, HPBUFFERARB, int) = NULL; BOOL (CODEGEN_FUNCPTR *_ptrc_wglGetVideoDeviceNV)(HDC, int, HPVIDEODEV *) = NULL; BOOL (CODEGEN_FUNCPTR *_ptrc_wglGetVideoInfoNV)(HPVIDEODEV, unsigned long *, unsigned long *) = NULL; BOOL (CODEGEN_FUNCPTR *_ptrc_wglReleaseVideoDeviceNV)(HPVIDEODEV) = NULL; BOOL (CODEGEN_FUNCPTR *_ptrc_wglReleaseVideoImageNV)(HPBUFFERARB, int) = NULL; BOOL (CODEGEN_FUNCPTR *_ptrc_wglSendPbufferToVideoNV)(HPBUFFERARB, int, unsigned long *, BOOL) = NULL; static int Load_NV_video_output() { int numFailed = 0; _ptrc_wglBindVideoImageNV = (BOOL (CODEGEN_FUNCPTR *)(HPVIDEODEV, HPBUFFERARB, int))IntGetProcAddress("wglBindVideoImageNV"); if(!_ptrc_wglBindVideoImageNV) numFailed++; _ptrc_wglGetVideoDeviceNV = (BOOL (CODEGEN_FUNCPTR *)(HDC, int, HPVIDEODEV *))IntGetProcAddress("wglGetVideoDeviceNV"); if(!_ptrc_wglGetVideoDeviceNV) numFailed++; _ptrc_wglGetVideoInfoNV = (BOOL (CODEGEN_FUNCPTR *)(HPVIDEODEV, unsigned long *, unsigned long *))IntGetProcAddress("wglGetVideoInfoNV"); if(!_ptrc_wglGetVideoInfoNV) numFailed++; _ptrc_wglReleaseVideoDeviceNV = (BOOL (CODEGEN_FUNCPTR *)(HPVIDEODEV))IntGetProcAddress("wglReleaseVideoDeviceNV"); if(!_ptrc_wglReleaseVideoDeviceNV) numFailed++; _ptrc_wglReleaseVideoImageNV = (BOOL (CODEGEN_FUNCPTR *)(HPBUFFERARB, int))IntGetProcAddress("wglReleaseVideoImageNV"); if(!_ptrc_wglReleaseVideoImageNV) numFailed++; _ptrc_wglSendPbufferToVideoNV = (BOOL (CODEGEN_FUNCPTR *)(HPBUFFERARB, int, unsigned long *, BOOL))IntGetProcAddress("wglSendPbufferToVideoNV"); if(!_ptrc_wglSendPbufferToVideoNV) numFailed++; return numFailed; } HDC (CODEGEN_FUNCPTR *_ptrc_wglCreateAffinityDCNV)(const HGPUNV *) = NULL; BOOL (CODEGEN_FUNCPTR *_ptrc_wglDeleteDCNV)(HDC) = NULL; BOOL (CODEGEN_FUNCPTR *_ptrc_wglEnumGpuDevicesNV)(HGPUNV, UINT, PGPU_DEVICE) = NULL; BOOL (CODEGEN_FUNCPTR *_ptrc_wglEnumGpusFromAffinityDCNV)(HDC, UINT, HGPUNV *) = NULL; BOOL (CODEGEN_FUNCPTR *_ptrc_wglEnumGpusNV)(UINT, HGPUNV *) = NULL; static int Load_NV_gpu_affinity() { int numFailed = 0; _ptrc_wglCreateAffinityDCNV = (HDC (CODEGEN_FUNCPTR *)(const HGPUNV *))IntGetProcAddress("wglCreateAffinityDCNV"); if(!_ptrc_wglCreateAffinityDCNV) numFailed++; _ptrc_wglDeleteDCNV = (BOOL (CODEGEN_FUNCPTR *)(HDC))IntGetProcAddress("wglDeleteDCNV"); if(!_ptrc_wglDeleteDCNV) numFailed++; _ptrc_wglEnumGpuDevicesNV = (BOOL (CODEGEN_FUNCPTR *)(HGPUNV, UINT, PGPU_DEVICE))IntGetProcAddress("wglEnumGpuDevicesNV"); if(!_ptrc_wglEnumGpuDevicesNV) numFailed++; _ptrc_wglEnumGpusFromAffinityDCNV = (BOOL (CODEGEN_FUNCPTR *)(HDC, UINT, HGPUNV *))IntGetProcAddress("wglEnumGpusFromAffinityDCNV"); if(!_ptrc_wglEnumGpusFromAffinityDCNV) numFailed++; _ptrc_wglEnumGpusNV = (BOOL (CODEGEN_FUNCPTR *)(UINT, HGPUNV *))IntGetProcAddress("wglEnumGpusNV"); if(!_ptrc_wglEnumGpusNV) numFailed++; return numFailed; } BOOL (CODEGEN_FUNCPTR *_ptrc_wglBindVideoCaptureDeviceNV)(UINT, HVIDEOINPUTDEVICENV) = NULL; UINT (CODEGEN_FUNCPTR *_ptrc_wglEnumerateVideoCaptureDevicesNV)(HDC, HVIDEOINPUTDEVICENV *) = NULL; BOOL (CODEGEN_FUNCPTR *_ptrc_wglLockVideoCaptureDeviceNV)(HDC, HVIDEOINPUTDEVICENV) = NULL; BOOL (CODEGEN_FUNCPTR *_ptrc_wglQueryVideoCaptureDeviceNV)(HDC, HVIDEOINPUTDEVICENV, int, int *) = NULL; BOOL (CODEGEN_FUNCPTR *_ptrc_wglReleaseVideoCaptureDeviceNV)(HDC, HVIDEOINPUTDEVICENV) = NULL; static int Load_NV_video_capture() { int numFailed = 0; _ptrc_wglBindVideoCaptureDeviceNV = (BOOL (CODEGEN_FUNCPTR *)(UINT, HVIDEOINPUTDEVICENV))IntGetProcAddress("wglBindVideoCaptureDeviceNV"); if(!_ptrc_wglBindVideoCaptureDeviceNV) numFailed++; _ptrc_wglEnumerateVideoCaptureDevicesNV = (UINT (CODEGEN_FUNCPTR *)(HDC, HVIDEOINPUTDEVICENV *))IntGetProcAddress("wglEnumerateVideoCaptureDevicesNV"); if(!_ptrc_wglEnumerateVideoCaptureDevicesNV) numFailed++; _ptrc_wglLockVideoCaptureDeviceNV = (BOOL (CODEGEN_FUNCPTR *)(HDC, HVIDEOINPUTDEVICENV))IntGetProcAddress("wglLockVideoCaptureDeviceNV"); if(!_ptrc_wglLockVideoCaptureDeviceNV) numFailed++; _ptrc_wglQueryVideoCaptureDeviceNV = (BOOL (CODEGEN_FUNCPTR *)(HDC, HVIDEOINPUTDEVICENV, int, int *))IntGetProcAddress("wglQueryVideoCaptureDeviceNV"); if(!_ptrc_wglQueryVideoCaptureDeviceNV) numFailed++; _ptrc_wglReleaseVideoCaptureDeviceNV = (BOOL (CODEGEN_FUNCPTR *)(HDC, HVIDEOINPUTDEVICENV))IntGetProcAddress("wglReleaseVideoCaptureDeviceNV"); if(!_ptrc_wglReleaseVideoCaptureDeviceNV) numFailed++; return numFailed; } BOOL (CODEGEN_FUNCPTR *_ptrc_wglCopyImageSubDataNV)(HGLRC, GLuint, GLenum, GLint, GLint, GLint, GLint, HGLRC, GLuint, GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei) = NULL; static int Load_NV_copy_image() { int numFailed = 0; _ptrc_wglCopyImageSubDataNV = (BOOL (CODEGEN_FUNCPTR *)(HGLRC, GLuint, GLenum, GLint, GLint, GLint, GLint, HGLRC, GLuint, GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei))IntGetProcAddress("wglCopyImageSubDataNV"); if(!_ptrc_wglCopyImageSubDataNV) numFailed++; return numFailed; } BOOL (CODEGEN_FUNCPTR *_ptrc_wglDXCloseDeviceNV)(HANDLE) = NULL; BOOL (CODEGEN_FUNCPTR *_ptrc_wglDXLockObjectsNV)(HANDLE, GLint, HANDLE *) = NULL; BOOL (CODEGEN_FUNCPTR *_ptrc_wglDXObjectAccessNV)(HANDLE, GLenum) = NULL; HANDLE (CODEGEN_FUNCPTR *_ptrc_wglDXOpenDeviceNV)(void *) = NULL; HANDLE (CODEGEN_FUNCPTR *_ptrc_wglDXRegisterObjectNV)(HANDLE, void *, GLuint, GLenum, GLenum) = NULL; BOOL (CODEGEN_FUNCPTR *_ptrc_wglDXSetResourceShareHandleNV)(void *, HANDLE) = NULL; BOOL (CODEGEN_FUNCPTR *_ptrc_wglDXUnlockObjectsNV)(HANDLE, GLint, HANDLE *) = NULL; BOOL (CODEGEN_FUNCPTR *_ptrc_wglDXUnregisterObjectNV)(HANDLE, HANDLE) = NULL; static int Load_NV_DX_interop() { int numFailed = 0; _ptrc_wglDXCloseDeviceNV = (BOOL (CODEGEN_FUNCPTR *)(HANDLE))IntGetProcAddress("wglDXCloseDeviceNV"); if(!_ptrc_wglDXCloseDeviceNV) numFailed++; _ptrc_wglDXLockObjectsNV = (BOOL (CODEGEN_FUNCPTR *)(HANDLE, GLint, HANDLE *))IntGetProcAddress("wglDXLockObjectsNV"); if(!_ptrc_wglDXLockObjectsNV) numFailed++; _ptrc_wglDXObjectAccessNV = (BOOL (CODEGEN_FUNCPTR *)(HANDLE, GLenum))IntGetProcAddress("wglDXObjectAccessNV"); if(!_ptrc_wglDXObjectAccessNV) numFailed++; _ptrc_wglDXOpenDeviceNV = (HANDLE (CODEGEN_FUNCPTR *)(void *))IntGetProcAddress("wglDXOpenDeviceNV"); if(!_ptrc_wglDXOpenDeviceNV) numFailed++; _ptrc_wglDXRegisterObjectNV = (HANDLE (CODEGEN_FUNCPTR *)(HANDLE, void *, GLuint, GLenum, GLenum))IntGetProcAddress("wglDXRegisterObjectNV"); if(!_ptrc_wglDXRegisterObjectNV) numFailed++; _ptrc_wglDXSetResourceShareHandleNV = (BOOL (CODEGEN_FUNCPTR *)(void *, HANDLE))IntGetProcAddress("wglDXSetResourceShareHandleNV"); if(!_ptrc_wglDXSetResourceShareHandleNV) numFailed++; _ptrc_wglDXUnlockObjectsNV = (BOOL (CODEGEN_FUNCPTR *)(HANDLE, GLint, HANDLE *))IntGetProcAddress("wglDXUnlockObjectsNV"); if(!_ptrc_wglDXUnlockObjectsNV) numFailed++; _ptrc_wglDXUnregisterObjectNV = (BOOL (CODEGEN_FUNCPTR *)(HANDLE, HANDLE))IntGetProcAddress("wglDXUnregisterObjectNV"); if(!_ptrc_wglDXUnregisterObjectNV) numFailed++; return numFailed; } static const char * (CODEGEN_FUNCPTR *_ptrc_wglGetExtensionsStringARB)(HDC) = NULL; typedef int (*PFN_LOADFUNCPOINTERS)(); typedef struct wgl_StrToExtMap_s { char *extensionName; int *extensionVariable; PFN_LOADFUNCPOINTERS LoadExtension; } wgl_StrToExtMap; static wgl_StrToExtMap ExtensionMap[8] = { {"WGL_NV_present_video", &wgl_ext_NV_present_video, Load_NV_present_video}, {"WGL_NV_video_output", &wgl_ext_NV_video_output, Load_NV_video_output}, {"WGL_NV_gpu_affinity", &wgl_ext_NV_gpu_affinity, Load_NV_gpu_affinity}, {"WGL_NV_video_capture", &wgl_ext_NV_video_capture, Load_NV_video_capture}, {"WGL_NV_copy_image", &wgl_ext_NV_copy_image, Load_NV_copy_image}, {"WGL_NV_multisample_coverage", &wgl_ext_NV_multisample_coverage, NULL}, {"WGL_NV_DX_interop", &wgl_ext_NV_DX_interop, Load_NV_DX_interop}, {"WGL_NV_DX_interop2", &wgl_ext_NV_DX_interop2, NULL}, }; static int g_extensionMapSize = 8; static wgl_StrToExtMap *FindExtEntry(const char *extensionName) { int loop; wgl_StrToExtMap *currLoc = ExtensionMap; for(loop = 0; loop < g_extensionMapSize; ++loop, ++currLoc) { if(strcmp(extensionName, currLoc->extensionName) == 0) return currLoc; } return NULL; } static void ClearExtensionVars() { wgl_ext_NV_present_video = wgl_LOAD_FAILED; wgl_ext_NV_video_output = wgl_LOAD_FAILED; wgl_ext_NV_gpu_affinity = wgl_LOAD_FAILED; wgl_ext_NV_video_capture = wgl_LOAD_FAILED; wgl_ext_NV_copy_image = wgl_LOAD_FAILED; wgl_ext_NV_multisample_coverage = wgl_LOAD_FAILED; wgl_ext_NV_DX_interop = wgl_LOAD_FAILED; wgl_ext_NV_DX_interop2 = wgl_LOAD_FAILED; } static void LoadExtByName(const char *extensionName) { wgl_StrToExtMap *entry = NULL; entry = FindExtEntry(extensionName); if(entry) { if(entry->LoadExtension) { int numFailed = entry->LoadExtension(); if(numFailed == 0) { *(entry->extensionVariable) = wgl_LOAD_SUCCEEDED; } else { *(entry->extensionVariable) = wgl_LOAD_SUCCEEDED + numFailed; } } else { *(entry->extensionVariable) = wgl_LOAD_SUCCEEDED; } } } static void ProcExtsFromExtString(const char *strExtList) { size_t iExtListLen = strlen(strExtList); const char *strExtListEnd = strExtList + iExtListLen; const char *strCurrPos = strExtList; char strWorkBuff[256]; while(*strCurrPos) { /*Get the extension at our position.*/ int iStrLen = 0; const char *strEndStr = strchr(strCurrPos, ' '); int iStop = 0; if(strEndStr == NULL) { strEndStr = strExtListEnd; iStop = 1; } iStrLen = (int)((ptrdiff_t)strEndStr - (ptrdiff_t)strCurrPos); if(iStrLen > 255) return; strncpy(strWorkBuff, strCurrPos, iStrLen); strWorkBuff[iStrLen] = '\0'; LoadExtByName(strWorkBuff); strCurrPos = strEndStr + 1; if(iStop) break; } } int wgl_LoadFunctions(HDC hdc) { ClearExtensionVars(); _ptrc_wglGetExtensionsStringARB = (const char * (CODEGEN_FUNCPTR *)(HDC))IntGetProcAddress("wglGetExtensionsStringARB"); if(!_ptrc_wglGetExtensionsStringARB) return wgl_LOAD_FAILED; ProcExtsFromExtString((const char *)_ptrc_wglGetExtensionsStringARB(hdc)); return wgl_LOAD_SUCCEEDED; }
{ "content_hash": "3cd5f83d93afb16ce010c230f382d935", "timestamp": "", "source": "github", "line_count": 353, "max_line_length": 229, "avg_line_length": 39.345609065155806, "alnum_prop": 0.743610051119591, "repo_name": "tliron/opengl-3d-vision-bridge", "id": "534107c0486cc5a30b7d7f55d2d947741cf95401", "size": "13889", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "wgl_custom.c", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "339825" }, { "name": "Shell", "bytes": "552" } ], "symlink_target": "" }
@implementation UITabBar (NightVersion) #pragma mark - ChangeColor - (void)changeColorWithDuration:(CGFloat)duration { if ([DKNightVersionUtility shouldChangeColor:self]) { [UIView animateWithDuration:duration animations:^{ [self setBackgroundColor:([DKNightVersionManager currentThemeVersion] == DKThemeVersionNight) ? self.nightBackgroundColor : self.normalBackgroundColor]; }]; } } - (void)changeColor { if ([DKNightVersionUtility shouldChangeColor:self]) { [self setBarTintColor:([DKNightVersionManager currentThemeVersion] == DKThemeVersionNight) ? self.nightBarTintColor : self.normalBarTintColor]; [self setBackgroundColor:([DKNightVersionManager currentThemeVersion] == DKThemeVersionNight) ? self.nightBackgroundColor : self.normalBackgroundColor]; } } @end
{ "content_hash": "103d924f13559113687381389a351f5c", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 164, "avg_line_length": 37.47826086956522, "alnum_prop": 0.7273781902552204, "repo_name": "LiuYulei001/BasicFramework", "id": "18cccf7b20d8551e8fd4dcd9f3f5fa5606b17bd7", "size": "1039", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BasicFramework/BasicFramework/Vender/NightModeManager/UIKit/UITabBar/UITabBar+NightVersion.m", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "392304" }, { "name": "C++", "bytes": "19355" }, { "name": "HTML", "bytes": "4555" }, { "name": "Objective-C", "bytes": "2254629" }, { "name": "Ruby", "bytes": "532" }, { "name": "Shell", "bytes": "9263" } ], "symlink_target": "" }
function initMap() { var myLatLng = {lat: 29.042536, lng: -110.956854}; // Create a map object and specify the DOM element for display. var map = new google.maps.Map(document.getElementById('map_canvas'), { center: myLatLng, scrollwheel: false, zoom: 18 }); // Create a marker and set its position. var marker = new google.maps.Marker({ map: map, position: myLatLng, title: 'UVGas' }); }
{ "content_hash": "a15a8bc9a290ddb9eaa010f55e8171b8", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 74, "avg_line_length": 29, "alnum_prop": 0.5969827586206896, "repo_name": "soycodigo/uvseg", "id": "cc004f1173edb324ac0eb0f00688f6f9fd020821", "size": "464", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/maps.js", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "22838" }, { "name": "HTML", "bytes": "95939" }, { "name": "JavaScript", "bytes": "42947" }, { "name": "PHP", "bytes": "1600" } ], "symlink_target": "" }
Vagrant box with lamp stack provision
{ "content_hash": "4a879ea140fa881885bba5293514e9da", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 37, "avg_line_length": 38, "alnum_prop": 0.8421052631578947, "repo_name": "dejan-babic/db-vagrant-precise64-lamp", "id": "dc3dd61a03def1b0cb869d3fd6ed86aa937dcf47", "size": "66", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Puppet", "bytes": "1596" } ], "symlink_target": "" }
#ifndef __PROJECT_EULER_PROBLEM177_H__ #define __PROJECT_EULER_PROBLEM177_H__ /* * ProjectEuler/include/c/ProjectEuler/Problem177.h * * Integer angled Quadrilaterals. * ============================== * Published on Friday, 11th January 2008, 09:00 pm * * Let ABCD be a convex quadrilateral, with diagonals AC and BD. At each vertex * the diagonal makes an angle with each of the two sides, creating eight corner * angles. For example, at vertex A, the two angles are CAD, CAB. We call such * a quadrilateral for which all eight corner angles have integer values when * measured in degrees an "integer angled quadrilateral". An example of an * integer angled quadrilateral is a square, where all eight corner angles are * 45°. Another example is given by DAC = 20°, BAC = 60°, ABD = 50°, CBD = 30°, * BCA = 40°, DCA = 30°, CDB = 80°, ADB = 50°. What is the total number of non- * similar integer angled quadrilaterals? Note: In your calculations you may * assume that a calculated angle is integral if it is within a tolerance of * 10-9 of an integer value. */ # ifdef __cplusplus extern "C" { # endif # ifdef __cplusplus } # endif #endif /* __PROJECT_EULER_PROBLEM177_H__ */
{ "content_hash": "5dc4a0ce4f4a0300b7b9d703eda21f54", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 80, "avg_line_length": 38.806451612903224, "alnum_prop": 0.6932668329177057, "repo_name": "olduvaihand/ProjectEuler", "id": "c2c982f9b9b70a9e9b7e182bf32ad7d3704cacbb", "size": "1214", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/c/ProjectEuler/Problem177.h", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "0" }, { "name": "Python", "bytes": "422751" } ], "symlink_target": "" }
<div class="commune_descr limited"> <p> Plouvain est un village géographiquement positionné dans le département des Pas-de-Calais en Nord-Pas-de-Calais. On dénombrait 491 habitants en 2008.</p> <p>À proximité de Plouvain sont situées les villes de <a href="{{VLROOT}}/immobilier/hamblain-les-pres_62405/">Hamblain-les-Prés</a> située à 2&nbsp;km, 484 habitants, <a href="{{VLROOT}}/immobilier/pelves_62650/">Pelves</a> à 1&nbsp;km, 718 habitants, <a href="{{VLROOT}}/immobilier/fresnes-les-montauban_62355/">Fresnes-lès-Montauban</a> à 2&nbsp;km, 469 habitants, <a href="{{VLROOT}}/immobilier/fampoux_62323/">Fampoux</a> à 4&nbsp;km, 1&nbsp;086 habitants, <a href="{{VLROOT}}/immobilier/biache-saint-vaast_62128/">Biache-Saint-Vaast</a> à 1&nbsp;km, 3&nbsp;789 habitants, <a href="{{VLROOT}}/immobilier/boiry-notre-dame_62145/">Boiry-Notre-Dame</a> localisée à 4&nbsp;km, 434 habitants, entre autres. De plus, Plouvain est située à seulement treize&nbsp;km de <a href="{{VLROOT}}/immobilier/douai_59178/">Douai</a>.</p> <p>Si vous envisagez de emmenager à Plouvain, vous pourrez aisément trouver une maison à acheter. </p> <p>Le nombre d'habitations, à Plouvain, était réparti en 2011 en cinq appartements et 163 maisons soit un marché relativement équilibré.</p> <p>Plouvain est situé à seulement 10 Kilomètres de Arras, les élèves qui souhaiteront se loger à moindre coût pourront envisager de louer un logement à Plouvain. Plouvain est aussi un bon investissement locatif du fait de sa proximité de Arras et de ses Universités. Il sera facile de trouver un logement à vendre. </p> <p>La commune offre quelques équipements sportifs, elle dispose, entre autres, de un terrain de tennis et un terrain de sport.</p> </div>
{ "content_hash": "ac2990a08e395b89381cd698e89d46a2", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 319, "avg_line_length": 91.63157894736842, "alnum_prop": 0.7507179781734635, "repo_name": "donaldinou/frontend", "id": "8ff577f6441ac229034d449070569f4d8730f1e1", "size": "1781", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Viteloge/CoreBundle/Resources/descriptions/62660.html", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3073" }, { "name": "CSS", "bytes": "111338" }, { "name": "HTML", "bytes": "58634405" }, { "name": "JavaScript", "bytes": "88564" }, { "name": "PHP", "bytes": "841919" } ], "symlink_target": "" }
require "spec_helper" require "KibanaConfig" require "id_request" describe IdRequest do context "#initialize" do id_req = IdRequest.new(42, "foo") id_req.request["id"] == 42 id_req.request["index"] == "foo" id_req.request["timeframe"] == KibanaConfig::Fallback_interval end end
{ "content_hash": "45bff8b8620efb29af590ef628d060db", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 66, "avg_line_length": 20.133333333333333, "alnum_prop": 0.6721854304635762, "repo_name": "alphagov/Kibana", "id": "3b36de63f871304f76d70ce354d41eec3d2d98c3", "size": "302", "binary": false, "copies": "5", "ref": "refs/heads/kibana-ruby", "path": "spec/id_request_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "168297" }, { "name": "Perl", "bytes": "792" }, { "name": "Ruby", "bytes": "51805" } ], "symlink_target": "" }
package org.openspaces.admin.internal.pu; import java.util.Map; import java.util.concurrent.Future; import net.jini.core.lookup.ServiceID; import org.jini.rio.monitor.ServiceFaultDetectionEvent; import org.openspaces.admin.gsc.GridServiceContainer; import org.openspaces.admin.internal.support.InternalGridComponent; import org.openspaces.admin.pu.ProcessingUnit; import org.openspaces.admin.pu.ProcessingUnitInstance; import org.openspaces.admin.pu.ProcessingUnitInstanceStatistics; import org.openspaces.admin.pu.ProcessingUnitPartition; import org.openspaces.admin.space.SpaceInstance; import org.openspaces.pu.container.servicegrid.PUServiceBean; /** * @author kimchy */ public interface InternalProcessingUnitInstance extends ProcessingUnitInstance, InternalGridComponent { ServiceID getServiceID(); ServiceID getGridServiceContainerServiceID(); void setProcessingUnit(ProcessingUnit processingUnit); void setGridServiceContainer(GridServiceContainer gridServiceContainer); void setProcessingUnitPartition(ProcessingUnitPartition processingUnitPartition); /** * Adds a space instance only if it is one that the processing unit has started. */ boolean addSpaceInstanceIfMatching(SpaceInstance spaceInstance); void removeSpaceInstance(String uid); PUServiceBean getPUServiceBean(); Future<Object> invoke(String serviceBeanName, Map<String, Object> namedArgs); boolean isUndeploying(); /** * @return Return instance name without prefix of application name ( if exists ) * @since 8.0.6 */ String getProcessingUnitInstanceSimpleName(); void setMemberAliveIndicatorStatus(ServiceFaultDetectionEvent serviceFaultDetectionEvent); /** * This method is non-blocking and should used in conjunction with {@link #getStatistics()} or {@link #setStatisticsInterval(long, java.util.concurrent.TimeUnit)} * @return the last statistics (regardless of its timestamp), or null if no statistics has been ever collected. * @since 8.0.6 */ ProcessingUnitInstanceStatistics getLastStatistics(); /** * @return the statistics interval milliseconds * @since 9.0.0 */ long getStatisticsIntervalMilliseconds(); }
{ "content_hash": "e5deb2004fa47d33fd8b76e97d38d807", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 166, "avg_line_length": 33.56716417910448, "alnum_prop": 0.7727879057358826, "repo_name": "Gigaspaces/xap-openspaces", "id": "fd34611def7acba38161efb46baa76e4d97eac87", "size": "3053", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/openspaces/admin/internal/pu/InternalProcessingUnitInstance.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1107" }, { "name": "Groovy", "bytes": "5372" }, { "name": "HTML", "bytes": "13501" }, { "name": "Java", "bytes": "8666667" }, { "name": "Shell", "bytes": "917" } ], "symlink_target": "" }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Text; namespace DocumentFormat.OpenXml.Packaging { /// <summary> /// Called from constructors of derived parts to initialize the IFixedContentTypePart interface. All derived parts must be parts that have fixed content type. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces")] public interface IFixedContentTypePart { } }
{ "content_hash": "70f268d46b1302368d95907ab9229422", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 184, "avg_line_length": 44.06666666666667, "alnum_prop": 0.7609682299546142, "repo_name": "syediddi/Open-XML-SDK", "id": "68f8c2672f88ad314f9b00bc183a05fb8f006fb3", "size": "663", "binary": false, "copies": "9", "ref": "refs/heads/vNext", "path": "DocumentFormat.OpenXml/src/Framework/IFixedTypePart.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "666" }, { "name": "C#", "bytes": "24260522" }, { "name": "Makefile", "bytes": "12876" }, { "name": "Shell", "bytes": "641" } ], "symlink_target": "" }
package org.apache.openaz.pepapi.std; import org.apache.openaz.pepapi.Matchable; import org.apache.openaz.pepapi.Obligation; import java.util.Collection; import java.util.HashSet; import java.util.Set; public final class ObligationCriteria implements Matchable<Obligation> { private Set<ObligationCriterion> criteria; ObligationCriteria(Collection<ObligationCriterion> criteria) { this.criteria = new HashSet<ObligationCriterion>(); this.criteria.addAll(criteria); } @Override public boolean match(Obligation obligation) { for (ObligationCriterion criterion : criteria) { if (!criterion.match(obligation)) { return false; } } return true; } }
{ "content_hash": "e3432c60ee9dc1c91228a8a7b5b9726e", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 72, "avg_line_length": 26.166666666666668, "alnum_prop": 0.6624203821656051, "repo_name": "OpenConext/incubator-openaz-openconext", "id": "88ee2c2213897dd346bb2170fd54ae65e44df68f", "size": "1627", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "openaz-pep/src/main/java/org/apache/openaz/pepapi/std/ObligationCriteria.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "248858" }, { "name": "Java", "bytes": "5560443" }, { "name": "PLpgSQL", "bytes": "198552" } ], "symlink_target": "" }
import extensionStore from './store' import extensionRoutes from './router' import EventBus from 'core/plugins/event-bus' const EXTENSION_KEY = 'mailchimp-subscribe' export default function (app, router, store, config) { router.addRoutes(extensionRoutes) // add custom routes store.registerModule(EXTENSION_KEY, extensionStore) // add custom store console.log('Mailchimp extension registered') EventBus.$on('newsletter-after-unsubscribe', (payload) => { console.log('Mailchimp unsubscribe') store.dispatch('sync/queue', { url: config.mailchimp.endpoint, payload: { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, mode: 'cors', body: JSON.stringify(payload) } }, { root: true }).then(task => { console.log('Mailchimp subscription removed ') console.log(task) }) }) EventBus.$on('newsletter-after-subscribe', (payload) => { store.dispatch('sync/queue', { url: config.mailchimp.endpoint, payload: { method: 'POST', headers: { 'Content-Type': 'application/json' }, mode: 'cors', body: JSON.stringify(payload) } }, { root: true }).then(task => { console.log('Mailchimp subscription added ') console.log(task) }) }) return { EXTENSION_KEY, extensionRoutes, extensionStore } }
{ "content_hash": "d71f2be0ceb5738509b1f318b4565529", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 73, "avg_line_length": 33.7, "alnum_prop": 0.6468842729970327, "repo_name": "patrykpiston/vue-storefront", "id": "9983970b866ecf5215e1048f29a64df01fd35e49", "size": "1348", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/extensions/mailchimp-subscribe/index.js", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "25200" }, { "name": "HTML", "bytes": "2832" }, { "name": "JavaScript", "bytes": "236917" }, { "name": "Vue", "bytes": "393806" } ], "symlink_target": "" }
![Language](https://img.shields.io/badge/Python-2.7-blue.svg) ![ROS](https://img.shields.io/badge/ROS-Kinetic%20Kame-brightgreen.svg) ![Ubuntu](https://img.shields.io/badge/Ubuntu-16.04LTS-orange.svg) ![Version](https://img.shields.io/badge/version-1.0-brightgreen.svg) ![License MIT](https://img.shields.io/cocoapods/l/AFNetworking.svg) This project aims at providing a way to annotate rosbag files by using the method of sliding windows. The annotation procedure is done by using the `annotator.py` script. At the end of the annotation procedure, the script generates a json file with timestamps and other general information about the data tagged. The generated json file, together with its associated bag file is then feed into a second script called the `annotation_parser.py` that extract the actual data from the rosbag into a `csv` file, for further processing. Note that the objective of this program is to use a video image topic as a guide for tagging numerical data. It is useful, for instance, if you want to work with activity recognition and need to annotate data from numerical sensors, like accelerometers, that were recorded in a given moment in time. In this case, the image topic is used as a guide for tagging numerical data in the same rosbag file, since using only the numerical values would be hard. ## DEPENDENCIES * **OS:** `Ubuntu 16.04` * **Python:** `Version 2.7.xx`. You can check your version from terminal, with: `python -V`. * **Ros:** [`Kinetic Kame`](http://wiki.ros.org/kinetic/Installation/Ubuntu) * **Libraries:** ```bash $ sudo apt-get install ros-kinetic-python-qt-binding pyqt5-dev pyqt5-dev-tools python-pyqt5.qtmultimedia python-pyqt5 ``` ##### Possible compementary dependencies: Depending on how you install ros (desktop-full or just desktop), you may run into the `defaultServiceProvider::requestService(): no service found for - "org.qt-project.qt.mediaplayer"` problem when playing the rosbag image topics in the `annotator.py` script. It is a problem most likely related with the qtmultimedia part of the pyqt5 library. A quick solution would be to install qtmultimedia5.examples, by issuing the folowing command in the terminal: ```sudo apt-get install qtmultimedia5-examples``` ## Setup and Usage Before using the scripts, place in the `config.json` file, that should be placed in the same directory location of the other scripts, the set of label, and their values, that are going to be considered during the annotation. **The current version only allows for mutually exclusive labels, though**. Below, there is an example of a valid `config.json`: ```json { "Human": { "Activity": ["Walking", "Running", "Jumping"], "Speed": ["Slow", "Normal", "Fast", "Very Fast"], "Force Intensity": ["Weak", "Medium", "Strong"], }, "Robot": { "Speed": ["Slow", "Normal", "fast"], "Is Matching Human?" : ["No","Almost","Yes"] } } ``` Note that if must basically follow the python dictinary sintax. At this point in version, only two nested values are allowed in the config.jason. That is, a more broad feature perspective ("Human", "Robot") and the feature labels themselves with their values being a list of strings (In case of just one value, place it as a single-element list). The called feature perspectives are used for grouping the labels into tabs in the `annotator.py` interface. This is directed for the case where the annotating data that have multiple tags perspective, for instance, we can annotate the data with the human perspective or doing that taking into consideration the robot behavior in the scene or both. Run the annotator with `annotator.py` command for actual data annotation. You can control parameters like: `overlap`: the amount of overlap between consecutive windows; `windows size`: the size of the data windows in seconds. Note that you should make sure you are using the right image topic for the selection. A image topic selection combo box is present in the interface. Run the `annotation_parser.py` if you are interested in getting the annotated bag file data from the corresponding generated json file and its associated rosbag file. Load the two using the appropriated buttons, choose the topics you want to extract and press the `Export CSV` button. The program then is going to save csv files with the bag data, given the annotation described in the json file. It generates a csv file for each perspective, taking into account ther corresponding annotations in the jason. Get involved! ------------- I am happy to receive bug reports, fixes, documentation enhancements, and other improvements. Please report bugs via the `github issue` tracker. Master git repository: `https://github.com/ewerlopes/rosbag_annotator.git` If you want to contribute, here is a TODO list of what would be interesting to do: #### TODO 1. prevent program crash if the config.json is not correctly formated. 2. combine `the annotation_parser.py` into the `annotator.py`. In case we want to generate the CSV directly after completing the annotation in the `annotator.py`. 3. add multithreading for avoiding getting an unresponsable windows if a function call (like opening a file) takes time to be completed. 4. allowing for plotting numerical values of selected topics when annotating. This would be useful if we need to make sure the numeral values are behaving in a desired way. 5. Allowing to ignore taggin a certain windows. LICENSE ------- The MIT License (MIT) Copyright (c) 2016 Ewerton Lopes Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Authors ------- These scripts are maintained by Ewerton Lopes and Davide Orrù. Parts of the GUI interface code were originally designed by @Diminal, at this [fork](https://github.com/dimimal/rosbag_annotator). However, his work is a folow up of the work of @dsou in [here](https://github.com/dsgou/rosbag_annotator.git), both developers focusing on the task of annotating video. This project, however, focus on the idea of annotating data (numeral values), with the help of an image data.
{ "content_hash": "a1d3ffe757e67f1a9ece06e881b2c165", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 694, "avg_line_length": 84.55952380952381, "alnum_prop": 0.7623539349570604, "repo_name": "ewerlopes/rosbag_annotator", "id": "023b802f63043a8033e2840d914b5f69862e4c15", "size": "7138", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "80862" } ], "symlink_target": "" }
package de.matthiasmann.twlthemeeditor.imgconv; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Iterator; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.metadata.IIOMetadata; import javax.imageio.stream.ImageInputStream; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * * @author Matthias Mann */ public class ImageData { private static final Color TRANSPARENT = new Color(0, 0, 0, 0); private final ImageReader imageReader; private final int numImages; private final BufferedImage[] images; private final GIFImageMetadata[] gifImagesMetadata; private int backgroundColorIndex; private Node globalColorTable; private BufferedImage backgroundForNext; private Rectangle eraseForNext; private int lastImgNr; private ImageData(ImageReader imageReader, int numImages) throws IOException { this.imageReader = imageReader; this.numImages = numImages; this.images = new BufferedImage[numImages]; IIOMetadata iiom = imageReader.getStreamMetadata(); Node gifMetadata = getMetaDataTree(iiom, "javax_imageio_gif_stream_1.0"); if(gifMetadata != null) { this.gifImagesMetadata = new GIFImageMetadata[numImages]; Node logicalScreenDescriptor = getChildNode(gifMetadata, "LogicalScreenDescriptor"); int logicalScreenWidth = getInt(logicalScreenDescriptor, "logicalScreenWidth", 0); int logicalScreenHeight = getInt(logicalScreenDescriptor, "logicalScreenHeight", 0); if(logicalScreenWidth <= 0 || logicalScreenHeight <= 0) { for(int i=0 ; i<numImages ; i++) { GIFImageMetadata gifim = getGIFImageMetadata(i); logicalScreenWidth = Math.max(logicalScreenWidth, gifim.imageLeftPosition + gifim.imageWidth); logicalScreenHeight = Math.max(logicalScreenHeight, gifim.imageTopPosition + gifim.imageHeight); } } backgroundForNext = new BufferedImage(logicalScreenWidth, logicalScreenHeight, BufferedImage.TYPE_INT_ARGB); globalColorTable = getChildNode(gifMetadata, "GlobalColorTable"); backgroundColorIndex = getInt(globalColorTable, "backgroundColorIndex", -1); eraseForNext = new Rectangle(0, 0, logicalScreenWidth, logicalScreenHeight); } else { gifImagesMetadata = null; } } public int getNumImages() { return numImages; } public BufferedImage getImage(int imageIndex) { decodeTo(imageIndex); return images[imageIndex]; } public int getDelayMS(int imageIndex) { if(gifImagesMetadata != null) { GIFImageMetadata gifim = getGIFImageMetadata(imageIndex); return gifim.delayTimeMS; } else { return 100; // assume 10 Hz } } public static ImageData create(File file) { try { ImageInputStream iis = ImageIO.createImageInputStream(file); if(iis != null) { Iterator<ImageReader> iri = ImageIO.getImageReaders(iis); while(iri.hasNext()) { ImageReader ir = iri.next(); ir.setInput(iis); try { int num = ir.getNumImages(true); if(num >= 1) { return new ImageData(ir, num); } } catch (IOException ex) { } } } } catch (IOException ex) { } return null; } private GIFImageMetadata getGIFImageMetadata(int imageIndex) { GIFImageMetadata gifim = gifImagesMetadata[imageIndex]; if(gifim == null) { Node gifMetadata; try { IIOMetadata iiom = imageReader.getImageMetadata(imageIndex); gifMetadata = getMetaDataTree(iiom, "javax_imageio_gif_image_1.0"); } catch (IOException ignore) { gifMetadata = null; } gifim = new GIFImageMetadata(gifMetadata); gifImagesMetadata[imageIndex] = gifim; } return gifim; } private void decodeTo(int imageIndex) { while(lastImgNr <= imageIndex) { decodeNextImage(); } } private void decodeNextImage() { BufferedImage img; try { img = imageReader.read(lastImgNr); if(gifImagesMetadata != null) { img = postProcessGIF(lastImgNr, img); } } catch (IOException ex) { img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); } images[lastImgNr++] = img; } private BufferedImage postProcessGIF(int imageIndex, BufferedImage img) { GIFImageMetadata gifim = getGIFImageMetadata(imageIndex); BufferedImage tmp = new BufferedImage(backgroundForNext.getWidth(), backgroundForNext.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g = tmp.createGraphics(); try { g.setComposite(AlphaComposite.Src); g.drawImage(backgroundForNext, 0, 0, null); if(eraseForNext != null) { Color backgroundColor; if(gifim.transparentColorFlag && gifim.transparentColorIndex == backgroundColorIndex) { backgroundColor = TRANSPARENT; } else { Node colorEntry = getChildNodeWithIndex(gifim.localColorTable, "ColorTableEntry", backgroundColorIndex); if(colorEntry == null) { colorEntry = getChildNodeWithIndex(globalColorTable, "ColorTableEntry", backgroundColorIndex); } int red = getInt(colorEntry, "red", 0); int green = getInt(colorEntry, "green", 0); int blue = getInt(colorEntry, "blue", 0); backgroundColor = new Color(red, green, blue); } g.setColor(backgroundColor); g.fillRect(eraseForNext.x, eraseForNext.y, eraseForNext.width, eraseForNext.height); } g.setComposite(AlphaComposite.SrcOver); g.drawImage(img, gifim.imageLeftPosition, gifim.imageTopPosition, null); } finally { g.dispose(); } img = tmp; eraseForNext = null; if("doNotDispose".equals(gifim.disposalMethod) || "none".equals(gifim.disposalMethod)) { backgroundForNext = img; } else if("restoreToBackgroundColor".equals(gifim.disposalMethod)) { eraseForNext = new Rectangle(gifim.imageLeftPosition, gifim.imageTopPosition, gifim.imageWidth, gifim.imageHeight); } else { // assume "restoreToPrevious" - so nothing to change } return img; } static Node getMetaDataTree(IIOMetadata iiom, String format) { if(iiom != null) { try { return iiom.getAsTree(format); } catch (IllegalArgumentException ignore) { } } return null; } static Node getChildNode(Node node, String name) { if(node != null) { NodeList children = node.getChildNodes(); for(int i=0 ; i<children.getLength() ; i++) { Node child = children.item(i); if(name.equals(child.getNodeName())) { return child; } } } return null; } static Node getChildNodeWithIndex(Node node, String name, int index) { if(node != null) { NodeList children = node.getChildNodes(); for(int i=0 ; i<children.getLength() ; i++) { Node child = children.item(i); if(name.equals(child.getNodeName())) { int childIndex = getInt(child, "index", -1); if(childIndex == index) { return child; } } } } return null; } static String getStr(Node node, String attribute, String defaultValue) { if(node != null) { Node attribNode = node.getAttributes().getNamedItem(attribute); if(attribNode != null) { return attribNode.getNodeValue(); } } return defaultValue; } static int getInt(Node node, String attribute, int defaultValue) { String value = getStr(node, attribute, null); if(value != null) { try { return Integer.parseInt(value); } catch (IllegalArgumentException ignore) { } } return defaultValue; } static class GIFImageMetadata { final int imageLeftPosition; final int imageTopPosition; final int imageWidth; final int imageHeight; final int delayTimeMS; final String disposalMethod; final int transparentColorIndex; final boolean transparentColorFlag; final Node localColorTable; public GIFImageMetadata(Node gifMetadata) { Node imageDescriptor = getChildNode(gifMetadata, "ImageDescriptor"); imageLeftPosition = getInt(imageDescriptor, "imageLeftPosition", 0); imageTopPosition = getInt(imageDescriptor, "imageTopPosition", 0); imageWidth = getInt(imageDescriptor, "imageWidth", 1); imageHeight = getInt(imageDescriptor, "imageHeight", 1); Node graphicControlExtension = getChildNode(gifMetadata, "GraphicControlExtension"); delayTimeMS = getInt(graphicControlExtension, "delayTime", 10) * 10; // in 10 ms steps disposalMethod = getStr(graphicControlExtension, "disposalMethod", "none"); transparentColorIndex = getInt(graphicControlExtension, "transparentColorIndex", 255); transparentColorFlag = Boolean.parseBoolean(getStr(graphicControlExtension, "transparentColorFlag", "false")); localColorTable = getChildNode(gifMetadata, "LocalColorTable"); } } }
{ "content_hash": "cacb4fd0047fafb563d6ebee98e45b89", "timestamp": "", "source": "github", "line_count": 282, "max_line_length": 136, "avg_line_length": 37.08156028368794, "alnum_prop": 0.5921392368748207, "repo_name": "MatthiasMann/TWLThemeEditor", "id": "d0ad559ece9a400a9ccf944e2bfabd958d4db9b1", "size": "12059", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/de/matthiasmann/twlthemeeditor/imgconv/ImageData.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "1270" }, { "name": "HTML", "bytes": "9342" }, { "name": "Java", "bytes": "1341870" } ], "symlink_target": "" }
<?php namespace Cms\Model\Entity; use Cake\ORM\Entity; use Cake\Utility\Inflector; use Cms\Utility\PathManager; /** * CmsData Entity. */ class Page extends Entity { /** * Fields that can be mass assigned using newEntity() or patchEntity(). * * @var array */ protected $_accessible = [ 'title' => true, 'slug' => true, 'body' => true, 'state' => true, 'created_by' => true, 'modified_by' => true, ]; protected function _setTitle($title) { if ($this->get('slug') === Inflector::slug($this->getOriginal('title'))) { $this->set('slug', Inflector::slug($title)); } return $title; } protected function _setSlug($slug) { $slug = Inflector::slug($slug); return $slug; } protected function _getPath() { if(array_key_exists('id', $this->_properties)) { return PathManager::instance()->getPath('pages', $this->_properties['id']); } return null; } protected $_virtual = ['path']; }
{ "content_hash": "5e55b59d2ec08c3d55c5e2ecc5ffc44b", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 87, "avg_line_length": 20.923076923076923, "alnum_prop": 0.5330882352941176, "repo_name": "cakemanager/cakeadmin-cms", "id": "50134ca7b86e1d619ffcb5630595a89f168bfd40", "size": "1576", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Model/Entity/Page.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "46319" } ], "symlink_target": "" }
A `string` in F# is an object that represents immutable text as a sequence of Unicode characters (letters, digits, punctuation, etc.) and is defined as follows: ```fsharp let fruit = "Apple" ``` Strings are manipulated by either calling the string's methods, or using the `String` module's functions. Once a string has been constructed, its value can never change. Any methods/functions that appear to modify a string will actually return a new string. Strings can be concatenated or formatted a few different ways. * You can use the `+` operator for concatenation: ```fsharp let sentence = "Apple" + " is a type of fruit." ``` * You can use the `sprintf` function for formatting text, where you have placeholders in a format text (`%s` for a `string`) and provide the values as arguments: ```fsharp let sentence = sprintf "%s is a type of %s." "Apple" "fruit" ```
{ "content_hash": "29dc5622498616781c2ac2c8c13fc4e0", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 257, "avg_line_length": 51, "alnum_prop": 0.7416378316032295, "repo_name": "exercism/xfsharp", "id": "961e138334c6515df445b7bae7dbdc2f5644b6b3", "size": "883", "binary": false, "copies": "3", "ref": "refs/heads/main", "path": "exercises/concept/log-levels/.docs/introduction.md", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "199" }, { "name": "F#", "bytes": "389677" }, { "name": "Shell", "bytes": "1256" } ], "symlink_target": "" }
package com.dev2.intern.util; import java.util.UUID; /** * * @author MJYoun * @since 2017. 03. 06. * */ public class UuidUtil { public static String createUuidWithoutHyphen() { return UUID.randomUUID().toString().replaceAll("-", ""); } public static String createUuid() { return UUID.randomUUID().toString(); } }
{ "content_hash": "46ac958412790580f50137c5ee311852", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 58, "avg_line_length": 16.5, "alnum_prop": 0.6696969696969697, "repo_name": "MJ-Youn/CustomUtil", "id": "f8ccd7fa6ae6348230f3144d0a80d5dbd1525407", "size": "330", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "JAVA/UuidUtil.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "33865" }, { "name": "JavaScript", "bytes": "3553" } ], "symlink_target": "" }
package org.apache.commons.io.monitor; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ThreadFactory; /** * A runnable that spawns a monitoring thread triggering any * registered {@link FileAlterationObserver} at a specified interval. * * @see FileAlterationObserver * @version $Id: FileAlterationMonitor.java 1304052 2012-03-22 20:55:29Z ggregory $ * @since 2.0 */ public final class FileAlterationMonitor implements Runnable { private final long interval; private final List<FileAlterationObserver> observers = new CopyOnWriteArrayList<FileAlterationObserver>(); private Thread thread = null; private ThreadFactory threadFactory; private volatile boolean running = false; /** * Construct a monitor with a default interval of 10 seconds. */ public FileAlterationMonitor() { this(10000); } /** * Construct a monitor with the specified interval. * * @param interval The amount of time in miliseconds to wait between * checks of the file system */ public FileAlterationMonitor(long interval) { this.interval = interval; } /** * Construct a monitor with the specified interval and set of observers. * * @param interval The amount of time in miliseconds to wait between * checks of the file system * @param observers The set of observers to add to the monitor. */ public FileAlterationMonitor(long interval, FileAlterationObserver... observers) { this(interval); if (observers != null) { for (FileAlterationObserver observer : observers) { addObserver(observer); } } } /** * Return the interval. * * @return the interval */ public long getInterval() { return interval; } /** * Set the thread factory. * * @param threadFactory the thread factory */ public synchronized void setThreadFactory(ThreadFactory threadFactory) { this.threadFactory = threadFactory; } /** * Add a file system observer to this monitor. * * @param observer The file system observer to add */ public void addObserver(final FileAlterationObserver observer) { if (observer != null) { observers.add(observer); } } /** * Remove a file system observer from this monitor. * * @param observer The file system observer to remove */ public void removeObserver(final FileAlterationObserver observer) { if (observer != null) { while (observers.remove(observer)) { } } } /** * Returns the set of {@link FileAlterationObserver} registered with * this monitor. * * @return The set of {@link FileAlterationObserver} */ public Iterable<FileAlterationObserver> getObservers() { return observers; } /** * Start monitoring. * * @throws Exception if an error occurs initializing the observer */ public synchronized void start() throws Exception { if (running) { throw new IllegalStateException("Monitor is already running"); } for (FileAlterationObserver observer : observers) { observer.initialize(); } running = true; if (threadFactory != null) { thread = threadFactory.newThread(this); } else { thread = new Thread(this); } thread.start(); } /** * Stop monitoring. * * @throws Exception if an error occurs initializing the observer */ public synchronized void stop() throws Exception { stop(interval); } /** * Stop monitoring. * * @param stopInterval the amount of time in milliseconds to wait for the thread to finish. * A value of zero will wait until the thread is finished (see {@link Thread#join(long)}). * @throws Exception if an error occurs initializing the observer * @since 2.1 */ public synchronized void stop(long stopInterval) throws Exception { if (running == false) { throw new IllegalStateException("Monitor is not running"); } running = false; try { thread.join(stopInterval); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } for (FileAlterationObserver observer : observers) { observer.destroy(); } } /** * Run. */ public void run() { while (running) { for (FileAlterationObserver observer : observers) { observer.checkAndNotify(); } if (!running) { break; } try { Thread.sleep(interval); } catch (final InterruptedException ignored) { } } } }
{ "content_hash": "2e33fc624eb9a0a98d4a6cedd27d0f3a", "timestamp": "", "source": "github", "line_count": 178, "max_line_length": 110, "avg_line_length": 28.05056179775281, "alnum_prop": 0.6034448227518526, "repo_name": "tringuyen1401/Stock-analyzing", "id": "776ff197eb94ac9b0e01ed1fb833a8cd01415fc7", "size": "5795", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "jdbc/lib/commons-io-2.4-src/src/main/java/org/apache/commons/io/monitor/FileAlterationMonitor.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "23219" }, { "name": "HTML", "bytes": "75486542" }, { "name": "Java", "bytes": "2810339" }, { "name": "Rust", "bytes": "92" } ], "symlink_target": "" }
iconfontr ========= An icon font viewer and material exporter * open TTF font to view * export as SVG and PNG * batch export into different resolutions ![](screenshot.png) This project's developing has been recorded as a blog series on [io-meter](http://io-meter.com/categories/iconfontr/). ## LICENSE Distributed under BSD 3-clause. See LICENSE file.
{ "content_hash": "1e3ce3799877de8835808061db521ddd", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 118, "avg_line_length": 23.8, "alnum_prop": 0.742296918767507, "repo_name": "moodpo/iconfontr", "id": "07f347b27acfe9cc130f1f8a70721638dc449e82", "size": "357", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Objective-C", "bytes": "50818" } ], "symlink_target": "" }
{% extends "base.html" %} {% block head %} {{ super() }} <title>Steam Playtime - Error!</title> {% endblock %} {% block content %} <h2 class="text-center text-danger" >Error'd/10!!</h2> <hr> <p class="text-center text-danger">{{error_message|safe}}</p> {% endblock content %}
{ "content_hash": "3ece082eefa3f8d8290eea8453c22d19", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 62, "avg_line_length": 28, "alnum_prop": 0.6214285714285714, "repo_name": "naiyt/steamplaytime", "id": "802cc07eb40420a84d09976619ecc301c676f7e4", "size": "280", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "templates/error.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "84094" }, { "name": "JavaScript", "bytes": "57269" }, { "name": "Python", "bytes": "76015" } ], "symlink_target": "" }
namespace syncer { class CommitContribution; namespace syncable { class Directory; } // This class represents a source of items to commit to the sync server. // // When asked, it can return CommitContribution objects that contain a set of // items to be committed from this source. class CommitContributor { public: CommitContributor(); virtual ~CommitContributor() = 0; // Gathers up to |max_entries| unsynced items from this contributor into a // CommitContribution. Returns NULL when the contributor has nothing to // contribute. virtual scoped_ptr<CommitContribution> GetContribution( size_t max_entries) = 0; }; } // namespace #endif // SYNC_ENGINE_COMMIT_CONTRIBUTOR_H_
{ "content_hash": "754e0d95f1eb73e653f7cfe389c267cb", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 77, "avg_line_length": 26.074074074074073, "alnum_prop": 0.7428977272727273, "repo_name": "ChromiumWebApps/chromium", "id": "2d190af135f9f1cac548b20ddea5f30292a39d92", "size": "1012", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sync/engine/commit_contributor.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "853" }, { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "52960" }, { "name": "Awk", "bytes": "8660" }, { "name": "C", "bytes": "42286199" }, { "name": "C#", "bytes": "1132" }, { "name": "C++", "bytes": "198616766" }, { "name": "CSS", "bytes": "937333" }, { "name": "DOT", "bytes": "2984" }, { "name": "Java", "bytes": "5695686" }, { "name": "JavaScript", "bytes": "21967126" }, { "name": "M", "bytes": "2190" }, { "name": "Matlab", "bytes": "2262" }, { "name": "Objective-C", "bytes": "7602057" }, { "name": "PHP", "bytes": "97817" }, { "name": "Perl", "bytes": "1210885" }, { "name": "Python", "bytes": "10774996" }, { "name": "R", "bytes": "262" }, { "name": "Shell", "bytes": "1316721" }, { "name": "Tcl", "bytes": "277091" }, { "name": "TypeScript", "bytes": "1560024" }, { "name": "XSLT", "bytes": "13493" }, { "name": "nesC", "bytes": "15243" } ], "symlink_target": "" }
<?php namespace tests; use jamband\schemadump\SchemaDumpController; use PHPUnit\Framework\TestCase; use Yii; use yii\db\Connection; class SchemaDumpControllerPostgreSQLTest extends TestCase { private $controller; public function setUp(): void { $this->controller = new BufferedSchemaDumpPostgreSQLController('schemadump', Yii::$app); } public static function setUpBeforeClass(): void { Yii::$app->set('db', [ 'class' => Connection::class, 'dsn' => 'pgsql:host=localhost;dbname=yii2_schemadump_test', 'username' => 'postgres', 'password' => 'postgres', ]); Yii::$app->db->open(); $statements = array_filter(explode(';', file_get_contents(__DIR__.'/schemas/postgre.sql')), 'trim'); foreach ($statements as $statement) { Yii::$app->db->pdo->exec($statement); } } public static function tearDownAfterClass(): void { $db = Yii::$app->db; foreach ($db->schema->getTableNames() as $table) { $db->createCommand("drop table \"$table\" CASCADE")->execute(); } } public function testActionCreate(): void { $this->controller->run('create'); $this->assertSame(<<<'STDOUT' // 0010_pk_ai $this->createTable('{{%0010_pk_ai}}', [ 'id' => $this->primaryKey(), ], $this->tableOptions); // 0020_pk_not_ai $this->createTable('{{%0020_pk_not_ai}}', [ 'id' => $this->integer()->notNull(), 'PRIMARY KEY (id)', ], $this->tableOptions); // 0030_pk_bigint_ai $this->createTable('{{%0030_pk_bigint_ai}}', [ 'id' => $this->bigPrimaryKey(), ], $this->tableOptions); // 0040_composite_pks $this->createTable('{{%0040_composite_pks}}', [ 'foo_id' => $this->integer()->notNull(), 'bar_id' => $this->integer()->notNull(), 'PRIMARY KEY (foo_id, bar_id)', ], $this->tableOptions); // 0050_uks $this->createTable('{{%0050_uks}}', [ 'id' => $this->primaryKey(), 'username' => $this->string(20)->notNull()->unique(), 'email' => $this->string(255)->notNull()->unique(), 'password' => $this->string(255)->notNull(), ], $this->tableOptions); // 0100_types $this->createTable('{{%0100_types}}', [ 'bool' => $this->boolean()->notNull()->defaultValue(false), 'boolean' => $this->boolean()->notNull()->defaultValue(false), 'character' => $this->char(20)->notNull(), 'char' => $this->char(20)->notNull(), 'character_varying' => $this->string(20)->notNull(), 'varchar' => $this->string(20)->notNull(), 'text' => $this->text()->notNull(), 'binary' => $this->binary()->notNull(), 'real' => $this->float()->notNull(), 'decimal' => $this->decimal(20,10)->notNull(), 'numeric' => $this->decimal(20,10)->notNull(), 'money_decimal' => $this->decimal(19,4)->notNull(), 'money' => $this->money()->notNull(), 'smallint' => $this->smallInteger()->notNull(), 'integer' => $this->integer()->notNull(), 'bigint' => $this->bigInteger()->notNull(), 'date' => $this->date()->notNull(), 'time' => $this->time()->notNull(), 'timestamp' => $this->timestamp()->notNull(), ], $this->tableOptions); // 0200_default_values $this->createTable('{{%0200_default_values}}', [ 'integer' => $this->smallInteger()->notNull()->defaultValue(1), 'string' => $this->string()->notNull()->defaultValue('UNKNOWN'), ], $this->tableOptions); // 0300_comment $this->createTable('{{%0300_comment}}', [ 'username' => $this->string(20)->notNull()->comment('ユーザ名'), ], $this->tableOptions); // 0400_fk_parent $this->createTable('{{%0400_fk_parent}}', [ 'id' => $this->primaryKey(), ], $this->tableOptions); // 0410_fk_child $this->createTable('{{%0410_fk_child}}', [ 'id' => $this->primaryKey(), 'parent_id' => $this->integer()->notNull(), ], $this->tableOptions); // fk: 0410_fk_child $this->addForeignKey('fk_0410_fk_child_parent_id', '{{%0410_fk_child}}', 'parent_id', '{{%0400_fk_parent}}', 'id'); STDOUT , $this->controller->flushStdOutBuffer()); } public function testDropAction(): void { $this->controller->run('drop'); $this->assertSame(<<<'STDOUT' $this->dropTable('{{%0010_pk_ai}}'); $this->dropTable('{{%0020_pk_not_ai}}'); $this->dropTable('{{%0030_pk_bigint_ai}}'); $this->dropTable('{{%0040_composite_pks}}'); $this->dropTable('{{%0050_uks}}'); $this->dropTable('{{%0100_types}}'); $this->dropTable('{{%0200_default_values}}'); $this->dropTable('{{%0300_comment}}'); $this->dropTable('{{%0400_fk_parent}}'); $this->dropTable('{{%0410_fk_child}}'); // fk: parent_id STDOUT , $this->controller->flushStdOutBuffer()); } } class BufferedSchemaDumpPostgreSQLController extends SchemaDumpController { use StdOutBufferControllerTrait; }
{ "content_hash": "2d7a77e67775b1fa5c91a465468aae1e", "timestamp": "", "source": "github", "line_count": 158, "max_line_length": 115, "avg_line_length": 30.31645569620253, "alnum_prop": 0.5893528183716075, "repo_name": "jamband/yii2-schemadump", "id": "94988c29b670381ea901471d8f8c1ca13ae7eb0b", "size": "5026", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "tests/SchemaDumpControllerPostgreSQLTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "26676" } ], "symlink_target": "" }
package com.mulodo.survey.batch.tasklet; import java.io.File; import java.util.Date; import org.apache.commons.io.FileUtils; import org.springframework.batch.core.StepContribution; import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.batch.core.step.tasklet.Tasklet; import org.springframework.batch.repeat.RepeatStatus; import org.springframework.core.io.Resource; import com.mulodo.survey.util.Util; public class SurveyBackupTasklet implements Tasklet { // fromDirectory is folder that contain zip file private Resource fromDirectory; // toDirectory is folder that we want to move private Resource toDirectory; @Override public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { String dateString = Util.formatDate(new Date()); File fromFolder = fromDirectory.getFile(); File toFolder = new File(toDirectory.getFile(), dateString); if (!toFolder.exists()) { FileUtils.forceMkdir(toFolder); } else { if (!toFolder.isDirectory()) { throw new IllegalArgumentException("To folder isn't folder"); } } File[] files = fromFolder.listFiles(); File desFile; for (File file : files) { desFile = new File(toFolder, file.getName()); if (desFile.exists()) { desFile.delete(); } FileUtils.moveFileToDirectory(file, toFolder, false); } return RepeatStatus.FINISHED; } public Resource getFromDirectory() { return fromDirectory; } public void setFromDirectory(Resource fromDirectory) { this.fromDirectory = fromDirectory; } public Resource getToDirectory() { return toDirectory; } public void setToDirectory(Resource toDirectory) { this.toDirectory = toDirectory; } }
{ "content_hash": "5dbff9e4324c42a091dc911953b3a43d", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 89, "avg_line_length": 27.48611111111111, "alnum_prop": 0.6619504800404244, "repo_name": "le-tri-mulodo/survey-batch", "id": "0a9036d8c80adfe1941f17efa637004a3c643462", "size": "1979", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/com/mulodo/survey/batch/tasklet/SurveyBackupTasklet.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "33875" } ], "symlink_target": "" }
'use strict'; var chai = require('chai'), gulp = require('gulp'), mockGulpDest = require('mock-gulp-dest')(gulp), expect = chai.expect, mockPrompt = require('../../components/mockPrompt'), fs = require('fs'); require('../../slushfile'); describe('Generator Base', function() { var filesToExist = [ 'app/index.html', 'README.md' ], filesToNotExist = [ 'index.js', 'index.spec.js' ]; before(function() { fs.stat('temp', function (er, s) { if(!er && s.isDirectory()) { process.chdir('temp'); } else { fs.mkdir('temp'); process.chdir('temp'); } }); }); beforeEach(function() { mockPrompt({ appName: 'test-app', userName: 'test user', authorName: 'Fancypants Harlin', authorEmail: 'derp@derp.derp', appDescription: 'some description', moveon: true }); }); afterEach(function() { mockGulpDest = require('mock-gulp-dest')(gulp); // Reset mockGulpDest asserts }); filesToExist.forEach(function(file) { it('it should generate '+file, function(done) { assertGeneratedFile(file, done); }); }); filesToNotExist.forEach(function(file) { it('it should NOT generate '+file, function(done) { assertUnGeneratedFile(file, done); }); }); it('should exit if moveon is false', function(done) { mockPrompt({ moveon: false }); gulp .start('default') .once('task_stop', function() { mockGulpDest.assertDestNotContains(filesToExist); done(); }); }); ///////////////////// function assertGeneratedFile(file, cb) { gulp .start('default') .once('task_stop', function() { mockGulpDest.assertDestContains(file); cb(); }); } function assertUnGeneratedFile(file, cb) { gulp .start('default') .once('task_stop', function() { mockGulpDest.assertDestNotContains(file); cb(); }); } });
{ "content_hash": "db0321e8d955544673b16697cd8157e6", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 85, "avg_line_length": 26.976744186046513, "alnum_prop": 0.4853448275862069, "repo_name": "AquilaSagitta/daVinci", "id": "b30de8f0c43b5f939cdbe99aac0b0eb9c2e08020", "size": "2320", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "generators/base/base.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "135" }, { "name": "JavaScript", "bytes": "8179" } ], "symlink_target": "" }
FROM balenalib/up-core-debian:sid-build ENV NODE_VERSION 12.21.0 ENV YARN_VERSION 1.22.4 RUN for key in \ 6A010C5166006599AA17F08146C2130DFD2497F5 \ ; do \ gpg --batch --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --batch --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --batch --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \ done \ && curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-x64.tar.gz" \ && echo "ab121de3c472d76ec425480b0594e43109ee607bd57c3d5314bdb65fa816bf1c node-v$NODE_VERSION-linux-x64.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-x64.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-x64.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \ && gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && mkdir -p /opt/yarn \ && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \ && rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && npm config set unsafe-perm true -g --unsafe-perm \ && rm -rf /tmp/* CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \ && echo "Running test-stack@node" \ && chmod +x test-stack@node.sh \ && bash test-stack@node.sh \ && rm -rf test-stack@node.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 64-bit (x86-64) \nOS: Debian Sid \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v12.21.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{ "content_hash": "f75afa30a6d32065841193ed6dbed1e1", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 706, "avg_line_length": 67.3170731707317, "alnum_prop": 0.7068840579710145, "repo_name": "nghiant2710/base-images", "id": "6ddb4bac05837d9818f1d1a838ea132779a448e7", "size": "2781", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/node/up-core/debian/sid/12.21.0/build/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "144558581" }, { "name": "JavaScript", "bytes": "16316" }, { "name": "Shell", "bytes": "368690" } ], "symlink_target": "" }
/* Generic definitions */ /* Assertions (useful to generate conditional code) */ /* Current type and class (and size, if applicable) */ /* Value methods */ /* Interfaces (keys) */ /* Interfaces (values) */ /* Abstract implementations (keys) */ /* Abstract implementations (values) */ /* Static containers (keys) */ /* Static containers (values) */ /* Implementations */ /* Synchronized wrappers */ /* Unmodifiable wrappers */ /* Other wrappers */ /* Methods (keys) */ /* Methods (values) */ /* Methods (keys/values) */ /* Methods that have special names depending on keys (but the special names depend on values) */ /* Equality */ /* Object/Reference-only definitions (keys) */ /* Primitive-type-only definitions (keys) */ /* Object/Reference-only definitions (values) */ /* Primitive-type-only definitions (values) */ /* * Copyright (C) 2002-2013 Sebastiano Vigna * * 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 it.unimi.dsi.fastutil.doubles; /** An abstract class providing basic methods for functions implementing a type-specific interface. * * <P>Optional operations just throw an {@link * UnsupportedOperationException}. Generic versions of accessors delegate to * the corresponding type-specific counterparts following the interface rules * (they take care of returning <code>null</code> on a missing key). * * <P>This class handles directly a default return * value (including {@linkplain #defaultReturnValue() methods to access * it}). Instances of classes inheriting from this class have just to return * <code>defRetValue</code> to denote lack of a key in type-specific methods. The value * is serialized. * * <P>Implementing subclasses have just to provide type-specific <code>get()</code>, * type-specific <code>containsKey()</code>, and <code>size()</code> methods. * */ public abstract class AbstractDouble2FloatFunction implements Double2FloatFunction , java.io.Serializable { private static final long serialVersionUID = -4940583368468432370L; protected AbstractDouble2FloatFunction() {} /** * The default return value for <code>get()</code>, <code>put()</code> and * <code>remove()</code>. */ protected float defRetValue; public void defaultReturnValue( final float rv ) { defRetValue = rv; } public float defaultReturnValue() { return defRetValue; } public float put( double key, float value ) { throw new UnsupportedOperationException(); } public float remove( double key ) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } public boolean containsKey( final Object ok ) { return containsKey( ((((Double)(ok)).doubleValue())) ); } /** Delegates to the corresponding type-specific method, taking care of returning <code>null</code> on a missing key. * * <P>This method must check whether the provided key is in the map using <code>containsKey()</code>. Thus, * it probes the map <em>twice</em>. Implementors of subclasses should override it with a more efficient method. */ public Float get( final Object ok ) { final double k = ((((Double)(ok)).doubleValue())); return containsKey( k ) ? (Float.valueOf(get( k ))) : null; } /** Delegates to the corresponding type-specific method, taking care of returning <code>null</code> on a missing key. * * <P>This method must check whether the provided key is in the map using <code>containsKey()</code>. Thus, * it probes the map <em>twice</em>. Implementors of subclasses should override it with a more efficient method. */ public Float put( final Double ok, final Float ov ) { final double k = ((ok).doubleValue()); final boolean containsKey = containsKey( k ); final float v = put( k, ((ov).floatValue()) ); return containsKey ? (Float.valueOf(v)) : null; } /** Delegates to the corresponding type-specific method, taking care of returning <code>null</code> on a missing key. * * <P>This method must check whether the provided key is in the map using <code>containsKey()</code>. Thus, * it probes the map <em>twice</em>. Implementors of subclasses should override it with a more efficient method. */ public Float remove( final Object ok ) { final double k = ((((Double)(ok)).doubleValue())); final boolean containsKey = containsKey( k ); final float v = remove( k ); return containsKey ? (Float.valueOf(v)) : null; } }
{ "content_hash": "361e087f43aebdc27b6ed0387740176b", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 119, "avg_line_length": 41.389830508474574, "alnum_prop": 0.7162162162162162, "repo_name": "karussell/fastutil", "id": "79b66abe34969249e0e4077eb06c81607be5f65c", "size": "4884", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/it/unimi/dsi/fastutil/doubles/AbstractDouble2FloatFunction.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "554418" }, { "name": "Shell", "bytes": "23387" } ], "symlink_target": "" }
package prebuild
{ "content_hash": "bf265f404da373165ede874a1e6a28aa", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 16, "avg_line_length": 17, "alnum_prop": 0.8823529411764706, "repo_name": "qb0C80aE/clay", "id": "9a2022cde5941634d138bd19eea5234deba6b2c0", "size": "38", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "prebuild/prebuild.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "417590" } ], "symlink_target": "" }
namespace rubinius { class BakerGC; namespace capi { class Handles { private: Allocator<Handle>* allocator_; public: Handles() : allocator_(new Allocator<Handle>()) {} ~Handles(); Handle* allocate(STATE, Object* obj); uintptr_t allocate_index(STATE, Object* obj); Handle* find_index(uintptr_t index) { return allocator_->from_index(index); } bool validate(Handle* handle); void deallocate_handles(std::list<Handle*>* cached, unsigned int mark, BakerGC* young); void flush_all(NativeMethodEnvironment* env); Allocator<Handle>* allocator() const { return allocator_; } int size() const { return allocator_->in_use_; } }; } } #endif
{ "content_hash": "572561d6737cfb03d103040e810f9387", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 93, "avg_line_length": 17.555555555555557, "alnum_prop": 0.5848101265822785, "repo_name": "pH14/rubinius", "id": "4b6443607801736ec24e0a843b803083b0fd61ac", "size": "967", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "vm/capi/handles.hpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "527563" }, { "name": "C++", "bytes": "3156005" }, { "name": "CSS", "bytes": "12326" }, { "name": "D", "bytes": "4932" }, { "name": "Erlang", "bytes": "2023" }, { "name": "JavaScript", "bytes": "116027" }, { "name": "Objective-C", "bytes": "243" }, { "name": "Perl", "bytes": "256305" }, { "name": "Python", "bytes": "21905" }, { "name": "Ruby", "bytes": "8233565" }, { "name": "Scheme", "bytes": "557" }, { "name": "Shell", "bytes": "17685" } ], "symlink_target": "" }
package test // Session functional tests. import ( "bytes" "github.com/cmars/go.crypto/ssh" "io" "strings" "testing" ) func TestRunCommandSuccess(t *testing.T) { server := newServer(t) defer server.Shutdown() conn := server.Dial(clientConfig()) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatalf("session failed: %v", err) } defer session.Close() err = session.Run("true") if err != nil { t.Fatalf("session failed: %v", err) } } func TestHostKeyCheck(t *testing.T) { server := newServer(t) defer server.Shutdown() conf := clientConfig() k := conf.HostKeyChecker.(*storedHostKey) // change the key. k.keys["ssh-rsa"][25]++ conn, err := server.TryDial(conf) if err == nil { conn.Close() t.Fatalf("dial should have failed.") } else if !strings.Contains(err.Error(), "host key mismatch") { t.Fatalf("'host key mismatch' not found in %v", err) } } func TestRunCommandFailed(t *testing.T) { server := newServer(t) defer server.Shutdown() conn := server.Dial(clientConfig()) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatalf("session failed: %v", err) } defer session.Close() err = session.Run(`bash -c "kill -9 $$"`) if err == nil { t.Fatalf("session succeeded: %v", err) } } func TestRunCommandWeClosed(t *testing.T) { server := newServer(t) defer server.Shutdown() conn := server.Dial(clientConfig()) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatalf("session failed: %v", err) } err = session.Shell() if err != nil { t.Fatalf("shell failed: %v", err) } err = session.Close() if err != nil { t.Fatalf("shell failed: %v", err) } } func TestFuncLargeRead(t *testing.T) { server := newServer(t) defer server.Shutdown() conn := server.Dial(clientConfig()) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatalf("unable to create new session: %s", err) } stdout, err := session.StdoutPipe() if err != nil { t.Fatalf("unable to acquire stdout pipe: %s", err) } err = session.Start("dd if=/dev/urandom bs=2048 count=1") if err != nil { t.Fatalf("unable to execute remote command: %s", err) } buf := new(bytes.Buffer) n, err := io.Copy(buf, stdout) if err != nil { t.Fatalf("error reading from remote stdout: %s", err) } if n != 2048 { t.Fatalf("Expected %d bytes but read only %d from remote command", 2048, n) } } func TestInvalidTerminalMode(t *testing.T) { server := newServer(t) defer server.Shutdown() conn := server.Dial(clientConfig()) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatalf("session failed: %v", err) } defer session.Close() if err = session.RequestPty("vt100", 80, 40, ssh.TerminalModes{255: 1984}); err == nil { t.Fatalf("req-pty failed: successful request with invalid mode") } } func TestValidTerminalMode(t *testing.T) { server := newServer(t) defer server.Shutdown() conn := server.Dial(clientConfig()) defer conn.Close() session, err := conn.NewSession() if err != nil { t.Fatalf("session failed: %v", err) } defer session.Close() stdout, err := session.StdoutPipe() if err != nil { t.Fatalf("unable to acquire stdout pipe: %s", err) } stdin, err := session.StdinPipe() if err != nil { t.Fatalf("unable to acquire stdin pipe: %s", err) } tm := ssh.TerminalModes{ssh.ECHO: 0} if err = session.RequestPty("xterm", 80, 40, tm); err != nil { t.Fatalf("req-pty failed: %s", err) } err = session.Shell() if err != nil { t.Fatalf("session failed: %s", err) } stdin.Write([]byte("stty -a && exit\n")) var buf bytes.Buffer if _, err := io.Copy(&buf, stdout); err != nil { t.Fatalf("reading failed: %s", err) } if sttyOutput := buf.String(); !strings.Contains(sttyOutput, "-echo ") { t.Fatalf("terminal mode failure: expected -echo in stty output, got %s", sttyOutput) } }
{ "content_hash": "9585bf69de386f1bb1ce528664d968a4", "timestamp": "", "source": "github", "line_count": 177, "max_line_length": 89, "avg_line_length": 22.005649717514125, "alnum_prop": 0.6482670089858793, "repo_name": "cmars/go.crypto", "id": "51224401e13ce9d62f026b1c684d91c662ebb80b", "size": "4075", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ssh/test/session_test.go", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "53267" }, { "name": "C", "bytes": "5538" }, { "name": "Go", "bytes": "908608" } ], "symlink_target": "" }
/* eslint-env node */ /* eslint strict: [2, "global"] */ "use strict"; var http = require("http"); var path = require("path"); var del = require("del"); var argv = require("yargs").argv; var ecstatic = require("ecstatic"); var gulp = require("gulp"); var $ = require("gulp-load-plugins")(); var LessPluginCleanCSS = require("less-plugin-clean-css"); var cleancss = new LessPluginCleanCSS({ advanced: true }); var distDir = "dist/"; var exDir = "example/"; gulp.task("clean", function (cb) { del([distDir, exDir + "lib/"], cb); }); gulp.task("template", function () { return gulp.src("src/template.html") .pipe($.minifyHtml({ empty: true})) .pipe(gulp.dest(distDir)); }); gulp.task("js", ["template"], function () { function addSlashes( str ) { return (str + "").replace(/[\\"']/g, "\\$&").replace(/\u0000/g, "\\0"); } var template = addSlashes(require("fs").readFileSync(distDir + "template.html").toString()); del([distDir + "template.html"]); return gulp.src(["src/combo-breaker.js"]) .pipe($.concat("combo-breaker.min.js")) .pipe($.replace(/___TEMPLATE___/, template)) .pipe($.ngAnnotate()) .pipe($.uglify()) .pipe(gulp.dest(distDir)); }); gulp.task("css", function () { return gulp.src(["src/combo-breaker.less"]) .pipe($.less({ plugins: [cleancss], strictMath: true })) .pipe(gulp.dest(distDir)); }); gulp.task("build", ["js", "css"]); gulp.task("buildExample", ["build"], function () { var sources = require("wiredep")().js; sources.push(distDir + "**/*"); return gulp.src(sources) .pipe(gulp.dest(exDir + "lib/")); }); gulp.task("bump", function () { return gulp.src(["./bower.json", "./package.json"]) .pipe($.bump({ type: argv.t })) .pipe(gulp.dest(".")); }); gulp.task("serve", ["buildExample"], function () { http.createServer(ecstatic({ root: path.join(__dirname, exDir) })).listen(8888); gulp.watch(["src/**/*"], ["buildExample"]); }); gulp.task("default", ["build"]);
{ "content_hash": "95b7e20a3f36c41df5c2310aebe19cb5", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 96, "avg_line_length": 28.216216216216218, "alnum_prop": 0.5727969348659003, "repo_name": "dmcass/cc-combo-breaker", "id": "8997da4b4ea19d42a6448f626b863c93974f640c", "size": "2088", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gulpfile.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3230" }, { "name": "HTML", "bytes": "1438" }, { "name": "JavaScript", "bytes": "15540" } ], "symlink_target": "" }
/* * This file should not be included directly. Include t4vf_common.h instead. */ #ifndef __CXGB4VF_ADAPTER_H__ #define __CXGB4VF_ADAPTER_H__ #include <linux/interrupt.h> #include <linux/pci.h> #include <linux/spinlock.h> #include <linux/skbuff.h> #include <linux/if_ether.h> #include <linux/netdevice.h> #include "../cxgb4/t4_hw.h" /* * Constants of the implementation. */ enum { MAX_NPORTS = 1, /* max # of "ports" */ MAX_PORT_QSETS = 8, /* max # of Queue Sets / "port" */ MAX_ETH_QSETS = MAX_NPORTS*MAX_PORT_QSETS, /* * MSI-X interrupt index usage. */ MSIX_FW = 0, /* MSI-X index for firmware Q */ MSIX_IQFLINT = 1, /* MSI-X index base for Ingress Qs */ MSIX_EXTRAS = 1, MSIX_ENTRIES = MAX_ETH_QSETS + MSIX_EXTRAS, /* * The maximum number of Ingress and Egress Queues is determined by * the maximum number of "Queue Sets" which we support plus any * ancillary queues. Each "Queue Set" requires one Ingress Queue * for RX Packet Ingress Event notifications and two Egress Queues for * a Free List and an Ethernet TX list. */ INGQ_EXTRAS = 2, /* firmware event queue and */ /* forwarded interrupts */ MAX_INGQ = MAX_ETH_QSETS+INGQ_EXTRAS, MAX_EGRQ = MAX_ETH_QSETS*2, }; /* * Forward structure definition references. */ struct adapter; struct sge_eth_rxq; struct sge_rspq; /* * Per-"port" information. This is really per-Virtual Interface information * but the use of the "port" nomanclature makes it easier to go back and forth * between the PF and VF drivers ... */ struct port_info { struct adapter *adapter; /* our adapter */ u16 viid; /* virtual interface ID */ s16 xact_addr_filt; /* index of our MAC address filter */ u16 rss_size; /* size of VI's RSS table slice */ u8 pidx; /* index into adapter port[] */ s8 mdio_addr; u8 port_type; /* firmware port type */ u8 mod_type; /* firmware module type */ u8 port_id; /* physical port ID */ u8 nqsets; /* # of "Queue Sets" */ u8 first_qset; /* index of first "Queue Set" */ struct link_config link_cfg; /* physical port configuration */ }; /* * Scatter Gather Engine resources for the "adapter". Our ingress and egress * queues are organized into "Queue Sets" with one ingress and one egress * queue per Queue Set. These Queue Sets are aportionable between the "ports" * (Virtual Interfaces). One extra ingress queue is used to receive * asynchronous messages from the firmware. Note that the "Queue IDs" that we * use here are really "Relative Queue IDs" which are returned as part of the * firmware command to allocate queues. These queue IDs are relative to the * absolute Queue ID base of the section of the Queue ID space allocated to * the PF/VF. */ /* * SGE free-list queue state. */ struct rx_sw_desc; struct sge_fl { unsigned int avail; /* # of available RX buffers */ unsigned int pend_cred; /* new buffers since last FL DB ring */ unsigned int cidx; /* consumer index */ unsigned int pidx; /* producer index */ unsigned long alloc_failed; /* # of buffer allocation failures */ unsigned long large_alloc_failed; unsigned long starving; /* # of times FL was found starving */ /* * Write-once/infrequently fields. * ------------------------------- */ unsigned int cntxt_id; /* SGE relative QID for the free list */ unsigned int abs_id; /* SGE absolute QID for the free list */ unsigned int size; /* capacity of free list */ struct rx_sw_desc *sdesc; /* address of SW RX descriptor ring */ __be64 *desc; /* address of HW RX descriptor ring */ dma_addr_t addr; /* PCI bus address of hardware ring */ void __iomem *bar2_addr; /* address of BAR2 Queue registers */ unsigned int bar2_qid; /* Queue ID for BAR2 Queue registers */ }; /* * An ingress packet gather list. */ struct pkt_gl { struct page_frag frags[MAX_SKB_FRAGS]; void *va; /* virtual address of first byte */ unsigned int nfrags; /* # of fragments */ unsigned int tot_len; /* total length of fragments */ }; typedef int (*rspq_handler_t)(struct sge_rspq *, const __be64 *, const struct pkt_gl *); /* * State for an SGE Response Queue. */ struct sge_rspq { struct napi_struct napi; /* NAPI scheduling control */ const __be64 *cur_desc; /* current descriptor in queue */ unsigned int cidx; /* consumer index */ u8 gen; /* current generation bit */ u8 next_intr_params; /* holdoff params for next interrupt */ int offset; /* offset into current FL buffer */ unsigned int unhandled_irqs; /* bogus interrupts */ /* * Write-once/infrequently fields. * ------------------------------- */ u8 intr_params; /* interrupt holdoff parameters */ u8 pktcnt_idx; /* interrupt packet threshold */ u8 idx; /* queue index within its group */ u16 cntxt_id; /* SGE rel QID for the response Q */ u16 abs_id; /* SGE abs QID for the response Q */ __be64 *desc; /* address of hardware response ring */ dma_addr_t phys_addr; /* PCI bus address of ring */ void __iomem *bar2_addr; /* address of BAR2 Queue registers */ unsigned int bar2_qid; /* Queue ID for BAR2 Queue registers */ unsigned int iqe_len; /* entry size */ unsigned int size; /* capcity of response Q */ struct adapter *adapter; /* our adapter */ struct net_device *netdev; /* associated net device */ rspq_handler_t handler; /* the handler for this response Q */ }; /* * Ethernet queue statistics */ struct sge_eth_stats { unsigned long pkts; /* # of ethernet packets */ unsigned long lro_pkts; /* # of LRO super packets */ unsigned long lro_merged; /* # of wire packets merged by LRO */ unsigned long rx_cso; /* # of Rx checksum offloads */ unsigned long vlan_ex; /* # of Rx VLAN extractions */ unsigned long rx_drops; /* # of packets dropped due to no mem */ }; /* * State for an Ethernet Receive Queue. */ struct sge_eth_rxq { struct sge_rspq rspq; /* Response Queue */ struct sge_fl fl; /* Free List */ struct sge_eth_stats stats; /* receive statistics */ }; /* * SGE Transmit Queue state. This contains all of the resources associated * with the hardware status of a TX Queue which is a circular ring of hardware * TX Descriptors. For convenience, it also contains a pointer to a parallel * "Software Descriptor" array but we don't know anything about it here other * than its type name. */ struct tx_desc { /* * Egress Queues are measured in units of SGE_EQ_IDXSIZE by the * hardware: Sizes, Producer and Consumer indices, etc. */ __be64 flit[SGE_EQ_IDXSIZE/sizeof(__be64)]; }; struct tx_sw_desc; struct sge_txq { unsigned int in_use; /* # of in-use TX descriptors */ unsigned int size; /* # of descriptors */ unsigned int cidx; /* SW consumer index */ unsigned int pidx; /* producer index */ unsigned long stops; /* # of times queue has been stopped */ unsigned long restarts; /* # of queue restarts */ /* * Write-once/infrequently fields. * ------------------------------- */ unsigned int cntxt_id; /* SGE relative QID for the TX Q */ unsigned int abs_id; /* SGE absolute QID for the TX Q */ struct tx_desc *desc; /* address of HW TX descriptor ring */ struct tx_sw_desc *sdesc; /* address of SW TX descriptor ring */ struct sge_qstat *stat; /* queue status entry */ dma_addr_t phys_addr; /* PCI bus address of hardware ring */ void __iomem *bar2_addr; /* address of BAR2 Queue registers */ unsigned int bar2_qid; /* Queue ID for BAR2 Queue registers */ }; /* * State for an Ethernet Transmit Queue. */ struct sge_eth_txq { struct sge_txq q; /* SGE TX Queue */ struct netdev_queue *txq; /* associated netdev TX queue */ unsigned long tso; /* # of TSO requests */ unsigned long tx_cso; /* # of TX checksum offloads */ unsigned long vlan_ins; /* # of TX VLAN insertions */ unsigned long mapping_err; /* # of I/O MMU packet mapping errors */ }; /* * The complete set of Scatter/Gather Engine resources. */ struct sge { /* * Our "Queue Sets" ... */ struct sge_eth_txq ethtxq[MAX_ETH_QSETS]; struct sge_eth_rxq ethrxq[MAX_ETH_QSETS]; /* * Extra ingress queues for asynchronous firmware events and * forwarded interrupts (when in MSI mode). */ struct sge_rspq fw_evtq ____cacheline_aligned_in_smp; struct sge_rspq intrq ____cacheline_aligned_in_smp; spinlock_t intrq_lock; /* * State for managing "starving Free Lists" -- Free Lists which have * fallen below a certain threshold of buffers available to the * hardware and attempts to refill them up to that threshold have * failed. We have a regular "slow tick" timer process which will * make periodic attempts to refill these starving Free Lists ... */ DECLARE_BITMAP(starving_fl, MAX_EGRQ); struct timer_list rx_timer; /* * State for cleaning up completed TX descriptors. */ struct timer_list tx_timer; /* * Write-once/infrequently fields. * ------------------------------- */ u16 max_ethqsets; /* # of available Ethernet queue sets */ u16 ethqsets; /* # of active Ethernet queue sets */ u16 ethtxq_rover; /* Tx queue to clean up next */ u16 timer_val[SGE_NTIMERS]; /* interrupt holdoff timer array */ u8 counter_val[SGE_NCOUNTERS]; /* interrupt RX threshold array */ /* Decoded Adapter Parameters. */ u32 fl_pg_order; /* large page allocation size */ u32 stat_len; /* length of status page at ring end */ u32 pktshift; /* padding between CPL & packet data */ u32 fl_align; /* response queue message alignment */ u32 fl_starve_thres; /* Free List starvation threshold */ /* * Reverse maps from Absolute Queue IDs to associated queue pointers. * The absolute Queue IDs are in a compact range which start at a * [potentially large] Base Queue ID. We perform the reverse map by * first converting the Absolute Queue ID into a Relative Queue ID by * subtracting off the Base Queue ID and then use a Relative Queue ID * indexed table to get the pointer to the corresponding software * queue structure. */ unsigned int egr_base; unsigned int ingr_base; void *egr_map[MAX_EGRQ]; struct sge_rspq *ingr_map[MAX_INGQ]; }; /* * Utility macros to convert Absolute- to Relative-Queue indices and Egress- * and Ingress-Queues. The EQ_MAP() and IQ_MAP() macros which provide * pointers to Ingress- and Egress-Queues can be used as both L- and R-values */ #define EQ_IDX(s, abs_id) ((unsigned int)((abs_id) - (s)->egr_base)) #define IQ_IDX(s, abs_id) ((unsigned int)((abs_id) - (s)->ingr_base)) #define EQ_MAP(s, abs_id) ((s)->egr_map[EQ_IDX(s, abs_id)]) #define IQ_MAP(s, abs_id) ((s)->ingr_map[IQ_IDX(s, abs_id)]) /* * Macro to iterate across Queue Sets ("rxq" is a historic misnomer). */ #define for_each_ethrxq(sge, iter) \ for (iter = 0; iter < (sge)->ethqsets; iter++) /* * Per-"adapter" (Virtual Function) information. */ struct adapter { /* PCI resources */ void __iomem *regs; void __iomem *bar2; struct pci_dev *pdev; struct device *pdev_dev; /* "adapter" resources */ unsigned long registered_device_map; unsigned long open_device_map; unsigned long flags; struct adapter_params params; /* queue and interrupt resources */ struct { unsigned short vec; char desc[22]; } msix_info[MSIX_ENTRIES]; struct sge sge; /* Linux network device resources */ struct net_device *port[MAX_NPORTS]; const char *name; unsigned int msg_enable; /* debugfs resources */ struct dentry *debugfs_root; /* various locks */ spinlock_t stats_lock; }; enum { /* adapter flags */ FULL_INIT_DONE = (1UL << 0), USING_MSI = (1UL << 1), USING_MSIX = (1UL << 2), QUEUES_BOUND = (1UL << 3), }; /* * The following register read/write routine definitions are required by * the common code. */ /** * t4_read_reg - read a HW register * @adapter: the adapter * @reg_addr: the register address * * Returns the 32-bit value of the given HW register. */ static inline u32 t4_read_reg(struct adapter *adapter, u32 reg_addr) { return readl(adapter->regs + reg_addr); } /** * t4_write_reg - write a HW register * @adapter: the adapter * @reg_addr: the register address * @val: the value to write * * Write a 32-bit value into the given HW register. */ static inline void t4_write_reg(struct adapter *adapter, u32 reg_addr, u32 val) { writel(val, adapter->regs + reg_addr); } #ifndef readq static inline u64 readq(const volatile void __iomem *addr) { return readl(addr) + ((u64)readl(addr + 4) << 32); } static inline void writeq(u64 val, volatile void __iomem *addr) { writel(val, addr); writel(val >> 32, addr + 4); } #endif /** * t4_read_reg64 - read a 64-bit HW register * @adapter: the adapter * @reg_addr: the register address * * Returns the 64-bit value of the given HW register. */ static inline u64 t4_read_reg64(struct adapter *adapter, u32 reg_addr) { return readq(adapter->regs + reg_addr); } /** * t4_write_reg64 - write a 64-bit HW register * @adapter: the adapter * @reg_addr: the register address * @val: the value to write * * Write a 64-bit value into the given HW register. */ static inline void t4_write_reg64(struct adapter *adapter, u32 reg_addr, u64 val) { writeq(val, adapter->regs + reg_addr); } /** * port_name - return the string name of a port * @adapter: the adapter * @pidx: the port index * * Return the string name of the selected port. */ static inline const char *port_name(struct adapter *adapter, int pidx) { return adapter->port[pidx]->name; } /** * t4_os_set_hw_addr - store a port's MAC address in SW * @adapter: the adapter * @pidx: the port index * @hw_addr: the Ethernet address * * Store the Ethernet address of the given port in SW. Called by the common * code when it retrieves a port's Ethernet address from EEPROM. */ static inline void t4_os_set_hw_addr(struct adapter *adapter, int pidx, u8 hw_addr[]) { memcpy(adapter->port[pidx]->dev_addr, hw_addr, ETH_ALEN); } /** * netdev2pinfo - return the port_info structure associated with a net_device * @dev: the netdev * * Return the struct port_info associated with a net_device */ static inline struct port_info *netdev2pinfo(const struct net_device *dev) { return netdev_priv(dev); } /** * adap2pinfo - return the port_info of a port * @adap: the adapter * @pidx: the port index * * Return the port_info structure for the adapter. */ static inline struct port_info *adap2pinfo(struct adapter *adapter, int pidx) { return netdev_priv(adapter->port[pidx]); } /** * netdev2adap - return the adapter structure associated with a net_device * @dev: the netdev * * Return the struct adapter associated with a net_device */ static inline struct adapter *netdev2adap(const struct net_device *dev) { return netdev2pinfo(dev)->adapter; } /* * OS "Callback" function declarations. These are functions that the OS code * is "contracted" to provide for the common code. */ void t4vf_os_link_changed(struct adapter *, int, int); void t4vf_os_portmod_changed(struct adapter *, int); /* * SGE function prototype declarations. */ int t4vf_sge_alloc_rxq(struct adapter *, struct sge_rspq *, bool, struct net_device *, int, struct sge_fl *, rspq_handler_t); int t4vf_sge_alloc_eth_txq(struct adapter *, struct sge_eth_txq *, struct net_device *, struct netdev_queue *, unsigned int); void t4vf_free_sge_resources(struct adapter *); int t4vf_eth_xmit(struct sk_buff *, struct net_device *); int t4vf_ethrx_handler(struct sge_rspq *, const __be64 *, const struct pkt_gl *); irq_handler_t t4vf_intr_handler(struct adapter *); irqreturn_t t4vf_sge_intr_msix(int, void *); int t4vf_sge_init(struct adapter *); void t4vf_sge_start(struct adapter *); void t4vf_sge_stop(struct adapter *); #endif /* __CXGB4VF_ADAPTER_H__ */
{ "content_hash": "45a557e7ff055058acd221f980ef01aa", "timestamp": "", "source": "github", "line_count": 519, "max_line_length": 79, "avg_line_length": 30.25626204238921, "alnum_prop": 0.6754123415907788, "repo_name": "mikedlowis-prototypes/albase", "id": "6049f70e110c5701d0a6cb8685b3dbf2a78ab38d", "size": "17248", "binary": false, "copies": "1010", "ref": "refs/heads/master", "path": "source/kernel/drivers/net/ethernet/chelsio/cxgb4vf/adapter.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Assembly", "bytes": "10263145" }, { "name": "Awk", "bytes": "55187" }, { "name": "Batchfile", "bytes": "31438" }, { "name": "C", "bytes": "551654518" }, { "name": "C++", "bytes": "11818066" }, { "name": "CMake", "bytes": "122998" }, { "name": "Clojure", "bytes": "945" }, { "name": "DIGITAL Command Language", "bytes": "232099" }, { "name": "GDB", "bytes": "18113" }, { "name": "Gherkin", "bytes": "5110" }, { "name": "HTML", "bytes": "18291" }, { "name": "Lex", "bytes": "58937" }, { "name": "M4", "bytes": "561745" }, { "name": "Makefile", "bytes": "7082768" }, { "name": "Objective-C", "bytes": "634652" }, { "name": "POV-Ray SDL", "bytes": "546" }, { "name": "Perl", "bytes": "1229221" }, { "name": "Perl6", "bytes": "11648" }, { "name": "Python", "bytes": "316536" }, { "name": "Roff", "bytes": "4201130" }, { "name": "Shell", "bytes": "2436879" }, { "name": "SourcePawn", "bytes": "2711" }, { "name": "TeX", "bytes": "182745" }, { "name": "UnrealScript", "bytes": "12824" }, { "name": "Visual Basic", "bytes": "11568" }, { "name": "XS", "bytes": "1239" }, { "name": "Yacc", "bytes": "146537" } ], "symlink_target": "" }
/* Theme Name: Circles Wordpress Theme Theme URI: http://themeforest.net/item/circles-retina-responsive-multipurpose-theme/4739370 Author URI:http://themeforest.net/user/ThemeSmack Description: Clean Corporate Theme Author: ThemeSmack Team Version: 3.8 License: GNU General Public License v2.0 License URI: http://www.gnu.org/licenses/gpl-2.0.html */ /* FOOTER */ #text-4 { margin-bottom:0px;} #text-4 p { margin-bottom:10px;} #random-work-2 h2 { margin-top:10px;} .brande { color:#353739;} .pie { color:#7B7B7B;} /* slogan */ .two-headers a { display:none;} .two-headers { padding-right:0px;} .two-headers h2, h3 { text-align:center;} .container .theme-two-third { margin-bottom:0px;} .container .theme-one-third { margin-bottom:0px; /*text-align:center;*/} .container .theme-one-third .alignnone { margin:15px 5px 0px 0;} /* paralax */ .wrapper.border-tb-white.marble-color .container { padding-top:0px;} .sc-highlight { padding-top:0px; padding-bottom:0px;} .sc-highlight p { margin-top:0px; margin-bottom:0px; line-height:0px;} /* titular */ h1.encabezado2 { font-size: 24px; font-weight: 300; text-align:center; color:#0a928b;} h2.encabezado2 { font-size: 24px; font-weight: 300; text-align:center; color:#0a928b;} h3.encabezado2 { font-size: 24px; font-weight: 300; text-align:center; color:#0a928b;} h3.encabezado3 { font-size: 24px; font-weight: 300; text-align:center; margin-top:25px;} h3.encabezado4 {color: #45484A; font-size: 24px; font-weight: 300; text-align: left;} h3.encabezadofooter {color: #4D565D; font-size: 14px; font-weight: 800; margin-bottom: 20px; text-transform: uppercase; text-align:left;} h4.encabezado4 { text-align:center; font-weight: 600;} h4.encabezado5 { color: #e2e5e8; font-size: 4.8em; font-weight: 300; padding: 0.3em 0; text-align: center; text-transform: uppercase;} p.espaciado { padding-top:1.2em;} p.texto-banner{ color: #e2e5e8; font-size: 1.35em; line-height: 1.6em; text-align: center;} img.btn-app {margin:10px 5px 10px 5px;} /*slide */ .tp-caption h3 { color: #FFFFFF; font: 100 46px/1 'Open Sans',sans-serif; margin: 0 0 7px; text-transform: uppercase; } /* modificaciones */ .sc-highlight h5 {font-size:14px; font-weight:300;} .sc-highlight .theme-one-half { margin-bottom:0;} .sc-highlight .theme-one-half .aligncenter { margin-bottom:0;} .project-body p {color: #474747; display: inline-block; font-size: 1em; margin-bottom: 0; padding: 1.2em 0; text-align: left; width: 100%; } .featured-project h3 {text-align: left; font-size:12px;} p.boton-banner{ margin-top: 1.5em; padding: 2.5em; text-align: center;} body .btn-style3 { font: 14px 'open sans', arial, tahoma; color: #e2e5e8; text-shadow: 1px 1px 1px rgba(0,0,0,0.1); border: 1px solid rgba(0,205,200,1); padding: 19px 40px; box-shadow: none; border-radius: 3px; text-transform: uppercase; } .btn-style3:before { font-family: fontawesome; margin-right: 10px; } /* portafolio */ .gallery .item-con-t1 header { top:0;} .visible-on-hover h2 { font-weight:bold;} .visible-on-hover a { color:#FFF;} .visible-on-hover p { color:#aefffb; padding:1em; text-align:center;} .visible-on-hover p a {color:#aefffb;} /* project-info */ .project-info h2 { font-size:22px; font-weight:300;} .project-info h4 { font-size: 14px;font-weight: 800;margin-bottom: 25px;text-transform: uppercase; } .project-info h5 { font-size:18px; font-weight:300;} .single-gallery .grid_3 section.project-info h1 { line-height:1.2em; margin-bottom:10px;} section h3.app-titular2 {font-size: 16px; text-align:center; font-weight:800; text-transform:uppercase; margin:20px 0px 10px 0px;} section h3.app-titular {font-size: 16px; text-align:center; font-weight:300; text-transform:uppercase; margin:10px 0px 10px 0px;} section h4.app-titular {font-size: 14px; font-weight: 300; text-align:center; margin-top:10px; margin-bottom:10px;} section p.app-titular {font-size: 11px; text-align:center; margin-bottom:10px;} section.app-fondo {background-image: url(http://www.hogarreparacion.com/wp-content/uploads/2013/08/wall-encabezado2.jpg); background-attachment: fixed; background-position: left bottom; padding: 10px 10px; border:solid 1px #E6E6E6; border-radius:4px; } section.formulario-fondo {background-image: url(http://www.hogarreparacion.com/wp-content/uploads/2013/08/wall-encabezado2.jpg); background-attachment: fixed; background-position: left bottom; padding: 10px 10px; border:solid 1px #E6E6E6; border-radius:4px; margin-top:30px; } section.paginacion { margin-top:30px;} .widget_recent_works .grid_3 h3 { font-size: 16px; font-weight: 700; margin-bottom: 22px; text-transform: uppercase; text-align:left;} .item-con-t1 h3 { color: #FFFFFF; font-size: 14px;/*16px;*/ font-weight: 400; margin-bottom: 0; margin-top: 14px;} .item-con-t1 h3.tex-relacionado { color: #FFFFFF; font-size: 11px; font-weight: 400; text-transform: uppercase; margin-bottom:0px; margin-top:0px;} .project-info ul li h2 { font-size:14px; display:inline; margin-bottom:0px;} .project-info ul li h2 a { font-size:14px; font-weight:600; } .project-info ul li p { margin:0px;} /* footer */ .copyright span.color {color:#00cdc8;} .copyright span.empresa {color:#0aa4b5;} /* blog */ h4.auto { text-transform:uppercase;} /*titulo categorias*/ .post h1 { color: #3B74AA; font-size: 25px; font-weight: 100; margin-bottom: 15px; text-transform: none; } /*titulo post*/ h2.opcional { line-height: 35px; margin-top: 26px; text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.5); color: #E7EBEE; display: block; float: left; font-size: 30px; font-weight: 800; margin-bottom: 0; text-transform: uppercase; } h2.opcional span { font-weight: 100; font-size: 21px; clear: both; display: block; line-height: 1; text-transform: none; background: rgba(0,0,0,0.34); padding: 6px 10px 9px; text-shadow: none; } .single-portfolio.headerstyle2 .headline h2.opcional, .woocommerce.headerstyle2 .headline h2.opcional, .single-post.headerstyle2 .headline h2.opcional, .category.headerstyle2 .headline h2.opcional { margin-top: 10px; } div.wpgmappity_container img { background: none !important; background-color: none !important; max-width: none !important; } /* formulario servicios */ .wpcf7-form p { margin-bottom:0px;} .leyenda span.sc-form-icon, .leyenda span.sc-form-clear { color: #FFF; /* #ABACAD; */ display: inline-block; position: absolute; right: 10px; top: 12px;} .sc-form-row select { background-color: #FFFFFF; background-image: none; border: 1px solid #E3E3E3; color: #006E8E; line-height: normal; margin-bottom: 15px; padding: 10px 3%; width: 100%; } .wpcf7-file { font-size:85%;} /* .sc-form-row textarea { margin-top:10px;}*/ .wpcf7-form div.leyenda { background-color: #068e87; border: 1px solid #00cdc8; color: #FFF; /*#45484A*/ line-height: normal; margin-top: 10px; padding: 10px 3%; width: 94%; display:block; position:relative; border-radius:3px; cursor:pointer; overflow: hidden; position: relative; } .leyenda [type=file] { cursor: inherit; display: block; font-size: 999px; filter: alpha(opacity=0); min-height: 100%; min-width: 100%; opacity: 0; position: absolute; right: 0; text-align: right; top: 0; } section.formulario-fondo2 { background-attachment: fixed; background-image: url("http://www.hogarreparacion.com/wp-content/uploads/2013/08/wall-encabezado21.jpg"); background-position: left bottom; border: 1px solid #00cdc8; border-radius: 4px; padding: 15px; margin-bottom:25px; } section.formulario-fondo2 h3.app-titular { color:#FFF; font-size:18px;} section.formulario-fondo2 h5 {text-align: center; color:#d5fffd;} section.formulario-fondo2 .sc-form-row select {border-radius: 3px; color:#01847d; } section.formulario-fondo2 .sc-form-row input {border-radius: 3px 3px 0px 0px; } section.formulario-fondo2 .sc-form-row [type=submit] { border-radius:3px; font-weight: bold; color:#333; padding-right:3.5%;} section.formulario-fondo2 .sc-form-no-top-border input { border-radius: 0px;} section.formulario-fondo2 .sc-form-row span.sc-form-icon {} section.formulario-fondo2 .sc-form-row span.sc-form-clear { color:#FFF;} section.formulario-fondo2 .sc-form-row .sc-form-icon { color:#00afa6;} section.formulario-fondo2 .leyenda .sc-form-icon { color:#FFF;} section.formulario-fondo2 .leyenda { color:#FFF;} section.formulario-fondo2 .wpcf7-not-valid-tip {color: #D5FFFD; display: block; font-size: 1em; padding:5px 0px;} section.formulario-fondo2 div.wpcf7-validation-errors { border:2px solid #D5FFFD; color:#D5FFFD; border-radius:3px;} section.formulario-fondo2 div.wpcf7-mail-sent-ok { border:2px solid #D5FFFD; color:#D5FFFD; border-radius:3px;} /* actualizacion FR */ .theme-one-third section.formulario-fondo2 { margin-bottom:0px;} .theme-one-third section.formulario-fondo2 h2.encabezado2 { color:#FFF;} .theme-one-third section.formulario-fondo2 h1.encabezado2 { color:#FFF;} /* actualizacion IDIOMAS */ ul#qtranslate-chooser { padding-left:20px;} ul#qtranslate-chooser li { float:left; border:1px solid #FFF; list-style:none; border-radius:2px; margin:5px 5px 0px 0px;} ul#qtranslate-chooser li a.qtrans_flag_es { background: url('http://www.hogarreparacion.com/wp-content/plugins/qtranslate/flags/es.png') no-repeat scroll 0% 0% transparent;} ul#qtranslate-chooser li a.qtrans_flag_en { background: url('http://www.hogarreparacion.com/wp-content/plugins/qtranslate/flags/gb.png') no-repeat scroll 0% 0% transparent;}
{ "content_hash": "a135fca31f8c89e7425b862d3a40879a", "timestamp": "", "source": "github", "line_count": 297, "max_line_length": 276, "avg_line_length": 32.31649831649832, "alnum_prop": 0.7149406126276308, "repo_name": "JoseLuisPucChan/Proyecto4Cuatrimestre", "id": "5db38d0085b46979b4915e7d202bd14c0ad56ad1", "size": "9598", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Proyecto integrador/Web/Proyecto 1.2 proyeco Reparado/MCTuristic_Centro_Historico/MCTuristic_Centro_Historico/Recursos/slider/style.css", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "586832" }, { "name": "C#", "bytes": "812479" }, { "name": "CSS", "bytes": "1237225" }, { "name": "HTML", "bytes": "6193174" }, { "name": "JavaScript", "bytes": "3865649" }, { "name": "SQLPL", "bytes": "4339" } ], "symlink_target": "" }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XX XX Utils.cpp XX XX XX XX Has miscellaneous utility functions XX XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ #include "jitpch.h" #ifdef _MSC_VER #pragma hdrstop #endif #include "opcode.h" /*****************************************************************************/ // Define the string platform name based on compilation #ifdefs. This is the // same code for all platforms, hence it is here instead of in the targetXXX.cpp // files. #ifdef _TARGET_UNIX_ // Should we distinguish Mac? Can we? // Should we distinguish flavors of Unix? Can we? const char* Target::g_tgtPlatformName = "Unix"; #else // !_TARGET_UNIX_ const char* Target::g_tgtPlatformName = "Windows"; #endif // !_TARGET_UNIX_ /*****************************************************************************/ #define DECLARE_DATA // clang-format off extern const signed char opcodeSizes[] = { #define InlineNone_size 0 #define ShortInlineVar_size 1 #define InlineVar_size 2 #define ShortInlineI_size 1 #define InlineI_size 4 #define InlineI8_size 8 #define ShortInlineR_size 4 #define InlineR_size 8 #define ShortInlineBrTarget_size 1 #define InlineBrTarget_size 4 #define InlineMethod_size 4 #define InlineField_size 4 #define InlineType_size 4 #define InlineString_size 4 #define InlineSig_size 4 #define InlineRVA_size 4 #define InlineTok_size 4 #define InlineSwitch_size 0 // for now #define InlinePhi_size 0 // for now #define InlineVarTok_size 0 // remove #define OPDEF(name,string,pop,push,oprType,opcType,l,s1,s2,ctrl) oprType ## _size , #include "opcode.def" #undef OPDEF #undef InlineNone_size #undef ShortInlineVar_size #undef InlineVar_size #undef ShortInlineI_size #undef InlineI_size #undef InlineI8_size #undef ShortInlineR_size #undef InlineR_size #undef ShortInlineBrTarget_size #undef InlineBrTarget_size #undef InlineMethod_size #undef InlineField_size #undef InlineType_size #undef InlineString_size #undef InlineSig_size #undef InlineRVA_size #undef InlineTok_size #undef InlineSwitch_size #undef InlinePhi_size }; // clang-format on const BYTE varTypeClassification[] = { #define DEF_TP(tn, nm, jitType, verType, sz, sze, asze, st, al, tf, howUsed) tf, #include "typelist.h" #undef DEF_TP }; /*****************************************************************************/ /*****************************************************************************/ #ifdef DEBUG extern const char* const opcodeNames[] = { #define OPDEF(name, string, pop, push, oprType, opcType, l, s1, s2, ctrl) string, #include "opcode.def" #undef OPDEF }; extern const BYTE opcodeArgKinds[] = { #define OPDEF(name, string, pop, push, oprType, opcType, l, s1, s2, ctrl) (BYTE) oprType, #include "opcode.def" #undef OPDEF }; #endif /*****************************************************************************/ const char* varTypeName(var_types vt) { static const char* const varTypeNames[] = { #define DEF_TP(tn, nm, jitType, verType, sz, sze, asze, st, al, tf, howUsed) nm, #include "typelist.h" #undef DEF_TP }; assert((unsigned)vt < sizeof(varTypeNames) / sizeof(varTypeNames[0])); return varTypeNames[vt]; } #if defined(DEBUG) || defined(LATE_DISASM) /***************************************************************************** * * Return the name of the given register. */ const char* getRegName(regNumber reg, bool isFloat) { // Special-case REG_NA; it's not in the regNames array, but we might want to print it. if (reg == REG_NA) { return "NA"; } #if defined(_TARGET_X86_) && defined(LEGACY_BACKEND) static const char* const regNames[] = { #define REGDEF(name, rnum, mask, sname) sname, #include "register.h" }; static const char* const floatRegNames[] = { #define REGDEF(name, rnum, mask, sname) sname, #include "registerxmm.h" }; if (isFloat) { assert(reg < ArrLen(floatRegNames)); return floatRegNames[reg]; } else { assert(reg < ArrLen(regNames)); return regNames[reg]; } #elif defined(_TARGET_ARM64_) static const char* const regNames[] = { #define REGDEF(name, rnum, mask, xname, wname) xname, #include "register.h" }; assert(reg < ArrLen(regNames)); return regNames[reg]; #else static const char* const regNames[] = { #define REGDEF(name, rnum, mask, sname) sname, #include "register.h" }; assert(reg < ArrLen(regNames)); return regNames[reg]; #endif } const char* getRegName(unsigned reg, bool isFloat) // this is for gcencode.cpp and disasm.cpp that dont use the regNumber type { return getRegName((regNumber)reg, isFloat); } #endif // defined(DEBUG) || defined(LATE_DISASM) #if defined(DEBUG) const char* getRegNameFloat(regNumber reg, var_types type) { #ifdef _TARGET_ARM_ assert(genIsValidFloatReg(reg)); if (type == TYP_FLOAT) return getRegName(reg); else { const char* regName; switch (reg) { default: assert(!"Bad double register"); regName = "d??"; break; case REG_F0: regName = "d0"; break; case REG_F2: regName = "d2"; break; case REG_F4: regName = "d4"; break; case REG_F6: regName = "d6"; break; case REG_F8: regName = "d8"; break; case REG_F10: regName = "d10"; break; case REG_F12: regName = "d12"; break; case REG_F14: regName = "d14"; break; case REG_F16: regName = "d16"; break; case REG_F18: regName = "d18"; break; case REG_F20: regName = "d20"; break; case REG_F22: regName = "d22"; break; case REG_F24: regName = "d24"; break; case REG_F26: regName = "d26"; break; case REG_F28: regName = "d28"; break; case REG_F30: regName = "d30"; break; } return regName; } #elif defined(_TARGET_X86_) && defined(LEGACY_BACKEND) static const char* regNamesFloat[] = { #define REGDEF(name, rnum, mask, sname) sname, #include "registerxmm.h" }; assert((unsigned)reg < ArrLen(regNamesFloat)); return regNamesFloat[reg]; #elif defined(_TARGET_ARM64_) static const char* regNamesFloat[] = { #define REGDEF(name, rnum, mask, xname, wname) xname, #include "register.h" }; assert((unsigned)reg < ArrLen(regNamesFloat)); return regNamesFloat[reg]; #else static const char* regNamesFloat[] = { #define REGDEF(name, rnum, mask, sname) "x" sname, #include "register.h" }; #ifdef FEATURE_AVX_SUPPORT static const char* regNamesYMM[] = { #define REGDEF(name, rnum, mask, sname) "y" sname, #include "register.h" }; #endif // FEATURE_AVX_SUPPORT assert((unsigned)reg < ArrLen(regNamesFloat)); #ifdef FEATURE_AVX_SUPPORT if (type == TYP_SIMD32) { return regNamesYMM[reg]; } #endif // FEATURE_AVX_SUPPORT return regNamesFloat[reg]; #endif } /***************************************************************************** * * Displays a register set. * TODO-ARM64-Cleanup: don't allow ip0, ip1 as part of a range. */ void dspRegMask(regMaskTP regMask, size_t minSiz) { const char* sep = ""; printf("["); bool inRegRange = false; regNumber regPrev = REG_NA; regNumber regHead = REG_NA; // When we start a range, remember the first register of the range, so we don't use // range notation if the range contains just a single register. for (regNumber regNum = REG_INT_FIRST; regNum <= REG_INT_LAST; regNum = REG_NEXT(regNum)) { regMaskTP regBit = genRegMask(regNum); if ((regMask & regBit) != 0) { // We have a register to display. It gets displayed now if: // 1. This is the first register to display of a new range of registers (possibly because // no register has ever been displayed). // 2. This is the last register of an acceptable range (either the last integer register, // or the last of a range that is displayed with range notation). if (!inRegRange) { // It's the first register of a potential range. const char* nam = getRegName(regNum); printf("%s%s", sep, nam); minSiz -= strlen(sep) + strlen(nam); // By default, we're not starting a potential register range. sep = " "; // What kind of separator should we use for this range (if it is indeed going to be a range)? CLANG_FORMAT_COMMENT_ANCHOR; #if defined(_TARGET_AMD64_) // For AMD64, create ranges for int registers R8 through R15, but not the "old" registers. if (regNum >= REG_R8) { regHead = regNum; inRegRange = true; sep = "-"; } #elif defined(_TARGET_ARM64_) // R17 and R28 can't be the start of a range, since the range would include TEB or FP if ((regNum < REG_R17) || ((REG_R19 <= regNum) && (regNum < REG_R28))) { regHead = regNum; inRegRange = true; sep = "-"; } #elif defined(_TARGET_ARM_) if (regNum < REG_R12) { regHead = regNum; inRegRange = true; sep = "-"; } #elif defined(_TARGET_X86_) // No register ranges #else // _TARGET_* #error Unsupported or unset target architecture #endif // _TARGET_* } #if defined(_TARGET_ARM64_) // We've already printed a register. Is this the end of a range? else if ((regNum == REG_INT_LAST) || (regNum == REG_R17) // last register before TEB || (regNum == REG_R28)) // last register before FP #else // _TARGET_ARM64_ // We've already printed a register. Is this the end of a range? else if (regNum == REG_INT_LAST) #endif // _TARGET_ARM64_ { const char* nam = getRegName(regNum); printf("%s%s", sep, nam); minSiz -= strlen(sep) + strlen(nam); inRegRange = false; // No longer in the middle of a register range regHead = REG_NA; sep = " "; } } else // ((regMask & regBit) == 0) { if (inRegRange) { assert(regHead != REG_NA); if (regPrev != regHead) { // Close out the previous range, if it included more than one register. const char* nam = getRegName(regPrev); printf("%s%s", sep, nam); minSiz -= strlen(sep) + strlen(nam); } sep = " "; inRegRange = false; regHead = REG_NA; } } if (regBit > regMask) { break; } regPrev = regNum; } #if CPU_HAS_BYTE_REGS if (regMask & RBM_BYTE_REG_FLAG) { const char* nam = "BYTE"; printf("%s%s", sep, nam); minSiz -= (strlen(sep) + strlen(nam)); } #endif #if !FEATURE_STACK_FP_X87 if (strlen(sep) > 0) { // We've already printed something. sep = " "; } inRegRange = false; regPrev = REG_NA; regHead = REG_NA; for (regNumber regNum = REG_FP_FIRST; regNum <= REG_FP_LAST; regNum = REG_NEXT(regNum)) { regMaskTP regBit = genRegMask(regNum); if (regMask & regBit) { if (!inRegRange || (regNum == REG_FP_LAST)) { const char* nam = getRegName(regNum); printf("%s%s", sep, nam); minSiz -= strlen(sep) + strlen(nam); sep = "-"; regHead = regNum; } inRegRange = true; } else { if (inRegRange) { if (regPrev != regHead) { const char* nam = getRegName(regPrev); printf("%s%s", sep, nam); minSiz -= (strlen(sep) + strlen(nam)); } sep = " "; } inRegRange = false; } if (regBit > regMask) { break; } regPrev = regNum; } #endif printf("]"); while ((int)minSiz > 0) { printf(" "); minSiz--; } } //------------------------------------------------------------------------ // dumpILBytes: Helper for dumpSingleInstr() to dump hex bytes of an IL stream, // aligning up to a minimum alignment width. // // Arguments: // codeAddr - Pointer to IL byte stream to display. // codeSize - Number of bytes of IL byte stream to display. // alignSize - Pad out to this many characters, if fewer than this were written. // void dumpILBytes(const BYTE* const codeAddr, unsigned codeSize, unsigned alignSize) // number of characters to write, for alignment { for (IL_OFFSET offs = 0; offs < codeSize; ++offs) { printf(" %02x", *(codeAddr + offs)); } unsigned charsWritten = 3 * codeSize; for (unsigned i = charsWritten; i < alignSize; i++) { printf(" "); } } //------------------------------------------------------------------------ // dumpSingleInstr: Display a single IL instruction. // // Arguments: // codeAddr - Base pointer to a stream of IL instructions. // offs - Offset from codeAddr of the IL instruction to display. // prefix - Optional string to prefix the IL instruction with (if nullptr, no prefix is output). // // Return Value: // Size of the displayed IL instruction in the instruction stream, in bytes. (Add this to 'offs' to // get to the next instruction.) // unsigned dumpSingleInstr(const BYTE* const codeAddr, IL_OFFSET offs, const char* prefix) { const BYTE* opcodePtr = codeAddr + offs; const BYTE* startOpcodePtr = opcodePtr; const unsigned ALIGN_WIDTH = 3 * 6; // assume 3 characters * (1 byte opcode + 4 bytes data + 1 prefix byte) for // most things if (prefix != nullptr) { printf("%s", prefix); } OPCODE opcode = (OPCODE)getU1LittleEndian(opcodePtr); opcodePtr += sizeof(__int8); DECODE_OPCODE: if (opcode >= CEE_COUNT) { printf("\nIllegal opcode: %02X\n", (int)opcode); return (IL_OFFSET)(opcodePtr - startOpcodePtr); } /* Get the size of additional parameters */ size_t sz = opcodeSizes[opcode]; unsigned argKind = opcodeArgKinds[opcode]; /* See what kind of an opcode we have, then */ switch (opcode) { case CEE_PREFIX1: opcode = OPCODE(getU1LittleEndian(opcodePtr) + 256); opcodePtr += sizeof(__int8); goto DECODE_OPCODE; default: { __int64 iOp; double dOp; int jOp; DWORD jOp2; switch (argKind) { case InlineNone: dumpILBytes(startOpcodePtr, (unsigned)(opcodePtr - startOpcodePtr), ALIGN_WIDTH); printf(" %-12s", opcodeNames[opcode]); break; case ShortInlineVar: iOp = getU1LittleEndian(opcodePtr); goto INT_OP; case ShortInlineI: iOp = getI1LittleEndian(opcodePtr); goto INT_OP; case InlineVar: iOp = getU2LittleEndian(opcodePtr); goto INT_OP; case InlineTok: case InlineMethod: case InlineField: case InlineType: case InlineString: case InlineSig: case InlineI: iOp = getI4LittleEndian(opcodePtr); goto INT_OP; case InlineI8: iOp = getU4LittleEndian(opcodePtr); iOp |= (__int64)getU4LittleEndian(opcodePtr + 4) << 32; goto INT_OP; INT_OP: dumpILBytes(startOpcodePtr, (unsigned)((opcodePtr - startOpcodePtr) + sz), ALIGN_WIDTH); printf(" %-12s 0x%X", opcodeNames[opcode], iOp); break; case ShortInlineR: dOp = getR4LittleEndian(opcodePtr); goto FLT_OP; case InlineR: dOp = getR8LittleEndian(opcodePtr); goto FLT_OP; FLT_OP: dumpILBytes(startOpcodePtr, (unsigned)((opcodePtr - startOpcodePtr) + sz), ALIGN_WIDTH); printf(" %-12s %f", opcodeNames[opcode], dOp); break; case ShortInlineBrTarget: jOp = getI1LittleEndian(opcodePtr); goto JMP_OP; case InlineBrTarget: jOp = getI4LittleEndian(opcodePtr); goto JMP_OP; JMP_OP: dumpILBytes(startOpcodePtr, (unsigned)((opcodePtr - startOpcodePtr) + sz), ALIGN_WIDTH); printf(" %-12s %d (IL_%04x)", opcodeNames[opcode], jOp, (int)(opcodePtr + sz - codeAddr) + jOp); break; case InlineSwitch: jOp2 = getU4LittleEndian(opcodePtr); opcodePtr += 4; opcodePtr += jOp2 * 4; // Jump over the table dumpILBytes(startOpcodePtr, (unsigned)(opcodePtr - startOpcodePtr), ALIGN_WIDTH); printf(" %-12s", opcodeNames[opcode]); break; case InlinePhi: jOp2 = getU1LittleEndian(opcodePtr); opcodePtr += 1; opcodePtr += jOp2 * 2; // Jump over the table dumpILBytes(startOpcodePtr, (unsigned)(opcodePtr - startOpcodePtr), ALIGN_WIDTH); printf(" %-12s", opcodeNames[opcode]); break; default: assert(!"Bad argKind"); } opcodePtr += sz; break; } } printf("\n"); return (IL_OFFSET)(opcodePtr - startOpcodePtr); } //------------------------------------------------------------------------ // dumpILRange: Display a range of IL instructions from an IL instruction stream. // // Arguments: // codeAddr - Pointer to IL byte stream to display. // codeSize - Number of bytes of IL byte stream to display. // void dumpILRange(const BYTE* const codeAddr, unsigned codeSize) // in bytes { for (IL_OFFSET offs = 0; offs < codeSize;) { char prefix[100]; sprintf_s(prefix, _countof(prefix), "IL_%04x ", offs); unsigned codeBytesDumped = dumpSingleInstr(codeAddr, offs, prefix); offs += codeBytesDumped; } } /***************************************************************************** * * Display a variable set. */ const char* genES2str(BitVecTraits* traits, EXPSET_TP set) { const int bufSize = 17; static char num1[bufSize]; static char num2[bufSize]; static char* nump = num1; char* temp = nump; nump = (nump == num1) ? num2 : num1; sprintf_s(temp, bufSize, "%s", BitVecOps::ToString(traits, set)); return temp; } const char* refCntWtd2str(unsigned refCntWtd) { const int bufSize = 17; static char num1[bufSize]; static char num2[bufSize]; static char* nump = num1; char* temp = nump; nump = (nump == num1) ? num2 : num1; if (refCntWtd == BB_MAX_WEIGHT) { sprintf_s(temp, bufSize, "MAX "); } else { unsigned valueInt = refCntWtd / BB_UNITY_WEIGHT; unsigned valueFrac = refCntWtd % BB_UNITY_WEIGHT; if (valueFrac == 0) { sprintf_s(temp, bufSize, "%u ", valueInt); } else { sprintf_s(temp, bufSize, "%u.%02u", valueInt, (valueFrac * 100 / BB_UNITY_WEIGHT)); } } return temp; } #endif // DEBUG #if defined(DEBUG) || defined(INLINE_DATA) //------------------------------------------------------------------------ // Contains: check if the range includes a particular method // // Arguments: // info -- jit interface pointer // method -- method handle for the method of interest bool ConfigMethodRange::Contains(ICorJitInfo* info, CORINFO_METHOD_HANDLE method) { _ASSERT(m_inited == 1); // No ranges specified means all methods included. if (m_lastRange == 0) { return true; } // Check the hash. Note we can't use the cached hash here since // we may not be asking about the method currently being jitted. const unsigned hash = info->getMethodHash(method); for (unsigned i = 0; i < m_lastRange; i++) { if ((m_ranges[i].m_low <= hash) && (hash <= m_ranges[i].m_high)) { return true; } } return false; } //------------------------------------------------------------------------ // InitRanges: parse the range string and set up the range info // // Arguments: // rangeStr -- string to parse (may be nullptr) // capacity -- number ranges to allocate in the range array // // Notes: // Does some internal error checking; clients can use Error() // to determine if the range string couldn't be fully parsed // because of bad characters or too many entries, or had values // that were too large to represent. void ConfigMethodRange::InitRanges(const wchar_t* rangeStr, unsigned capacity) { // Make sure that the memory was zero initialized assert(m_inited == 0 || m_inited == 1); assert(m_entries == 0); assert(m_ranges == nullptr); assert(m_lastRange == 0); // Flag any crazy-looking requests assert(capacity < 100000); if (rangeStr == nullptr) { m_inited = 1; return; } // Allocate some persistent memory ICorJitHost* jitHost = g_jitHost; m_ranges = (Range*)jitHost->allocateMemory(capacity * sizeof(Range)); m_entries = capacity; const wchar_t* p = rangeStr; unsigned lastRange = 0; bool setHighPart = false; while ((*p != 0) && (lastRange < m_entries)) { while (*p == L' ') { p++; } int i = 0; while (L'0' <= *p && *p <= L'9') { int j = 10 * i + ((*p++) - L'0'); // Check for overflow if ((m_badChar != 0) && (j <= i)) { m_badChar = (p - rangeStr) + 1; } i = j; } // Was this the high part of a low-high pair? if (setHighPart) { // Yep, set it and move to the next range m_ranges[lastRange].m_high = i; // Sanity check that range is proper if ((m_badChar != 0) && (m_ranges[lastRange].m_high < m_ranges[lastRange].m_low)) { m_badChar = (p - rangeStr) + 1; } lastRange++; setHighPart = false; continue; } // Must have been looking for the low part of a range m_ranges[lastRange].m_low = i; while (*p == L' ') { p++; } // Was that the low part of a low-high pair? if (*p == L'-') { // Yep, skip the dash and set high part next time around. p++; setHighPart = true; continue; } // Else we have a point range, so set high = low m_ranges[lastRange].m_high = i; lastRange++; } // If we didn't parse the full range string, note index of the the // first bad char. if ((m_badChar != 0) && (*p != 0)) { m_badChar = (p - rangeStr) + 1; } // Finish off any remaining open range if (setHighPart) { m_ranges[lastRange].m_high = UINT_MAX; lastRange++; } assert(lastRange <= m_entries); m_lastRange = lastRange; m_inited = 1; } #endif // defined(DEBUG) || defined(INLINE_DATA) #if CALL_ARG_STATS || COUNT_BASIC_BLOCKS || COUNT_LOOPS || EMITTER_STATS || MEASURE_NODE_SIZE || MEASURE_MEM_ALLOC /***************************************************************************** * Histogram class. */ Histogram::Histogram(IAllocator* allocator, const unsigned* const sizeTable) : m_allocator(allocator), m_sizeTable(sizeTable), m_counts(nullptr) { unsigned sizeCount = 0; do { sizeCount++; } while ((sizeTable[sizeCount] != 0) && (sizeCount < 1000)); m_sizeCount = sizeCount; } Histogram::~Histogram() { if (m_counts != nullptr) { m_allocator->Free(m_counts); } } // We need to lazy allocate the histogram data so static `Histogram` variables don't try to // call the host memory allocator in the loader lock, which doesn't work. void Histogram::ensureAllocated() { if (m_counts == nullptr) { m_counts = new (m_allocator) unsigned[m_sizeCount + 1]; memset(m_counts, 0, (m_sizeCount + 1) * sizeof(*m_counts)); } } void Histogram::dump(FILE* output) { ensureAllocated(); unsigned t = 0; for (unsigned i = 0; i < m_sizeCount; i++) { t += m_counts[i]; } for (unsigned c = 0, i = 0; i <= m_sizeCount; i++) { if (i == m_sizeCount) { if (m_counts[i] == 0) { break; } fprintf(output, " > %7u", m_sizeTable[i - 1]); } else { if (i == 0) { fprintf(output, " <= "); } else { fprintf(output, "%7u .. ", m_sizeTable[i - 1] + 1); } fprintf(output, "%7u", m_sizeTable[i]); } c += m_counts[i]; fprintf(output, " ===> %7u count (%3u%% of total)\n", m_counts[i], (int)(100.0 * c / t)); } } void Histogram::record(unsigned size) { ensureAllocated(); unsigned i; for (i = 0; i < m_sizeCount; i++) { if (m_sizeTable[i] >= size) { break; } } m_counts[i]++; } #endif // CALL_ARG_STATS || COUNT_BASIC_BLOCKS || COUNT_LOOPS || EMITTER_STATS || MEASURE_NODE_SIZE /***************************************************************************** * Fixed bit vector class */ // bitChunkSize() - Returns number of bits in a bitVect chunk inline UINT FixedBitVect::bitChunkSize() { return sizeof(UINT) * 8; } // bitNumToBit() - Returns a bit mask of the given bit number inline UINT FixedBitVect::bitNumToBit(UINT bitNum) { assert(bitNum < bitChunkSize()); assert(bitChunkSize() <= sizeof(int) * 8); return 1 << bitNum; } // bitVectInit() - Initializes a bit vector of a given size FixedBitVect* FixedBitVect::bitVectInit(UINT size, Compiler* comp) { UINT bitVectMemSize, numberOfChunks; FixedBitVect* bv; assert(size != 0); numberOfChunks = (size - 1) / bitChunkSize() + 1; bitVectMemSize = numberOfChunks * (bitChunkSize() / 8); // size in bytes assert(bitVectMemSize * bitChunkSize() >= size); bv = (FixedBitVect*)comp->compGetMemA(sizeof(FixedBitVect) + bitVectMemSize, CMK_FixedBitVect); memset(bv->bitVect, 0, bitVectMemSize); bv->bitVectSize = size; return bv; } // bitVectSet() - Sets the given bit void FixedBitVect::bitVectSet(UINT bitNum) { UINT index; assert(bitNum <= bitVectSize); index = bitNum / bitChunkSize(); bitNum -= index * bitChunkSize(); bitVect[index] |= bitNumToBit(bitNum); } // bitVectTest() - Tests the given bit bool FixedBitVect::bitVectTest(UINT bitNum) { UINT index; assert(bitNum <= bitVectSize); index = bitNum / bitChunkSize(); bitNum -= index * bitChunkSize(); return (bitVect[index] & bitNumToBit(bitNum)) != 0; } // bitVectOr() - Or in the given bit vector void FixedBitVect::bitVectOr(FixedBitVect* bv) { UINT bitChunkCnt = (bitVectSize - 1) / bitChunkSize() + 1; assert(bitVectSize == bv->bitVectSize); // Or each chunks for (UINT i = 0; i < bitChunkCnt; i++) { bitVect[i] |= bv->bitVect[i]; } } // bitVectAnd() - And with passed in bit vector void FixedBitVect::bitVectAnd(FixedBitVect& bv) { UINT bitChunkCnt = (bitVectSize - 1) / bitChunkSize() + 1; assert(bitVectSize == bv.bitVectSize); // And each chunks for (UINT i = 0; i < bitChunkCnt; i++) { bitVect[i] &= bv.bitVect[i]; } } // bitVectGetFirst() - Find the first bit on and return bit num, // Return -1 if no bits found. UINT FixedBitVect::bitVectGetFirst() { return bitVectGetNext((UINT)-1); } // bitVectGetNext() - Find the next bit on given previous position and return bit num. // Return -1 if no bits found. UINT FixedBitVect::bitVectGetNext(UINT bitNumPrev) { UINT bitNum = (UINT)-1; UINT index; UINT bitMask; UINT bitChunkCnt = (bitVectSize - 1) / bitChunkSize() + 1; UINT i; if (bitNumPrev == (UINT)-1) { index = 0; bitMask = (UINT)-1; } else { UINT bit; index = bitNumPrev / bitChunkSize(); bitNumPrev -= index * bitChunkSize(); bit = bitNumToBit(bitNumPrev); bitMask = ~(bit | (bit - 1)); } // Find first bit for (i = index; i < bitChunkCnt; i++) { UINT bitChunk = bitVect[i] & bitMask; if (bitChunk != 0) { BitScanForward((ULONG*)&bitNum, bitChunk); break; } bitMask = 0xFFFFFFFF; } // Empty bit vector? if (bitNum == (UINT)-1) { return (UINT)-1; } bitNum += i * bitChunkSize(); assert(bitNum <= bitVectSize); return bitNum; } // bitVectGetNextAndClear() - Find the first bit on, clear it and return it. // Return -1 if no bits found. UINT FixedBitVect::bitVectGetNextAndClear() { UINT bitNum = (UINT)-1; UINT bitChunkCnt = (bitVectSize - 1) / bitChunkSize() + 1; UINT i; // Find first bit for (i = 0; i < bitChunkCnt; i++) { if (bitVect[i] != 0) { BitScanForward((ULONG*)&bitNum, bitVect[i]); break; } } // Empty bit vector? if (bitNum == (UINT)-1) { return (UINT)-1; } // Clear the bit in the right chunk bitVect[i] &= ~bitNumToBit(bitNum); bitNum += i * bitChunkSize(); assert(bitNum <= bitVectSize); return bitNum; } int SimpleSprintf_s(__in_ecount(cbBufSize - (pWriteStart - pBufStart)) char* pWriteStart, __in_ecount(cbBufSize) char* pBufStart, size_t cbBufSize, __in_z const char* fmt, ...) { assert(fmt); assert(pBufStart); assert(pWriteStart); assert((size_t)pBufStart <= (size_t)pWriteStart); int ret; // compute the space left in the buffer. if ((pBufStart + cbBufSize) < pWriteStart) { NO_WAY("pWriteStart is past end of buffer"); } size_t cbSpaceLeft = (size_t)((pBufStart + cbBufSize) - pWriteStart); va_list args; va_start(args, fmt); ret = vsprintf_s(pWriteStart, cbSpaceLeft, const_cast<char*>(fmt), args); va_end(args); if (ret < 0) { NO_WAY("vsprintf_s failed."); } return ret; } #ifdef DEBUG void hexDump(FILE* dmpf, const char* name, BYTE* addr, size_t size) { if (!size) { return; } assert(addr); fprintf(dmpf, "Hex dump of %s:\n", name); for (unsigned i = 0; i < size; i++) { if ((i % 16) == 0) { fprintf(dmpf, "\n %04X: ", i); } fprintf(dmpf, "%02X ", *addr++); } fprintf(dmpf, "\n\n"); } #endif // DEBUG void HelperCallProperties::init() { for (CorInfoHelpFunc helper = CORINFO_HELP_UNDEF; // initialize helper (helper < CORINFO_HELP_COUNT); // test helper for loop exit helper = CorInfoHelpFunc(int(helper) + 1)) // update helper to next { // Generally you want initialize these to their most typical/safest result // bool isPure = false; // true if the result only depends upon input args and not any global state bool noThrow = false; // true if the helper will never throw bool nonNullReturn = false; // true if the result will never be null or zero bool isAllocator = false; // true if the result is usually a newly created heap item, or may throw OutOfMemory bool mutatesHeap = false; // true if any previous heap objects [are|can be] modified bool mayRunCctor = false; // true if the helper call may cause a static constructor to be run. bool mayFinalize = false; // true if the helper call allocates an object that may need to run a finalizer switch (helper) { // Arithmetic helpers that cannot throw case CORINFO_HELP_LLSH: case CORINFO_HELP_LRSH: case CORINFO_HELP_LRSZ: case CORINFO_HELP_LMUL: case CORINFO_HELP_LNG2DBL: case CORINFO_HELP_ULNG2DBL: case CORINFO_HELP_DBL2INT: case CORINFO_HELP_DBL2LNG: case CORINFO_HELP_DBL2UINT: case CORINFO_HELP_DBL2ULNG: case CORINFO_HELP_FLTREM: case CORINFO_HELP_DBLREM: case CORINFO_HELP_FLTROUND: case CORINFO_HELP_DBLROUND: isPure = true; noThrow = true; break; // Arithmetic helpers that *can* throw. // This (or these) are not pure, in that they have "VM side effects"...but they don't mutate the heap. case CORINFO_HELP_ENDCATCH: noThrow = true; break; // Arithmetic helpers that may throw case CORINFO_HELP_LMOD: // Mods throw div-by zero, and signed mods have problems with the smallest integer // mod -1, case CORINFO_HELP_MOD: // which is not representable as a positive integer. case CORINFO_HELP_UMOD: case CORINFO_HELP_ULMOD: case CORINFO_HELP_UDIV: // Divs throw divide-by-zero. case CORINFO_HELP_DIV: case CORINFO_HELP_LDIV: case CORINFO_HELP_ULDIV: case CORINFO_HELP_LMUL_OVF: case CORINFO_HELP_ULMUL_OVF: case CORINFO_HELP_DBL2INT_OVF: case CORINFO_HELP_DBL2LNG_OVF: case CORINFO_HELP_DBL2UINT_OVF: case CORINFO_HELP_DBL2ULNG_OVF: isPure = true; break; // Heap Allocation helpers, these all never return null case CORINFO_HELP_NEWSFAST: case CORINFO_HELP_NEWSFAST_ALIGN8: isAllocator = true; nonNullReturn = true; noThrow = true; // only can throw OutOfMemory break; case CORINFO_HELP_NEW_CROSSCONTEXT: case CORINFO_HELP_NEWFAST: case CORINFO_HELP_READYTORUN_NEW: mayFinalize = true; // These may run a finalizer isAllocator = true; nonNullReturn = true; noThrow = true; // only can throw OutOfMemory break; // These allocation helpers do some checks on the size (and lower bound) inputs, // and can throw exceptions other than OOM. case CORINFO_HELP_NEWARR_1_VC: case CORINFO_HELP_NEWARR_1_ALIGN8: isAllocator = true; nonNullReturn = true; break; // These allocation helpers do some checks on the size (and lower bound) inputs, // and can throw exceptions other than OOM. case CORINFO_HELP_NEW_MDARR: case CORINFO_HELP_NEWARR_1_DIRECT: case CORINFO_HELP_NEWARR_1_OBJ: case CORINFO_HELP_NEWARR_1_R2R_DIRECT: case CORINFO_HELP_READYTORUN_NEWARR_1: mayFinalize = true; // These may run a finalizer isAllocator = true; nonNullReturn = true; break; // Heap Allocation helpers that are also pure case CORINFO_HELP_STRCNS: isPure = true; isAllocator = true; nonNullReturn = true; noThrow = true; // only can throw OutOfMemory break; case CORINFO_HELP_BOX: nonNullReturn = true; isAllocator = true; noThrow = true; // only can throw OutOfMemory break; case CORINFO_HELP_BOX_NULLABLE: // Box Nullable is not a 'pure' function // It has a Byref argument that it reads the contents of. // // So two calls to Box Nullable that pass the same address (with the same Value Number) // will produce different results when the contents of the memory pointed to by the Byref changes // isAllocator = true; noThrow = true; // only can throw OutOfMemory break; case CORINFO_HELP_RUNTIMEHANDLE_METHOD: case CORINFO_HELP_RUNTIMEHANDLE_CLASS: case CORINFO_HELP_RUNTIMEHANDLE_METHOD_LOG: case CORINFO_HELP_RUNTIMEHANDLE_CLASS_LOG: // logging helpers are not technically pure but can be optimized away isPure = true; noThrow = true; nonNullReturn = true; break; // type casting helpers case CORINFO_HELP_ISINSTANCEOFINTERFACE: case CORINFO_HELP_ISINSTANCEOFARRAY: case CORINFO_HELP_ISINSTANCEOFCLASS: case CORINFO_HELP_ISINSTANCEOFANY: case CORINFO_HELP_READYTORUN_ISINSTANCEOF: case CORINFO_HELP_TYPEHANDLE_TO_RUNTIMETYPE: isPure = true; noThrow = true; // These return null for a failing cast break; // type casting helpers that throw case CORINFO_HELP_CHKCASTINTERFACE: case CORINFO_HELP_CHKCASTARRAY: case CORINFO_HELP_CHKCASTCLASS: case CORINFO_HELP_CHKCASTANY: case CORINFO_HELP_CHKCASTCLASS_SPECIAL: case CORINFO_HELP_READYTORUN_CHKCAST: // These throw for a failing cast // But if given a null input arg will return null isPure = true; break; // helpers returning addresses, these can also throw case CORINFO_HELP_UNBOX: case CORINFO_HELP_GETREFANY: case CORINFO_HELP_LDELEMA_REF: isPure = true; break; // helpers that return internal handle case CORINFO_HELP_GETCLASSFROMMETHODPARAM: case CORINFO_HELP_GETSYNCFROMCLASSHANDLE: isPure = true; noThrow = true; break; // Helpers that load the base address for static variables. // We divide these between those that may and may not invoke // static class constructors. case CORINFO_HELP_GETSHARED_GCSTATIC_BASE: case CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE: case CORINFO_HELP_GETSHARED_GCSTATIC_BASE_DYNAMICCLASS: case CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE_DYNAMICCLASS: case CORINFO_HELP_GETGENERICS_GCTHREADSTATIC_BASE: case CORINFO_HELP_GETGENERICS_NONGCTHREADSTATIC_BASE: case CORINFO_HELP_GETSHARED_GCTHREADSTATIC_BASE: case CORINFO_HELP_GETSHARED_NONGCTHREADSTATIC_BASE: case CORINFO_HELP_CLASSINIT_SHARED_DYNAMICCLASS: case CORINFO_HELP_GETSHARED_GCTHREADSTATIC_BASE_DYNAMICCLASS: case CORINFO_HELP_GETSHARED_NONGCTHREADSTATIC_BASE_DYNAMICCLASS: case CORINFO_HELP_GETSTATICFIELDADDR_CONTEXT: case CORINFO_HELP_GETSTATICFIELDADDR_TLS: case CORINFO_HELP_GETGENERICS_GCSTATIC_BASE: case CORINFO_HELP_GETGENERICS_NONGCSTATIC_BASE: case CORINFO_HELP_READYTORUN_STATIC_BASE: case CORINFO_HELP_READYTORUN_GENERIC_STATIC_BASE: // These may invoke static class constructors // These can throw InvalidProgram exception if the class can not be constructed // isPure = true; nonNullReturn = true; mayRunCctor = true; break; case CORINFO_HELP_GETSHARED_GCSTATIC_BASE_NOCTOR: case CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE_NOCTOR: case CORINFO_HELP_GETSHARED_GCTHREADSTATIC_BASE_NOCTOR: case CORINFO_HELP_GETSHARED_NONGCTHREADSTATIC_BASE_NOCTOR: // These do not invoke static class constructors // isPure = true; noThrow = true; nonNullReturn = true; break; // GC Write barrier support // TODO-ARM64-Bug?: Can these throw or not? case CORINFO_HELP_ASSIGN_REF: case CORINFO_HELP_CHECKED_ASSIGN_REF: case CORINFO_HELP_ASSIGN_REF_ENSURE_NONHEAP: case CORINFO_HELP_ASSIGN_BYREF: case CORINFO_HELP_ASSIGN_STRUCT: mutatesHeap = true; break; // Accessing fields (write) case CORINFO_HELP_SETFIELD32: case CORINFO_HELP_SETFIELD64: case CORINFO_HELP_SETFIELDOBJ: case CORINFO_HELP_SETFIELDSTRUCT: case CORINFO_HELP_SETFIELDFLOAT: case CORINFO_HELP_SETFIELDDOUBLE: case CORINFO_HELP_ARRADDR_ST: mutatesHeap = true; break; // These helper calls always throw an exception case CORINFO_HELP_OVERFLOW: case CORINFO_HELP_VERIFICATION: case CORINFO_HELP_RNGCHKFAIL: case CORINFO_HELP_THROWDIVZERO: case CORINFO_HELP_THROWNULLREF: case CORINFO_HELP_THROW: case CORINFO_HELP_RETHROW: case CORINFO_HELP_THROW_ARGUMENTEXCEPTION: case CORINFO_HELP_THROW_ARGUMENTOUTOFRANGEEXCEPTION: break; // These helper calls may throw an exception case CORINFO_HELP_METHOD_ACCESS_CHECK: case CORINFO_HELP_FIELD_ACCESS_CHECK: case CORINFO_HELP_CLASS_ACCESS_CHECK: case CORINFO_HELP_DELEGATE_SECURITY_CHECK: case CORINFO_HELP_MON_EXIT_STATIC: break; // This is a debugging aid; it simply returns a constant address. case CORINFO_HELP_LOOP_CLONE_CHOICE_ADDR: isPure = true; noThrow = true; break; case CORINFO_HELP_DBG_IS_JUST_MY_CODE: case CORINFO_HELP_BBT_FCN_ENTER: case CORINFO_HELP_POLL_GC: case CORINFO_HELP_MON_ENTER: case CORINFO_HELP_MON_EXIT: case CORINFO_HELP_MON_ENTER_STATIC: case CORINFO_HELP_JIT_REVERSE_PINVOKE_ENTER: case CORINFO_HELP_JIT_REVERSE_PINVOKE_EXIT: case CORINFO_HELP_SECURITY_PROLOG: case CORINFO_HELP_SECURITY_PROLOG_FRAMED: case CORINFO_HELP_VERIFICATION_RUNTIME_CHECK: case CORINFO_HELP_GETFIELDADDR: case CORINFO_HELP_INIT_PINVOKE_FRAME: case CORINFO_HELP_JIT_PINVOKE_BEGIN: case CORINFO_HELP_JIT_PINVOKE_END: case CORINFO_HELP_GETCURRENTMANAGEDTHREADID: noThrow = true; break; // Not sure how to handle optimization involving the rest of these helpers default: // The most pessimistic results are returned for these helpers mutatesHeap = true; break; } m_isPure[helper] = isPure; m_noThrow[helper] = noThrow; m_nonNullReturn[helper] = nonNullReturn; m_isAllocator[helper] = isAllocator; m_mutatesHeap[helper] = mutatesHeap; m_mayRunCctor[helper] = mayRunCctor; m_mayFinalize[helper] = mayFinalize; } } //============================================================================= // AssemblyNamesList2 //============================================================================= // The string should be of the form // MyAssembly // MyAssembly;mscorlib;System // MyAssembly;mscorlib System AssemblyNamesList2::AssemblyNamesList2(const wchar_t* list, IAllocator* alloc) : m_alloc(alloc) { assert(m_alloc != nullptr); WCHAR prevChar = '?'; // dummy LPWSTR nameStart = nullptr; // start of the name currently being processed. nullptr if no current name AssemblyName** ppPrevLink = &m_pNames; for (LPWSTR listWalk = const_cast<LPWSTR>(list); prevChar != '\0'; prevChar = *listWalk, listWalk++) { WCHAR curChar = *listWalk; if (iswspace(curChar) || curChar == W(';') || curChar == W('\0')) { // // Found white-space // if (nameStart) { // Found the end of the current name; add a new assembly name to the list. AssemblyName* newName = new (m_alloc) AssemblyName(); // Null out the current character so we can do zero-terminated string work; we'll restore it later. *listWalk = W('\0'); // How much space do we need? int convertedNameLenBytes = WszWideCharToMultiByte(CP_UTF8, 0, nameStart, -1, nullptr, 0, nullptr, nullptr); newName->m_assemblyName = new (m_alloc) char[convertedNameLenBytes]; // convertedNameLenBytes includes // the trailing null character if (WszWideCharToMultiByte(CP_UTF8, 0, nameStart, -1, newName->m_assemblyName, convertedNameLenBytes, nullptr, nullptr) != 0) { *ppPrevLink = newName; ppPrevLink = &newName->m_next; } else { // Failed to convert the string. Ignore this string (and leak the memory). } nameStart = nullptr; // Restore the current character. *listWalk = curChar; } } else if (!nameStart) { // // Found the start of a new name // nameStart = listWalk; } } assert(nameStart == nullptr); // cannot be in the middle of a name *ppPrevLink = nullptr; // Terminate the last element of the list. } AssemblyNamesList2::~AssemblyNamesList2() { for (AssemblyName* pName = m_pNames; pName != nullptr; /**/) { AssemblyName* cur = pName; pName = pName->m_next; m_alloc->Free(cur->m_assemblyName); m_alloc->Free(cur); } } bool AssemblyNamesList2::IsInList(const char* assemblyName) { for (AssemblyName* pName = m_pNames; pName != nullptr; pName = pName->m_next) { if (_stricmp(pName->m_assemblyName, assemblyName) == 0) { return true; } } return false; } #ifdef FEATURE_JIT_METHOD_PERF CycleCount::CycleCount() : cps(CycleTimer::CyclesPerSecond()) { } bool CycleCount::GetCycles(unsigned __int64* time) { return CycleTimer::GetThreadCyclesS(time); } bool CycleCount::Start() { return GetCycles(&beginCycles); } double CycleCount::ElapsedTime() { unsigned __int64 nowCycles; (void)GetCycles(&nowCycles); return ((double)(nowCycles - beginCycles) / cps) * 1000.0; } bool PerfCounter::Start() { bool result = QueryPerformanceFrequency(&beg) != 0; if (!result) { return result; } freq = (double)beg.QuadPart / 1000.0; (void)QueryPerformanceCounter(&beg); return result; } // Return elapsed time from Start() in millis. double PerfCounter::ElapsedTime() { LARGE_INTEGER li; (void)QueryPerformanceCounter(&li); return (double)(li.QuadPart - beg.QuadPart) / freq; } #endif #ifdef DEBUG /***************************************************************************** * Return the number of digits in a number of the given base (default base 10). * Used when outputting strings. */ unsigned CountDigits(unsigned num, unsigned base /* = 10 */) { assert(2 <= base && base <= 16); // sanity check unsigned count = 1; while (num >= base) { num /= base; ++count; } return count; } #endif // DEBUG double FloatingPointUtils::convertUInt64ToDouble(unsigned __int64 uIntVal) { __int64 s64 = uIntVal; double d; if (s64 < 0) { #if defined(_TARGET_XARCH_) // RyuJIT codegen and clang (or gcc) may produce different results for casting uint64 to // double, and the clang result is more accurate. For example, // 1) (double)0x84595161401484A0UL --> 43e08b2a2c280290 (RyuJIT codegen or VC++) // 2) (double)0x84595161401484A0UL --> 43e08b2a2c280291 (clang or gcc) // If the folding optimization below is implemented by simple casting of (double)uint64_val // and it is compiled by clang, casting result can be inconsistent, depending on whether // the folding optimization is triggered or the codegen generates instructions for casting. // // The current solution is to force the same math as the codegen does, so that casting // result is always consistent. // d = (double)(int64_t)uint64 + 0x1p64 uint64_t adjHex = 0x43F0000000000000UL; d = (double)s64 + *(double*)&adjHex; #else d = (double)uIntVal; #endif } else { d = (double)uIntVal; } return d; } float FloatingPointUtils::convertUInt64ToFloat(unsigned __int64 u64) { double d = convertUInt64ToDouble(u64); return (float)d; } unsigned __int64 FloatingPointUtils::convertDoubleToUInt64(double d) { unsigned __int64 u64; if (d >= 0.0) { // Work around a C++ issue where it doesn't properly convert large positive doubles const double two63 = 2147483648.0 * 4294967296.0; if (d < two63) { u64 = UINT64(d); } else { // subtract 0x8000000000000000, do the convert then add it back again u64 = INT64(d - two63) + I64(0x8000000000000000); } return u64; } #ifdef _TARGET_XARCH_ // While the Ecma spec does not specifically call this out, // the case of conversion from negative double to unsigned integer is // effectively an overflow and therefore the result is unspecified. // With MSVC for x86/x64, such a conversion results in the bit-equivalent // unsigned value of the conversion to integer. Other compilers convert // negative doubles to zero when the target is unsigned. // To make the behavior consistent across OS's on TARGET_XARCH, // this double cast is needed to conform MSVC behavior. u64 = UINT64(INT64(d)); #else u64 = UINT64(d); #endif // _TARGET_XARCH_ return u64; } // Rounds a double-precision floating-point value to the nearest integer, // and rounds midpoint values to the nearest even number. double FloatingPointUtils::round(double x) { // ************************************************************************************ // IMPORTANT: Do not change this implementation without also updating Math.Round(double), // MathF.Round(float), and FloatingPointUtils::round(float) // ************************************************************************************ // If the number has no fractional part do nothing // This shortcut is necessary to workaround precision loss in borderline cases on some platforms if (x == (double)((INT64)x)) { return x; } // We had a number that was equally close to 2 integers. // We need to return the even one. double flrTempVal = floor(x + 0.5); if ((x == (floor(x) + 0.5)) && (fmod(flrTempVal, 2.0) != 0)) { flrTempVal -= 1.0; } return _copysign(flrTempVal, x); } // Windows x86 and Windows ARM/ARM64 may not define _copysignf() but they do define _copysign(). // We will redirect the macro to this other functions if the macro is not defined for the platform. // This has the side effect of a possible implicit upcasting for arguments passed in and an explicit // downcasting for the _copysign() call. #if (defined(_TARGET_X86_) || defined(_TARGET_ARM_) || defined(_TARGET_ARM64_)) && !defined(FEATURE_PAL) #if !defined(_copysignf) #define _copysignf (float)_copysign #endif #endif // Rounds a single-precision floating-point value to the nearest integer, // and rounds midpoint values to the nearest even number. float FloatingPointUtils::round(float x) { // ************************************************************************************ // IMPORTANT: Do not change this implementation without also updating MathF.Round(float), // Math.Round(double), and FloatingPointUtils::round(double) // ************************************************************************************ // If the number has no fractional part do nothing // This shortcut is necessary to workaround precision loss in borderline cases on some platforms if (x == (float)((INT32)x)) { return x; } // We had a number that was equally close to 2 integers. // We need to return the even one. float flrTempVal = floorf(x + 0.5f); if ((x == (floorf(x) + 0.5f)) && (fmodf(flrTempVal, 2.0f) != 0)) { flrTempVal -= 1.0f; } return _copysignf(flrTempVal, x); } namespace MagicDivide { template <int TableBase = 0, int TableSize, typename Magic> static const Magic* TryGetMagic(const Magic (&table)[TableSize], typename Magic::DivisorType index) { if ((index < TableBase) || (TableBase + TableSize <= index)) { return nullptr; } const Magic* p = &table[index - TableBase]; if (p->magic == 0) { return nullptr; } return p; }; template <typename T> struct UnsignedMagic { typedef T DivisorType; T magic; bool add; int shift; }; template <typename T> const UnsignedMagic<T>* TryGetUnsignedMagic(T divisor) { return nullptr; } template <> const UnsignedMagic<uint32_t>* TryGetUnsignedMagic(uint32_t divisor) { static const UnsignedMagic<uint32_t> table[]{ {0xaaaaaaab, false, 1}, // 3 {}, {0xcccccccd, false, 2}, // 5 {0xaaaaaaab, false, 2}, // 6 {0x24924925, true, 3}, // 7 {}, {0x38e38e39, false, 1}, // 9 {0xcccccccd, false, 3}, // 10 {0xba2e8ba3, false, 3}, // 11 {0xaaaaaaab, false, 3}, // 12 }; return TryGetMagic<3>(table, divisor); } template <> const UnsignedMagic<uint64_t>* TryGetUnsignedMagic(uint64_t divisor) { static const UnsignedMagic<uint64_t> table[]{ {0xaaaaaaaaaaaaaaab, false, 1}, // 3 {}, {0xcccccccccccccccd, false, 2}, // 5 {0xaaaaaaaaaaaaaaab, false, 2}, // 6 {0x2492492492492493, true, 3}, // 7 {}, {0xe38e38e38e38e38f, false, 3}, // 9 {0xcccccccccccccccd, false, 3}, // 10 {0x2e8ba2e8ba2e8ba3, false, 1}, // 11 {0xaaaaaaaaaaaaaaab, false, 3}, // 12 }; return TryGetMagic<3>(table, divisor); } //------------------------------------------------------------------------ // GetUnsignedMagic: Generates a magic number and shift amount for the magic // number unsigned division optimization. // // Arguments: // d - The divisor // add - Pointer to a flag indicating the kind of code to generate // shift - Pointer to the shift value to be returned // // Returns: // The magic number. // // Notes: // This code is adapted from _The_PowerPC_Compiler_Writer's_Guide_, pages 57-58. // The paper is based on "Division by invariant integers using multiplication" // by Torbjorn Granlund and Peter L. Montgomery in PLDI 94 template <typename T> T GetUnsignedMagic(T d, bool* add /*out*/, int* shift /*out*/) { assert((d >= 3) && !isPow2(d)); const UnsignedMagic<T>* magic = TryGetUnsignedMagic(d); if (magic != nullptr) { *shift = magic->shift; *add = magic->add; return magic->magic; } typedef typename jitstd::make_signed<T>::type ST; const unsigned bits = sizeof(T) * 8; const unsigned bitsMinus1 = bits - 1; const T twoNMinus1 = T(1) << bitsMinus1; *add = false; const T nc = -ST(1) - -ST(d) % ST(d); unsigned p = bitsMinus1; T q1 = twoNMinus1 / nc; T r1 = twoNMinus1 - (q1 * nc); T q2 = (twoNMinus1 - 1) / d; T r2 = (twoNMinus1 - 1) - (q2 * d); T delta; do { p++; if (r1 >= (nc - r1)) { q1 = 2 * q1 + 1; r1 = 2 * r1 - nc; } else { q1 = 2 * q1; r1 = 2 * r1; } if ((r2 + 1) >= (d - r2)) { if (q2 >= (twoNMinus1 - 1)) { *add = true; } q2 = 2 * q2 + 1; r2 = 2 * r2 + 1 - d; } else { if (q2 >= twoNMinus1) { *add = true; } q2 = 2 * q2; r2 = 2 * r2 + 1; } delta = d - 1 - r2; } while ((p < (bits * 2)) && ((q1 < delta) || ((q1 == delta) && (r1 == 0)))); *shift = p - bits; // resulting shift return q2 + 1; // resulting magic number } uint32_t GetUnsigned32Magic(uint32_t d, bool* add /*out*/, int* shift /*out*/) { return GetUnsignedMagic<uint32_t>(d, add, shift); } #ifdef _TARGET_64BIT_ uint64_t GetUnsigned64Magic(uint64_t d, bool* add /*out*/, int* shift /*out*/) { return GetUnsignedMagic<uint64_t>(d, add, shift); } #endif template <typename T> struct SignedMagic { typedef T DivisorType; T magic; int shift; }; template <typename T> const SignedMagic<T>* TryGetSignedMagic(T divisor) { return nullptr; } template <> const SignedMagic<int32_t>* TryGetSignedMagic(int32_t divisor) { static const SignedMagic<int32_t> table[]{ {0x55555556, 0}, // 3 {}, {0x66666667, 1}, // 5 {0x2aaaaaab, 0}, // 6 {0x92492493, 2}, // 7 {}, {0x38e38e39, 1}, // 9 {0x66666667, 2}, // 10 {0x2e8ba2e9, 1}, // 11 {0x2aaaaaab, 1}, // 12 }; return TryGetMagic<3>(table, divisor); } template <> const SignedMagic<int64_t>* TryGetSignedMagic(int64_t divisor) { static const SignedMagic<int64_t> table[]{ {0x5555555555555556, 0}, // 3 {}, {0x6666666666666667, 1}, // 5 {0x2aaaaaaaaaaaaaab, 0}, // 6 {0x4924924924924925, 1}, // 7 {}, {0x1c71c71c71c71c72, 0}, // 9 {0x6666666666666667, 2}, // 10 {0x2e8ba2e8ba2e8ba3, 1}, // 11 {0x2aaaaaaaaaaaaaab, 1}, // 12 }; return TryGetMagic<3>(table, divisor); } //------------------------------------------------------------------------ // GetSignedMagic: Generates a magic number and shift amount for // the magic number division optimization. // // Arguments: // denom - The denominator // shift - Pointer to the shift value to be returned // // Returns: // The magic number. // // Notes: // This code is previously from UTC where it notes it was taken from // _The_PowerPC_Compiler_Writer's_Guide_, pages 57-58. The paper is is based on // is "Division by invariant integers using multiplication" by Torbjorn Granlund // and Peter L. Montgomery in PLDI 94 template <typename T> T GetSignedMagic(T denom, int* shift /*out*/) { const SignedMagic<T>* magic = TryGetSignedMagic(denom); if (magic != nullptr) { *shift = magic->shift; return magic->magic; } const int bits = sizeof(T) * 8; const int bits_minus_1 = bits - 1; typedef typename jitstd::make_unsigned<T>::type UT; const UT two_nminus1 = UT(1) << bits_minus_1; int p; UT absDenom; UT absNc; UT delta; UT q1; UT r1; UT r2; UT q2; UT t; T result_magic; int result_shift; int iters = 0; absDenom = abs(denom); t = two_nminus1 + ((unsigned int)denom >> 31); absNc = t - 1 - (t % absDenom); // absolute value of nc p = bits_minus_1; // initialize p q1 = two_nminus1 / absNc; // initialize q1 = 2^p / abs(nc) r1 = two_nminus1 - (q1 * absNc); // initialize r1 = rem(2^p, abs(nc)) q2 = two_nminus1 / absDenom; // initialize q1 = 2^p / abs(denom) r2 = two_nminus1 - (q2 * absDenom); // initialize r1 = rem(2^p, abs(denom)) do { iters++; p++; q1 *= 2; // update q1 = 2^p / abs(nc) r1 *= 2; // update r1 = rem(2^p / abs(nc)) if (r1 >= absNc) { // must be unsigned comparison q1++; r1 -= absNc; } q2 *= 2; // update q2 = 2^p / abs(denom) r2 *= 2; // update r2 = rem(2^p / abs(denom)) if (r2 >= absDenom) { // must be unsigned comparison q2++; r2 -= absDenom; } delta = absDenom - r2; } while (q1 < delta || (q1 == delta && r1 == 0)); result_magic = q2 + 1; // resulting magic number if (denom < 0) { result_magic = -result_magic; } *shift = p - bits; // resulting shift return result_magic; } int32_t GetSigned32Magic(int32_t d, int* shift /*out*/) { return GetSignedMagic<int32_t>(d, shift); } #ifdef _TARGET_64BIT_ int64_t GetSigned64Magic(int64_t d, int* shift /*out*/) { return GetSignedMagic<int64_t>(d, shift); } #endif }
{ "content_hash": "b09103f05fadc104d92e1f7ff0b27a8b", "timestamp": "", "source": "github", "line_count": 2174, "max_line_length": 120, "avg_line_length": 29.99310027598896, "alnum_prop": 0.5342074994248908, "repo_name": "kyulee1/coreclr", "id": "85aec5464c1e768f36ad38886d4c670b1191956e", "size": "65205", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/jit/utils.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "939689" }, { "name": "Awk", "bytes": "5861" }, { "name": "Batchfile", "bytes": "149949" }, { "name": "C", "bytes": "3033230" }, { "name": "C#", "bytes": "134176775" }, { "name": "C++", "bytes": "68835435" }, { "name": "CMake", "bytes": "641442" }, { "name": "Groovy", "bytes": "202872" }, { "name": "Makefile", "bytes": "2736" }, { "name": "Objective-C", "bytes": "471678" }, { "name": "PAWN", "bytes": "903" }, { "name": "Perl", "bytes": "23640" }, { "name": "PowerShell", "bytes": "9319" }, { "name": "Python", "bytes": "242544" }, { "name": "Roff", "bytes": "529523" }, { "name": "Shell", "bytes": "222489" }, { "name": "Smalltalk", "bytes": "1162648" }, { "name": "SuperCollider", "bytes": "4752" }, { "name": "XSLT", "bytes": "1016" }, { "name": "Yacc", "bytes": "157348" } ], "symlink_target": "" }
set weSayDir=..\wesayDev copy /Y output\debug\*.dll %weSayDir%\lib\debug copy /Y output\debug\*.pdb %weSayDir%\lib\debug copy /Y output\debug\Palaso.BuildTasks.dll %weSayDir%\bld copy /Y %weSayDir%\lib\debug\palaso*.* %weSayDir%\output\debug pause
{ "content_hash": "391abea0e62bac91ce33e4595e8066f0", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 62, "avg_line_length": 27.77777777777778, "alnum_prop": 0.744, "repo_name": "hatton/libpalaso", "id": "29b0f85521b4a61945a29928c2342adc57e984d3", "size": "250", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "CopyTo Dev WeSay.bat", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "6038" }, { "name": "C#", "bytes": "5764106" }, { "name": "HTML", "bytes": "46279" }, { "name": "Makefile", "bytes": "529" }, { "name": "Python", "bytes": "7859" }, { "name": "Shell", "bytes": "9757" }, { "name": "XSLT", "bytes": "22208" } ], "symlink_target": "" }
namespace Moritz.Spec { /// <summary> /// A helper class storing a Mode and its proximity to another Mode. /// </summary> public class ModeProximity { public ModeProximity(Mode mode, int proximity) { _mode = mode; _proximity = proximity; } public override string ToString() { return $"Mode: {_mode.ToString()}, proximity={_proximity}"; } public Mode Mode { get => _mode; } private Mode _mode; public int Proximity { get => _proximity; } private readonly int _proximity = 0; } }
{ "content_hash": "3366616e4dd6248c68f1c2740b8a3dbe", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 72, "avg_line_length": 24.84, "alnum_prop": 0.5410628019323671, "repo_name": "notator/Moritz", "id": "0aac74611e3cba0a1c6092b84c2c743edd7bd1dc", "size": "623", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Moritz.Spec/ModeProximity.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "2460055" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8" ?> <object name="Lookup2ListItem" connection="TestConnectionString" generator="ObjectGenerator.xslt" xmlns="urn:schemas-bv:objectmodel"> <storage> <get name="fnLookupTable2_SelectList" type="fnlist" /> </storage> <tables> <table name="Lookup2ListItem"> <properties permissionObject="Test" /> <extfilters> <filter> <join>inner join dbo.LookupTable1 t1 on t1.Lookup1ID = Lookup2ParentID</join> <where> <expr param="par11" value="t1.Lookup1Field1 {0} @par11" /> </where> </filter> <filter> <join>inner join dbo.LookupTable1 t2 on t2.Lookup1ID = Lookup2ParentID</join> <where> <expr param="par21" value="t2.Lookup1ID {0} @par21" /> <expr param="par22" value="t2.Lookup1ID {0} @par22" /> </where> </filter> </extfilters> <searchpanel> <item name="par21" isParam="true" defaultoper=">=" labelId="par21_TtlId" location="Additional" editor="Numeric" range="false" mandatory="false" /> <item name="par22" isParam="true" defaultoper="&lt;=" labelId="par22_TtlId" location="Additional" editor="Numeric" /> <item name="Lookup2Field1" editor="Text" mandatory="true" labelId="lblID" default="DateTime.Now.ToString()" /> <item name="par11" isParam="true" editor="Text" labelId="par11_TtlId" /> <item name="Lookup2ParentID" editor="Lookup" labelId="lblIDLookup" lookupName="ParentLookupLookup" lookupType="Lookup1Table" lookupText='c.Lookup1ID.ToString() + " - " + c.Lookup1Field1' lookupValue="c.Lookup1ID" /> </searchpanel> <grid> <item name="Lookup2ID" key="true" /> <item name="Lookup2Field1" defaultSort="Descending" /> </grid> <lookups> <lookup name="ParentLookup" table="Lookup1Table" source="Lookup2ParentID" target="Lookup1ID" /> </lookups> <actions child="Lookup2Table"></actions> </table> </tables> </object>
{ "content_hash": "23ba0a689db01a1eecb0cc191c13d94c", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 170, "avg_line_length": 48.791666666666664, "alnum_prop": 0.5439795046968403, "repo_name": "EIDSS/EIDSS-Legacy", "id": "c65ea9733d069cd414008493c46b190f3ca48701", "size": "2344", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "EIDSS v5/bv.tests/Schema/Lookup2List.xml", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "ASP", "bytes": "256377" }, { "name": "Batchfile", "bytes": "30009" }, { "name": "C#", "bytes": "106160789" }, { "name": "CSS", "bytes": "833586" }, { "name": "HTML", "bytes": "7507" }, { "name": "Java", "bytes": "2188690" }, { "name": "JavaScript", "bytes": "17000221" }, { "name": "PLSQL", "bytes": "2499" }, { "name": "PLpgSQL", "bytes": "6422" }, { "name": "Pascal", "bytes": "159898" }, { "name": "PowerShell", "bytes": "339522" }, { "name": "Puppet", "bytes": "3758" }, { "name": "SQLPL", "bytes": "12198" }, { "name": "Smalltalk", "bytes": "301266" }, { "name": "Visual Basic", "bytes": "20819564" }, { "name": "XSLT", "bytes": "4253600" } ], "symlink_target": "" }
"use strict" /** * @see http://moobilejs.com/doc/latest/moobile.Control/Text * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com) * @edited 0.2.0 * @since 0.1.0 */ var Text = moobile.Text = new Class({ Extends: moobile.Control, /** * @see http://moobilejs.com/doc/latest/moobile.Control/Text#options * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com) * @edited 0.3.0 * @since 0.1.0 */ options: { tagName: 'span', text: null, }, /** * @overridden * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com) * @since 0.1.0 */ willBuild: function() { this.parent(); this.addClass('text'); }, /** * @overridden * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com) * @since 0.2.0 */ didBuild: function() { this.parent(); var text = this.options.text; if (text) this.setText(text); }, /** * @see http://moobilejs.com/doc/latest/moobile.Control/Text#setText * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com) * @edited 0.2.0 * @since 0.1.0 */ setText: function(text) { this.element.set('html', text instanceof Text ? text.getText() : (text || typeof text === 'number' ? text + '' : '')); return this; }, /** * @see http://moobilejs.com/doc/latest/moobile.Control/Text#getText * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com) * @since 0.1.0 */ getText: function() { return this.element.get('html'); }, /** * @see http://moobilejs.com/doc/latest/moobile.Control/Text#isEmpty * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com) * @since 0.2.0 */ isEmpty: function() { return !this.getText(); } }); /** * @see http://moobilejs.com/doc/latest/moobile.Control/Text#from * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com) * @since 0.2.0 */ Text.from = function(source) { if (source instanceof Text) return source; var text = new Text(); text.setText(source); return text; }; //------------------------------------------------------------------------------ // Roles //------------------------------------------------------------------------------ /** * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com) * @since 0.1.0 */ moobile.Component.defineRole('text', null, function(element) { this.addChildComponent(moobile.Component.create(Text, element, 'data-text')); });
{ "content_hash": "49c4c214e1df2c743ae71f48c878e694", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 121, "avg_line_length": 24.081632653061224, "alnum_prop": 0.601271186440678, "repo_name": "moobilejs/moobile-core", "id": "ba5e960bda64bc6c3ac26557fd7bcb204cb36911", "size": "2360", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/control/text.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "105265" }, { "name": "HTML", "bytes": "9750" }, { "name": "JavaScript", "bytes": "467544" } ], "symlink_target": "" }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System.Collections.Generic; using System.Linq; using System.Xml.Serialization; using SharpGen.Config; using SharpGen.CppModel; namespace SharpGen.Model { [XmlType("interface")] public class CsInterface : CsTypeBase { public CsInterface() : this(null) { } public CsInterface(CppInterface cppInterface) { CppElement = cppInterface; if (cppInterface != null) Guid = cppInterface.Guid; NativeImplem = this; } public IEnumerable<CsMethod> Methods { get { return Items.OfType<CsMethod>(); } } public IEnumerable<CsProperty> Properties { get { return Items.OfType<CsProperty>(); } } protected override void UpdateFromTag(MappingRule tag) { base.UpdateFromTag(tag); IsCallback = tag.IsCallbackInterface.HasValue?tag.IsCallbackInterface.Value:false; IsDualCallback = tag.IsDualCallbackInterface.HasValue ? tag.IsDualCallbackInterface.Value : false; } /// <summary> /// Class Parent inheritance /// </summary> public CsTypeBase Base { get; set; } /// <summary> /// Interface Parent inheritance /// </summary> public CsTypeBase IBase { get; set; } public CsInterface NativeImplem { get; set; } public string Guid { get; set; } /// <summary> /// Only valid for inner interface. Specify the name of the property in the outer interface to access to the inner interface /// </summary> public string PropertyAccesName { get; set; } /// <summary> /// True if this interface is used as a callback to a C# object /// </summary> public bool IsCallback { get; set; } /// <summary> /// True if this interface is used as a dual-callback to a C# object /// </summary> public bool IsDualCallback { get; set; } /// <summary> /// List of declared inner structs /// </summary> public bool HasInnerInterfaces { get { return Items.OfType<CsInterface>().Count() > 0; } } /// <summary> /// Gets a value indicating whether this instance is base COM object. /// </summary> /// <value> /// <c>true</c> if this instance is base COM object; otherwise, <c>false</c>. /// </value> public bool IsBaseComObject { get { return Base != null && (Base as CsInterface).QualifiedName == Global.Name + ".ComObject"; } } public override string ToString() { return string.Format(System.Globalization.CultureInfo.InvariantCulture, "csinterface {0} => {1}", CppElementName, QualifiedName); } /// <summary> /// List of declared inner structs /// </summary> public IEnumerable<CsInterface> InnerInterfaces { get { return Items.OfType<CsInterface>(); } } } }
{ "content_hash": "19740189ffd1005c19e9f5156959bd6c", "timestamp": "", "source": "github", "line_count": 121, "max_line_length": 141, "avg_line_length": 34.97520661157025, "alnum_prop": 0.6200378071833649, "repo_name": "davidlee80/SharpDX-1", "id": "ee7d3c443edb9a968352ae6d76e45d28ca6bae6a", "size": "4234", "binary": false, "copies": "15", "ref": "refs/heads/master", "path": "Source/Tools/SharpGen/Model/CsInterface.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "3277" }, { "name": "C", "bytes": "2692245" }, { "name": "C#", "bytes": "11410481" }, { "name": "C++", "bytes": "7462517" }, { "name": "Groff", "bytes": "15315" }, { "name": "HTML", "bytes": "13912" }, { "name": "PowerShell", "bytes": "2056" } ], "symlink_target": "" }
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S15.10.2.6_A3_T11; * @section: 15.10.2.6; * @assertion: The production Assertion :: \b evaluates by returning an internal AssertionTester closure that takes a State argument x and performs the ...; * @description: Execute /\b\w{5}\b/.exec("pilot\nsoviet robot\topenoffice") and check results; */ __executed = /\b\w{5}\b/.exec("pilot\nsoviet robot\topenoffice"); __expected = ["pilot"]; __expected.index = 0; __expected.input = "pilot\nsoviet robot\topenoffice"; //CHECK#1 if (__executed.length !== __expected.length) { $ERROR('#1: __executed = /\\b\\w{5}\\b/.exec("pilot\\nsoviet robot\\topenoffice"); __executed.length === ' + __expected.length + '. Actual: ' + __executed.length); } //CHECK#2 if (__executed.index !== __expected.index) { $ERROR('#2: __executed = /\\b\\w{5}\\b/.exec("pilot\\nsoviet robot\\topenoffice"); __executed.index === ' + __expected.index + '. Actual: ' + __executed.index); } //CHECK#3 if (__executed.input !== __expected.input) { $ERROR('#3: __executed = /\\b\\w{5}\\b/.exec("pilot\\nsoviet robot\\topenoffice"); __executed.input === ' + __expected.input + '. Actual: ' + __executed.input); } //CHECK#4 for(var index=0; index<__expected.length; index++) { if (__executed[index] !== __expected[index]) { $ERROR('#4: __executed = /\\b\\w{5}\\b/.exec("pilot\\nsoviet robot\\topenoffice"); __executed[' + index + '] === ' + __expected[index] + '. Actual: ' + __executed[index]); } }
{ "content_hash": "003daa15d61e5673733ef514f64feca2", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 173, "avg_line_length": 41.23684210526316, "alnum_prop": 0.6317804722399489, "repo_name": "seraum/nectarjs", "id": "a49e6709373b6aaa14a89bab2cb83a276dbc3b33", "size": "1567", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "tests/ES3/Conformance/15_Native_ECMA_Script_Objects/15.10_RegExp_Objects/15.10.2_Pattern_Semantics/15.10.2.6_Assertion/S15.10.2.6_A3_T11.js", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "122" }, { "name": "CSS", "bytes": "28166" }, { "name": "HTML", "bytes": "43809" }, { "name": "JavaScript", "bytes": "55917" }, { "name": "Python", "bytes": "35" }, { "name": "TypeScript", "bytes": "45" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <title>账户权限 — 管理中心</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link rel="stylesheet" type="text/css" href="lib/bootstrap/css/bootstrap.css"> <link rel="stylesheet" type="text/css" href="css/main.css"> <script src="lib/jquery-1.7.2.min.js" type="text/javascript"></script> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <!--the top nav begin--> <div class="navbar navbar-default" role="navigation"> <div class="navbar-inner"> <div class="navbar-header"> <a class="navbar-brand" href="index.html">智慧农业物联网</a> </div> <ul class="nav navbar-nav pull-right" > <li id= "fat-menu" class="dropdown"> <a href="#" role="button" class="dropdown-toggle" data-toggle="dropdown"> <span class="glyphicon glyphicon-user"></span> 用户名 <span class="glyphicon glyphicon-chevron-down"></span> </a> <ul class="dropdown-menu" role="menu"> <li role="presentation"><a role="menuitem" tabindex="-1" href="account_info.html">我的账户</a></li> <li role="presentation"><a role="menuitem" tabindex="-1" href="#">登出</a></li> </ul> </li> </ul> </div> </div> <!--the top nav end--> <!--the sidebar nav begin --> <div class="sidebar-nav"> <a href="index.html" class="nav-header" ><span class="glyphicon glyphicon-home"></span> 管理中心 首页</a> <a href="#dashboard-menu" class="nav-header collapsed" data-toggle="collapse"><span class="glyphicon glyphicon-dashboard"></span> 设备管理<span class="glyphicon glyphicon-chevron-up"></span></a> <ul id="dashboard-menu" class="nav nav-list collapse"> <li ><a href="new_device.html">绑定新设备</a></li> <li ><a href="my_device.html">我的设备</a></li> <li ><a href="str_device.html">设备组织结构</a></li> </ul> <a href="led_manage.html" class="nav-header"><span class="glyphicon glyphicon-hd-video"></span> LED管理</a> <a href="real_time_data.html" class="nav-header"><span class="glyphicon glyphicon-eye-open"></span> 实时数据</a> <a href="history_data.html" class="nav-header" ><span class="glyphicon glyphicon-cloud"></span> 历史数据查询</a> <a href="error.html" class="nav-header"><span class="glyphicon glyphicon-bell"></span> 异常警报<span class="label label-danger">4</span></a> <a href="#account-menu" class="nav-header collapsed" data-toggle="collapse"><span class="glyphicon glyphicon-user"></span> 账户管理 <span class="glyphicon glyphicon-chevron-up"></span></a> <ul id="account-menu" class="nav nav-list collapse in"> <li ><a href="account_info.html">我的账户</a></li> <li class="active"><a href="account_permission.html">账户权限</a></li> <li ><a href="change_password.html">修改密码</a></li> </ul> <a href="logout.html" class="nav-header" ><span class="glyphicon glyphicon-log-out"></span> 登出</a> </div> <!--the siderbar nav en--> <div class="content"> <div class="header"> <!--page title begin--> <h1 class="page-title">账户权限</h1> </div> <ul class="breadcrumb"> <li><a href="account_permission.html">账户权限</a> <span class="divider">/</span></li> <li class="active">账户管理</li> </ul> <!--page title end and the main content begin--> <div class="container"> <!--the toolbar begin --> <div class="toolbar"> <div class="row"> <div class="col-xs-6"> <div class="quick-add-btn"> <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#new-user"><span class="glyphicon glyphicon-new-window"></span> 创建新用户</button> </div> </div> <div class="col-xs-6"> <form class="form-inline pull-right" id="device-search" role="form"> <div class="form-group"> <select class="form-control"> <option value="all">全部用户</option> <option value="admin-user">管理员用户</option> <option value="normal-user">普通用户</option> </select> </div> <div class="form-group"> <input type="text" class="form-control" placeholder="用户名……"> </div> <button type="submit" class="btn btn-default">筛选</button> </form> </div> </div> </div> <!--all user detail begin --> <div class="panel panel-default" id="all-device-detail"> <div class="panel-heading"> <h5>所有用户信息</h5> </div> <table class="table"> <thead><tr> <th>用户名</th> <th>用户类型</th> <th>联系邮箱</th> <th>操作</th> </tr></thead> <tbody> <tr> <td>张三</td> <td>普通用户</td> <td>example01@example.com</td> <td> <button class="btn btn-primary btn-xs" data-toggle="modal" data-target="#permission—manage">权限管理</button> <a class="btn btn-default btn-xs" href="#">删除</a> </td> </tr> <tr> <td>李四</td> <td>管理员用户</td> <td>example02@example.com</td> <td> <button class="btn btn-primary btn-xs" data-toggle="modal" data-target="#permission—manage">权限管理</button> <a class="btn btn-default btn-xs" href="#">删除</a> </td> </tr> <tr> <td>王五</td> <td>管理员用户</td> <td>example03@example.com</td> <td> <button class="btn btn-primary btn-xs " data-toggle="modal" data-target="#permission—manage">权限管理</button> <a class="btn btn-default btn-xs " href="#">删除</a> </td> </tr> <tr> <td>赵六</td> <td>普通用户</td> <td>example04@example.com</td> <td> <button class="btn btn-primary btn-xs" data-toggle="modal" data-target="#permission—manage">权限管理</button> <a class="btn btn-default btn-xs" href="#">删除</a> </td> </tr> </tbody> </table> </div> </div> <!--the container end --> <!-- new-user Modal --> <div class="modal fade" id="new-user" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title" id="myModalLabel">创建新用户</h4> </div> <div class="modal-body row"> <form action="#" class="form-horizontal" id="add-user" role="form" method="post"> <div class="form-group"> <label for="user-name" class="col-xs-4 control-label">用户名</label> <div class="col-xs-6"> <input type="text" class="form-control" id="user-name" name="user-name"> </div> </div> <div class="form-group"> <label for="user-password" class="col-xs-4 control-label">初始密码</label> <div class="col-xs-6"> <input type="password" class="form-control" id="user-password" name="user-password"> </div> </div> <div class="form-group"> <label for="re-user-password" class="col-xs-4 control-label">确认密码</label> <div class="col-xs-6"> <input type="password" class="form-control" id="re-user-password" name="re-user-password"> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button> <button type="submit" class="btn btn-primary">确定</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> <!-- permission—manage Modal --> <div class="modal fade" id="permission—manage" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body row"> <form action="#" class="form-horizontal" id="add-user" role="form" method="post"> <div class="modal-header"> <label class="checkbox-inline pull-right"> <input type="checkbox" id="all"> 全选 </label> <h4 class="modal-title">设备权限管理 </h4> </div> <div class="form-group"> <label for="if-new-device" class="col-xs-4 control-label">可绑定新设备</label> <div class="col-xs-6"> <label class="checkbox-inline"> <input type="checkbox" id="device-type" name="device-permission" value="true"> 是 </label> </div> </div> <div class="form-group"> <label for="device-permission" class="col-xs-4 control-label">气象站01</label> <div class="col-xs-6"> <label class="checkbox-inline"> <input type="checkbox" id="device-permission" name="device-permission" value="edit"> 可修改 </label> <label class="checkbox-inline"> <input type="checkbox" id="device-permission" name="device-permission" value="delete"> 可删除 </label> </div> </div> <div class="form-group"> <label for="device-permission" class="col-xs-4 control-label">气象站02</label> <div class="col-xs-6"> <label class="checkbox-inline"> <input type="checkbox" id="device-permission" name="device-permission" value="edit"> 可修改 </label> <label class="checkbox-inline"> <input type="checkbox" id="device-permission" name="device-permission" value="delete"> 可删除 </label> </div> </div> <div class="form-group"> <label for="device-permission" class="col-xs-4 control-label">led测试01</label> <div class="col-xs-6"> <label class="checkbox-inline"> <input type="checkbox" id="device-permission" name="device-permission" value="edit"> 可修改 </label> <label class="checkbox-inline"> <input type="checkbox" id="device-permission" name="device-permission" value="delete"> 可删除 </label> </div> </div> <div class="form-group"> <label for="device-permission" class="col-xs-4 control-label">led测试02</label> <div class="col-xs-6"> <label class="checkbox-inline"> <input type="checkbox" id="device-permission" name="device-permission" value="edit"> 可修改 </label> <label class="checkbox-inline"> <input type="checkbox" id="device-permission" name="device-permission" value="delete"> 可删除 </label> </div> </div> <div class="modal-header"> <h4 class="modal-title">LED显示权限管理</h4> </div> <div class="form-group"> <label for="device-permission" class="col-xs-4 control-label">led测试01</label> <div class="col-xs-6"> <label class="checkbox-inline"> <input type="checkbox" id="device-permission" name="device-permission" value="true"> 可开关 </label> <label class="checkbox-inline"> <input type="checkbox" id="device-permission" name="device-permission" value="false"> 可绑定传感设备 </label> </div> </div> <div class="form-group"> <label for="device-permission" class="col-xs-4 control-label">led测试02</label> <div class="col-xs-6"> <label class="checkbox-inline"> <input type="checkbox" id="device-permission" name="device-permission" value="true"> 可开关 </label> <label class="checkbox-inline"> <input type="checkbox" id="device-permission" name="device-permission" value="false"> 可绑定传感设备 </label> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button> <button type="submit" class="btn btn-primary">确定</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> <footer> <hr> <p class="pull-right">&copy; 2013 智慧农业物联网</p> </footer> </div> <!--the content end --> <script src="lib/bootstrap/js/bootstrap.js"></script> <!--全选按钮实现--> <script> $(function () { $("#all").click(function () { var checked_status = this.checked; $("input[name=device-permission]").each(function () { this.checked = checked_status; }); }); }); </script> </body> </html>
{ "content_hash": "25ea8f411fcf73a3f10315e89522ac61", "timestamp": "", "source": "github", "line_count": 327, "max_line_length": 198, "avg_line_length": 54.666666666666664, "alnum_prop": 0.3990266278809577, "repo_name": "Copypeng/A-bootstrap-admin", "id": "493e207174721c0cd1e5391638fe26b535d0d9c8", "size": "18500", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "account_permission.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "141920" }, { "name": "JavaScript", "bytes": "1342872" } ], "symlink_target": "" }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _moment = require('moment'); var _moment2 = _interopRequireDefault(_moment); require('moment/locale/ru'); var _ru_RU = require('rc-pagination/lib/locale/ru_RU'); var _ru_RU2 = _interopRequireDefault(_ru_RU); var _ru_RU3 = require('../date-picker/locale/ru_RU'); var _ru_RU4 = _interopRequireDefault(_ru_RU3); var _ru_RU5 = require('../time-picker/locale/ru_RU'); var _ru_RU6 = _interopRequireDefault(_ru_RU5); var _ru_RU7 = require('../calendar/locale/ru_RU'); var _ru_RU8 = _interopRequireDefault(_ru_RU7); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Created by Andrey Gayvoronsky on 13/04/16. */ _moment2['default'].locale('ru'); exports['default'] = { locale: 'ru', Pagination: _ru_RU2['default'], DatePicker: _ru_RU4['default'], TimePicker: _ru_RU6['default'], Calendar: _ru_RU8['default'], Table: { filterTitle: 'Фильтр', filterConfirm: 'OK', filterReset: 'Сбросить', emptyText: 'Нет данных', selectAll: 'Выбрать всё', selectInvert: 'Инвертировать выбор' }, Modal: { okText: 'OK', cancelText: 'Отмена', justOkText: 'OK' }, Popconfirm: { okText: 'OK', cancelText: 'Отмена' }, Transfer: { notFoundContent: 'Ничего не найдено', searchPlaceholder: 'Введите название для поиска', itemUnit: 'item', itemsUnit: 'items' }, Select: { notFoundContent: 'Ничего не найдено' }, Upload: { uploading: 'Закачиваю...', removeFile: 'Удалить файл', uploadError: 'Ошибка при закачке', previewFile: 'Предпросмотр файла' } }; module.exports = exports['default'];
{ "content_hash": "a9d87255a6397fccee7038c2eee17683", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 97, "avg_line_length": 24.783783783783782, "alnum_prop": 0.6025081788440567, "repo_name": "prodigalyijun/demo-by-antd", "id": "2122a95b4b8b664ceaad245027c7bc779219a23a", "size": "2004", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "node_modules/antd/lib/locale-provider/ru_RU.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1262" }, { "name": "HTML", "bytes": "524" }, { "name": "JavaScript", "bytes": "33367" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>mathcomp-algebra-tactics: 22 s 🏆</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.13.0 / mathcomp-algebra-tactics - 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> mathcomp-algebra-tactics <small> 0.1.0 <span class="label label-success">22 s 🏆</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-04-05 07:15:45 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-04-05 07:15:45 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.13.0 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.10.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.10.2 Official release 4.10.2 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;sakaguchi@coins.tsukuba.ac.jp&quot; homepage: &quot;https://github.com/math-comp/algebra-tactics&quot; dev-repo: &quot;git+https://github.com/math-comp/algebra-tactics.git&quot; bug-reports: &quot;https://github.com/math-comp/algebra-tactics/issues&quot; license: &quot;CECILL-B&quot; synopsis: &quot;Ring and field tactics for Mathematical Components&quot; description: &quot;&quot;&quot; This library provides `ring` and `field` tactics for Mathematical Components, that work with any `comRingType` and `fieldType` instances, respectively. Their instance resolution is done through canonical structure inference. Therefore, they work with abstract rings and do not require `Add Ring` and `Add Field` commands. Another key feature of this library is that they automatically push down ring morphisms and additive functions to leaves of ring/field expressions before normalization to the Horner form.&quot;&quot;&quot; build: [make &quot;-j%{jobs}%&quot; ] install: [make &quot;install&quot;] depends: [ &quot;coq&quot; {(&gt;= &quot;8.13&quot; &amp; &lt; &quot;8.15~&quot;)} &quot;coq-mathcomp-algebra&quot; {(&gt;= &quot;1.12&quot; &amp; &lt; &quot;1.14~&quot;)} &quot;coq-mathcomp-zify&quot; {(&gt;= &quot;1.1.0&quot;)} &quot;coq-elpi&quot; {(&gt;= &quot;1.10.1&quot;)} ] tags: [ &quot;logpath:mathcomp.algebra_tactics&quot; ] authors: [ &quot;Kazuhiko Sakaguchi&quot; ] url { src: &quot;https://github.com/math-comp/algebra-tactics/archive/refs/tags/0.1.0.tar.gz&quot; checksum: &quot;sha256=aca9d33fec72a9e2fb37ccbc91c492ceae9b75d3cdce37ddd9a224ea3cef0f3f&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-mathcomp-algebra-tactics.0.1.0 coq.8.13.0</code></dd> <dt>Return code</dt> <dd>0</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>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-mathcomp-algebra-tactics.0.1.0 coq.8.13.0</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>17 m 5 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-mathcomp-algebra-tactics.0.1.0 coq.8.13.0</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>22 s</dd> </dl> <h2>Installation size</h2> <p>Total: 362 K</p> <ul> <li>266 K <code>../ocaml-base-compiler.4.10.2/lib/coq/user-contrib/mathcomp/algebra_tactics/ring.vo</code></li> <li>84 K <code>../ocaml-base-compiler.4.10.2/lib/coq/user-contrib/mathcomp/algebra_tactics/ring.glob</code></li> <li>13 K <code>../ocaml-base-compiler.4.10.2/lib/coq/user-contrib/mathcomp/algebra_tactics/ring.v</code></li> </ul> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq-mathcomp-algebra-tactics.0.1.0</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": "f9c04ab1067609e6054a0c6fbe06ed43", "timestamp": "", "source": "github", "line_count": 171, "max_line_length": 159, "avg_line_length": 44.87719298245614, "alnum_prop": 0.5625488663017982, "repo_name": "coq-bench/coq-bench.github.io", "id": "a821db23b9cb50316f1edd16610fbcd3d3fbc083", "size": "7699", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.10.2-2.0.6/released/8.13.0/mathcomp-algebra-tactics/0.1.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
##########################GO-LICENSE-START################################ # Copyright 2014 ThoughtWorks, Inc. # # 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. ##########################GO-LICENSE-END################################## require 'buildr/java/cobertura' unless ENV['INSTRUMENT_FOR_COVERAGE'].nil? require 'buildr/core/util' task :prepare do # Temporary: Feature toggle "use.new.rails" is related to this. bcprov_dependency_params = ENV['USE_NEW_RAILS'] == "Y" ? "-Dbcprov.groupId=org.bouncycastle -Dbcprov.artifactId=bcprov-jdk15on -Dbcprov.version=1.47" : "" system("mvn install -DskipTests #{bcprov_dependency_params}") || raise("Failed to run: mvn install -DskipTests") task("cruise:server:db:refresh").invoke end task :clean do # Clean Go dependencies from local maven repo maven_local_repo_location = `mvn help:effective-settings`.match("<localRepository.*>(.*)</localRepository>")[1] rm_rf maven_local_repo_location + "/com/thoughtworks/go" end define "cruise:agent-bootstrapper", :layout => agent_bootstrapper_layout("agent-bootstrapper") do bootstrapper = tw_go_jar('agent-bootstrapper') define :dist, :layout => package_submodule_layout(self, :dist, 'go-agent') do name_with_version = "go-agent-#{VERSION_NUMBER}" zip_file = zip(_(:zip_package)).clean.enhance(['cruise:agent-bootstrapper:package']).tap do |zip| agent_dir = "go-agent-#{VERSION_NUMBER}" zip.path(agent_dir).include(self.path_to('../../installers/agent/releaseGoLauncher.class") include_fileset_from_target(jar, 'server', "**/GoLauncher.class") include_fileset_from_target(jar, 'server', "**/GoSslSocketConnector.class") include_fileset_from_target(jar, 'server', "**/GoCipherSuite.class") include_fileset_from_target(jar, 'server', "**/GoServer*.class") include_fileset_from_target(jar, 'server', "**/JettyServer*.class") include_fileset_from_target(jar, 'server', "**/GoWebXmlConfiguration*.class") include_fileset_from_target(jar, 'server', "**/StopJettyFromLocalhostServlet*.class") include_fileset_from_target(jar, 'server', "**/DeploymentContextWriter*.class") include_fileset_from_target(jar, 'server', "**/BaseUrlProvider*.class") include_fileset_from_target(jar, 'common', "**/SubprocessLogger*.class") include_fileset_from_target(jar, 'common', "**/validators/*.class") include_fileset_from_target(jar, 'common', "**/Environment*.class") include_fileset_from_target(jar, 'common', "**/X509CertificateGenerator*.class") include_fileset_from_target(jar, 'common', "**/X509PrincipalGenerator*.class") include_fileset_from_target(jar, 'common', "**/KeyStoreManager.class") include_fileset_from_target(jar, 'common', "**/PKCS12BagAttributeSetter.class") include_fileset_from_target(jar, 'common', "**/KeyPairCreator.class") include_fileset_from_target(jar, 'common', "**/Registration.class") include_fileset_from_target(jar, 'common', "**/CommandLineException.class") include_fileset_from_target(jar, 'base', "**/OperatingSystem.class") include_fileset_from_target(jar, 'base', "**/SystemEnvironment*.class") include_fileset_from_target(jar, 'base', "**/ConfigDirProvider.class") include_fileset_from_target(jar, 'base', "**/validators/*.class") include_fileset_from_target(jar, 'base', "**/SystemUtil.class") include_fileset_from_target(jar, 'base', "**/Os.class") include_fileset_from_target(jar, 'base', "**/ExceptionUtils.class") include_fileset_from_target(jar, 'base', "**/FileUtil*.class") include_fileset_from_target(jar, 'base', "**/StreamConsumer.class") include_fileset_from_target(jar, 'base', "**/InMemoryConsumer.class") include_fileset_from_target(jar, 'base', "**/InMemoryStreamConsumer.class") include_fileset_from_target(jar, 'base', "**/ConsoleOutputStreamConsumer.class") exclude_fileset_from_target(jar, 'common', "**/domain/*.class") exclude_fileset_from_target(jar, 'common', "**/validation/*.class") exclude_fileset_from_target(jar, 'common', "**/remote/*.class") exclude_fileset_from_target(jar, 'common', "**/remote/work/*.class") end h2db_zip = package(:zip, :file => _(:target, "include/defaultFiles/h2db.zip")).clean.enhance do |zip| zip.include _('db/h2db/*'), :path => "h2db" end deltas_zip = package(:zip, :file => _(:target, "include/defaultFiles/h2deltas.zip")).clean.enhance do |zip| zip.include _('db/migrate/h2deltas/*'), :path => "h2deltas" end command_repository_zip = package(:zip, :file => _(:target, "include/defaultFiles/defaultCommandSnippets.zip")).clean.enhance(['cruise:server:pull_from_central_command_repo']) do |zip| command_repo_name = ENV['COMMAND_REPO_NAME'] || 'go-command-repo' zip.include _("../#{command_repo_name}/*") zip.include _("../#{command_repo_name}/.git") end plugins_zip = package(:zip, :file => _(:target, "include/defaultFiles/plugins.zip")).clean.enhance(['cruise:server:write_server_version_for_plugins']) do |zip| zip.include _("../tw-go-plugins/dist/*") end task :write_server_version_for_plugins do plugins_dist_dir = 'tw-go-plugins/dist' File.open("#{plugins_dist_dir}/version.txt", "w") { |h| h.write("%s(%s)" % [VERSION_NUMBER, RELEASE_COMMIT]) } if File.exists? plugins_dist_dir end cruise_war = _('target/cruise.war') cruise_jar = onejar(_(:target, 'go.jar')).enhance(['cruise:agent-bootstrapper:package']) do |onejar| onejar.path('defaultFiles/').include(cruise_war, h2db_zip, deltas_zip, command_repository_zip, plugins_zip, tw_go_jar('agent-bootstrapper'), tw_go_jar('agent-launcher'), tw_go_jar('agent'), _('historical_jars'), _('jruby_jars')) onejar.path('defaultFiles/config/').include( _("..", "config", "config-server", "resources", "cruise-config.xsd"), _("../installers/server/release/cruise-config.xml"), _("../installers/server/release/config.properties"), _("properties/src/log4j.properties"), _("config/jetty.xml")) # Temporary: Feature toggle "use.new.rails" is related to this. onejar.path('lib/').include(server_launcher_dependencies).include(bouncy_castle_jar).include(tw_go_jar('tfs-impl')).include(tw_go_jar('plugin-infra/go-plugin-activator', 'go-plugin-activator')) include_fileset_from_target(onejar, 'server', "**/GoMacLauncher*") include_fileset_from_target(onejar, 'server', "**/Mac*") include_fileset_from_target(onejar, 'common', "log4j.upgrade.*.properties") onejar.include(in_root('LICENSE')) end server = self define :dist, :layout => package_submodule_layout(self, :dist, 'go-server') do name_with_version = "go-server-#{VERSION_NUMBER}" zip_file = zip(_(:zip_package)).clean.enhance(['cruise:server:package']).tap do |zip| zip.path(name_with_version).include(server.path_to('../installers/server/release/*'), cruise_jar, in_root('LICENSE')). exclude(server.path_to('../installers/server/release/cruise-config.xml')) end task :zip => zip_file exploded_zip = unzip(_(:target, "explode") => zip_file).target class << self include DebPackageHelper include RpmPackageHelper include WinPackageHelper include SolarisPackageHelper include CopyHelper end self.metadata_src_project = 'cruise:server' explode = _(:target, "explode", name_with_version) task :linux_data => exploded_zip do shared_dir = _(linux_dir, "usr/share/go-server") doc_dir = _(linux_dir, "usr/share/doc/go-server") working_dir = _(linux_dir, "var/lib/go-server") copy_all_with_mode(_(explode, "default.cruise-server") => dest_with_mode(_(linux_dir, "etc/default/go-server"), 0644), _(explode, "init.cruise-server") => dest_with_mode(_(linux_dir, "etc/init.d/go-server")), _(explode, "server.sh") => dest_with_mode(_(shared_dir, 'server.sh')), _(explode, "stop-server.sh") => dest_with_mode(_(shared_dir, 'stop-server.sh')), _(explode, "go.jar") => dest_with_mode(_(shared_dir, 'go.jar'), 0644), _(explode, "config.properties") => dest_with_mode(_(shared_dir, 'config.properties'), 0644), _(explode, "LICENSE") => [dest_with_mode(_(shared_dir, 'LICENSE'), 0644), dest_with_mode(_(doc_dir, "copyright"), 0644)], debian_metadata('server', 'changelog.go-server') => _(doc_dir, "changelog")) gzip_changelog doc_dir mkdir_p working_dir, :mode => 0755 config_dir = _(linux_dir, "etc/go") mkdir_p config_dir, :mode => 0755 filter.from(_("../properties/src")).include("log4j.properties").into(config_dir).using(/[^=]+$/, 'go-server.log' => '/var/log/go-server/go-server.log', 'go-shine.log' => '/var/log/go-server/go-shine.log').run end dpkg_deb(:linux_data, 'server', 'go-server') rpm_build(:linux_data, 'server', 'go-server') task :windows_data => exploded_zip do mkdir_p windows_dir cp_r explode, win_pkg_content_dir_child('go-server', '') cp win_pkg_src('server', 'JavaHome.ini'), windows_dir mkdir_p win_pkg_content_dir_child('go-server', 'tmp') end win_build(:windows_data, 'server', 'go-server', 'Server', 'jre') sol_build(exploded_zip, 'server', name_with_version) end task :pull_from_central_command_repo do command_repo_name = ENV['COMMAND_REPO_NAME'] || 'go-command-repo' command_repository_default_dir = _("../#{command_repo_name}") rm_rf command_repository_default_dir clone_command_repo(command_repository_default_dir) end task :bump_version_of_command_repository do repo_url = ENV["COMMAND_REPO_URL"] || 'github.com/goteam/go-command-repo.git' repo_full_url = "https://#{repo_url}" require 'tmpdir' tmp_dir = Dir.tmpdir temp_checkout_dir_location = File.join(tmp_dir, 'go-command-repo-for-push') if (File.directory? temp_checkout_dir_location) FileUtils.remove_dir temp_checkout_dir_location end if (File.file? temp_checkout_dir_location) FileUtils.rm temp_checkout_dir_location end FileUtils.mkdir(temp_checkout_dir_location) system "git clone #{repo_full_url} #{temp_checkout_dir_location}" version_file_location = File.join(temp_checkout_dir_location, 'version.txt') version_content_array = File.read(version_file_location).split('=') bump_version = bump_by_1(version_content_array[1]) File.open(version_file_location, 'w') { |f| f.write("#{version_content_array[0]}=#{bump_version}") } system <<END cd #{temp_checkout_dir_location}; git config user.name goteam; git config user.email support@thoughtworks.com; git add #{version_file_location}; git commit -m 'Version - #{bump_version}'; git config remote.origin.url #{repo_full_url}; git push; END end def bump_by_1 old_value old_value.to_i + 1 end end define "cruise:misc", :layout => submodule_layout_for_different_src("server") do JS_UNIT_URL = "\"http://localhost:8585/jsunit/testRunner.html?testPage=http://localhost:8585/jsunit/tests/jsUnitTestSuite.html\&autoRun=true\&submitResults=localhost:8585/jsunit/acceptor\"" task :assert_all_partitions_executed do Buildr.ant('check-missing-partitions') do |ant| tlb_deps = [maven_dependency('commons-io', 'commons-io', '1.4'), maven_dependency('commons-codec', 'commons-codec', '1.4'), maven_dependency('commons-httpclient', 'commons-httpclient', '3.0.1'), maven_dependency('dom4j', 'dom4j', '1.6.1'), maven_dependency('org.apache.httpcomponents', 'httpcore', '4.1'), maven_dependency('org.apache.httpcomponents', 'httpclient', '4.1'), maven_dependency('commons-logging', 'commons-logging', '1.1.1'), maven_dependency('log4j', 'log4j', '1.2.12'), local_maven_dependency('com.tlb', 'tlb-java', '0.3.2-90-g6df47e3')].flatten ant.path :id => 'tlb.class.path' do ant.filelist :dir => File.expand_path(File.dirname(__FILE__)), :files => tlb_deps.join(",") end ant.taskdef :name => 'check_missing_partitions', :classname => 'tlb.ant.CheckMissingPartitions', :classpathref => 'tlb.class.path' if ENV.has_key?('check_correctness_for') ant.check_missing_partitions(:moduleNames => ENV['check_correctness_for']) else ant.check_missing_partitions(:moduleNames => "util,common,agent,agent-bootstrapper,test-utils,server") end end end def javascript_lint(files) jslint_root = project('cruise:server').path_to("webapp/WEB-INF/rails/vendor/other/jslint") jslint = %[java -jar #{File.join(jslint_root, "rhino.jar")} #{File.join(jslint_root, "jslint.js")}] fail = false errors = [] files.each do |file| path = File.expand_path(file) command = %[#{jslint} #{path}] output = `#{command}` unless output =~ /No problems found/i errors << "#{path}:\n#{output}" putc "F" $stdout.flush fail = true else putc "." $stdout.flush end end if fail puts "\n" + errors.join("\n") exit 1 else puts "\n" end end task :jslint do javascript_lint Dir[project('cruise:server').path_to("webapp/javascripts/*.js")] end task :jsunit => [:set_browser_path, :prepare_jsunit_file_structure] do jsunit_jars = (Dir.glob(project('cruise:server').path_to("jsunit/java/lib/*.jar")) + jars_with_abs_path('ant')) << _(:target, 'jsunit/java/config') properties = { "java.io.tmpdir" => _(:target, 'jsunit/tmp'), "browserFileNames" => "\"#{$browser_path}\"", "description" => "\"javascript unit tests\"", "closeBrowsersAfterTestRuns" => true, "logsDirectory" => _(:target, "jsunit/logs"), "port" => 8585, "resourceBase" => _(:target, 'jsunit'), "timeoutSeconds" => 300, "url" => JS_UNIT_URL} properties = properties.inject("") { |injected, tuple| injected + " -D#{tuple.first}=#{tuple.last}" } sh "java #{properties} -classpath #{ jsunit_jars.join(File::PATH_SEPARATOR) } org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner net.jsunit.StandaloneTest filtertrace=true haltOnError=true haltOnFailure=true showoutput=true outputtoformatters=true logtestlistenerevents=true formatter=org.apache.tools.ant.taskdefs.optional.junit.PlainJUnitResultFormatter" end task :jsunit_server => [:prepare_jsunit_file_structure] do properties = { "java.io.tmpdir" => _(:target, 'jsunit/tmp'), "browserFileNames" => $browser_path, "description" => "'javascript unit tests'", "closeBrowsersAfterTestRuns" => true, "logsDirectory" => _(:target, "jsunit/logs"), "port" => 8585, "resourceBase" => _(:target, 'jsunit'), "timeoutSeconds" => 300, "url" => JS_UNIT_URL} properties = properties.inject("") { |injected, tuple| injected + " -D#{tuple.first}=#{tuple.last}" } sh "cd #{_(:target)} && ant -f jsunit.xml start_server" end task :jsunit_test => [:prepare_jsunit_file_structure] do sh "firefox http://localhost:8585/jsunit/testRunner.html?testPage=http://localhost:8585/jsunit/tests/#{ENV['test']}.html\\&autoRun=true" end COMPRESSED_ALL_DOT_JS = "server/target/all.js" task :prepare_jsunit_file_structure do mkdir_p _(:target, 'jsunit/compressed') filter_files(project('cruise:server').path_to("jsunit"), _(:target, "jsunit")) cp project('cruise:server').path_to("jsunit.xml"), _(:target) cp COMPRESSED_ALL_DOT_JS, _(:target, 'jsunit/compressed/all.js') cp project('cruise:server').path_to('webapp/javascripts/d3.js'), _(:target, 'jsunit/compressed/d3.js') cp project('cruise:server').path_to('webapp/stylesheets/module.css'), _(:target, 'jsunit/css/module.css') end task :set_browser_path do $browser_path = (ENV['BROWSER_PATH'] || ENV['BROWSER_PATH_JSUNIT'] || '/usr/bin/firefox') raise "Browser executable not found @ #{$browser_path}" unless File.exists?($browser_path) $stderr.write("Using browser path: [#{$browser_path}]\n") end task :sync_xsd do xsd = _("..", "config", "config-server", "resources", "cruise-config.xsd") [_("..", "manual-testing", "perftest", "cruise-config.xsd"), _("..", "manual-testing", "multiple", "cruise-config.xsd")].each do |dest| cp xsd, dest end end task :verify_packaged_command_repo do cmd_repo_verification_dir = "cmd_repo_verification" cmd_repo_verification_dir_absolute_path = _("../#{cmd_repo_verification_dir}") packaged_rev_file = "#{cmd_repo_verification_dir_absolute_path}/git_revision_packaged.txt" current_rev_file = "#{cmd_repo_verification_dir_absolute_path}/git_revision_current.txt" zip_file_name = "" Dir.glob("#{cmd_repo_verification_dir}/zip/*").each do |f| zip_file_name = f if !f.scan(/go-server-.*-[0-9]+.zip/).empty? end `unzip -o #{zip_file_name} -d #{cmd_repo_verification_dir}/go-server` #unzip go.jar and defaultFiles/defaultCommandSnippets.zip unzipped_go_server_dir = Dir.glob("#{cmd_repo_verification_dir}/go-server/*")[0] `unzip -o #{unzipped_go_server_dir}/go.jar -d #{unzipped_go_server_dir}` `unzip -o #{unzipped_go_server_dir}/defaultFiles/defaultCommandSnippets.zip -d #{unzipped_go_server_dir}/defaultCommandRepo` `cd #{unzipped_go_server_dir}/defaultCommandRepo; git rev-parse HEAD > #{packaged_rev_file}` clone_command_repo("#{cmd_repo_verification_dir_absolute_path}/go-command-repo") `cd #{cmd_repo_verification_dir}/go-command-repo; git rev-parse HEAD > #{current_rev_file}` packaged_revision = File.read("#{packaged_rev_file}") current_revision = File.read("#{current_rev_file}") puts "Packaged Revision - #{packaged_revision}" puts "Current Revision - #{current_revision}" if packaged_revision != current_revision puts "Revisions do not match !!" exit 1 end end task :maven_clean do system("mvn clean") || raise("Failed to run: mvn clean") end end define 'cruise:pkg', :layout => submodule_layout('pkg') do task :zip => ['cruise:agent-bootstrapper:dist:zip', 'cruise:server:dist:zip'] do mkdir_p _(:target) cp project('cruise:agent-bootstrapper:dist').path_to(:zip_package), _(:target) cp project('cruise:server:dist').path_to(:zip_package), _(:target) end task :unzip => ['cruise:agent-bootstrapper:dist:zip', 'cruise:server:dist:zip'] do `unzip -o #{project('cruise:agent-bootstrapper:dist').path_to(:zip_package)} -d #{_(:target, '..')}` `unzip -o #{project('cruise:server:dist').path_to(:zip_package)} -d #{_(:target, '..')}` end task :debian => ['cruise:agent-bootstrapper:dist:debian', 'cruise:server:dist:debian'] do mkdir_p _(:target) cp project('cruise:agent-bootstrapper:dist').path_to(:debian_package), _(:target) cp project('cruise:server:dist').path_to(:debian_package), _(:target) cp project('cruise:server').path_to("../installers/server/debian/install-server.sh"), _(:target) end task :redhat => ['cruise:agent-bootstrapper:dist:rpm', 'cruise:server:dist:rpm'] do mkdir_p _(:target) cp project('cruise:agent-bootstrapper:dist').path_to(:redhat_package), _(:target) cp project('cruise:server:dist').path_to(:redhat_package), _(:target) end task :windows => ['cruise:agent-bootstrapper:dist:exe', 'cruise:server:dist:exe'] do mkdir_p _(:target) cp project('cruise:agent-bootstrapper:dist').path_to(:windows_package), _(:target) cp project('cruise:server:dist').path_to(:windows_package), _(:target) end task :solaris => ['cruise:agent-bootstrapper:dist:solaris', 'cruise:server:dist:solaris'] do mkdir_p _(:target) cp project('cruise:agent-bootstrapper:dist').path_to(:solaris_package), _(:target) cp project('cruise:server:dist').path_to(:solaris_package), _(:target) end task :installer_links do go_site_url = ENV['GO_SITE_URL'] || ENV['GO_SERVER_URL'] raise 'Can only works on GO agent' unless go_site_url artifacts_dir = go_site_url + 'files/' artifacts_dir << %w{GO_PIPELINE_NAME GO_PIPELINE_COUNTER GO_STAGE_NAME GO_STAGE_COUNTER GO_JOB_NAME}.collect { |v| ENV[v] }.join("/") puts "Saving the installers_link in the #{_(:target)} folder" mkdir_p _(:target) File.open(File.join(_(:target), "installers_link.html"), 'w') do |f| f << <<-HTML <br /> <h2> Go Installers (Pipeline Label -> #{ENV['GO_PIPELINE_LABEL']}) </h2> HTML [project('cruise:agent-bootstrapper:dist'), project('cruise:server:dist')].each do |project| package_name = project.path_to(:redhat_package).split('/').last f << <<-HTML <p> <a href="#{artifacts_dir}/pkg/rpm/#{package_name}">#{package_name}</a> </p> HTML end end end end
{ "content_hash": "266217593092b359500d484304a2f591", "timestamp": "", "source": "github", "line_count": 440, "max_line_length": 370, "avg_line_length": 49.45909090909091, "alnum_prop": 0.6424501424501424, "repo_name": "turbine-rpowers/gocd-add-agent-sandbox-config", "id": "76e2fa9386a8c53d44ede2230ddf91217b65a458", "size": "26574", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cruise-modules.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "522614" }, { "name": "Java", "bytes": "13425172" }, { "name": "JavaScript", "bytes": "676743" }, { "name": "PowerShell", "bytes": "1365" }, { "name": "Ruby", "bytes": "2219674" }, { "name": "SQL", "bytes": "250235" }, { "name": "Shell", "bytes": "77692" }, { "name": "Slash", "bytes": "90112" }, { "name": "XSLT", "bytes": "140343" } ], "symlink_target": "" }
// Code generated by client-gen. DO NOT EDIT. package fake import ( traefikv1alpha1 "github.com/traefik/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" schema "k8s.io/apimachinery/pkg/runtime/schema" serializer "k8s.io/apimachinery/pkg/runtime/serializer" utilruntime "k8s.io/apimachinery/pkg/util/runtime" ) var scheme = runtime.NewScheme() var codecs = serializer.NewCodecFactory(scheme) var localSchemeBuilder = runtime.SchemeBuilder{ traefikv1alpha1.AddToScheme, } // AddToScheme adds all types of this clientset into the given scheme. This allows composition // of clientsets, like in: // // import ( // "k8s.io/client-go/kubernetes" // clientsetscheme "k8s.io/client-go/kubernetes/scheme" // aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" // ) // // kclientset, _ := kubernetes.NewForConfig(c) // _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) // // After this, RawExtensions in Kubernetes types will serialize kube-aggregator types // correctly. var AddToScheme = localSchemeBuilder.AddToScheme func init() { v1.AddToGroupVersion(scheme, schema.GroupVersion{Version: "v1"}) utilruntime.Must(AddToScheme(scheme)) }
{ "content_hash": "73f88c4cda2cc19b3e0fa8158592f3c2", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 103, "avg_line_length": 31.142857142857142, "alnum_prop": 0.7752293577981652, "repo_name": "mmatur/traefik", "id": "3ab7c4b7308246afb11a4d58c4e993256c70cb7f", "size": "2423", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "pkg/provider/kubernetes/crd/generated/clientset/versioned/fake/register.go", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "4091" }, { "name": "Go", "bytes": "3712135" }, { "name": "HTML", "bytes": "1480" }, { "name": "JavaScript", "bytes": "83425" }, { "name": "Makefile", "bytes": "7174" }, { "name": "SCSS", "bytes": "6743" }, { "name": "Shell", "bytes": "10820" }, { "name": "Stylus", "bytes": "665" }, { "name": "Vue", "bytes": "175802" } ], "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_151) on Wed Jun 10 10:20:18 MST 2020 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class org.wildfly.swarm.config.resource.adapters.resource_adapter.ConfigProperties (BOM: * : All 2.6.1.Final-SNAPSHOT API)</title> <meta name="date" content="2020-06-10"> <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.wildfly.swarm.config.resource.adapters.resource_adapter.ConfigProperties (BOM: * : All 2.6.1.Final-SNAPSHOT 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/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">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-all.html">Index</a></li> <li><a href="../../../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Thorntail API, 2.6.1.Final-SNAPSHOT</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../index.html?org/wildfly/swarm/config/resource/adapters/resource_adapter/class-use/ConfigProperties.html" target="_top">Frames</a></li> <li><a href="ConfigProperties.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.wildfly.swarm.config.resource.adapters.resource_adapter.ConfigProperties" class="title">Uses of Class<br>org.wildfly.swarm.config.resource.adapters.resource_adapter.ConfigProperties</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.wildfly.swarm.config.resource.adapters">org.wildfly.swarm.config.resource.adapters</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.wildfly.swarm.config.resource.adapters.resource_adapter">org.wildfly.swarm.config.resource.adapters.resource_adapter</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.wildfly.swarm.config.resource.adapters"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a> in <a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/package-summary.html">org.wildfly.swarm.config.resource.adapters</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/package-summary.html">org.wildfly.swarm.config.resource.adapters</a> that return <a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a></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> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a></code></td> <td class="colLast"><span class="typeNameLabel">ResourceAdapter.ResourceAdapterResources.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/ResourceAdapter.ResourceAdapterResources.html#configProperties-java.lang.String-">configProperties</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;key)</code>&nbsp;</td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/package-summary.html">org.wildfly.swarm.config.resource.adapters</a> that return types with arguments of type <a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a></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> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a>&lt;<a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a>&gt;</code></td> <td class="colLast"><span class="typeNameLabel">ResourceAdapter.ResourceAdapterResources.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/ResourceAdapter.ResourceAdapterResources.html#configProperties--">configProperties</a></span>()</code> <div class="block">Get the list of ConfigProperties resources</div> </td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/package-summary.html">org.wildfly.swarm.config.resource.adapters</a> with parameters of type <a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a></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> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/ResourceAdapter.html" title="type parameter in ResourceAdapter">T</a></code></td> <td class="colLast"><span class="typeNameLabel">ResourceAdapter.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/ResourceAdapter.html#configProperties-org.wildfly.swarm.config.resource.adapters.resource_adapter.ConfigProperties-">configProperties</a></span>(<a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a>&nbsp;value)</code> <div class="block">Add the ConfigProperties object to the list of subresources</div> </td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Method parameters in <a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/package-summary.html">org.wildfly.swarm.config.resource.adapters</a> with type arguments of type <a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a></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> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/ResourceAdapter.html" title="type parameter in ResourceAdapter">T</a></code></td> <td class="colLast"><span class="typeNameLabel">ResourceAdapter.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/ResourceAdapter.html#configProperties-java.util.List-">configProperties</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a>&lt;<a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a>&gt;&nbsp;value)</code> <div class="block">Add all ConfigProperties objects to this subresource</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.wildfly.swarm.config.resource.adapters.resource_adapter"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a> in <a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/package-summary.html">org.wildfly.swarm.config.resource.adapters.resource_adapter</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/package-summary.html">org.wildfly.swarm.config.resource.adapters.resource_adapter</a> with type parameters of type <a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a>&lt;T extends <a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a>&lt;T&gt;&gt;</span></code> <div class="block">A custom defined config property.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>interface&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigPropertiesConsumer.html" title="interface in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigPropertiesConsumer</a>&lt;T extends <a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a>&lt;T&gt;&gt;</span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>interface&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigPropertiesSupplier.html" title="interface in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigPropertiesSupplier</a>&lt;T extends <a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a>&gt;</span></code>&nbsp;</td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/package-summary.html">org.wildfly.swarm.config.resource.adapters.resource_adapter</a> that return <a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a></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> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a></code></td> <td class="colLast"><span class="typeNameLabel">AdminObjects.AdminObjectsResources.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/AdminObjects.AdminObjectsResources.html#configProperties-java.lang.String-">configProperties</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;key)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a></code></td> <td class="colLast"><span class="typeNameLabel">ConnectionDefinitions.ConnectionDefinitionsResources.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConnectionDefinitions.ConnectionDefinitionsResources.html#configProperties-java.lang.String-">configProperties</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;key)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a></code></td> <td class="colLast"><span class="typeNameLabel">ConfigPropertiesSupplier.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigPropertiesSupplier.html#get--">get</a></span>()</code> <div class="block">Constructed instance of ConfigProperties resource</div> </td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/package-summary.html">org.wildfly.swarm.config.resource.adapters.resource_adapter</a> that return types with arguments of type <a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a></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> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a>&lt;<a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a>&gt;</code></td> <td class="colLast"><span class="typeNameLabel">AdminObjects.AdminObjectsResources.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/AdminObjects.AdminObjectsResources.html#configProperties--">configProperties</a></span>()</code> <div class="block">Get the list of ConfigProperties resources</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a>&lt;<a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a>&gt;</code></td> <td class="colLast"><span class="typeNameLabel">ConnectionDefinitions.ConnectionDefinitionsResources.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConnectionDefinitions.ConnectionDefinitionsResources.html#configProperties--">configProperties</a></span>()</code> <div class="block">Get the list of ConfigProperties resources</div> </td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/package-summary.html">org.wildfly.swarm.config.resource.adapters.resource_adapter</a> with parameters of type <a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a></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> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/AdminObjects.html" title="type parameter in AdminObjects">T</a></code></td> <td class="colLast"><span class="typeNameLabel">AdminObjects.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/AdminObjects.html#configProperties-org.wildfly.swarm.config.resource.adapters.resource_adapter.ConfigProperties-">configProperties</a></span>(<a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a>&nbsp;value)</code> <div class="block">Add the ConfigProperties object to the list of subresources</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConnectionDefinitions.html" title="type parameter in ConnectionDefinitions">T</a></code></td> <td class="colLast"><span class="typeNameLabel">ConnectionDefinitions.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConnectionDefinitions.html#configProperties-org.wildfly.swarm.config.resource.adapters.resource_adapter.ConfigProperties-">configProperties</a></span>(<a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a>&nbsp;value)</code> <div class="block">Add the ConfigProperties object to the list of subresources</div> </td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Method parameters in <a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/package-summary.html">org.wildfly.swarm.config.resource.adapters.resource_adapter</a> with type arguments of type <a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a></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> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/AdminObjects.html" title="type parameter in AdminObjects">T</a></code></td> <td class="colLast"><span class="typeNameLabel">AdminObjects.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/AdminObjects.html#configProperties-java.util.List-">configProperties</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a>&lt;<a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a>&gt;&nbsp;value)</code> <div class="block">Add all ConfigProperties objects to this subresource</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConnectionDefinitions.html" title="type parameter in ConnectionDefinitions">T</a></code></td> <td class="colLast"><span class="typeNameLabel">ConnectionDefinitions.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConnectionDefinitions.html#configProperties-java.util.List-">configProperties</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a>&lt;<a href="../../../../../../../../org/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">ConfigProperties</a>&gt;&nbsp;value)</code> <div class="block">Add all ConfigProperties objects to this subresource</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </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/wildfly/swarm/config/resource/adapters/resource_adapter/ConfigProperties.html" title="class in org.wildfly.swarm.config.resource.adapters.resource_adapter">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-all.html">Index</a></li> <li><a href="../../../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Thorntail API, 2.6.1.Final-SNAPSHOT</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../index.html?org/wildfly/swarm/config/resource/adapters/resource_adapter/class-use/ConfigProperties.html" target="_top">Frames</a></li> <li><a href="ConfigProperties.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 ======= --> <p class="legalCopy"><small>Copyright &#169; 2020 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "cf68c598fff2f75102b880a3a0161d1c", "timestamp": "", "source": "github", "line_count": 331, "max_line_length": 671, "avg_line_length": 82.30211480362537, "alnum_prop": 0.7032890389839219, "repo_name": "wildfly-swarm/wildfly-swarm-javadocs", "id": "2475991411de3f4eb40a706ca7976ab42c7c321c", "size": "27242", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "2.6.1.Final-SNAPSHOT/apidocs/org/wildfly/swarm/config/resource/adapters/resource_adapter/class-use/ConfigProperties.html", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.sfkiller.net; import com.sfkiller.utils.Constants; /** * FileName: NetworkStatenotify * Description: Interface for monitor network change * Date: 2015/10/24 * @author SFKiller * */ public interface NetworkStateHandler { /** * @param: networkstateCode State of network */ public abstract void onNetworkStateChange(Constants.NetworkSate networkstateCode); }
{ "content_hash": "62397ba9fe5408055c4563daa242cab9", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 90, "avg_line_length": 21.68421052631579, "alnum_prop": 0.7038834951456311, "repo_name": "SFKiller/NetworkStateMonitor", "id": "0397def686686e212b1fa16825982a0e95e7d5df", "size": "412", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/sfkiller/net/NetworkStateHandler.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2388" } ], "symlink_target": "" }
/* global QUnit,JSZip,JSZipTestUtils */ 'use strict'; QUnit.module("load", function () { JSZipTestUtils.testZipFile("load(string) works", "ref/all.zip", function(assert, file) { var done = assert.async(); assert.ok(typeof file === "string"); JSZip.loadAsync(file) .then(function (zip) { return zip.file("Hello.txt").async("string"); }) .then(function(result) { assert.equal(result, "Hello World\n", "the zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); JSZipTestUtils.testZipFile("Load files which shadow Object prototype methods", "ref/pollution.zip", function(assert, file) { var done = assert.async(); assert.ok(typeof file === "string"); JSZip.loadAsync(file) .then(function (zip) { assert.notEqual(Object.getPrototypeOf(zip.files), zip.files.__proto__); // jshint ignore:line return zip.file("__proto__").async("string"); }) .then(function(result) { assert.equal(result, "hello\n", "the zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); JSZipTestUtils.testZipFile("load(string) handles bytes > 255", "ref/all.zip", function(assert, file) { var done = assert.async(); // the method used to load zip with ajax will remove the extra bits. // adding extra bits :) var updatedFile = ""; for (var i = 0; i < file.length; i++) { updatedFile += String.fromCharCode((file.charCodeAt(i) & 0xff) + 0x4200); } JSZip.loadAsync(updatedFile) .then(function (zip) { return zip.file("Hello.txt").async("string"); }) .then(function (content) { assert.equal(content, "Hello World\n", "the zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); JSZipTestUtils.testZipFile("load(Array) works", "ref/deflate.zip", function(assert, file) { var done = assert.async(); var updatedFile = new Array(file.length); for( var i = 0; i < file.length; ++i ) { updatedFile[i] = file.charCodeAt(i); } JSZip.loadAsync(updatedFile) .then(function (zip) { return zip.file("Hello.txt").async("string"); }) .then(function (content) { assert.equal(content, "This a looong file : we need to see the difference between the different compression methods.\n", "the zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); JSZipTestUtils.testZipFile("load(array) handles bytes > 255", "ref/deflate.zip", function(assert, file) { var done = assert.async(); var updatedFile = new Array(file.length); for( var i = 0; i < file.length; ++i ) { updatedFile[i] = file.charCodeAt(i) + 0x4200; } JSZip.loadAsync(updatedFile) .then(function (zip) { return zip.file("Hello.txt").async("string"); }) .then(function (content) { assert.equal(content, "This a looong file : we need to see the difference between the different compression methods.\n", "the zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); if (JSZip.support.arraybuffer) { JSZipTestUtils.testZipFile("load(ArrayBuffer) works", "ref/all.zip", function(assert, fileAsString) { var done = assert.async(3); var file = new ArrayBuffer(fileAsString.length); var bufferView = new Uint8Array(file); for( var i = 0; i < fileAsString.length; ++i ) { bufferView[i] = fileAsString.charCodeAt(i); } assert.ok(file instanceof ArrayBuffer); // when reading an arraybuffer, the CompressedObject mechanism will keep it and subarray() a Uint8Array. // if we request a file in the same format, we might get the same Uint8Array or its ArrayBuffer (the original zip file). JSZip.loadAsync(file) .then(function (zip) { return zip.file("Hello.txt").async("arraybuffer"); }).then(function (content){ assert.equal(content.byteLength, 12, "don't get the original buffer"); done(); })['catch'](JSZipTestUtils.assertNoError); JSZip.loadAsync(file) .then(function (zip) { return zip.file("Hello.txt").async("uint8array"); }).then(function (content){ assert.equal(content.buffer.byteLength, 12, "don't get a view of the original buffer"); done(); }); JSZip.loadAsync(file) .then(function (zip) { return zip.file("Hello.txt").async("string"); }).then(function (content){ assert.equal(content, "Hello World\n", "the zip was correctly read."); done(); }); }); } if (JSZip.support.nodebuffer) { JSZipTestUtils.testZipFile("load(Buffer) works", "ref/all.zip", function(assert, fileAsString) { var done = assert.async(); var file = new Buffer(fileAsString.length); for( var i = 0; i < fileAsString.length; ++i ) { file[i] = fileAsString.charCodeAt(i); } JSZip.loadAsync(file) .then(function (zip) { return zip.file("Hello.txt").async("string"); }).then(function (content){ assert.equal(content, "Hello World\n", "the zip was correctly read."); done(); }); }); } if (JSZip.support.uint8array) { JSZipTestUtils.testZipFile("load(Uint8Array) works", "ref/all.zip", function(assert, fileAsString) { var done = assert.async(3); var file = new Uint8Array(fileAsString.length); for( var i = 0; i < fileAsString.length; ++i ) { file[i] = fileAsString.charCodeAt(i); } assert.ok(file instanceof Uint8Array); // when reading an arraybuffer, the CompressedObject mechanism will keep it and subarray() a Uint8Array. // if we request a file in the same format, we might get the same Uint8Array or its ArrayBuffer (the original zip file). JSZip.loadAsync(file) .then(function (zip) { return zip.file("Hello.txt").async("arraybuffer"); }).then(function (content){ assert.equal(content.byteLength, 12, "don't get the original buffer"); done(); })['catch'](JSZipTestUtils.assertNoError); JSZip.loadAsync(file) .then(function (zip) { return zip.file("Hello.txt").async("uint8array"); }).then(function (content){ assert.equal(content.buffer.byteLength, 12, "don't get a view of the original buffer"); done(); })['catch'](JSZipTestUtils.assertNoError); JSZip.loadAsync(file) .then(function (zip) { return zip.file("Hello.txt").async("string"); }).then(function (content){ assert.equal(content, "Hello World\n", "the zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); } // zip -6 -X deflate.zip Hello.txt JSZipTestUtils.testZipFile("zip with DEFLATE", "ref/deflate.zip", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file) .then(function (zip) { return zip.file("Hello.txt").async("string"); }).then(function (content){ assert.equal(content, "This a looong file : we need to see the difference between the different compression methods.\n", "the zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); // zip -0 -X -z -c archive_comment.zip Hello.txt JSZipTestUtils.testZipFile("read zip with comment", "ref/archive_comment.zip", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file) .then(function (zip) { assert.equal(zip.comment, "file comment", "the archive comment was correctly read."); assert.equal(zip.file("Hello.txt").comment, "entry comment", "the entry comment was correctly read."); return zip.file("Hello.txt").async("string"); }).then(function (content){ assert.equal(content, "Hello World\n", "the zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); JSZipTestUtils.testZipFile("generate zip with comment", "ref/archive_comment.zip", function(assert, file) { var zip = new JSZip(); zip.file("Hello.txt", "Hello World\n", {comment:"entry comment"}); var done = assert.async(); zip.generateAsync({type:"binarystring", comment:"file comment"}).then(function(generated) { assert.ok(JSZipTestUtils.similar(generated, file, JSZipTestUtils.MAX_BYTES_DIFFERENCE_PER_ZIP_ENTRY) , "Generated ZIP matches reference ZIP"); JSZipTestUtils.checkGenerateStability(assert, generated); done(); })['catch'](JSZipTestUtils.assertNoError); }); // zip -0 extra_attributes.zip Hello.txt JSZipTestUtils.testZipFile("zip with extra attributes", "ref/extra_attributes.zip", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file) .then(function (zip) { return zip.file("Hello.txt").async("string"); }).then(function (content){ assert.equal(content, "Hello World\n", "the zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); // use -fz to force use of Zip64 format // zip -fz -0 zip64.zip Hello.txt JSZipTestUtils.testZipFile("zip 64", "ref/zip64.zip", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file) .then(function (zip) { return zip.file("Hello.txt").async("string"); }).then(function (content){ assert.equal(content, "Hello World\n", "the zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); // use -fd to force data descriptors as if streaming // zip -fd -0 data_descriptor.zip Hello.txt JSZipTestUtils.testZipFile("zip with data descriptor", "ref/data_descriptor.zip", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file) .then(function (zip) { return zip.file("Hello.txt").async("string"); }).then(function (content){ assert.equal(content, "Hello World\n", "the zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); // combo of zip64 and data descriptors : // zip -fz -fd -0 data_descriptor_zip64.zip Hello.txt // this generate a corrupted zip file :( // TODO : find how to get the two features // zip -0 -X zip_within_zip.zip Hello.txt && zip -0 -X nested.zip Hello.txt zip_within_zip.zip JSZipTestUtils.testZipFile("nested zip", "ref/nested.zip", function(assert, file) { var done = assert.async(2); JSZip.loadAsync(file) .then(function (zip) { return zip.file("zip_within_zip.zip").async("binarystring"); }) .then(JSZip.loadAsync) .then(function (innerZip) { return innerZip.file("Hello.txt").async("string"); }).then(function (content) { assert.equal(content, "Hello World\n", "the inner zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); JSZip.loadAsync(file) .then(function (zip) { return zip.file("Hello.txt").async("string"); }).then(function (content){ assert.equal(content, "Hello World\n", "the zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); // zip -fd -0 nested_data_descriptor.zip data_descriptor.zip JSZipTestUtils.testZipFile("nested zip with data descriptors", "ref/nested_data_descriptor.zip", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file) .then(function (zip) { return zip.file("data_descriptor.zip").async("binarystring"); }) .then(JSZip.loadAsync) .then(function (zip) { return zip.file("Hello.txt").async("string"); }).then(function (content) { assert.equal(content, "Hello World\n", "the inner zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); // zip -fz -0 nested_zip64.zip zip64.zip JSZipTestUtils.testZipFile("nested zip 64", "ref/nested_zip64.zip", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file) .then(function (zip) { return zip.file("zip64.zip").async("binarystring"); }) .then(JSZip.loadAsync) .then(function (zip) { return zip.file("Hello.txt").async("string"); }).then(function (content) { assert.equal(content, "Hello World\n", "the inner zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); // nested zip 64 with data descriptors // zip -fz -fd -0 nested_data_descriptor_zip64.zip data_descriptor_zip64.zip // this generate a corrupted zip file :( // TODO : find how to get the two features // zip -X -0 utf8_in_name.zip €15.txt JSZipTestUtils.testZipFile("Zip text file with UTF-8 characters in filename", "ref/utf8_in_name.zip", function(assert, file) { var done = assert.async(2); JSZip.loadAsync(file) .then(function (zip){ assert.ok(zip.file("€15.txt") !== null, "the utf8 file is here."); return zip.file("€15.txt").async("string"); }) .then(function (content) { assert.equal(content, "€15\n", "the utf8 content was correctly read (with file().async)."); done(); })['catch'](JSZipTestUtils.assertNoError); JSZip.loadAsync(file) .then(function (zip){ return zip.files["€15.txt"].async("string"); }) .then(function (content) { assert.equal(content, "€15\n", "the utf8 content was correctly read (with files[].async)."); done(); })['catch'](JSZipTestUtils.assertNoError); }); // Created with winrar // winrar will replace the euro symbol with a '_' but set the correct unicode path in an extra field. JSZipTestUtils.testZipFile("Zip text file with UTF-8 characters in filename and windows compatibility", "ref/winrar_utf8_in_name.zip", function(assert, file) { var done = assert.async(2); JSZip.loadAsync(file) .then(function (zip){ assert.ok(zip.file("€15.txt") !== null, "the utf8 file is here."); return zip.file("€15.txt").async("string"); }) .then(function (content) { assert.equal(content, "€15\n", "the utf8 content was correctly read (with file().async)."); done(); })['catch'](JSZipTestUtils.assertNoError); JSZip.loadAsync(file) .then(function (zip){ return zip.files["€15.txt"].async("string"); }) .then(function (content) { assert.equal(content, "€15\n", "the utf8 content was correctly read (with files[].async)."); done(); })['catch'](JSZipTestUtils.assertNoError); }); // zip backslash.zip -0 -X Hel\\lo.txt JSZipTestUtils.testZipFile("Zip text file with backslash in filename", "ref/backslash.zip", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file) .then(function (zip){ return zip.file("Hel\\lo.txt").async("string"); }) .then(function (content) { assert.equal(content, "Hello World\n", "the utf8 content was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); // use izarc to generate a zip file on windows JSZipTestUtils.testZipFile("Zip text file from windows with \\ in central dir", "ref/slashes_and_izarc.zip", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file) .then(function (zip){ return zip.folder("test").file("Hello.txt").async("string"); }) .then(function (content) { assert.equal(content, "Hello world\r\n", "the content was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); // cat Hello.txt all.zip > all_prepended_bytes.zip JSZipTestUtils.testZipFile("zip file with prepended bytes", "ref/all_prepended_bytes.zip", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file) .then(function success(zip) { return zip.file("Hello.txt").async("string"); }).then(function (content) { assert.equal(content, "Hello World\n", "the zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); // cat all.zip Hello.txt > all_appended_bytes.zip JSZipTestUtils.testZipFile("zip file with appended bytes", "ref/all_appended_bytes.zip", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file) .then(function success(zip) { return zip.file("Hello.txt").async("string"); }).then(function (content) { assert.equal(content, "Hello World\n", "the zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); // cat Hello.txt zip64.zip > zip64_prepended_bytes.zip JSZipTestUtils.testZipFile("zip64 file with extra bytes", "ref/zip64_prepended_bytes.zip", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file) .then(function success(zip) { return zip.file("Hello.txt").async("string"); }).then(function (content) { assert.equal(content, "Hello World\n", "the zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); // cat zip64.zip Hello.txt > zip64_appended_bytes.zip JSZipTestUtils.testZipFile("zip64 file with extra bytes", "ref/zip64_appended_bytes.zip", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file) .then(function success(zip) { return zip.file("Hello.txt").async("string"); }).then(function (content) { assert.equal(content, "Hello World\n", "the zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); JSZipTestUtils.testZipFile("load(promise) works", "ref/all.zip", function(assert, fileAsString) { var done = assert.async(); JSZip.loadAsync(JSZip.external.Promise.resolve(fileAsString)) .then(function (zip) { return zip.file("Hello.txt").async("string"); }).then(function (content){ assert.equal(content, "Hello World\n", "the zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); if (JSZip.support.blob) { JSZipTestUtils.testZipFile("load(blob) works", "ref/all.zip", function(assert, fileAsString) { var u8 = new Uint8Array(fileAsString.length); for( var i = 0; i < fileAsString.length; ++i ) { u8[i] = fileAsString.charCodeAt(i); } var file = null; try { // don't use an Uint8Array, see the comment on utils.newBlob file = new Blob([u8.buffer], {type:"application/zip"}); } catch (e) { var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder; var builder = new Builder(); builder.append(u8.buffer); file = builder.getBlob("application/zip"); } var done = assert.async(); JSZip.loadAsync(file) .then(function (zip) { return zip.file("Hello.txt").async("string"); }).then(function (content){ assert.equal(content, "Hello World\n", "the zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); } JSZipTestUtils.testZipFile("valid crc32", "ref/all.zip", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file, {checkCRC32:true}) .then(function success() { assert.ok(true, "no exception were thrown"); done(); }, function failure(e) { assert.ok(false, "An exception were thrown: " + e.message); done(); }); }); JSZipTestUtils.testZipFile("loading in a sub folder", "ref/all.zip", function(assert, file) { var done = assert.async(); var zip = new JSZip(); zip.folder("sub").loadAsync(file) .then(function success(zip) { assert.ok(zip.file("Hello.txt"), "the zip was correctly read."); assert.equal(zip.file("Hello.txt").name, "sub/Hello.txt", "the zip was read in a sub folder"); assert.equal(zip.root, "sub/", "the promise contains the correct folder level"); done(); }, function failure(e) { assert.ok(false, "An exception were thrown: " + e.message); done(); }); }); JSZipTestUtils.testZipFile("loading overwrite files", "ref/all.zip", function(assert, file) { var done = assert.async(); var zip = new JSZip(); zip.file("Hello.txt", "bonjour à tous"); zip.file("Bye.txt", "au revoir"); zip.loadAsync(file) .then(function success(zip) { return JSZip.external.Promise.all([ zip.file("Hello.txt").async("text"), zip.file("Bye.txt").async("text") ]); }).then(function (result) { var hello = result[0]; var bye = result[1]; assert.equal(hello, "Hello World\n", "conflicting content was overwritten."); assert.equal(bye, "au revoir", "other content was kept."); done(); }, function failure(e) { assert.ok(false, "An exception were thrown: " + e.message); done(); }); }); QUnit.module("not supported features"); // zip -0 -X -e encrypted.zip Hello.txt JSZipTestUtils.testZipFile("basic encryption", "ref/encrypted.zip", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file) .then(function success() { assert.ok(false, "Encryption is not supported, but no exception were thrown"); done(); }, function failure(e) { assert.equal(e.message, "Encrypted zip are not supported", "the error message is useful"); done(); }); }); QUnit.module("corrupted zip"); JSZipTestUtils.testZipFile("bad compression method", "ref/invalid/compression.zip", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file) .then(function success() { assert.ok(false, "no exception were thrown"); done(); }, function failure(e) { assert.ok(e.message.match("Corrupted zip"), "the error message is useful"); done(); }); }); // dd if=all.zip of=all_missing_bytes.zip bs=32 skip=1 JSZipTestUtils.testZipFile("zip file with missing bytes", "ref/all_missing_bytes.zip", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file) .then(function success() { assert.ok(false, "no exception were thrown"); done(); }, function failure(e) { assert.ok(e.message.match("Corrupted zip"), "the error message is useful"); done(); }); }); // dd if=zip64.zip of=zip64_missing_bytes.zip bs=32 skip=1 JSZipTestUtils.testZipFile("zip64 file with missing bytes", "ref/zip64_missing_bytes.zip", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file) .then(function success() { assert.ok(false, "no exception were thrown"); done(); }, function failure(e) { assert.ok(e.message.match("Corrupted zip"), "the error message is useful"); done(); }); }); JSZipTestUtils.testZipFile("zip file with extra field is Non-standard", "ref/extra_filed_non_standard.zip", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file) .then(function success() { assert.ok(true, "no exception were thrown"); done(); }, function failure(e) { assert.ok(false, "An exception were thrown: " + e.message); done(); }); }); QUnit.test("not a zip file", function(assert) { var done = assert.async(); JSZip.loadAsync("this is not a zip file") .then(function success() { assert.ok(false, "no exception were thrown"); done(); }, function failure(e) { assert.ok(e.message.match("stuk.github.io/jszip/documentation"), "the error message is useful"); done(); }); }); QUnit.test("truncated zip file", function(assert) { var done = assert.async(); JSZip.loadAsync("PK\x03\x04\x0A\x00\x00\x00<cut>") .then(function success() { done(); assert.ok(false, "no exception were thrown"); }, function failure(e) { assert.ok(e.message.match("Corrupted zip"), "the error message is useful"); done(); }); }); JSZipTestUtils.testZipFile("invalid crc32 but no check", "ref/invalid/crc32.zip", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file, {checkCRC32:false}) .then(function success() { assert.ok(true, "no exception were thrown"); done(); }, function failure(e) { assert.ok(false, "An exception were thrown but the check should have been disabled."); done(); }); }); JSZipTestUtils.testZipFile("invalid crc32", "ref/invalid/crc32.zip", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file, {checkCRC32:true}) .then(function success() { assert.ok(false, "no exception were thrown"); done(); }, function failure(e) { assert.ok(e.message.match("Corrupted zip"), "the error message is useful"); done(); }); }); JSZipTestUtils.testZipFile("bad offset", "ref/invalid/bad_offset.zip", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file, {checkCRC32:false}) .then(function success() { assert.ok(false, "no exception were thrown"); done(); }, function failure(e) { assert.ok(e.message.match("Corrupted zip"), "the error message is useful"); done(); }); }); JSZipTestUtils.testZipFile("bad decompressed size, read a file", "ref/invalid/bad_decompressed_size.zip", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file) .then(function (zip) { return zip.file("Hello.txt").async("string"); }) .then(function success() { assert.ok(false, "successful result in an error test"); done(); }, function failure(e) { assert.ok(e.message.match("size mismatch"), "async call : the error message is useful"); done(); }); }); JSZipTestUtils.testZipFile("bad decompressed size, generate a zip", "ref/invalid/bad_decompressed_size.zip", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file) .then(function (zip) { // add other files to be sure to trigger the right code path zip.file("zz", "zz"); return zip.generateAsync({ type:"string", compression:"DEFLATE" // a different compression to force a read }); }) .then(function success() { assert.ok(false, "successful result in an error test"); done(); }, function failure(e) { assert.ok(e.message.match("size mismatch"), "async call : the error message is useful"); done(); }); }); QUnit.module("complex files"); if (typeof window === "undefined" || QUnit.urlParams.complexfiles) { // http://www.feedbooks.com/book/8/the-metamorphosis JSZipTestUtils.testZipFile("Franz Kafka - The Metamorphosis.epub", "ref/complex_files/Franz Kafka - The Metamorphosis.epub", function(assert, file) { var done = assert.async(2); JSZip.loadAsync(file) .then(function(zip) { assert.equal(zip.filter(function(){return true;}).length, 26, "the zip contains the good number of elements."); return zip.file("mimetype").async("string"); }) .then(function (content) { assert.equal(content, "application/epub+zip\r\n", "the zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); JSZip.loadAsync(file) .then(function(zip) { return zip.file("OPS/main0.xml").async("string"); }) .then(function (content) { // the .ncx file tells us that the first chapter is in the main0.xml file. assert.ok(content.indexOf("One morning, as Gregor Samsa was waking up from anxious dreams") !== -1, "the zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); // a showcase in http://msdn.microsoft.com/en-us/windows/hardware/gg463429 JSZipTestUtils.testZipFile("Outlook2007_Calendar.xps, createFolders: false", "ref/complex_files/Outlook2007_Calendar.xps", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file, {createFolders: false}) .then(function(zip) { // the zip file contains 15 entries. assert.equal(zip.filter(function(){return true;}).length, 15, "the zip contains the good number of elements."); return zip.file("[Content_Types].xml").async("string"); }) .then(function (content) { assert.ok(content.indexOf("application/vnd.ms-package.xps-fixeddocument+xml") !== -1, "the zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); // Same test as above, but with createFolders option set to true JSZipTestUtils.testZipFile("Outlook2007_Calendar.xps, createFolders: true", "ref/complex_files/Outlook2007_Calendar.xps", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file, {createFolders: true}) .then(function(zip) { // the zip file contains 15 entries, but we get 23 when creating all the sub-folders. assert.equal(zip.filter(function(){return true;}).length, 23, "the zip contains the good number of elements."); return zip.file("[Content_Types].xml").async("string"); }) .then(function (content) { assert.ok(content.indexOf("application/vnd.ms-package.xps-fixeddocument+xml") !== -1, "the zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); // an example file in http://cheeso.members.winisp.net/srcview.aspx?dir=js-unzip // the data come from http://www.antarctica.ac.uk/met/READER/upper_air/ JSZipTestUtils.testZipFile("AntarcticaTemps.xlsx, createFolders: false", "ref/complex_files/AntarcticaTemps.xlsx", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file, {createFolders: false}) .then(function(zip) { // the zip file contains 17 entries. assert.equal(zip.filter(function(){return true;}).length, 17, "the zip contains the good number of elements."); return zip.file("[Content_Types].xml").async("string"); }).then(function (content) { assert.ok(content.indexOf("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml") !== -1, "the zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); // Same test as above, but with createFolders option set to true JSZipTestUtils.testZipFile("AntarcticaTemps.xlsx, createFolders: true", "ref/complex_files/AntarcticaTemps.xlsx", function(assert, file) { var done = assert.async(); JSZip.loadAsync(file, {createFolders: true}) .then(function(zip) { // the zip file contains 16 entries, but we get 27 when creating all the sub-folders. assert.equal(zip.filter(function(){return true;}).length, 27, "the zip contains the good number of elements."); return zip.file("[Content_Types].xml").async("string"); }).then(function (content) { assert.ok(content.indexOf("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml") !== -1, "the zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); // same as two up, but in the Open Document format JSZipTestUtils.testZipFile("AntarcticaTemps.ods, createFolders: false", "ref/complex_files/AntarcticaTemps.ods", function (assert, file) { var done = assert.async(); JSZip.loadAsync(file, {createFolders: false}) .then(function(zip) { // the zip file contains 20 entries. assert.equal(zip.filter(function () {return true;}).length, 20, "the zip contains the good number of elements."); return zip.file("META-INF/manifest.xml").async("string"); }) .then(function (content) { assert.ok(content.indexOf("application/vnd.oasis.opendocument.spreadsheet") !== -1, "the zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); // same as above, but in the Open Document format JSZipTestUtils.testZipFile("AntarcticaTemps.ods, createFolders: true", "ref/complex_files/AntarcticaTemps.ods", function (assert, file) { var done = assert.async(); JSZip.loadAsync(file, {createFolders: true}) .then(function(zip) { // the zip file contains 19 entries, but we get 27 when creating all the sub-folders. assert.equal(zip.filter(function () {return true;}).length, 27, "the zip contains the good number of elements."); return zip.file("META-INF/manifest.xml").async("string"); }) .then(function (content) { assert.ok(content.indexOf("application/vnd.oasis.opendocument.spreadsheet") !== -1, "the zip was correctly read."); done(); })['catch'](JSZipTestUtils.assertNoError); }); } });
{ "content_hash": "d7f1a441372a7ef8e649370b6182e754", "timestamp": "", "source": "github", "line_count": 813, "max_line_length": 164, "avg_line_length": 44.460024600246, "alnum_prop": 0.5775189509212638, "repo_name": "cloudfoundry-incubator/admin-ui", "id": "669b9fdf78f9e7a1f0ac3ba4a10f8cb6fdf4a888", "size": "36169", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/admin/public/js/external/jszip-3.9.1/test/asserts/load.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "14079" }, { "name": "HTML", "bytes": "108646" }, { "name": "JavaScript", "bytes": "697152" }, { "name": "Ruby", "bytes": "2181290" } ], "symlink_target": "" }
namespace Azure.Data.Tables.Models { /// <summary> Parameter group. </summary> internal partial class QueryOptions { /// <summary> Initializes a new instance of QueryOptions. </summary> public QueryOptions() { } /// <summary> Specifies the media type for the response. </summary> public OdataMetadataFormat? Format { get; set; } /// <summary> Maximum number of records to return. </summary> public int? Top { get; set; } /// <summary> Select expression using OData notation. Limits the columns on each record to just those requested, e.g. &quot;$select=PolicyAssignmentId, ResourceId&quot;. </summary> public string Select { get; set; } /// <summary> OData filter expression. </summary> public string Filter { get; set; } } }
{ "content_hash": "c78369d1f95694a5cbc679606ac724ac", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 188, "avg_line_length": 41.95, "alnum_prop": 0.6317044100119189, "repo_name": "brjohnstmsft/azure-sdk-for-net", "id": "c07ef9ca8029e4c3f83eb25da76f83b706e4148c", "size": "977", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "sdk/tables/Azure.Data.Tables/src/Generated/Models/QueryOptions.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "16774" }, { "name": "C#", "bytes": "36517517" }, { "name": "HTML", "bytes": "234899" }, { "name": "JavaScript", "bytes": "7875" }, { "name": "PowerShell", "bytes": "257257" }, { "name": "Shell", "bytes": "13061" }, { "name": "Smarty", "bytes": "11135" }, { "name": "TypeScript", "bytes": "143209" } ], "symlink_target": "" }
using System; using System.IO; namespace AsyncProgrammingModels { public class ApmSample { static readonly byte[] Buffer = new byte[100]; static void Main(string[] args) { const string filePath = @"C:\Apps\Foo.txt"; FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 1024, FileOptions.Asynchronous); IAsyncResult result = fileStream.BeginRead(Buffer, 0, Buffer.Length, new AsyncCallback(CompleteRead), fileStream); } static void CompleteRead(IAsyncResult result) { Console.WriteLine("Read Completed"); FileStream strm = (FileStream)result.AsyncState; int numBytes = strm.EndRead(result); strm.Close(); Console.WriteLine("Read {0} Bytes", numBytes); Console.WriteLine(BitConverter.ToString(Buffer)); } } }
{ "content_hash": "3ae6e3592210226714999434ce1e28e1", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 80, "avg_line_length": 30.87878787878788, "alnum_prop": 0.5750736015701668, "repo_name": "tugberkugurlu/AsyncTips", "id": "de248111a6f2643f93fb340dffbead5967c2ff6e", "size": "1021", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AsyncProgrammingModels/APMSample.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "117" }, { "name": "C#", "bytes": "27290" }, { "name": "CSS", "bytes": "537" }, { "name": "JavaScript", "bytes": "10714" } ], "symlink_target": "" }
function bias_plotMovement(preHeader, plotMode, axHandle, trialOrBlock) % function bias_plotMovement(preHeader, trial, axHandle, mice) % bias_plotMovement(preHeader, trial, axHandle, mice) % % Plots the path the first mouse in a block followed in 'trial' # on 'axHandle'. % % Call with mice set to '3' to plot all mice. % % See also % % rbm 3.16 % if nargin==2, % axHandle = gca; % end % % if nargin==4 && mice==3, % cla % plot(preHeader.micePos(trial).mPosX', preHeader.micePos(trial).mPosY') % else % H = preHeader.micePos(trial).mPosX(1,:); % V = preHeader.micePos(trial).mPosY(1,:); % frameLabel = preHeader.mLabAll(trial).mll(1,:); % % % plot(axHandle, H(1:150), V(1:150)) % hold(axHandle,'on') % plot(axHandle, H(151:end), V(151:end)) % % plot(axHandle, H, V) % % for i = 1:4, % % scatter(H(frameLabel==i),V(frameLabel==i)) % % end % end % Recover when focal animal reached reward port enter_reward = preHeader.events.enter_reward; enter_reward_frames = round((enter_reward/1000)*29.97); % from ms to frames % Plot outline of analysis boxes if isfield(preHeader,'boxes'), startBox = preHeader.boxes.startBox; decisionBox = preHeader.boxes.decisionBox; leftRewBox = preHeader.boxes.leftRewBox; rightRewBox = preHeader.boxes.rightRewBox; else startBox = [560 820 480 720]; decisionBox = [560 820 1 480]; leftRewBox = [ 90 540 1 340]; rightRewBox = [840 1280 1 340]; end plot(axHandle,startBox([1 2 2 1 1]), startBox([3 3 4 4 3]),'b') hold(axHandle,'on') plot(axHandle,decisionBox([1 2 2 1 1]), decisionBox([3 3 4 4 3]),'r') plot(axHandle,leftRewBox([1 2 2 1 1]), leftRewBox([3 3 4 4 3]),'g') plot(axHandle,rightRewBox([1 2 2 1 1]), rightRewBox([3 3 4 4 3]),'g') switch plotMode case 'singleTrial' th = enter_reward_frames(trialOrBlock)+15; if isnan(th), return, end % % Plotting all mice mice = size(preHeader.micePos(trialOrBlock).mPosX,1); for tm = 1:mice H = preHeader.micePos(trialOrBlock).mPosX(tm,:); V = preHeader.micePos(trialOrBlock).mPosY(tm,:); plot(axHandle, H(151:end), V(151:end),'LineWidth',2) end % Indicate the focal animal's choice s = {'None','Left','Right'}; in.HEADER = preHeader; beh = bias_findBehaviour(in); fn = sprintf('Session %s Trial #%d. Chose %s',... preHeader.session,trialOrBlock, s{beh(trialOrBlock,1)+1}); title(fn) set(gcf,'name',['movement trace ' fn]) case 'blockOfTrials' % Find cutoff trials for dividng a block in trials tb = preHeader.sessionTable.Block_no_sess==trialOrBlock; defaultClr = [254,196,79; 236,112,20; 140,45,4]./255; pt = preHeader.sessionTable.Trial_No(tb); p = fix(prctile(pt, [33 66])); learningStage = ones(preHeader.trials,1); learningStage(p(1):p(2)) = 2; learningStage(p(2)+1:end) = 3; % find index to the focal mouse miceID = [preHeader.xlsSheet{find(tb==1,1)+1,12:14}]; if ischar(miceID), return, end [~,s] = sort(miceID); tm = find(s==1); % Loop trials within block of interest for trial = pt' if ~isnan(enter_reward_frames(trial)) th = enter_reward_frames(trial)+30; th(th>449) = 449; H = preHeader.micePos(trial).mPosX(tm,:); V = preHeader.micePos(trial).mPosY(tm,:); plot(axHandle, H(151:th), V(151:th),... 'Color',defaultClr(learningStage(trial),:),... 'LineWidth',2) end end rew = preHeader.sessionTable.W_position(find(tb==1,1)); bi = preHeader.sessionTable.Bias_cond(find(tb==1,1)); fn = sprintf('Session %s Block #%d Bias %d Reward %d', ... preHeader.session, trialOrBlock, bi, rew); title(fn) set(gcf,'name',['tracks ' fn]) end % Beautify plot set(axHandle,'ydir','reverse') set(axHandle,'tickdir','out','fontsize',14) xlabel('cm'), ylabel('cm') hold(axHandle,'off') axis(axHandle,'tight') axis(axHandle,'equal')
{ "content_hash": "38ea0c785a1f287e91a661d5f31cbfa7", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 80, "avg_line_length": 37.56521739130435, "alnum_prop": 0.5800925925925926, "repo_name": "rb476/Picasso", "id": "2af1ba930cb22dc4a63379f473746f4956c3489e", "size": "4320", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Project_specific/bias_analysis/bias_plotMovement.m", "mode": "33188", "license": "mit", "language": [ { "name": "M", "bytes": "671" }, { "name": "MATLAB", "bytes": "1949066" } ], "symlink_target": "" }
#pragma once #include <aws/s3/S3_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/s3/model/Owner.h> #include <aws/s3/model/Bucket.h> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Xml { class XmlDocument; } // namespace Xml } // namespace Utils namespace S3 { namespace Model { /* $shape.documentation */ class AWS_S3_API ListBucketsResult { public: ListBucketsResult(); ListBucketsResult(const AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result); ListBucketsResult& operator=(const AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result); inline const Aws::Vector<Bucket>& GetBuckets() const{ return m_buckets; } inline void SetBuckets(const Aws::Vector<Bucket>& value) { m_buckets = value; } inline void SetBuckets(Aws::Vector<Bucket>&& value) { m_buckets = value; } inline ListBucketsResult& WithBuckets(const Aws::Vector<Bucket>& value) { SetBuckets(value); return *this;} inline ListBucketsResult& WithBuckets(Aws::Vector<Bucket>&& value) { SetBuckets(value); return *this;} inline ListBucketsResult& AddBuckets(const Bucket& value) { m_buckets.push_back(value); return *this; } inline ListBucketsResult& AddBuckets(Bucket&& value) { m_buckets.push_back(value); return *this; } inline const Owner& GetOwner() const{ return m_owner; } inline void SetOwner(const Owner& value) { m_owner = value; } inline void SetOwner(Owner&& value) { m_owner = value; } inline ListBucketsResult& WithOwner(const Owner& value) { SetOwner(value); return *this;} inline ListBucketsResult& WithOwner(Owner&& value) { SetOwner(value); return *this;} private: Aws::Vector<Bucket> m_buckets; Owner m_owner; }; } // namespace Model } // namespace S3 } // namespace Aws
{ "content_hash": "06aa4214ec6b061752c387c38781962f", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 111, "avg_line_length": 24.83116883116883, "alnum_prop": 0.6898535564853556, "repo_name": "d9magai/aws-sdk-cpp", "id": "916ba7e6d2cd44eaeb45e56309a5ac121b16c1cd", "size": "2483", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "aws-cpp-sdk-s3/include/aws/s3/model/ListBucketsResult.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "7365" }, { "name": "C++", "bytes": "30637992" }, { "name": "CMake", "bytes": "226208" }, { "name": "Java", "bytes": "3886" }, { "name": "Python", "bytes": "21069" } ], "symlink_target": "" }
package javax.time.zone; import static java.time.calendrical.ChronoUnit.HOURS; import static org.testng.Assert.assertEquals; import java.io.IOException; import java.time.Duration; import java.time.LocalDateTime; import java.time.Year; import java.time.ZoneOffset; import java.time.zone.ZoneOffsetTransition; import javax.time.AbstractTCKTest; import org.testng.annotations.Test; /** * Test ZoneOffsetTransition. */ @Test public class TCKZoneOffsetTransition extends AbstractTCKTest { private static final ZoneOffset OFFSET_0100 = ZoneOffset.ofHours(1); private static final ZoneOffset OFFSET_0200 = ZoneOffset.ofHours(2); private static final ZoneOffset OFFSET_0230 = ZoneOffset.ofHoursMinutes(2, 30); private static final ZoneOffset OFFSET_0300 = ZoneOffset.ofHours(3); private static final ZoneOffset OFFSET_0400 = ZoneOffset.ofHours(4); // ----------------------------------------------------------------------- // factory // ----------------------------------------------------------------------- @Test(expectedExceptions = NullPointerException.class, groups = { "tck" }) public void test_factory_nullTransition() { ZoneOffsetTransition.of(null, OFFSET_0100, OFFSET_0200); } @Test(expectedExceptions = NullPointerException.class, groups = { "tck" }) public void test_factory_nullOffsetBefore() { ZoneOffsetTransition.of(LocalDateTime.of(2010, 12, 3, 11, 30), null, OFFSET_0200); } @Test(expectedExceptions = NullPointerException.class, groups = { "tck" }) public void test_factory_nullOffsetAfter() { ZoneOffsetTransition.of(LocalDateTime.of(2010, 12, 3, 11, 30), OFFSET_0200, null); } @Test(expectedExceptions = IllegalArgumentException.class, groups = { "tck" }) public void test_factory_sameOffset() { ZoneOffsetTransition.of(LocalDateTime.of(2010, 12, 3, 11, 30), OFFSET_0200, OFFSET_0200); } @Test(expectedExceptions = IllegalArgumentException.class, groups = { "tck" }) public void test_factory_noNanos() { ZoneOffsetTransition.of(LocalDateTime.of(2010, 12, 3, 11, 30, 0, 500), OFFSET_0200, OFFSET_0300); } // ----------------------------------------------------------------------- // getters // ----------------------------------------------------------------------- @Test(groups = { "tck" }) public void test_getters_gap() throws Exception { LocalDateTime before = LocalDateTime.of(2010, 3, 31, 1, 0); LocalDateTime after = LocalDateTime.of(2010, 3, 31, 2, 0); ZoneOffsetTransition test = ZoneOffsetTransition.of(before, OFFSET_0200, OFFSET_0300); assertEquals(test.isGap(), true); assertEquals(test.isOverlap(), false); assertEquals(test.getDateTimeBefore(), before); assertEquals(test.getDateTimeAfter(), after); assertEquals(test.getInstant(), before.toInstant(OFFSET_0200)); assertEquals(test.getOffsetBefore(), OFFSET_0200); assertEquals(test.getOffsetAfter(), OFFSET_0300); assertEquals(test.getDuration(), Duration.of(1, HOURS)); assertSerializable(test); } @Test(groups = { "tck" }) public void test_getters_overlap() throws Exception { LocalDateTime before = LocalDateTime.of(2010, 10, 31, 1, 0); LocalDateTime after = LocalDateTime.of(2010, 10, 31, 0, 0); ZoneOffsetTransition test = ZoneOffsetTransition.of(before, OFFSET_0300, OFFSET_0200); assertEquals(test.isGap(), false); assertEquals(test.isOverlap(), true); assertEquals(test.getDateTimeBefore(), before); assertEquals(test.getDateTimeAfter(), after); assertEquals(test.getInstant(), before.toInstant(OFFSET_0300)); assertEquals(test.getOffsetBefore(), OFFSET_0300); assertEquals(test.getOffsetAfter(), OFFSET_0200); assertEquals(test.getDuration(), Duration.of(-1, HOURS)); assertSerializable(test); } // ----------------------------------------------------------------------- @Test(groups = { "tck" }) public void test_serialization_unusual1() throws Exception { LocalDateTime ldt = LocalDateTime.of(Year.MAX_YEAR, 12, 31, 1, 31, 53); ZoneOffsetTransition test = ZoneOffsetTransition.of(ldt, ZoneOffset.of("+02:04:56"), ZoneOffset.of("-10:02:34")); assertSerializable(test); } @Test(groups = { "tck" }) public void test_serialization_unusual2() throws Exception { LocalDateTime ldt = LocalDateTime.of(Year.MIN_YEAR, 1, 1, 12, 1, 3); ZoneOffsetTransition test = ZoneOffsetTransition.of(ldt, ZoneOffset.of("+02:04:56"), ZoneOffset.of("+10:02:34")); assertSerializable(test); } @Test(groups = { "tck" }) public void test_serialization_format() throws ClassNotFoundException, IOException { LocalDateTime ldt = LocalDateTime.of(Year.MIN_YEAR, 1, 1, 12, 1, 3); ZoneOffsetTransition test = ZoneOffsetTransition.of(ldt, ZoneOffset.of("+02:04:56"), ZoneOffset.of("+10:02:34")); assertEqualsSerialisedForm(test); } // ----------------------------------------------------------------------- // isValidOffset() // ----------------------------------------------------------------------- @Test(groups = { "tck" }) public void test_isValidOffset_gap() { LocalDateTime ldt = LocalDateTime.of(2010, 3, 31, 1, 0); ZoneOffsetTransition test = ZoneOffsetTransition.of(ldt, OFFSET_0200, OFFSET_0300); assertEquals(test.isValidOffset(OFFSET_0100), false); assertEquals(test.isValidOffset(OFFSET_0200), false); assertEquals(test.isValidOffset(OFFSET_0230), false); assertEquals(test.isValidOffset(OFFSET_0300), false); assertEquals(test.isValidOffset(OFFSET_0400), false); } @Test(groups = { "tck" }) public void test_isValidOffset_overlap() { LocalDateTime ldt = LocalDateTime.of(2010, 10, 31, 1, 0); ZoneOffsetTransition test = ZoneOffsetTransition.of(ldt, OFFSET_0300, OFFSET_0200); assertEquals(test.isValidOffset(OFFSET_0100), false); assertEquals(test.isValidOffset(OFFSET_0200), true); assertEquals(test.isValidOffset(OFFSET_0230), false); assertEquals(test.isValidOffset(OFFSET_0300), true); assertEquals(test.isValidOffset(OFFSET_0400), false); } // ----------------------------------------------------------------------- // compareTo() // ----------------------------------------------------------------------- @Test(groups = { "tck" }) public void test_compareTo() { ZoneOffsetTransition a = ZoneOffsetTransition.of(LocalDateTime.ofEpochSecond(23875287L - 1, 0, OFFSET_0200), OFFSET_0200, OFFSET_0300); ZoneOffsetTransition b = ZoneOffsetTransition.of(LocalDateTime.ofEpochSecond(23875287L, 0, OFFSET_0300), OFFSET_0300, OFFSET_0200); ZoneOffsetTransition c = ZoneOffsetTransition.of(LocalDateTime.ofEpochSecond(23875287L + 1, 0, OFFSET_0100), OFFSET_0100, OFFSET_0400); assertEquals(a.compareTo(a) == 0, true); assertEquals(a.compareTo(b) < 0, true); assertEquals(a.compareTo(c) < 0, true); assertEquals(b.compareTo(a) > 0, true); assertEquals(b.compareTo(b) == 0, true); assertEquals(b.compareTo(c) < 0, true); assertEquals(c.compareTo(a) > 0, true); assertEquals(c.compareTo(b) > 0, true); assertEquals(c.compareTo(c) == 0, true); } @Test(groups = { "tck" }) public void test_compareTo_sameInstant() { ZoneOffsetTransition a = ZoneOffsetTransition.of(LocalDateTime.ofEpochSecond(23875287L, 0, OFFSET_0200), OFFSET_0200, OFFSET_0300); ZoneOffsetTransition b = ZoneOffsetTransition.of(LocalDateTime.ofEpochSecond(23875287L, 0, OFFSET_0300), OFFSET_0300, OFFSET_0200); ZoneOffsetTransition c = ZoneOffsetTransition.of(LocalDateTime.ofEpochSecond(23875287L, 0, OFFSET_0100), OFFSET_0100, OFFSET_0400); assertEquals(a.compareTo(a) == 0, true); assertEquals(a.compareTo(b) == 0, true); assertEquals(a.compareTo(c) == 0, true); assertEquals(b.compareTo(a) == 0, true); assertEquals(b.compareTo(b) == 0, true); assertEquals(b.compareTo(c) == 0, true); assertEquals(c.compareTo(a) == 0, true); assertEquals(c.compareTo(b) == 0, true); assertEquals(c.compareTo(c) == 0, true); } // ----------------------------------------------------------------------- // equals() // ----------------------------------------------------------------------- @Test(groups = { "tck" }) public void test_equals() { LocalDateTime ldtA = LocalDateTime.of(2010, 3, 31, 1, 0); ZoneOffsetTransition a1 = ZoneOffsetTransition.of(ldtA, OFFSET_0200, OFFSET_0300); ZoneOffsetTransition a2 = ZoneOffsetTransition.of(ldtA, OFFSET_0200, OFFSET_0300); LocalDateTime ldtB = LocalDateTime.of(2010, 10, 31, 1, 0); ZoneOffsetTransition b = ZoneOffsetTransition.of(ldtB, OFFSET_0300, OFFSET_0200); assertEquals(a1.equals(a1), true); assertEquals(a1.equals(a2), true); assertEquals(a1.equals(b), false); assertEquals(a2.equals(a1), true); assertEquals(a2.equals(a2), true); assertEquals(a2.equals(b), false); assertEquals(b.equals(a1), false); assertEquals(b.equals(a2), false); assertEquals(b.equals(b), true); assertEquals(a1.equals(""), false); assertEquals(a1.equals(null), false); } // ----------------------------------------------------------------------- // hashCode() // ----------------------------------------------------------------------- @Test(groups = { "tck" }) public void test_hashCode_floatingWeek_gap_notEndOfDay() { LocalDateTime ldtA = LocalDateTime.of(2010, 3, 31, 1, 0); ZoneOffsetTransition a1 = ZoneOffsetTransition.of(ldtA, OFFSET_0200, OFFSET_0300); ZoneOffsetTransition a2 = ZoneOffsetTransition.of(ldtA, OFFSET_0200, OFFSET_0300); LocalDateTime ldtB = LocalDateTime.of(2010, 10, 31, 1, 0); ZoneOffsetTransition b = ZoneOffsetTransition.of(ldtB, OFFSET_0300, OFFSET_0200); assertEquals(a1.hashCode(), a1.hashCode()); assertEquals(a1.hashCode(), a2.hashCode()); assertEquals(b.hashCode(), b.hashCode()); } // ----------------------------------------------------------------------- // toString() // ----------------------------------------------------------------------- @Test(groups = { "tck" }) public void test_toString_gap() { LocalDateTime ldt = LocalDateTime.of(2010, 3, 31, 1, 0); ZoneOffsetTransition test = ZoneOffsetTransition.of(ldt, OFFSET_0200, OFFSET_0300); assertEquals(test.toString(), "Transition[Gap at 2010-03-31T01:00+02:00 to +03:00]"); } @Test(groups = { "tck" }) public void test_toString_overlap() { LocalDateTime ldt = LocalDateTime.of(2010, 10, 31, 1, 0); ZoneOffsetTransition test = ZoneOffsetTransition.of(ldt, OFFSET_0300, OFFSET_0200); assertEquals(test.toString(), "Transition[Overlap at 2010-10-31T01:00+03:00 to +02:00]"); } }
{ "content_hash": "71e0fbdc575bcedb8a1c14c8e13d4a59", "timestamp": "", "source": "github", "line_count": 267, "max_line_length": 117, "avg_line_length": 40.08988764044944, "alnum_prop": 0.6299514200298953, "repo_name": "m-m-m/java8-backports", "id": "7574f6e962ea0119a344453fcbd2266fc6e49498", "size": "12315", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mmm-util-backport-java.time/src/test/java/javax/time/zone/TCKZoneOffsetTransition.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "5337" }, { "name": "Java", "bytes": "3543978" }, { "name": "JavaScript", "bytes": "3555" } ], "symlink_target": "" }
<?php namespace Converter\Rule; use Converter\ConversionRule; use Converter\Tag; class GridConversion extends ConversionRule { private $_element; protected $_rules; public function __construct() { $this->_rules = array( "row-fluid" => "row", "container-fluid" => "", "span(\\d+)" => array("col-md-$1", 'specialReplace'), "offset(\\d+)" => array("col-md-offset-$1", 'specialReplace') ); } /** * Revamped Grid System * * * Looks for 'spanX' non-form containers and replaces with 'col-md-X' * * Looks for 'offsetX' non-form containers and replaces with 'col-lg-offset-X' * * Change 'row-fluid' to 'row' * * Remove 'container-fluid' * * @param Tag $tag */ public function run(Tag $tag) { $this->_element = $tag->tag; // take the class attribute for element $_tag if (isset($tag->attributes['class'])) { $before = $tag->attributes['class']; $classes_str = $tag->attributes['class']; // each rule foreach ($this->_rules as $old => $new) { // plain old preg_replace, or custom replace? if (is_array($new)) $classes_str = call_user_func_array(array($this, $new[1]), array($old, $new, $classes_str)); else $classes_str = preg_replace("/$old/", $new, $classes_str); } // set modified if ($before != $classes_str) { $tag->SetClassesStr($classes_str); $tag->is_modified = true; } } } /** * Only runs class replacement if conditions are met * * @param string $old regex * @param array $new (css class, callable) * @param string $classes_str * * @return mixed replaced class name */ private function specialReplace($old, $new, $classes_str) { if (strpos('li|section|div|aside|article', $this->_element) !== false) { return preg_replace("/$old/", $new[0], $classes_str); } // else return the original class return $classes_str; } }
{ "content_hash": "19bf0f5375ead3013271f5dc9ba721c5", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 97, "avg_line_length": 22.841463414634145, "alnum_prop": 0.6155899626268019, "repo_name": "Claromentis/bootstrap2-3converter", "id": "f58344fac0297772eb9534f5fa614bcd4285eddb", "size": "1873", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Converter/Rule/GridConversion.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "25695" } ], "symlink_target": "" }
[?php require_once(dirname(__FILE__).'/../lib/Base<?php echo ucfirst($this->moduleName) ?>GeneratorConfiguration.class.php'); require_once(dirname(__FILE__).'/../lib/Base<?php echo ucfirst($this->moduleName) ?>GeneratorHelper.class.php'); /** * <?php echo $this->getModuleName() ?> actions. * * @package ##PROJECT_NAME## * @subpackage <?php echo $this->getModuleName()."\n" ?> * @author ##AUTHOR_NAME## * @version SVN: $Id: actions.class.php 31002 2010-09-27 12:04:07Z Kris.Wallsmith $ */ abstract class <?php echo $this->getGeneratedModuleName() ?>Actions extends <?php echo $this->getActionsBaseClass()."\n" ?> { public function preExecute() { $this->configuration = new <?php echo $this->getModuleName() ?>GeneratorConfiguration(); if (!$this->getUser()->hasCredential($this->configuration->getCredentials($this->getActionName()))) { $this->forward(sfConfig::get('sf_secure_module'), sfConfig::get('sf_secure_action')); } $this->dispatcher->notify(new sfEvent($this, 'admin.pre_execute', array('configuration' => $this->configuration))); $this->helper = new <?php echo $this->getModuleName() ?>GeneratorHelper(); parent::preExecute(); } <?php include dirname(__FILE__).'/../../parts/indexAction.php' ?> <?php if ($this->configuration->hasFilterForm()): ?> <?php include dirname(__FILE__).'/../../parts/filterAction.php' ?> <?php endif; ?> <?php include dirname(__FILE__).'/../../parts/newAction.php' ?> <?php include dirname(__FILE__).'/../../parts/createAction.php' ?> <?php include dirname(__FILE__).'/../../parts/showAction.php' ?> <?php include dirname(__FILE__).'/../../parts/editAction.php' ?> <?php include dirname(__FILE__).'/../../parts/updateAction.php' ?> <?php include dirname(__FILE__).'/../../parts/deleteAction.php' ?> <?php if ($this->configuration->getValue('list.batch_actions')): ?> <?php include dirname(__FILE__).'/../../parts/batchAction.php' ?> <?php endif; ?> <?php include dirname(__FILE__).'/../../parts/processFormAction.php' ?> <?php if ($this->configuration->hasFilterForm()): ?> <?php include dirname(__FILE__).'/../../parts/filtersAction.php' ?> <?php endif; ?> <?php include dirname(__FILE__).'/../../parts/paginationAction.php' ?> <?php include dirname(__FILE__).'/../../parts/sortingAction.php' ?> }
{ "content_hash": "4c29e382402d57349e7d38af53a84aee", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 123, "avg_line_length": 36.714285714285715, "alnum_prop": 0.6368352788586251, "repo_name": "izarus/izarusBootstrap3AdminThemePlugin", "id": "b4d0c5c48d226432e104997fd625aac552f62a83", "size": "2313", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "data/generator/sfDoctrineModule/bootstrap/template/actions/actions.class.php", "mode": "33188", "license": "mit", "language": [ { "name": "Hack", "bytes": "2986" }, { "name": "JavaScript", "bytes": "1383" }, { "name": "PHP", "bytes": "125776" } ], "symlink_target": "" }
<!-- saved from url=(0013)about:internet --> <!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" xml:lang="es" lang="es"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>index</title> </head> <body bgcolor="#ffffff"> <script language="JavaScript"> <!-- var isInternetExplorer = navigator.appName.indexOf("Microsoft") != -1; // Gestionar todos los mensajes de FSCommand de una película Flash function index_DoFSCommand(command, args) { var indexObj = isInternetExplorer ? document.all.index : document.index; // // Introduzca su código aquí. // } // Ancla para Internet Explorer if (navigator.appName && navigator.appName.indexOf("Microsoft") != -1 && navigator.userAgent.indexOf("Windows") != -1 && navigator.userAgent.indexOf("Windows 3.1") == -1) { document.write('<script language=\"VBScript\"\>\n'); document.write('On Error Resume Next\n'); document.write('Sub index_FSCommand(ByVal command, ByVal args)\n'); document.write(' Call index_DoFSCommand(command, args)\n'); document.write('End Sub\n'); document.write('</script\>\n'); } //--> </script> <!--URL utilizadas en la película--> <!--Texto utilizado en la película--> <!-- <p align="left"><font face="Arial" size="68" color="#ff0099" letterSpacing="0.000000" kerning="0">C</font></p> <p align="left"><font face="Arial" size="68" color="#ff0099" letterSpacing="0.000000" kerning="0">u</font></p> <p align="left"><font face="Arial" size="68" color="#ff0099" letterSpacing="0.000000" kerning="0">e</font></p> <p align="left"><font face="Arial" size="68" color="#ff0099" letterSpacing="0.000000" kerning="0">r</font></p> <p align="left"><font face="Arial" size="68" color="#ff0099" letterSpacing="0.000000" kerning="0">p</font></p> <p align="left"><font face="Arial" size="68" color="#ff0099" letterSpacing="0.000000" kerning="0">o</font></p> <p align="left"><font face="Arial" size="68" color="#ff0099" letterSpacing="0.000000" kerning="0">s</font></p> <p align="left"><font face="Arial" size="68" color="#0099cc" letterSpacing="0.000000" kerning="0">s</font></p> <p align="left"><font face="Arial" size="68" color="#0099cc" letterSpacing="0.000000" kerning="0">o</font></p> <p align="left"><font face="Arial" size="68" color="#0099cc" letterSpacing="0.000000" kerning="0">c</font></p> <p align="left"><font face="Arial" size="68" color="#0099cc" letterSpacing="0.000000" kerning="0">i</font></p> <p align="left"><font face="Arial" size="68" color="#0099cc" letterSpacing="0.000000" kerning="0">r</font></p> <p align="left"><font face="Arial" size="68" color="#0099cc" letterSpacing="0.000000" kerning="0">t</font></p> <p align="left"><font face="Arial" size="68" color="#0099cc" letterSpacing="0.000000" kerning="0">é</font></p> <p align="left"><font face="Arial" size="68" color="#0099cc" letterSpacing="0.000000" kerning="0">m</font></p> <p align="left"><font face="Arial" size="68" color="#0099cc" letterSpacing="0.000000" kerning="0">o</font></p> <p align="left"><font face="Arial" size="68" color="#0099cc" letterSpacing="0.000000" kerning="0">e</font></p> <p align="left"><font face="Arial" size="68" color="#0099cc" letterSpacing="0.000000" kerning="0">G</font></p> --> <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" id="index" width="100%" height="100%" align="middle"> <param name="allowScriptAccess" value="sameDomain" /> <param name="movie" value="index.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" /><embed src="index.swf" quality="high" bgcolor="#ffffff" width="100%" height="100%" swLiveConnect=true id="index" name="index" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer_es" /> </object> </body> </html>
{ "content_hash": "eac595cb0c1b698d5330cdadf60b42e7", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 389, "avg_line_length": 69.84210526315789, "alnum_prop": 0.6890228585782466, "repo_name": "rjsteinert/taktaktak", "id": "f7c1baaaeb90809faa3974ac3bba04436cd5ecdb", "size": "3981", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "assets/files/games/roms/cuerposgeometricos/index.php", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
from .base import * from .fields import * from .serializer_fields import * from .time_fields import *
{ "content_hash": "63ce6452b841a16e6b9d923772da3169", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 32, "avg_line_length": 25.5, "alnum_prop": 0.7450980392156863, "repo_name": "onyg/aserializer", "id": "0fbaa4ed4ee79a7fd35f9b7cad192a934236f9ee", "size": "127", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aserializer/fields/__init__.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "217282" } ], "symlink_target": "" }
package hashdb.main.tasks.disk; import hashdb.Settings; import hashdb.Utilities; import hashdb.exceptions.DifferentSizeOfArrayException; import hashdb.main.tasks.response.ExistsResponseTask; import hashdb.main.threads.DiskManager; import hashdb.main.threads.WorkerThread; import hashdb.storage.EntryReaderWriter; import hashdb.storage.entities.Entry; import hashdb.storage.entities.fields.EntryKeyLink; public class CheckIfExists extends DiskTask { public CheckIfExists(Entry entry, ExistsResponseTask ert) { super(entry.getKey(), entry, ert); } public CheckIfExists(EntryKeyLink key, ExistsResponseTask ert) { super(key.getPayload(), null, ert); } public CheckIfExists(byte[] key, ExistsResponseTask ert) { super(key, null, ert); } private CheckIfExists(byte[] key, int nextEntry, int primary, ExistsResponseTask ert) { super(key, null, nextEntry, primary, ert); } private CheckIfExists(Entry entry, int nextEntry, int primary, ExistsResponseTask ert) { super(entry.getKey(), entry, nextEntry, primary, ert); } public void work() { try { EntryReaderWriter erw = DiskManager.getErw(); Entry res = erw.read(entryNumber); ExistsResponseTask ert = (ExistsResponseTask) rt; final boolean empty = Utilities.checkMask(Settings.EMPTY, res.getStatus()); final boolean jumped = Utilities.checkMask(Settings.JUMPED, res.getStatus()); if (!empty) { if (Utilities.sameArray(key, res.getKey())) { if (checkEntry(entry, res)) { ert.setStatus(true); WorkerThread.addTask(ert); return; } } } else if (!jumped) { ert.setStatus(false); WorkerThread.addTask(ert); return; } int nextEntry = iProtocol.getNextPosition(key, entryNumber); while (nextEntry<0) nextEntry+=DiskManager.getCap(); if (nextEntry == primary) { ert.setStatus(false); WorkerThread.addTask(ert); } else { CheckIfExists cie; if (entry == null) { cie = new CheckIfExists(key, nextEntry, primary, ert); } else { cie = new CheckIfExists(entry, nextEntry, primary, ert); } DiskManager.addDiskTask(cie); } } catch (DifferentSizeOfArrayException e) { log.error(e); } } }
{ "content_hash": "e3545ca6ecb12cdd02c6ec0a606a3ef6", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 89, "avg_line_length": 29.18421052631579, "alnum_prop": 0.7010820559062219, "repo_name": "vivitas/hashdb", "id": "8215af6bd346ea8fde0e4eba34fc702e0e0e2d47", "size": "2218", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/hashdb/main/tasks/disk/CheckIfExists.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "175440" } ], "symlink_target": "" }
ZBeach::ZBeach() : Zone (getResources().getTexture(Texture_ID::Zone_Beach), Zone_ID::Beach) { } void ZBeach::onUpdate(World& world, Player& player, float dt) { m_enemyCount -= checkForDeadEntities(player); static sf::Clock clock; if (m_enemyCount < 10) //if (clock.getElapsedTime().asSeconds() > 0.5) { addEnemy(); clock.restart(); } } void ZBeach::onDraw() { } void ZBeach::addEnemy() { m_enemyCount++; addEntity(std::make_unique<Coral_Slime>()); }
{ "content_hash": "1687a30a437fa4d5a4fc8b02ff732c4e", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 76, "avg_line_length": 16.9, "alnum_prop": 0.6173570019723866, "repo_name": "Hopson97/Hero", "id": "e2041dbd8f6d1b04e9c30a0595e0b2a98bd74cf0", "size": "675", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/Game/Zone/ZBeach.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "170" }, { "name": "C++", "bytes": "87485" }, { "name": "CMake", "bytes": "14114" }, { "name": "Shell", "bytes": "762" } ], "symlink_target": "" }
<?php namespace Deployer; require_once __DIR__ . '/common.php'; add('recipes', ['cakephp']); /** * CakePHP 4 Project Template configuration */ // CakePHP 4 Project Template shared dirs set('shared_dirs', [ 'logs', 'tmp', ]); // CakePHP 4 Project Template shared files set('shared_files', [ 'config/.env', 'config/app.php', ]); /** * Create plugins' symlinks */ task('deploy:init', function () { run('{{bin/php}} {{release_or_current_path}}/bin/cake.php plugin assets symlink'); })->desc('Initialization'); /** * Run migrations */ task('deploy:run_migrations', function () { run('{{bin/php}} {{release_or_current_path}}/bin/cake.php migrations migrate --no-lock'); run('{{bin/php}} {{release_or_current_path}}/bin/cake.php schema_cache build'); })->desc('Run migrations'); /** * Main task */ task('deploy', [ 'deploy:prepare', 'deploy:vendors', 'deploy:init', 'deploy:run_migrations', 'deploy:publish', ])->desc('Deploy your project');
{ "content_hash": "d53bb6e41083fe97eca98960da01c160", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 93, "avg_line_length": 20.8125, "alnum_prop": 0.6226226226226226, "repo_name": "deployphp/deployer", "id": "451d1a99534ce33a660222b2e5eb5c3af5cfb9ad", "size": "999", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "recipe/cakephp.php", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "3140" }, { "name": "HTML", "bytes": "58" }, { "name": "PHP", "bytes": "573036" }, { "name": "Shell", "bytes": "966" } ], "symlink_target": "" }
<?php $to = "support@myclario.com"; //Change email here $from = $_REQUEST['email']; $name = $_REQUEST['name']; $headers = "From: $from"; $subject = "You have a message sent from your site"; $fields = array(); $fields{"name"} = "name"; $fields{"phone"} = "phone"; $fields{"email"} = "email"; $fields{"message"} = "message"; $body = "Here is what was sent:\n\n"; foreach($fields as $a => $b){ $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); } $send = mail($to, $subject, $body, $headers); ?>
{ "content_hash": "f60d2f40f6fb4a718013f3bdd5fcccda", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 121, "avg_line_length": 36.5, "alnum_prop": 0.5714285714285714, "repo_name": "Magik3a/PatientManagement_Admin", "id": "6e402d7ce05fab6ebb8289069932764c809214a0", "size": "511", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "PatientManagement.Public/wwwroot/comingsoon/assets/inc/contact.php", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1143" }, { "name": "C#", "bytes": "1630015" }, { "name": "CSS", "bytes": "3093746" }, { "name": "CoffeeScript", "bytes": "103432" }, { "name": "Dockerfile", "bytes": "400" }, { "name": "HTML", "bytes": "1276856" }, { "name": "JavaScript", "bytes": "14922709" }, { "name": "Makefile", "bytes": "1369" }, { "name": "PHP", "bytes": "1738" }, { "name": "PowerShell", "bytes": "4761" }, { "name": "Shell", "bytes": "3020" }, { "name": "TypeScript", "bytes": "407622" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VirtualPresta { public class Product { bool persian = false; Dictionary<string, string> persianDic = new Dictionary<string, string>() { { "ID", "شناسه" }, { "File", "File" }, { "ImageFiles", "ImageFiles" }, { "Name *", "نام" } }; private string translate(string property) { if (!persian) { return property; } else { return persianDic[property]; } } public Product(bool persian = false) { this.persian = persian; Data = new CsvCollection(); } public int Id { get { return Convert.ToInt32( Data[translate("ID")]); } set { Data[translate("ID")] = value.ToString(); } } public string Name { get { return Data[translate("Name *")]; } set { Data[translate("Name *")] = value; } } public string File { get { return Data[translate("File")]; } set { Data[translate("File")] = value; } } public List<string> ImageFiles { get { return new List<string>(Data[translate("ImageFiles")].Split(',')); } set { string res = ""; foreach (string image in value) { if (res != "") res += ','; res += image; } Data[translate("ImageFiles")] = res; } } public CsvCollection Data { get; set; } public CsvCollection StandardCSV { get { CsvCollection collection = new CsvCollection(); foreach (string key in Data.Keys) { if (key != translate("ImageFiles") && key != translate("File")) { collection.Add(key, Data[key]); } } return collection; } } public bool CSVPushed { get; set; } public bool Saved { get; set; } public bool FileAndImagesSaved { get; set; } } }
{ "content_hash": "add37bc6d6ab8ad91e00f6ec5bbc394b", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 83, "avg_line_length": 26.505050505050505, "alnum_prop": 0.4035823170731707, "repo_name": "altostratous/VirtualPresta", "id": "010b1e462115b1fa3686c7603f290e1338c87311", "size": "2634", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "VirtualPresta/Product.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "39782" } ], "symlink_target": "" }
BEGIN; SELECT plan(1); SELECT functions_are('dummy_landable', ARRAY['pages_revision_ordinal', 'tg_disallow', 'template_revision_ordinal'], 'dummy_Landable schema should have funcitons'); SELECT finish(); ROLLBACK;
{ "content_hash": "a7d9961342765b22e4f236adeb91c380", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 163, "avg_line_length": 24.22222222222222, "alnum_prop": 0.7477064220183486, "repo_name": "mlarraz/landable", "id": "07ea2ebbe2c6c1d885956480feb832d2ea7fce80", "size": "218", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "db/test/landable.general.sql", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "546" }, { "name": "JavaScript", "bytes": "595" }, { "name": "Ruby", "bytes": "312337" }, { "name": "Shell", "bytes": "369" } ], "symlink_target": "" }
''' This module defines :class:`Segment`, a container for data sharing a common time basis. :class:`Segment` derives from :class:`Container`, from :module:`neo.core.container`. ''' from datetime import datetime import numpy as np from copy import deepcopy from neo.core.container import Container from neo.core.spiketrainlist import SpikeTrainList class Segment(Container): ''' A container for data sharing a common time basis. A :class:`Segment` is a heterogeneous container for discrete or continuous data sharing a common clock (time basis) but not necessary the same sampling rate, start or end time. *Usage*:: >>> from neo.core import Segment, SpikeTrain, AnalogSignal >>> from quantities import Hz, s >>> >>> seg = Segment(index=5) >>> >>> train0 = SpikeTrain(times=[.01, 3.3, 9.3], units='sec', t_stop=10) >>> seg.spiketrains.append(train0) >>> >>> train1 = SpikeTrain(times=[100.01, 103.3, 109.3], units='sec', ... t_stop=110) >>> seg.spiketrains.append(train1) >>> >>> sig0 = AnalogSignal(signal=[.01, 3.3, 9.3], units='uV', ... sampling_rate=1*Hz) >>> seg.analogsignals.append(sig0) >>> >>> sig1 = AnalogSignal(signal=[100.01, 103.3, 109.3], units='nA', ... sampling_period=.1*s) >>> seg.analogsignals.append(sig1) *Required attributes/properties*: None *Recommended attributes/properties*: :name: (str) A label for the dataset. :description: (str) Text description. :file_origin: (str) Filesystem path or URL of the original data file. :file_datetime: (datetime) The creation date and time of the original data file. :rec_datetime: (datetime) The date and time of the original recording :index: (int) You can use this to define a temporal ordering of your Segment. For instance you could use this for trial numbers. Note: Any other additional arguments are assumed to be user-specific metadata and stored in :attr:`annotations`. *Properties available on this object*: :all_data: (list) A list of all child objects in the :class:`Segment`. *Container of*: :class:`Epoch` :class:`Event` :class:`AnalogSignal` :class:`IrregularlySampledSignal` :class:`SpikeTrain` ''' _data_child_objects = ('AnalogSignal', 'Epoch', 'Event', 'IrregularlySampledSignal', 'SpikeTrain', 'ImageSequence') _parent_objects = ('Block',) _recommended_attrs = ((('file_datetime', datetime), ('rec_datetime', datetime), ('index', int)) + Container._recommended_attrs) _repr_pretty_containers = ('analogsignals',) def __init__(self, name=None, description=None, file_origin=None, file_datetime=None, rec_datetime=None, index=None, **annotations): ''' Initialize a new :class:`Segment` instance. ''' super().__init__(name=name, description=description, file_origin=file_origin, **annotations) self.spiketrains = SpikeTrainList(segment=self) self.file_datetime = file_datetime self.rec_datetime = rec_datetime self.index = index # t_start attribute is handled as a property so type checking can be done @property def t_start(self): ''' Time when first signal begins. ''' t_starts = [sig.t_start for sig in self.analogsignals + self.spiketrains + self.irregularlysampledsignals] for e in self.epochs + self.events: if hasattr(e, 't_start'): # in case of proxy objects t_starts += [e.t_start] elif len(e) > 0: t_starts += [e.times[0]] # t_start is not defined if no children are present if len(t_starts) == 0: return None t_start = min(t_starts) return t_start # t_stop attribute is handled as a property so type checking can be done @property def t_stop(self): ''' Time when last signal ends. ''' t_stops = [sig.t_stop for sig in self.analogsignals + self.spiketrains + self.irregularlysampledsignals] for e in self.epochs + self.events: if hasattr(e, 't_stop'): # in case of proxy objects t_stops += [e.t_stop] elif len(e) > 0: t_stops += [e.times[-1]] # t_stop is not defined if no children are present if len(t_stops) == 0: return None t_stop = max(t_stops) return t_stop def time_slice(self, t_start=None, t_stop=None, reset_time=False, **kwargs): """ Creates a time slice of a Segment containing slices of all child objects. Parameters ---------- t_start: Quantity Starting time of the sliced time window. t_stop: Quantity Stop time of the sliced time window. reset_time: bool, optional, default: False If True the time stamps of all sliced objects are set to fall in the range from t_start to t_stop. If False, original time stamps are retained. **kwargs Additional keyword arguments used for initialization of the sliced Segment object. Returns ------- subseg: Segment Temporal slice of the original Segment from t_start to t_stop. """ subseg = Segment(**kwargs) for attr in ['file_datetime', 'rec_datetime', 'index', 'name', 'description', 'file_origin']: setattr(subseg, attr, getattr(self, attr)) subseg.annotations = deepcopy(self.annotations) if t_start is None: t_start = self.t_start if t_stop is None: t_stop = self.t_stop t_shift = - t_start # cut analogsignals and analogsignalarrays for ana_id in range(len(self.analogsignals)): if hasattr(self.analogsignals[ana_id], '_rawio'): ana_time_slice = self.analogsignals[ana_id].load(time_slice=(t_start, t_stop)) else: ana_time_slice = self.analogsignals[ana_id].time_slice(t_start, t_stop) if reset_time: ana_time_slice = ana_time_slice.time_shift(t_shift) subseg.analogsignals.append(ana_time_slice) # cut irregularly sampled signals for irr_id in range(len(self.irregularlysampledsignals)): if hasattr(self.irregularlysampledsignals[irr_id], '_rawio'): ana_time_slice = self.irregularlysampledsignals[irr_id].load( time_slice=(t_start, t_stop)) else: ana_time_slice = self.irregularlysampledsignals[irr_id].time_slice(t_start, t_stop) if reset_time: ana_time_slice = ana_time_slice.time_shift(t_shift) subseg.irregularlysampledsignals.append(ana_time_slice) # cut spiketrains for st_id in range(len(self.spiketrains)): if hasattr(self.spiketrains[st_id], '_rawio'): st_time_slice = self.spiketrains[st_id].load(time_slice=(t_start, t_stop)) else: st_time_slice = self.spiketrains[st_id].time_slice(t_start, t_stop) if reset_time: st_time_slice = st_time_slice.time_shift(t_shift) subseg.spiketrains.append(st_time_slice) # cut events for ev_id in range(len(self.events)): if hasattr(self.events[ev_id], '_rawio'): ev_time_slice = self.events[ev_id].load(time_slice=(t_start, t_stop)) else: ev_time_slice = self.events[ev_id].time_slice(t_start, t_stop) if reset_time: ev_time_slice = ev_time_slice.time_shift(t_shift) # appending only non-empty events if len(ev_time_slice): subseg.events.append(ev_time_slice) # cut epochs for ep_id in range(len(self.epochs)): if hasattr(self.epochs[ep_id], '_rawio'): ep_time_slice = self.epochs[ep_id].load(time_slice=(t_start, t_stop)) else: ep_time_slice = self.epochs[ep_id].time_slice(t_start, t_stop) if reset_time: ep_time_slice = ep_time_slice.time_shift(t_shift) # appending only non-empty epochs if len(ep_time_slice): subseg.epochs.append(ep_time_slice) subseg.create_relationship() return subseg
{ "content_hash": "ac66ab4f3c55ddad75f67d3b6a5336ad", "timestamp": "", "source": "github", "line_count": 239, "max_line_length": 99, "avg_line_length": 37.24267782426778, "alnum_prop": 0.5697112683968093, "repo_name": "apdavison/python-neo", "id": "db0004496092370b94ffc305f85bb85f0bf89929", "size": "8901", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "neo/core/segment.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "2476868" } ], "symlink_target": "" }
<?php use app\models\general\GeneralLabel; use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model app\models\RefJenisKontrakPenajaan */ $this->title = GeneralLabel::updateTitle.' '.GeneralLabel::jenis_kontrak_penajaan.': ' . ' ' . $model->id; $this->params['breadcrumbs'][] = ['label' => GeneralLabel::jenis_kontrak_penajaan, 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => $model->id, 'url' => ['view', 'id' => $model->id]]; $this->params['breadcrumbs'][] = GeneralLabel::updateTitle; ?> <div class="ref-jenis-kontrak-penajaan-update"> <h1><?= Html::encode($this->title) ?></h1> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div>
{ "content_hash": "a8fbbb612d9e90e42ee02b2a24a06c5b", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 106, "avg_line_length": 29.125, "alnum_prop": 0.6080114449213162, "repo_name": "hung101/kbs", "id": "57ad8f9980053df423972e5e3bee6118a4e561c0", "size": "699", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "frontend/views/ref-jenis-kontrak-penajaan/update.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "113" }, { "name": "Batchfile", "bytes": "1541" }, { "name": "CSS", "bytes": "4999813" }, { "name": "HTML", "bytes": "32884422" }, { "name": "JavaScript", "bytes": "38543640" }, { "name": "PHP", "bytes": "30558998" }, { "name": "PowerShell", "bytes": "936" }, { "name": "Shell", "bytes": "5561" } ], "symlink_target": "" }
package com.yokmama.learn10.chapter07.lesson33; import android.content.Context; import android.support.v4.content.AsyncTaskLoader; import com.yokmama.learn10.chapter07.lesson33.item.BaseItem; import com.yokmama.learn10.chapter07.lesson33.item.BigImageItem; import com.yokmama.learn10.chapter07.lesson33.item.ImageItem; import com.yokmama.learn10.chapter07.lesson33.item.IndexItem; import java.util.ArrayList; import java.util.List; /** * Created by yokmama on 15/03/10. */ public class SampleDataGenerator extends AsyncTaskLoader<List<BaseItem>> { private int mViewStyle; public SampleDataGenerator(Context context, int viewStyle) { super(context); mViewStyle = viewStyle; } @Override public List<BaseItem> loadInBackground() { List<BaseItem> list = new ArrayList<>(); String name; for (int i = 0; i < 21; i++) { name = "dog" + (i + 1); int id = getContext().getResources().getIdentifier(name, "drawable", "com.yokmama.learn10.demo"); if (mViewStyle == R.id.radioList || mViewStyle == R.id.radioGrid) { //5個単位で目次を生成 if (i % 3 == 0) { IndexItem item = new IndexItem(); item.setName("Index Title[" + i + "]"); list.add(item); } ImageItem item = new ImageItem(); item.setId(id); item.setName(name); list.add(item); } else if (mViewStyle == R.id.radioStaggered) { //3個ずつ並べるうち、一つ目を大きい画像に設定 if (i % 3 == 0) { BigImageItem item = new BigImageItem(); item.setId(id); item.setName(name); list.add(item); } else { ImageItem item = new ImageItem(); item.setId(id); item.setName(name); list.add(item); } } else{ ImageItem item = new ImageItem(); item.setId(id); item.setName(name); list.add(item); } } return list; } @Override protected void onStartLoading() { forceLoad(); } }
{ "content_hash": "eb9270e0429e71520db8012c6a4813df", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 109, "avg_line_length": 31.643835616438356, "alnum_prop": 0.5303030303030303, "repo_name": "yokmama/honki_android", "id": "0e9dd56754be51446f55abd21448cc481f6a2c05", "size": "2374", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Demo/lesson33/src/main/java/com/yokmama/learn10/chapter07/lesson33/SampleDataGenerator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1140302" } ], "symlink_target": "" }
#ifndef _BCM_PCI_SPI_H #define _BCM_PCI_SPI_H /* cpp contortions to concatenate w/arg prescan */ #ifndef PAD #define _PADLINE(line) pad ## line #define _XSTR(line) _PADLINE(line) #define PAD _XSTR(__LINE__) #endif /* PAD */ typedef volatile struct { uint32 spih_ctrl; /* 0x00 SPI Control Register */ uint32 spih_stat; /* 0x04 SPI Status Register */ uint32 spih_data; /* 0x08 SPI Data Register, 32-bits wide */ uint32 spih_ext; /* 0x0C SPI Extension Register */ uint32 PAD[4]; /* 0x10-0x1F PADDING */ uint32 spih_gpio_ctrl; /* 0x20 SPI GPIO Control Register */ uint32 spih_gpio_data; /* 0x24 SPI GPIO Data Register */ uint32 PAD[6]; /* 0x28-0x3F PADDING */ uint32 spih_int_edge; /* 0x40 SPI Interrupt Edge Register (0=Level, 1=Edge) */ uint32 spih_int_pol; /* 0x44 SPI Interrupt Polarity Register (0=Active Low, */ /* 1=Active High) */ uint32 spih_int_mask; /* 0x48 SPI Interrupt Mask */ uint32 spih_int_status; /* 0x4C SPI Interrupt Status */ uint32 PAD[4]; /* 0x50-0x5F PADDING */ uint32 spih_hex_disp; /* 0x60 SPI 4-digit hex display value */ uint32 spih_current_ma; /* 0x64 SPI SD card current consumption in mA */ uint32 PAD[1]; /* 0x68 PADDING */ uint32 spih_disp_sel; /* 0x6c SPI 4-digit hex display mode select (1=current) */ uint32 PAD[4]; /* 0x70-0x7F PADDING */ uint32 PAD[8]; /* 0x80-0x9F PADDING */ uint32 PAD[8]; /* 0xA0-0xBF PADDING */ uint32 spih_pll_ctrl; /* 0xC0 PLL Control Register */ uint32 spih_pll_status; /* 0xC4 PLL Status Register */ uint32 spih_xtal_freq; /* 0xC8 External Clock Frequency in units of 10000Hz */ uint32 spih_clk_count; /* 0xCC External Clock Count Register */ } spih_regs_t; typedef volatile struct { uint32 cfg_space[0x40]; /* 0x000-0x0FF PCI Configuration Space (Read Only) */ uint32 P_IMG_CTRL0; /* 0x100 PCI Image0 Control Register */ uint32 P_BA0; /* 0x104 32 R/W PCI Image0 Base Address register */ uint32 P_AM0; /* 0x108 32 R/W PCI Image0 Address Mask register */ uint32 P_TA0; /* 0x10C 32 R/W PCI Image0 Translation Address register */ uint32 P_IMG_CTRL1; /* 0x110 32 R/W PCI Image1 Control register */ uint32 P_BA1; /* 0x114 32 R/W PCI Image1 Base Address register */ uint32 P_AM1; /* 0x118 32 R/W PCI Image1 Address Mask register */ uint32 P_TA1; /* 0x11C 32 R/W PCI Image1 Translation Address register */ uint32 P_IMG_CTRL2; /* 0x120 32 R/W PCI Image2 Control register */ uint32 P_BA2; /* 0x124 32 R/W PCI Image2 Base Address register */ uint32 P_AM2; /* 0x128 32 R/W PCI Image2 Address Mask register */ uint32 P_TA2; /* 0x12C 32 R/W PCI Image2 Translation Address register */ uint32 P_IMG_CTRL3; /* 0x130 32 R/W PCI Image3 Control register */ uint32 P_BA3; /* 0x134 32 R/W PCI Image3 Base Address register */ uint32 P_AM3; /* 0x138 32 R/W PCI Image3 Address Mask register */ uint32 P_TA3; /* 0x13C 32 R/W PCI Image3 Translation Address register */ uint32 P_IMG_CTRL4; /* 0x140 32 R/W PCI Image4 Control register */ uint32 P_BA4; /* 0x144 32 R/W PCI Image4 Base Address register */ uint32 P_AM4; /* 0x148 32 R/W PCI Image4 Address Mask register */ uint32 P_TA4; /* 0x14C 32 R/W PCI Image4 Translation Address register */ uint32 P_IMG_CTRL5; /* 0x150 32 R/W PCI Image5 Control register */ uint32 P_BA5; /* 0x154 32 R/W PCI Image5 Base Address register */ uint32 P_AM5; /* 0x158 32 R/W PCI Image5 Address Mask register */ uint32 P_TA5; /* 0x15C 32 R/W PCI Image5 Translation Address register */ uint32 P_ERR_CS; /* 0x160 32 R/W PCI Error Control and Status register */ uint32 P_ERR_ADDR; /* 0x164 32 R PCI Erroneous Address register */ uint32 P_ERR_DATA; /* 0x168 32 R PCI Erroneous Data register */ uint32 PAD[5]; /* 0x16C-0x17F PADDING */ uint32 WB_CONF_SPC_BAR; /* 0x180 32 R WISHBONE Configuration Space Base Address */ uint32 W_IMG_CTRL1; /* 0x184 32 R/W WISHBONE Image1 Control register */ uint32 W_BA1; /* 0x188 32 R/W WISHBONE Image1 Base Address register */ uint32 W_AM1; /* 0x18C 32 R/W WISHBONE Image1 Address Mask register */ uint32 W_TA1; /* 0x190 32 R/W WISHBONE Image1 Translation Address reg */ uint32 W_IMG_CTRL2; /* 0x194 32 R/W WISHBONE Image2 Control register */ uint32 W_BA2; /* 0x198 32 R/W WISHBONE Image2 Base Address register */ uint32 W_AM2; /* 0x19C 32 R/W WISHBONE Image2 Address Mask register */ uint32 W_TA2; /* 0x1A0 32 R/W WISHBONE Image2 Translation Address reg */ uint32 W_IMG_CTRL3; /* 0x1A4 32 R/W WISHBONE Image3 Control register */ uint32 W_BA3; /* 0x1A8 32 R/W WISHBONE Image3 Base Address register */ uint32 W_AM3; /* 0x1AC 32 R/W WISHBONE Image3 Address Mask register */ uint32 W_TA3; /* 0x1B0 32 R/W WISHBONE Image3 Translation Address reg */ uint32 W_IMG_CTRL4; /* 0x1B4 32 R/W WISHBONE Image4 Control register */ uint32 W_BA4; /* 0x1B8 32 R/W WISHBONE Image4 Base Address register */ uint32 W_AM4; /* 0x1BC 32 R/W WISHBONE Image4 Address Mask register */ uint32 W_TA4; /* 0x1C0 32 R/W WISHBONE Image4 Translation Address reg */ uint32 W_IMG_CTRL5; /* 0x1C4 32 R/W WISHBONE Image5 Control register */ uint32 W_BA5; /* 0x1C8 32 R/W WISHBONE Image5 Base Address register */ uint32 W_AM5; /* 0x1CC 32 R/W WISHBONE Image5 Address Mask register */ uint32 W_TA5; /* 0x1D0 32 R/W WISHBONE Image5 Translation Address reg */ uint32 W_ERR_CS; /* 0x1D4 32 R/W WISHBONE Error Control and Status reg */ uint32 W_ERR_ADDR; /* 0x1D8 32 R WISHBONE Erroneous Address register */ uint32 W_ERR_DATA; /* 0x1DC 32 R WISHBONE Erroneous Data register */ uint32 CNF_ADDR; /* 0x1E0 32 R/W Configuration Cycle register */ uint32 CNF_DATA; /* 0x1E4 32 R/W Configuration Cycle Generation Data reg */ uint32 INT_ACK; /* 0x1E8 32 R Interrupt Acknowledge register */ uint32 ICR; /* 0x1EC 32 R/W Interrupt Control register */ uint32 ISR; /* 0x1F0 32 R/W Interrupt Status register */ } spih_pciregs_t; /* * PCI Core interrupt enable and status bit definitions. */ /* PCI Core ICR Register bit definitions */ #define PCI_INT_PROP_EN (1 << 0) /* Interrupt Propagation Enable */ #define PCI_WB_ERR_INT_EN (1 << 1) /* Wishbone Error Interrupt Enable */ #define PCI_PCI_ERR_INT_EN (1 << 2) /* PCI Error Interrupt Enable */ #define PCI_PAR_ERR_INT_EN (1 << 3) /* Parity Error Interrupt Enable */ #define PCI_SYS_ERR_INT_EN (1 << 4) /* System Error Interrupt Enable */ #define PCI_SOFTWARE_RESET (1U << 31) /* Software reset of the PCI Core. */ /* PCI Core ISR Register bit definitions */ #define PCI_INT_PROP_ST (1 << 0) /* Interrupt Propagation Status */ #define PCI_WB_ERR_INT_ST (1 << 1) /* Wishbone Error Interrupt Status */ #define PCI_PCI_ERR_INT_ST (1 << 2) /* PCI Error Interrupt Status */ #define PCI_PAR_ERR_INT_ST (1 << 3) /* Parity Error Interrupt Status */ #define PCI_SYS_ERR_INT_ST (1 << 4) /* System Error Interrupt Status */ /* Registers on the Wishbone bus */ #define SPIH_CTLR_INTR (1 << 0) /* SPI Host Controller Core Interrupt */ #define SPIH_DEV_INTR (1 << 1) /* SPI Device Interrupt */ #define SPIH_WFIFO_INTR (1 << 2) /* SPI Tx FIFO Empty Intr (FPGA Rev >= 8) */ /* GPIO Bit definitions */ #define SPIH_CS (1 << 0) /* SPI Chip Select (active low) */ #define SPIH_SLOT_POWER (1 << 1) /* SD Card Slot Power Enable */ #define SPIH_CARD_DETECT (1 << 2) /* SD Card Detect */ /* SPI Status Register Bit definitions */ #define SPIH_STATE_MASK 0x30 /* SPI Transfer State Machine state mask */ #define SPIH_STATE_SHIFT 4 /* SPI Transfer State Machine state shift */ #define SPIH_WFFULL (1 << 3) /* SPI Write FIFO Full */ #define SPIH_WFEMPTY (1 << 2) /* SPI Write FIFO Empty */ #define SPIH_RFFULL (1 << 1) /* SPI Read FIFO Full */ #define SPIH_RFEMPTY (1 << 0) /* SPI Read FIFO Empty */ #define SPIH_EXT_CLK (1U << 31) /* Use External Clock as PLL Clock source. */ #define SPIH_PLL_NO_CLK (1 << 1) /* Set to 1 if the PLL's input clock is lost. */ #define SPIH_PLL_LOCKED (1 << 3) /* Set to 1 when the PLL is locked. */ /* Spin bit loop bound check */ #define SPI_SPIN_BOUND 0xf4240 /* 1 million */ #endif /* _BCM_PCI_SPI_H */
{ "content_hash": "4c500c54a55a962f6576d812d81498f7", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 84, "avg_line_length": 51.31210191082803, "alnum_prop": 0.6829692154915591, "repo_name": "Ant-OS/android_kernel_moto_shamu", "id": "8ecb7c2ac5b07044f775fb1e6bcdaf0a1e76ea24", "size": "9314", "binary": false, "copies": "1473", "ref": "refs/heads/master", "path": "drivers/net/wireless/bcmdhd/include/bcmpcispi.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "4528" }, { "name": "Assembly", "bytes": "9738337" }, { "name": "Awk", "bytes": "18681" }, { "name": "C", "bytes": "467488098" }, { "name": "C++", "bytes": "3473858" }, { "name": "Clojure", "bytes": "547" }, { "name": "Groff", "bytes": "22012" }, { "name": "Lex", "bytes": "40805" }, { "name": "Makefile", "bytes": "1342678" }, { "name": "Objective-C", "bytes": "1121986" }, { "name": "Perl", "bytes": "461504" }, { "name": "Python", "bytes": "33978" }, { "name": "Scilab", "bytes": "21433" }, { "name": "Shell", "bytes": "138789" }, { "name": "SourcePawn", "bytes": "4687" }, { "name": "UnrealScript", "bytes": "6113" }, { "name": "Yacc", "bytes": "83091" } ], "symlink_target": "" }
SELECT REPLACE(name, 'H1', 'X') FROM virus;
{ "content_hash": "0b0564da3d97b322f26892808e88433b", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 43, "avg_line_length": 43, "alnum_prop": 0.6744186046511628, "repo_name": "miguelarauj1o/UOJ", "id": "b20b6e97e955c4e9ef2603f68a935b78e5e6bdbe", "size": "43", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/URI_2746 - (12609328) - Accepted.sql", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "219333" }, { "name": "Java", "bytes": "13505" }, { "name": "Python", "bytes": "565" } ], "symlink_target": "" }