text
stringlengths
2
1.04M
meta
dict
package db import ( "testing" _ "github.com/lib/pq" . "github.com/smartystreets/goconvey/convey" "github.com/stellar/go-stellar-base/xdr" "github.com/stellar/horizon/test" ) func TestOrderBookSummaryQuery(t *testing.T) { Convey("OrderBookSummaryQuery", t, func() { test.LoadScenario("order_books") q := &OrderBookSummaryQuery{ SqlQuery: SqlQuery{core}, SellingType: xdr.AssetTypeAssetTypeCreditAlphanum4, SellingCode: "USD", SellingIssuer: "GC23QF2HUE52AMXUFUH3AYJAXXGXXV2VHXYYR6EYXETPKDXZSAW67XO4", BuyingType: xdr.AssetTypeAssetTypeNative, } Convey("loads correctly", func() { var result OrderBookSummaryRecord So(Select(ctx, q, &result), ShouldBeNil) asks := result.Asks() bids := result.Bids() So(asks[0].Amount, ShouldEqual, 100000000) So(asks[0].Pricen, ShouldEqual, 15) So(asks[0].Priced, ShouldEqual, 1) So(asks[1].Amount, ShouldEqual, 1000000000) So(asks[1].Pricen, ShouldEqual, 20) So(asks[1].Priced, ShouldEqual, 1) So(asks[2].Amount, ShouldEqual, 10000000000) So(asks[2].Pricen, ShouldEqual, 50) So(asks[2].Priced, ShouldEqual, 1) So(bids[0].Amount, ShouldEqual, 10000000) So(bids[0].Pricen, ShouldEqual, 10) So(bids[0].Priced, ShouldEqual, 1) So(bids[1].Amount, ShouldEqual, 110000000) So(bids[1].Pricen, ShouldEqual, 9) So(bids[1].Priced, ShouldEqual, 1) So(bids[2].Amount, ShouldEqual, 2000000000) So(bids[2].Pricen, ShouldEqual, 5) So(bids[2].Priced, ShouldEqual, 1) }) Convey("works in either direction", func() { var result OrderBookSummaryRecord var inversion OrderBookSummaryRecord So(Select(ctx, q, &result), ShouldBeNil) So(Select(ctx, q.Invert(), &inversion), ShouldBeNil) asks := result.Asks() bids := result.Bids() iasks := inversion.Asks() ibids := inversion.Bids() So(len(result), ShouldEqual, 6) So(len(inversion), ShouldEqual, 6) // the asks of one side are the bids on the other So(asks[0].Pricef, ShouldEqual, ibids[0].InvertPricef()) So(asks[1].Pricef, ShouldEqual, ibids[1].InvertPricef()) So(asks[2].Pricef, ShouldEqual, ibids[2].InvertPricef()) So(bids[0].Pricef, ShouldEqual, iasks[0].InvertPricef()) So(bids[1].Pricef, ShouldEqual, iasks[1].InvertPricef()) So(bids[2].Pricef, ShouldEqual, iasks[2].InvertPricef()) }) Convey("Invert()", func() { q2 := q.Invert() So(q2.SellingType, ShouldEqual, q.BuyingType) So(q2.SellingCode, ShouldEqual, q.BuyingCode) So(q2.SellingIssuer, ShouldEqual, q.BuyingIssuer) So(q2.BuyingType, ShouldEqual, q.SellingType) So(q2.BuyingCode, ShouldEqual, q.SellingCode) So(q2.BuyingIssuer, ShouldEqual, q.SellingIssuer) }) }) }
{ "content_hash": "4f43efad3746c4425e84caa27659730e", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 77, "avg_line_length": 29.358695652173914, "alnum_prop": 0.6934468715290633, "repo_name": "masonforest/go-horizon", "id": "a105cbf284864dfb843974d0fd6f5256b2e5df92", "size": "2701", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/github.com/stellar/horizon/db/query_order_book_summary_test.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "378361" }, { "name": "Ruby", "bytes": "1672" }, { "name": "Shell", "bytes": "758" } ], "symlink_target": "" }
class GithubPullRequest attr_reader :full_name, :sha, :branch attr_accessor :number def initialize(pull_request_data) @full_name = pull_request_data['full_name'] @sha = pull_request_data['sha'] @branch = pull_request_data['branch'] end end
{ "content_hash": "e8b2d499b11816b9424771dcdc4dfb17", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 47, "avg_line_length": 26.1, "alnum_prop": 0.6896551724137931, "repo_name": "Wolox/codestats", "id": "0e2fd9596502be2959f39cb319d551505d9fb5af", "size": "261", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/models/github_pull_request.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "12996" }, { "name": "CoffeeScript", "bytes": "6646" }, { "name": "HTML", "bytes": "45965" }, { "name": "Ruby", "bytes": "123700" }, { "name": "Shell", "bytes": "3322" } ], "symlink_target": "" }
YUI.add('parallel', function (Y, NAME) { /** * A concurrent parallel processor to help in running several async functions. * @module parallel * @main parallel */ /** A concurrent parallel processor to help in running several async functions. var stack = new Y.Parallel(); for (var i = 0; i < 15; i++) { Y.io('./api/json/' + i, { on: { success: stack.add(function() { }) } }); } stack.done(function() { }); @class Parallel @param {Object} o A config object @param {Object} [o.context=Y] The execution context of the callback to done */ Y.Parallel = function(o) { this.config = o || {}; this.results = []; this.context = this.config.context || Y; this.total = 0; this.finished = 0; }; Y.Parallel.prototype = { /** * An Array of results from all the callbacks in the stack * @property results * @type Array */ results: null, /** * The total items in the stack * @property total * @type Number */ total: null, /** * The number of stacked callbacks executed * @property finished * @type Number */ finished: null, /** * Add a callback to the stack * @method add * @param {Function} fn The function callback we are waiting for */ add: function (fn) { var self = this, index = self.total; self.total += 1; return function () { self.finished++; self.results[index] = (fn && fn.apply(self.context, arguments)) || (arguments.length === 1 ? arguments[0] : Y.Array(arguments)); self.test(); }; }, /** * Test to see if all registered items in the stack have completed, if so call the callback to `done` * @method test */ test: function () { var self = this; if (self.finished >= self.total && self.callback) { self.callback.call(self.context, self.results, self.data); } }, /** * The method to call when all the items in the stack are complete. * @method done * @param {Function} callback The callback to execute on complete * @param {Mixed} callback.results The results of all the callbacks in the stack * @param {Mixed} [callback.data] The data given to the `done` method * @param {Mixed} data Mixed data to pass to the success callback */ done: function (callback, data) { this.callback = callback; this.data = data; this.test(); } }; }, '3.7.2', {"requires": ["yui-base"]});
{ "content_hash": "ba2da215ffc563716a365b6ca6d29f56", "timestamp": "", "source": "github", "line_count": 108, "max_line_length": 104, "avg_line_length": 24.212962962962962, "alnum_prop": 0.5632887189292543, "repo_name": "spadin/coverphoto", "id": "d1d1aefd4621e2eb09fed3745262b5fd454bb304", "size": "2754", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "node_modules/grunt-contrib/node_modules/grunt-contrib-yuidoc/node_modules/yuidocjs/node_modules/yui/parallel/parallel.js", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "5206" }, { "name": "JavaScript", "bytes": "69266" } ], "symlink_target": "" }
PP.systemWindow = function(hostname) { //var sv=new PP.SystemViewPanel({layout_view:'horizontal'}); PP.log('getting system from backend'); var system = Ext.ModelManager.getModel('system'); var w; system.load(hostname, { success: function(sys, o) { if (o.response.status == 204) { Ext.notify.msg(' Entry not found', ''); return; } w = new Ext.Window({ width: 800, height: window.innerHeight < 700 ? window.innerHeight - 80 : 600, layout: 'fit', title: hostname, //items:sv items: new PP.SystemViewPanel({ layout_view: 'horizontal' }) }); w.show(); // remove dock with save button w.items.items[0].removeDocked(w.items.items[0].getDockedItems()[0]); delete w.items.items[0]['saveButton']; w.items.items[0].load(sys); // dealing with race condition of setting combos before they have loaded. } }); return w; } var filters = { ftype: 'filters', // encode and local configuration options defined previously for easier reuse encode: 'encode', // json encode the filter query local: 'local', // defaults to false (remote filtering) // Filters are most naturally placed in the column definition, but can also be // added here. filters: [{ type: 'boolean', dataIndex: 'visible' }] }; Ext.define('PP.SystemViewPanel', { extend: 'Ext.FormPanel', alias: 'widget.systemviewpanel', entity: 'system', layout_view: 'vertical', system: {}, defaultType: 'textfield', layout: { type: 'vbox', align: 'stretch' }, maskDisabled: false, addNagiosPanel: false, initComponent: function() { var me = this; if (me.layout_view == 'vertical') { me.layout = { type: 'vbox', align: 'stretch' }; } else { me.layout = { type: 'hbox', align: 'stretch' }; } me.field_config = {}; me.remaining_fields = []; me.hardware_fields = []; me.config_fields = []; me.fieldchk = {}; if (PP.config.jira) { me.jirapanel = new PP.JiraGridPanel({ title: 'Jira' }); } me.auditpanel = new PP.AuditPanel(); if (PP.config.enableSplunk) { me.splunkpanel = new PP.SplunkPanel(); } if (PP.config.enableLogStash) { me.logpanel = new PP.LogPanel(); } // initialize form fields by processing them into field defnitions // grouped by cagetory. the 'main' categeory will be in the form fieldset // the rest of the fields in categories will be created inside tabs labelled with the // category. // the 'More Data' category will contain fields without categories var entity_field_list = PP.getEntityFields(me.entity); var entity_definition = PP.entities[me.entity]; entity_field_list.forEach(function(field_name) { if (!entity_definition[field_name] || entity_definition[field_name] == undefined) { return; } if (entity_definition[field_name].field_category == undefined) { entity_definition[field_name].field_category = 'More Data'; } var tmp = PP.getEditorConfig(field_name, { entity: me.entity, labels: true }); tmp['instance'] = me; if (!tmp['listeners']) { tmp.listeners = {}; } tmp.listeners.change = me.fieldSaveValue; tmp.listeners.scope = me; if (tmp.name == 'date_created' || tmp.name == 'date_modified') { tmp.xtype = 'displayfield'; tmp.fieldBodyCls = 'cmdb_display_field'; } // create the field_config category if it doesn't exist if (me.field_config[entity_definition[field_name].field_category] == undefined) { me.field_config[entity_definition[field_name].field_category] = []; } me.field_config[entity_definition[field_name].field_category].push(tmp); }); me.saveButton = new Ext.Button({ icon: 'images/save.gif', cls: 'x-btn-text-icon', disabled: true, text: 'Save', scope: me, handler: me.saveRecord }); me.cancelButton = new Ext.Button({ xtype: 'button', text: 'Cancel', disabled: true, handler: function() { me.system.reject(); me.load(me.system); }, scope: me }); me.tbar = [{ xtype: 'button', icon: 'images/icon_popout.gif', handler: function() { if (me.getRecord() && me.getRecord().get('fqdn')) { me.collapse(); PP.systemWindow(me.getRecord().get('fqdn')); } }, scope: me }, { xtype: 'tbfill' }, me.saveButton, me.cancelButton, ]; this.rackButton = new Ext.Button({ text: 'View in Rack', disabled: true, handler: function() { PP.showRackElevation({ rack_code: me.system.get('rack_code'), data_center_code: (me.system.get('data_center_code') ? me.system.get('data_center_code') : undefined) }, 'Rack Elevation: ' + me.system.get('rack_code'), me.system.get('rack_position')); }, scope: me }); if (Ext.ux.panel.Rack) { me.tbar.splice(2, 0, this.rackButton, '-'); } var svTabs = []; var categories = Object.keys(me.field_config); categories.forEach(function(category) { if (category == 'main') { return; } svTabs.push({ xtype: 'panel', title: category, layout: 'fit', frame: true, items: [{ xtype: 'fieldset', baseCls: '', autoScroll: true, defaults: { anchor: '95%' }, defaultType: 'textfield', items: me.field_config[category] }] }); }); svTabs.push(me.auditpanel); if (PP.config.jira) { svTabs.push(me.jirapanel); } if (me.addNagiosPanel) { me.nagiospanel = Ext.create('NagUI.NagiosGridPanel', { viewConfig: { loadMask: true } }); me.nagiospanel.addListener({ 'activate': { fn: function(p) { me.loadNagios(me.nagiospanel.system_fqdn); }, scope: me }, 'boxready': { fn: function(p) { me.loadNagios(me.nagiospanel.system_fqdn); }, scope: me } }); me.nagiospanel.loaded = false; svTabs.push(me.nagiospanel); } if (PP.config.enableLogStash) { svTabs.push(me.logpanel); } if (PP.config.enableSplunk) { svTabs.push(me.splunkpanel); } if (PP.config.graphite.enable) { me.graphPanel = new Graphite.GraphitePanel(); svTabs.push(me.graphPanel); } me.items = [{ xtype: 'panel', // region:'center', frame: true, flex: 0, width: me.layout_view == 'horizontal' ? 350 : undefined, items: [{ xtype: 'fieldset', defaultType: 'textfield', autoScroll: true, border: false, defaults: { anchor: '100%' }, items: me.field_config['main'] }] }, { xtype: 'tabpanel', split: true, flex: 2, stateful: me.stateful, activeTab: 0, items: svTabs.sort() }]; PP.SystemViewPanel.superclass.initComponent.call(me); }, saveRecord: function() { PP.saveRecord(this.getForm().getRecord(), function() { if (this.saveButton) { this.saveButton.disable(); this.cancelButton.disable(); } }); }, fieldSaveValue: function(f, n, o) { if (this.loading) { return; } if (PP.allowEditing) { if (f.xtype == 'combo' && n == null) { return; } if (this.saveButton) { this.saveButton.enable(); this.cancelButton.enable(); } this.getForm().updateRecord(this.getForm().getRecord()); return; } }, clear: function() { if (this.getRecord()) { this.saveButton.disable(); this.cancelButton.disable(); this.getForm().reset(true); this.auditpanel.clear(); if (this.nagiospanel) { this.nagiospanel.loaded = false; } } }, load: function(system) { this.setLoading(true); // PP.log('loading:'); // PP.log(system); // PP.log(typeof system); if (typeof system == 'object') { this.system = system; } else { var system_lookup = system; PP.log('getting system from backend'); this.system = Ext.ModelManager.getModel('system'); this.system.load(system_lookup, { scope: this, success: function(entry) { this.load(entry); } }); return; } if (PP.config.jira) { this.jirapanel.load(this.system.get('fqdn')); } if (this.nagiospanel) { this.loadNagios(this.system.get('fqdn')); } this.auditpanel.load(this.system.get('fqdn')); if (PP.config.enableLogStash) { this.logpanel.load(this.system.get('fqdn')); } if (PP.config.enableSplunk) { this.splunkpanel.load(this.system.get('fqdn')); } if (this.system.dirty && PP.allowEditing && this.saveButton) { this.saveButton.enable(); this.cancelButton.enable(); } if (PP.config.graphite.enable && this.graphPanel) { this.graphPanel.load(this.system.get('fqdn')); } else { if (this.saveButton) { this.saveButton.disable(); this.cancelButton.disable(); } } Ext.Function.defer(this.loadRec, 50, this, [this.system]); }, // checks to see if combo stores have loaded. checkCombos: function() { var loading = false; this.getForm().getFields().each(function(i) { // console.log(i.xtype); if (i.xtype == 'combo') { if (i.store.loading) { loading = true; return false; } } }); return loading; }, loadNagios: function(system_fqdn) { if (system_fqdn) { if (this.system_fqdn != system_fqdn) { this.nagiospanel.loaded = false; } this.nagiospanel.system_fqdn = system_fqdn; } if (!this.nagiospanel.loaded && this.nagiospanel.isVisible() && this.nagiospanel.system_fqdn) { this.nagiospanel.load(this.nagiospanel.system_fqdn); this.nagiospanel.loaded = true; } }, loadRec: function(rec) { if (Ext.Ajax.isLoading() || this.checkCombos()) { Ext.Function.defer(this.loadRec, 200, this, [rec]); } else { this.enable(); this.loading = true; this.getForm().loadRecord(this.system); if (this.system.get('rack_code') && this.system.get('rack_position') && this.rackButton && this.rackButton.isVisible()) { this.rackButton.enable(); } this.loading = false; this.setLoading(false); } } });
{ "content_hash": "71604f234aa683d593b0702d73eca2a9", "timestamp": "", "source": "github", "line_count": 385, "max_line_length": 133, "avg_line_length": 33.52467532467532, "alnum_prop": 0.47082978228868055, "repo_name": "proofpoint/cmdb-ui", "id": "6840ea17649837298cd931b277cd49f758ccc7ab", "size": "13506", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/SystemViewPanel.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "14983" }, { "name": "JavaScript", "bytes": "371594" } ], "symlink_target": "" }
package bucketer import ( "fmt" "github.com/CapillarySoftware/gostat/stat" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "time" ) var _ = Describe("Bucketer", func() { var stats <-chan *stat.Stat var bucketedStats chan<- []*stat.Stat var shutdown <-chan bool JustBeforeEach(func() { stats = make(chan *stat.Stat) bucketedStats = make(chan []*stat.Stat) shutdown = make(chan bool) }) Describe("construction", func() { It("should return a properly initialized Bucketer", func() { x := NewBucketer(stats, bucketedStats, shutdown) // a newly constructed Bucketer has nothing in it's buckets Expect(len(x.currentBuckets)).To(Equal(0)) Expect(len(x.previousBuckets)).To(Equal(0)) Expect(len(x.futureBuckets)).To(Equal(0)) // the current bucket min time is rounded down to the minute boundary // so it should not have any 'seconds' or 'nanoseconds' part Expect(x.currentBucketMinTime.Second()).To(Equal(0)) Expect(x.currentBucketMinTime.Nanosecond()).To(Equal(0)) // the previous bucket's min time is exactly one minute less than the current bucket's min time, and the future bucket is one min ahead Expect(x.currentBucketMinTime.Sub(x.previousBucketMinTime)).To(Equal(time.Duration(time.Minute))) Expect(x.futureBucketMinTime.Sub(x.currentBucketMinTime)).To(Equal(time.Duration(time.Minute))) // verify the input channels Expect(x.input).NotTo(BeClosed()) Expect(x.shutdown).NotTo(BeClosed()) }) }) Describe("insert", func() { It("should return an error if a nil stat is inserted", func() { x := NewBucketer(stats, bucketedStats, shutdown) Expect(x.insert(nil)).To(Equal(fmt.Errorf("dropping nil stat"))) }) It("should NOT insert the stat if the Timestamp is > the max future bucket time", func() { x := NewBucketer(stats, bucketedStats, shutdown) s := stat.Stat{Name: "foo", Timestamp: x.futureBucketMinTime.Add(time.Duration(time.Minute)), Value: 1} Expect(s.Timestamp).To(BeTemporally(">", x.currentBucketMinTime)) Expect(s.Timestamp).To(BeTemporally(">", x.previousBucketMinTime)) Expect(s.Timestamp).To(BeTemporally(">", x.futureBucketMinTime)) Expect(x.currentBuckets[s.Name]).To(BeNil()) Expect(x.previousBuckets[s.Name]).To(BeNil()) Expect(x.futureBuckets[s.Name]).To(BeNil()) Expect(x.insert(&s)).To(Equal(fmt.Errorf("Bucketer: dropping 'future' stat that is 'after' %v: %+v", x.futureBucketMinTime.Add(time.Nanosecond*(NaonsecondsPerMin-1)), s))) Expect(x.currentBuckets[s.Name]).To(BeNil()) Expect(x.previousBuckets[s.Name]).To(BeNil()) Expect(x.futureBuckets[s.Name]).To(BeNil()) }) It("should insert the stat in the future bucket if the Timestamp is > the future bucket's min time and less than the max time for future stats", func() { x := NewBucketer(stats, bucketedStats, shutdown) s := stat.Stat{Name: "foo", Timestamp: x.futureBucketMinTime.Add(time.Duration(time.Second)), Value: 1} Expect(s.Timestamp).To(BeTemporally(">", x.currentBucketMinTime)) Expect(s.Timestamp).To(BeTemporally(">", x.previousBucketMinTime)) Expect(s.Timestamp).To(BeTemporally(">", x.futureBucketMinTime)) Expect(s.Timestamp).To(BeTemporally("<", x.futureBucketMinTime.Add(time.Duration(time.Minute)))) Expect(x.currentBuckets[s.Name]).To(BeNil()) Expect(x.previousBuckets[s.Name]).To(BeNil()) Expect(x.futureBuckets[s.Name]).To(BeNil()) Expect(x.insert(&s)).To(BeNil()) Expect(x.currentBuckets[s.Name]).To(BeNil()) Expect(x.previousBuckets[s.Name]).To(BeNil()) Expect(x.futureBuckets[s.Name]).To(ConsistOf(&s)) }) It("should insert the stat in the future bucket if the Timestamp is equal to the future bucket's min time", func() { x := NewBucketer(stats, bucketedStats, shutdown) s := stat.Stat{Name: "foo", Timestamp: x.futureBucketMinTime, Value: 1} Expect(s.Timestamp).To(BeTemporally(">", x.currentBucketMinTime)) Expect(s.Timestamp).To(BeTemporally(">", x.previousBucketMinTime)) Expect(s.Timestamp).To(BeTemporally("==", x.futureBucketMinTime)) Expect(x.currentBuckets[s.Name]).To(BeNil()) Expect(x.previousBuckets[s.Name]).To(BeNil()) Expect(x.futureBuckets[s.Name]).To(BeNil()) Expect(x.insert(&s)).To(BeNil()) Expect(x.currentBuckets[s.Name]).To(BeNil()) Expect(x.previousBuckets[s.Name]).To(BeNil()) Expect(x.futureBuckets[s.Name]).To(ConsistOf(&s)) }) It("should insert the stat in the current bucket if the Timestamp is after the current bucket's min time and less than the future bucket's min time", func() { x := NewBucketer(stats, bucketedStats, shutdown) s := stat.Stat{Name: "foo", Timestamp: x.currentBucketMinTime.Add(time.Duration(time.Second)), Value: 1} Expect(s.Timestamp).To(BeTemporally(">", x.currentBucketMinTime)) Expect(s.Timestamp).To(BeTemporally(">", x.previousBucketMinTime)) Expect(s.Timestamp).To(BeTemporally("<", x.futureBucketMinTime)) Expect(x.currentBuckets[s.Name]).To(BeNil()) Expect(x.previousBuckets[s.Name]).To(BeNil()) Expect(x.futureBuckets[s.Name]).To(BeNil()) Expect(x.insert(&s)).To(BeNil()) Expect(x.currentBuckets[s.Name]).To(ConsistOf(&s)) Expect(x.previousBuckets[s.Name]).To(BeNil()) Expect(x.futureBuckets[s.Name]).To(BeNil()) }) It("should insert the stat in the current bucket if the Timestamp is equal to the current bucket's min time", func() { x := NewBucketer(stats, bucketedStats, shutdown) s := stat.Stat{Name: "foo", Timestamp: x.currentBucketMinTime, Value: 1} Expect(s.Timestamp).To(BeTemporally("==", x.currentBucketMinTime)) Expect(s.Timestamp).To(BeTemporally(">", x.previousBucketMinTime)) Expect(s.Timestamp).To(BeTemporally("<", x.futureBucketMinTime)) Expect(x.currentBuckets[s.Name]).To(BeNil()) Expect(x.previousBuckets[s.Name]).To(BeNil()) Expect(x.futureBuckets[s.Name]).To(BeNil()) Expect(x.insert(&s)).To(BeNil()) Expect(x.currentBuckets[s.Name]).To(ConsistOf(&s)) Expect(x.previousBuckets[s.Name]).To(BeNil()) Expect(x.futureBuckets[s.Name]).To(BeNil()) }) It("should insert the stat in the previous bucket if the Timestamp is less than the current bucket's min time and greater than the previous bucket's min time", func() { x := NewBucketer(stats, bucketedStats, shutdown) s := stat.Stat{Name: "foo", Timestamp: x.currentBucketMinTime.Add(time.Duration(time.Second * -1)), Value: 1} Expect(s.Timestamp).To(BeTemporally("<", x.currentBucketMinTime)) Expect(s.Timestamp).To(BeTemporally(">", x.previousBucketMinTime)) Expect(s.Timestamp).To(BeTemporally("<", x.futureBucketMinTime)) Expect(x.currentBuckets[s.Name]).To(BeNil()) Expect(x.previousBuckets[s.Name]).To(BeNil()) Expect(x.futureBuckets[s.Name]).To(BeNil()) Expect(x.insert(&s)).To(BeNil()) Expect(x.currentBuckets[s.Name]).To(BeNil()) Expect(x.previousBuckets[s.Name]).To(ConsistOf(&s)) Expect(x.futureBuckets[s.Name]).To(BeNil()) }) It("should insert the stat in the previous bucket if the Timestamp is equal to the previous bucket's min time", func() { x := NewBucketer(stats, bucketedStats, shutdown) s := stat.Stat{Name: "foo", Timestamp: x.previousBucketMinTime, Value: 1} Expect(s.Timestamp).To(BeTemporally("<", x.currentBucketMinTime)) Expect(s.Timestamp).To(BeTemporally("==", x.previousBucketMinTime)) Expect(s.Timestamp).To(BeTemporally("<", x.futureBucketMinTime)) Expect(x.currentBuckets[s.Name]).To(BeNil()) Expect(x.previousBuckets[s.Name]).To(BeNil()) Expect(x.futureBuckets[s.Name]).To(BeNil()) Expect(x.insert(&s)).To(BeNil()) Expect(x.currentBuckets[s.Name]).To(BeNil()) Expect(x.previousBuckets[s.Name]).To(ConsistOf(&s)) Expect(x.futureBuckets[s.Name]).To(BeNil()) }) It("should NOT insert the stat if the Timestamp is less than the previous bucket's min time", func() { x := NewBucketer(stats, bucketedStats, shutdown) s := stat.Stat{Name: "foo", Timestamp: x.previousBucketMinTime.Add(time.Duration(time.Second * -1)), Value: 1} Expect(s.Timestamp).To(BeTemporally("<", x.currentBucketMinTime)) Expect(s.Timestamp).To(BeTemporally("<", x.previousBucketMinTime)) Expect(s.Timestamp).To(BeTemporally("<", x.futureBucketMinTime)) Expect(x.currentBuckets[s.Name]).To(BeNil()) Expect(x.previousBuckets[s.Name]).To(BeNil()) Expect(x.futureBuckets[s.Name]).To(BeNil()) Expect(x.insert(&s)).To(Equal(fmt.Errorf("Bucketer: dropping stat older than %v: %+v", x.previousBucketMinTime, s))) Expect(x.currentBuckets[s.Name]).To(BeNil()) Expect(x.previousBuckets[s.Name]).To(BeNil()) Expect(x.futureBuckets[s.Name]).To(BeNil()) }) It("should insert the same stat in the current bucket TWICE we call insert() on the same stat twice and the Timestamp is after the current bucket's min time", func() { x := NewBucketer(stats, bucketedStats, shutdown) s := stat.Stat{Name: "foo", Timestamp: x.currentBucketMinTime.Add(time.Duration(time.Second)), Value: 1} Expect(s.Timestamp).To(BeTemporally(">", x.currentBucketMinTime)) Expect(s.Timestamp).To(BeTemporally(">", x.previousBucketMinTime)) Expect(x.currentBuckets[s.Name]).To(BeNil()) Expect(x.previousBuckets[s.Name]).To(BeNil()) Expect(x.futureBuckets[s.Name]).To(BeNil()) Expect(x.insert(&s)).To(BeNil()) Expect(x.insert(&s)).To(BeNil()) Expect(x.currentBuckets[s.Name]).To(ConsistOf(&s, &s)) Expect(x.previousBuckets[s.Name]).To(BeNil()) Expect(x.futureBuckets[s.Name]).To(BeNil()) }) }) Describe("next", func() { It("should advance the current/previous/future bucket min times by one minute", func() { x := NewBucketer(stats, bucketedStats, shutdown) // the previous bucket's min time is exactly one minute less than the current bucket's min time, and the future is one min ahead Expect(x.currentBucketMinTime.Sub(x.previousBucketMinTime)).To(Equal(time.Duration(time.Minute))) Expect(x.futureBucketMinTime.Sub(x.currentBucketMinTime)).To(Equal(time.Duration(time.Minute))) t := x.currentBucketMinTime // save to compare x.next() Expect(x.currentBucketMinTime.Sub(t)).To(Equal(time.Duration(time.Minute))) // the previous bucket's min time should STILL be exactly one minute less than the current bucket's min time, and the future is STILL one min ahead Expect(x.currentBucketMinTime.Sub(x.previousBucketMinTime)).To(Equal(time.Duration(time.Minute))) Expect(x.futureBucketMinTime.Sub(x.currentBucketMinTime)).To(Equal(time.Duration(time.Minute))) }) It("should not change the length of the current/previous/future buckets if they are all empty", func() { x := NewBucketer(stats, bucketedStats, shutdown) x.next() // all the buckets are still empty Expect(len(x.currentBuckets)).To(Equal(0)) Expect(len(x.previousBuckets)).To(Equal(0)) Expect(len(x.futureBuckets)).To(Equal(0)) }) It("should advance the stats to their next buckets", func() { const STAT_NAME = "foo" x := NewBucketer(stats, bucketedStats, shutdown) // both the current, previous, and future buckets are initially empty Expect(len(x.currentBuckets)).To(Equal(0)) Expect(len(x.previousBuckets)).To(Equal(0)) Expect(len(x.futureBuckets)).To(Equal(0)) // insert a "current" stat s1 := stat.Stat{Name: STAT_NAME, Timestamp: x.currentBucketMinTime.Add(time.Duration(time.Second)), Value: 1} Expect(s1.Timestamp).To(BeTemporally(">", x.currentBucketMinTime)) Expect(s1.Timestamp).To(BeTemporally(">", x.previousBucketMinTime)) Expect(s1.Timestamp).To(BeTemporally("<", x.futureBucketMinTime)) Expect(x.insert(&s1)).To(BeNil()) Expect(x.currentBuckets[STAT_NAME]).To(ConsistOf(&s1)) Expect(x.previousBuckets[STAT_NAME]).To(BeNil()) Expect(x.futureBuckets[STAT_NAME]).To(BeNil()) // insert a "previous" stat s2 := stat.Stat{Name: STAT_NAME, Timestamp: x.currentBucketMinTime.Add(time.Duration(time.Second * -1)), Value: 2} Expect(s2.Timestamp).To(BeTemporally("<", x.currentBucketMinTime)) Expect(s2.Timestamp).To(BeTemporally(">", x.previousBucketMinTime)) Expect(s2.Timestamp).To(BeTemporally("<", x.futureBucketMinTime)) Expect(x.insert(&s2)).To(BeNil()) Expect(x.currentBuckets[STAT_NAME]).To(ConsistOf(&s1)) Expect(x.previousBuckets[STAT_NAME]).To(ConsistOf(&s2)) Expect(x.futureBuckets[STAT_NAME]).To(BeNil()) x.next() // after advancing, the current stats are empty, and what was once current is now previous Expect(x.currentBuckets[STAT_NAME]).To(BeNil()) Expect(x.previousBuckets[STAT_NAME]).To(ConsistOf(&s1)) Expect(x.futureBuckets[STAT_NAME]).To(BeNil()) // insert a "future" stat s3 := stat.Stat{Name: STAT_NAME, Timestamp: x.futureBucketMinTime.Add(time.Duration(time.Second)), Value: 3} Expect(s3.Timestamp).To(BeTemporally(">", x.currentBucketMinTime)) Expect(s3.Timestamp).To(BeTemporally(">", x.previousBucketMinTime)) Expect(s3.Timestamp).To(BeTemporally(">", x.futureBucketMinTime)) Expect(x.insert(&s3)).To(BeNil()) Expect(x.currentBuckets[STAT_NAME]).To(BeNil()) Expect(x.previousBuckets[STAT_NAME]).To(ConsistOf(&s1)) Expect(x.futureBuckets[STAT_NAME]).To(ConsistOf(&s3)) x.next() // after advancing, the future stats are empty, the previous stats are empty, and what was once the future is now 'current' Expect(x.currentBuckets[STAT_NAME]).To(ConsistOf(&s3)) Expect(x.previousBuckets[STAT_NAME]).To(BeNil()) Expect(x.futureBuckets[STAT_NAME]).To(BeNil()) }) }) Describe("publish", func() { It("should publish the expected stats", func(done Done) { const STAT_NAME = "foo" output := make(chan []*stat.Stat) x := NewBucketer(stats, output, shutdown) // insert two "current" stats s1 := stat.Stat{Name: STAT_NAME, Timestamp: x.currentBucketMinTime.Add(time.Duration(time.Second)), Value: 1} s2 := stat.Stat{Name: STAT_NAME, Timestamp: x.currentBucketMinTime.Add(time.Duration(time.Second * 2)), Value: 2} x.insert(&s1) x.insert(&s2) Expect(x.currentBuckets[STAT_NAME]).To(ConsistOf(&s1, &s2)) // start a goroutine to consume and verify the output go func(bucketed chan []*stat.Stat) { bucket := <-bucketed Expect(bucket).To(ConsistOf(&s1, &s2)) close(done) }(output) x.publish(x.currentBuckets) }) }) Describe("pub", func() { It("should publish the expected current and previous stats", func(done Done) { const STAT_NAME = "foo" output := make(chan []*stat.Stat) x := NewBucketer(stats, output, shutdown) // insert two "current" stats s1 := stat.Stat{Name: STAT_NAME, Timestamp: x.currentBucketMinTime.Add(time.Duration(time.Second)), Value: 1} s2 := stat.Stat{Name: STAT_NAME, Timestamp: x.currentBucketMinTime.Add(time.Duration(time.Second * 2)), Value: 2} x.insert(&s1) x.insert(&s2) // insert two previous stats s3 := stat.Stat{Name: STAT_NAME, Timestamp: x.currentBucketMinTime.Add(time.Duration(time.Second * -2)), Value: 3} s4 := stat.Stat{Name: STAT_NAME, Timestamp: x.currentBucketMinTime.Add(time.Duration(time.Second * -1)), Value: 4} x.insert(&s3) x.insert(&s4) // verify the stats went to the appropriate buckets Expect(x.currentBuckets[STAT_NAME]).To(ConsistOf(&s1, &s2)) Expect(x.previousBuckets[STAT_NAME]).To(ConsistOf(&s3, &s4)) Expect(x.futureBuckets[STAT_NAME]).To(BeNil()) // start a goroutine to consume and verify the output go func(bucketed chan []*stat.Stat) { // the "current" bucket is published/received first bucket := <-bucketed Expect(bucket).To(ConsistOf(&s1, &s2)) // the "previous" bucket is published/received second bucket = <-bucketed Expect(bucket).To(ConsistOf(&s3, &s4)) close(done) }(output) x.pub() }) It("should publish the expected current and previous stats before and after next() is invoked", func(done Done) { const STAT_NAME = "foo" output := make(chan []*stat.Stat) x := NewBucketer(stats, output, shutdown) // insert two "current" stats s1 := stat.Stat{Name: STAT_NAME, Timestamp: x.currentBucketMinTime.Add(time.Duration(time.Second)), Value: 1} s2 := stat.Stat{Name: STAT_NAME, Timestamp: x.currentBucketMinTime.Add(time.Duration(time.Second * 2)), Value: 2} x.insert(&s1) x.insert(&s2) // insert two previous stats s3 := stat.Stat{Name: STAT_NAME, Timestamp: x.currentBucketMinTime.Add(time.Duration(time.Second * -2)), Value: 3} s4 := stat.Stat{Name: STAT_NAME, Timestamp: x.currentBucketMinTime.Add(time.Duration(time.Second * -1)), Value: 4} x.insert(&s3) x.insert(&s4) // verify the stats went to the appropriate buckets Expect(x.currentBuckets[STAT_NAME]).To(ConsistOf(&s1, &s2)) Expect(x.previousBuckets[STAT_NAME]).To(ConsistOf(&s3, &s4)) Expect(x.futureBuckets[STAT_NAME]).To(BeNil()) // start a goroutine to consume and verify the output go func(bucketed chan []*stat.Stat) { // the "current" bucket is published/received first bucket := <-bucketed Expect(bucket).To(ConsistOf(&s1, &s2)) // the "previous" bucket is published/received second bucket = <-bucketed Expect(bucket).To(ConsistOf(&s3, &s4)) // after next() was invoked, there were no new "current" buckets to publish, however // the "previous" bucket is published/received, because it had data bucket = <-bucketed Expect(bucket).To(ConsistOf(&s1, &s2)) close(done) }(output) x.pub() x.next() // verify the stats went to the appropriate buckets Expect(x.currentBuckets[STAT_NAME]).To(BeNil()) Expect(x.previousBuckets[STAT_NAME]).To(ConsistOf(&s1, &s2)) Expect(x.futureBuckets[STAT_NAME]).To(BeNil()) x.pub() }) }) })
{ "content_hash": "05dab94887c75fc86b184b1fbb4c01eb", "timestamp": "", "source": "github", "line_count": 417, "max_line_length": 174, "avg_line_length": 42.2589928057554, "alnum_prop": 0.6998638066053796, "repo_name": "CapillarySoftware/gostat", "id": "df671d33ca0f6c72acc1f13ea7350c19324f1168", "size": "17622", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bucketer/bucketer_test.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "75033" }, { "name": "JavaScript", "bytes": "155214" }, { "name": "Shell", "bytes": "147" } ], "symlink_target": "" }
dot -Tpng heterograph-mapping.gv -oheterograph-mapping.png
{ "content_hash": "0662bf3f5c5a47a7123fd9f5dd1d6a62", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 58, "avg_line_length": 59, "alnum_prop": 0.8305084745762712, "repo_name": "OpenTaal/heterographic-character-mapping", "id": "abc3c76cb098bdc0f4c926eee32460b147890807", "size": "59", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "document.sh", "mode": "33261", "license": "mit", "language": [ { "name": "Shell", "bytes": "59" } ], "symlink_target": "" }
/* #include "XKBfile.h" */ extern int ProcXkbUseExtension(ClientPtr client); extern int ProcXkbSelectEvents(ClientPtr client); extern int ProcXkbBell(ClientPtr client); extern int ProcXkbGetState(ClientPtr client); extern int ProcXkbLatchLockState(ClientPtr client); extern int ProcXkbGetControls(ClientPtr client); extern int ProcXkbSetControls(ClientPtr client); extern int ProcXkbGetMap(ClientPtr client); extern int ProcXkbSetMap(ClientPtr client); extern int ProcXkbGetCompatMap(ClientPtr client); extern int ProcXkbSetCompatMap(ClientPtr client); extern int ProcXkbGetIndicatorState(ClientPtr client); extern int ProcXkbGetIndicatorMap(ClientPtr client); extern int ProcXkbSetIndicatorMap(ClientPtr client); extern int ProcXkbGetNamedIndicator(ClientPtr client); extern int ProcXkbSetNamedIndicator(ClientPtr client); extern int ProcXkbGetNames(ClientPtr client); extern int ProcXkbSetNames(ClientPtr client); extern int ProcXkbGetGeometry(ClientPtr client); extern int ProcXkbSetGeometry(ClientPtr client); extern int ProcXkbPerClientFlags(ClientPtr client); extern int ProcXkbListComponents(ClientPtr client); extern int ProcXkbGetKbdByName(ClientPtr client); extern int ProcXkbGetDeviceInfo(ClientPtr client); extern int ProcXkbSetDeviceInfo(ClientPtr client); extern int ProcXkbSetDebuggingFlags(ClientPtr client); extern void XkbExtensionInit(void); extern Bool XkbFilterEvents(ClientPtr pClient, int nEvents, xEvent *xE); extern Bool XkbCopyKeymap( XkbDescPtr src, XkbDescPtr dst, Bool sendNotifies);
{ "content_hash": "d6f889e2602714bfdb41393fc05fb763", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 72, "avg_line_length": 42.54054054054054, "alnum_prop": 0.8163913595933926, "repo_name": "egraba/vbox_openbsd", "id": "99b60bf5e0fb2d519e33713697a6c8330e1150b8", "size": "1574", "binary": false, "copies": "20", "ref": "refs/heads/master", "path": "VirtualBox-5.0.0/src/VBox/Additions/x11/x11include/xorg-server-1.4.2/xkb.h", "mode": "33188", "license": "mit", "language": [ { "name": "Ada", "bytes": "88714" }, { "name": "Assembly", "bytes": "4303680" }, { "name": "AutoIt", "bytes": "2187" }, { "name": "Batchfile", "bytes": "95534" }, { "name": "C", "bytes": "192632221" }, { "name": "C#", "bytes": "64255" }, { "name": "C++", "bytes": "83842667" }, { "name": "CLIPS", "bytes": "5291" }, { "name": "CMake", "bytes": "6041" }, { "name": "CSS", "bytes": "26756" }, { "name": "D", "bytes": "41844" }, { "name": "DIGITAL Command Language", "bytes": "56579" }, { "name": "DTrace", "bytes": "1466646" }, { "name": "GAP", "bytes": "350327" }, { "name": "Groff", "bytes": "298540" }, { "name": "HTML", "bytes": "467691" }, { "name": "IDL", "bytes": "106734" }, { "name": "Java", "bytes": "261605" }, { "name": "JavaScript", "bytes": "80927" }, { "name": "Lex", "bytes": "25122" }, { "name": "Logos", "bytes": "4941" }, { "name": "Makefile", "bytes": "426902" }, { "name": "Module Management System", "bytes": "2707" }, { "name": "NSIS", "bytes": "177212" }, { "name": "Objective-C", "bytes": "5619792" }, { "name": "Objective-C++", "bytes": "81554" }, { "name": "PHP", "bytes": "58585" }, { "name": "Pascal", "bytes": "69941" }, { "name": "Perl", "bytes": "240063" }, { "name": "PowerShell", "bytes": "10664" }, { "name": "Python", "bytes": "9094160" }, { "name": "QMake", "bytes": "3055" }, { "name": "R", "bytes": "21094" }, { "name": "SAS", "bytes": "1847" }, { "name": "Shell", "bytes": "1460572" }, { "name": "SourcePawn", "bytes": "4139" }, { "name": "TypeScript", "bytes": "142342" }, { "name": "Visual Basic", "bytes": "7161" }, { "name": "XSLT", "bytes": "1034475" }, { "name": "Yacc", "bytes": "22312" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Annls mycol. 12(2): 209 (1914) #### Original name Gloeosporium pineae Bubák ### Remarks null
{ "content_hash": "3630b50a7468f95c0c87db1cf876ef08", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 30, "avg_line_length": 12, "alnum_prop": 0.6987179487179487, "repo_name": "mdoering/backbone", "id": "41c77aae31d9209f920c4a50ec1d6982c22ae6cb", "size": "207", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Leotiomycetes/Helotiales/Dermateaceae/Marssonina/Gloeosporium pineae/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.albedinsky.android.ui.examples.fragment.animation; import android.os.Bundle; import android.support.annotation.NonNull; import android.view.View; import com.albedinsky.android.ui.examples.R; import com.albedinsky.android.ui.examples.transition.RevealFabTransition; /** * @author Martin Albedinsky */ public final class RevealFabTransitionFragment extends TransitionFragmentA { @SuppressWarnings("unused") private static final String TAG = "RevealFabTransitionFragment"; @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.findViewById(R.id.fab).setOnClickListener(this); } @Override protected boolean onViewClick(@NonNull View view, int id) { switch (id) { case R.id.fab: RevealFabTransition.get().example(mExample).start(getActivity()); return true; } return false; } }
{ "content_hash": "2a0b45fcddc937a919344898ddec22f9", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 76, "avg_line_length": 26.38235294117647, "alnum_prop": 0.7759197324414716, "repo_name": "android-libraries/android_ui", "id": "130f1c32d26c99b7a307e3248336ac9c7da61a9a", "size": "2013", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/src/main/java/com/albedinsky/android/ui/examples/fragment/animation/RevealFabTransitionFragment.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2430528" } ], "symlink_target": "" }
@import UIKit; #import "LYAppDelegate.h" int main(int argc, char * argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([LYAppDelegate class])); } }
{ "content_hash": "6c9104648aa7d0ee5cca39163b924c2c", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 92, "avg_line_length": 22.444444444444443, "alnum_prop": 0.6782178217821783, "repo_name": "yelon21/LTExtNSObject", "id": "7f53d4b6d047d1122fea2914489a069af9cd7d7d", "size": "332", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Example/LTExtNSObject/main.m", "mode": "33261", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "65944" }, { "name": "Ruby", "bytes": "1748" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "3039f212b5771b702060766d3eeb21e8", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "7151d2e26cc43ec453a4ebde583b22a0fca5ec9c", "size": "175", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Dilleniales/Dilleniaceae/Davilla/Davilla asperrima/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
#ifndef CRIMILD_FOUNDATION_CONTAINERS_QUEUE_ #define CRIMILD_FOUNDATION_CONTAINERS_QUEUE_ #include "Foundation/Types.hpp" #include "Foundation/Policies/ThreadingPolicy.hpp" #include "Mathematics/Numeric.hpp" #include <functional> #include <iostream> #include <deque> #include <algorithm> namespace crimild { /** \brief A resizable queue implementation \todo Implement index bound checking policy \todo Implement parallel policy */ template< typename T, class ThreadingPolicy = policies::SingleThreaded > class Queue : public ThreadingPolicy { private: using LockImpl = typename ThreadingPolicy::Lock; public: Queue( void ) = default; Queue( const Queue &other ) noexcept : _impl( other._impl ) { } virtual ~Queue( void ) = default; Queue &operator=( const Queue &other ) noexcept { LockImpl lock( this ); _impl = other._impl; return *this; } /** \brief Compare two stacks up to getSize() elements */ bool operator==( const Queue &other ) const noexcept { LockImpl lock( this ); return _impl == other._impl; } inline bool empty( void ) noexcept { LockImpl lock( this ); return _impl.empty(); } inline Size size( void ) noexcept { LockImpl lock( this ); return _impl.size(); } inline void clear( void ) noexcept { LockImpl lock( this ); return _impl.clear(); } void push( T const &elem ) noexcept { LockImpl lock( this ); _impl.push_back( elem ); } T pop( void ) noexcept { LockImpl lock( this ); T front = _impl.front(); _impl.pop_front(); return front; } inline T &front( void ) noexcept { return _impl.front(); } inline const T &top( void ) const noexcept { return _impl.front(); } inline Bool contains( const T &e ) const noexcept { LockImpl lock( this ); return std::find( _impl.begin(), _impl.end(), e ) != _impl.end(); } void remove( const T &elem ) noexcept { LockImpl lock( this ); _impl.erase( std::remove( _impl.begin(), _impl.end(), elem ), _impl.end() ); } template< typename Callback > void each( Callback callback ) noexcept { LockImpl lock( this ); Size i = 0; for ( auto &e : _impl ) { callback( e, i++ ); } } template< typename Callback > void each( Callback callback ) const noexcept { LockImpl lock( this ); Size i = 0; for ( auto &e : _impl ) { callback( e, i++ ); } } private: std::deque< T > _impl; public: friend std::ostream& operator<<( std::ostream& os, const Queue &s ) noexcept { os << "["; s.each( [ &os ]( const T &a, Size i ) { os << ( i == 0 ? "" : ", " ) << a; }); os << "]"; return os; } }; } #endif
{ "content_hash": "d31a5af26b111db7da9c96791ebdc924", "timestamp": "", "source": "github", "line_count": 150, "max_line_length": 88, "avg_line_length": 23.106666666666666, "alnum_prop": 0.4766301211771495, "repo_name": "hhsaez/crimild", "id": "9aa82cba530394b15e9ce1f521b357b99b06b021", "size": "5053", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/Foundation/Containers/Queue.hpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "404879" }, { "name": "C++", "bytes": "10274496" }, { "name": "CMake", "bytes": "36291" }, { "name": "GLSL", "bytes": "25866" }, { "name": "Lua", "bytes": "1039" }, { "name": "Metal", "bytes": "11994" }, { "name": "Objective-C", "bytes": "432010" }, { "name": "Objective-C++", "bytes": "118466" }, { "name": "Shell", "bytes": "943" } ], "symlink_target": "" }
package mengde import ( "context" "encoding/json" "errors" "fmt" "io/ioutil" "net" "net/http" "os" "strconv" "strings" "sync" "sync/atomic" "time" "go-common/library/log" ) const ( kSvenCheckTimeout = time.Minute kSvenGetTimeout = 30 * time.Second kSvenHost = "http://config.bilibili.co" kSvenCheckAPI = kSvenHost + "/config/v2/check" kSvenGetAPI = kSvenHost + "/config/v2/get" kDefaultHost = "invalid-host-name" kDefaultIP = "127.0.0.1" kCodeNotModified = -304 ) type MengdeClient struct { treeID string zone string env string build string token string host string ip string config atomic.Value notify chan *MengdeConfig changeSignal chan struct{} httpClient *http.Client ctx context.Context cancel context.CancelFunc closeSignal chan struct{} configLoadWg sync.WaitGroup configNotifyWg sync.WaitGroup } type MengdeConfig struct { Version int Config map[string]string } func NewMengdeClient(treeID string, zone string, env string, build string, token string) (*MengdeClient, error) { host, err := os.Hostname() if err != nil { host = kDefaultHost } ip := kDefaultIP addr, err := net.InterfaceAddrs() if err == nil { for _, a := range addr { if n, ok := a.(*net.IPNet); ok && !n.IP.IsLoopback() && n.IP.To4() != nil { ip = n.IP.String() } } } c := &MengdeClient{ treeID: treeID, zone: zone, env: env, build: build, token: token, host: host, ip: ip, notify: make(chan *MengdeConfig), changeSignal: make(chan struct{}, 1), httpClient: new(http.Client), closeSignal: make(chan struct{}), } c.ctx, c.cancel = context.WithCancel(context.Background()) version, config, err := c.svenConfigSync() if err != nil { return nil, err } c.config.Store(&MengdeConfig{ Version: version, Config: config, }) c.changeSignal <- struct{}{} c.configLoadWg.Add(1) go func() { defer c.configLoadWg.Done() c.configLoadProcess() }() c.configNotifyWg.Add(1) go func() { defer c.configNotifyWg.Done() c.configNotifyProcess() }() return c, nil } func (c *MengdeClient) Close() { close(c.closeSignal) c.cancel() c.configLoadWg.Wait() close(c.changeSignal) c.configNotifyWg.Wait() } func (c *MengdeClient) Config() *MengdeConfig { result := &MengdeConfig{ Version: -1, Config: make(map[string]string), } if config, ok := c.config.Load().(*MengdeConfig); ok { result.Version = config.Version for k, v := range config.Config { result.Config[k] = v } } return result } func (c *MengdeClient) ConfigNotify() <-chan *MengdeConfig { return c.notify } func (c *MengdeClient) configLoadProcess() { for { select { case <-c.closeSignal: return default: } current, ok := c.config.Load().(*MengdeConfig) if !ok { current = &MengdeConfig{ Version: -1, } } version, err := c.svenCheckVersion(current.Version) //config not modified if version == current.Version { log.Info("[sven]check version config not modified") continue } if err != nil { log.Error("[sven]check version error:%s", err.Error()) continue } if current.Version == version { continue } config, err := c.svenGetConfig(version) if err != nil { log.Error(err.Error()) continue } c.config.Store(&MengdeConfig{ Version: version, Config: config, }) select { case c.changeSignal <- struct{}{}: default: } } } func (c *MengdeClient) configNotifyProcess() { for range c.changeSignal { select { case <-c.closeSignal: return case c.notify <- c.Config(): } } } func (c *MengdeClient) svenConfigSync() (int, map[string]string, error) { version, err := c.svenCheckVersion(-1) if err != nil { return -1, nil, err } config, err := c.svenGetConfig(version) if err != nil { return -1, nil, err } return version, config, nil } func (c *MengdeClient) svenCheckVersion(version int) (int, error) { var err error req, err := http.NewRequest("GET", kSvenCheckAPI, nil) if err != nil { return -1, err } q := req.URL.Query() q.Add("build", c.build) q.Add("hostname", c.host) q.Add("ip", c.ip) q.Add("service", strings.Join([]string{c.treeID, c.env, c.zone}, "_")) q.Add("token", c.token) q.Add("version", strconv.Itoa(version)) req.URL.RawQuery = q.Encode() ctx, cancel := context.WithTimeout(c.ctx, kSvenCheckTimeout) defer cancel() req = req.WithContext(ctx) resp, err := c.httpClient.Do(req) if err != nil { return -1, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return -1, errors.New(fmt.Sprintf("http request URL:%s result:%s", req.URL.RawQuery, resp.Status)) } result, err := ioutil.ReadAll(resp.Body) if err != nil { return -1, err } var svenCheckRespBody struct { Code int `json:"code"` Message string `json:"message"` Data struct { Version int `json:"version"` } `json:"data"` } if err = json.Unmarshal(result, &svenCheckRespBody); err != nil { return -1, err } if svenCheckRespBody.Code != 0 { if svenCheckRespBody.Code == kCodeNotModified { return version, nil } return -1, errors.New(svenCheckRespBody.Message) } return svenCheckRespBody.Data.Version, nil } func (c *MengdeClient) svenGetConfig(version int) (map[string]string, error) { var err error req, err := http.NewRequest("GET", kSvenGetAPI, nil) if err != nil { return nil, err } q := req.URL.Query() q.Add("build", c.build) q.Add("hostname", c.host) q.Add("ip", c.ip) q.Add("service", strings.Join([]string{c.treeID, c.env, c.zone}, "_")) q.Add("token", c.token) q.Add("version", strconv.Itoa(version)) req.URL.RawQuery = q.Encode() ctx, cancel := context.WithTimeout(c.ctx, kSvenGetTimeout) defer cancel() req = req.WithContext(ctx) resp, err := c.httpClient.Do(req) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, errors.New(fmt.Sprintf("http request URL:%s result:%s", req.URL.RawQuery, resp.Status)) } result, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } var svenGetRespBody struct { Code int `json:"code"` Message string `json:"message"` TTL int `json:"ttl"` Data struct { Version int `json:"version"` MD5 string `json:"md5"` Content string `json:"content"` } `json:"data"` } if err = json.Unmarshal(result, &svenGetRespBody); err != nil { return nil, err } if svenGetRespBody.Code != 0 { return nil, errors.New(svenGetRespBody.Message) } var configContent []struct { Name string `json:"name"` Config string `json:"config"` } if err = json.Unmarshal([]byte(svenGetRespBody.Data.Content), &configContent); err != nil { return nil, err } config := make(map[string]string) for _, c := range configContent { config[c.Name] = strings.TrimSpace(c.Config) } return config, nil }
{ "content_hash": "19ae302bd45d350b100b1f69cd0aca6e", "timestamp": "", "source": "github", "line_count": 309, "max_line_length": 113, "avg_line_length": 22.689320388349515, "alnum_prop": 0.640707459706176, "repo_name": "LQJJ/demo", "id": "6de570960c7ca1b466ca4d98305df9ec49ad6db0", "size": "7011", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "126-go-common-master/app/common/live/library/mengde/mengde.go", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "5910716" }, { "name": "C++", "bytes": "113072" }, { "name": "CSS", "bytes": "10791" }, { "name": "Dockerfile", "bytes": "934" }, { "name": "Go", "bytes": "40121403" }, { "name": "Groovy", "bytes": "347" }, { "name": "HTML", "bytes": "359263" }, { "name": "JavaScript", "bytes": "545384" }, { "name": "Makefile", "bytes": "6671" }, { "name": "Mathematica", "bytes": "14565" }, { "name": "Objective-C", "bytes": "14900720" }, { "name": "Objective-C++", "bytes": "20070" }, { "name": "PureBasic", "bytes": "4152" }, { "name": "Python", "bytes": "4490569" }, { "name": "Ruby", "bytes": "44850" }, { "name": "Shell", "bytes": "33251" }, { "name": "Swift", "bytes": "463286" }, { "name": "TSQL", "bytes": "108861" } ], "symlink_target": "" }
 #pragma once #include <aws/network-firewall/NetworkFirewall_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace NetworkFirewall { namespace Model { enum class StreamExceptionPolicy { NOT_SET, DROP, CONTINUE }; namespace StreamExceptionPolicyMapper { AWS_NETWORKFIREWALL_API StreamExceptionPolicy GetStreamExceptionPolicyForName(const Aws::String& name); AWS_NETWORKFIREWALL_API Aws::String GetNameForStreamExceptionPolicy(StreamExceptionPolicy value); } // namespace StreamExceptionPolicyMapper } // namespace Model } // namespace NetworkFirewall } // namespace Aws
{ "content_hash": "477f2ea8555fdecfceb23962fe08b181", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 103, "avg_line_length": 22.285714285714285, "alnum_prop": 0.7916666666666666, "repo_name": "aws/aws-sdk-cpp", "id": "ea8a018db74203e4e196410b88ab5c223b5432bb", "size": "743", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "aws-cpp-sdk-network-firewall/include/aws/network-firewall/model/StreamExceptionPolicy.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "309797" }, { "name": "C++", "bytes": "476866144" }, { "name": "CMake", "bytes": "1245180" }, { "name": "Dockerfile", "bytes": "11688" }, { "name": "HTML", "bytes": "8056" }, { "name": "Java", "bytes": "413602" }, { "name": "Python", "bytes": "79245" }, { "name": "Shell", "bytes": "9246" } ], "symlink_target": "" }
// 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. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddImport { internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax> : IAddImportFeatureService, IEqualityComparer<PortableExecutableReference> where TSimpleNameSyntax : SyntaxNode { protected abstract bool CanAddImport(SyntaxNode node, bool allowInHiddenRegions, CancellationToken cancellationToken); protected abstract bool CanAddImportForMethod(string diagnosticId, ISyntaxFacts syntaxFacts, SyntaxNode node, out TSimpleNameSyntax nameNode); protected abstract bool CanAddImportForNamespace(string diagnosticId, SyntaxNode node, out TSimpleNameSyntax nameNode); protected abstract bool CanAddImportForDeconstruct(string diagnosticId, SyntaxNode node); protected abstract bool CanAddImportForGetAwaiter(string diagnosticId, ISyntaxFacts syntaxFactsService, SyntaxNode node); protected abstract bool CanAddImportForGetEnumerator(string diagnosticId, ISyntaxFacts syntaxFactsService, SyntaxNode node); protected abstract bool CanAddImportForGetAsyncEnumerator(string diagnosticId, ISyntaxFacts syntaxFactsService, SyntaxNode node); protected abstract bool CanAddImportForQuery(string diagnosticId, SyntaxNode node); protected abstract bool CanAddImportForType(string diagnosticId, SyntaxNode node, out TSimpleNameSyntax nameNode); protected abstract ISet<INamespaceSymbol> GetImportNamespacesInScope(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken); protected abstract ITypeSymbol GetDeconstructInfo(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken); protected abstract ITypeSymbol GetQueryClauseInfo(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken); protected abstract bool IsViableExtensionMethod(IMethodSymbol method, SyntaxNode expression, SemanticModel semanticModel, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken); protected abstract Task<Document> AddImportAsync(SyntaxNode contextNode, INamespaceOrTypeSymbol symbol, Document document, bool specialCaseSystem, bool allowInHiddenRegions, CancellationToken cancellationToken); protected abstract Task<Document> AddImportAsync(SyntaxNode contextNode, IReadOnlyList<string> nameSpaceParts, Document document, bool specialCaseSystem, bool allowInHiddenRegions, CancellationToken cancellationToken); protected abstract bool IsAddMethodContext(SyntaxNode node, SemanticModel semanticModel); protected abstract string GetDescription(IReadOnlyList<string> nameParts); protected abstract (string description, bool hasExistingImport) GetDescription(Document document, INamespaceOrTypeSymbol symbol, SemanticModel semanticModel, SyntaxNode root, CancellationToken cancellationToken); public async Task<ImmutableArray<AddImportFixData>> GetFixesAsync( Document document, TextSpan span, string diagnosticId, int maxResults, bool placeSystemNamespaceFirst, bool allowInHiddenRegions, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(document.Project, cancellationToken).ConfigureAwait(false); if (client != null) { var result = await client.TryInvokeAsync<IRemoteMissingImportDiscoveryService, ImmutableArray<AddImportFixData>>( document.Project.Solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetFixesAsync(solutionInfo, callbackId, document.Id, span, diagnosticId, maxResults, placeSystemNamespaceFirst, allowInHiddenRegions, searchReferenceAssemblies, packageSources, cancellationToken), callbackTarget: symbolSearchService, cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<AddImportFixData>.Empty; } return await GetFixesInCurrentProcessAsync( document, span, diagnosticId, maxResults, placeSystemNamespaceFirst, allowInHiddenRegions, symbolSearchService, searchReferenceAssemblies, packageSources, cancellationToken).ConfigureAwait(false); } private async Task<ImmutableArray<AddImportFixData>> GetFixesInCurrentProcessAsync( Document document, TextSpan span, string diagnosticId, int maxResults, bool placeSystemNamespaceFirst, bool allowInHiddenRegions, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var node = root.FindToken(span.Start, findInsideTrivia: true) .GetAncestor(n => n.Span.Contains(span) && n != root); using var _ = ArrayBuilder<AddImportFixData>.GetInstance(out var result); if (node != null) { using (Logger.LogBlock(FunctionId.Refactoring_AddImport, cancellationToken)) { if (!cancellationToken.IsCancellationRequested) { if (CanAddImport(node, allowInHiddenRegions, cancellationToken)) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var allSymbolReferences = await FindResultsAsync( document, semanticModel, diagnosticId, node, maxResults, symbolSearchService, searchReferenceAssemblies, packageSources, cancellationToken).ConfigureAwait(false); // Nothing found at all. No need to proceed. foreach (var reference in allSymbolReferences) { cancellationToken.ThrowIfCancellationRequested(); var fixData = await reference.TryGetFixDataAsync(document, node, placeSystemNamespaceFirst, allowInHiddenRegions, cancellationToken).ConfigureAwait(false); result.AddIfNotNull(fixData); } } } } } return result.ToImmutable(); } private async Task<ImmutableArray<Reference>> FindResultsAsync( Document document, SemanticModel semanticModel, string diagnosticId, SyntaxNode node, int maxResults, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { // Caches so we don't produce the same data multiple times while searching // all over the solution. var project = document.Project; var projectToAssembly = new ConcurrentDictionary<Project, AsyncLazy<IAssemblySymbol>>(concurrencyLevel: 2, capacity: project.Solution.ProjectIds.Count); var referenceToCompilation = new ConcurrentDictionary<PortableExecutableReference, Compilation>(concurrencyLevel: 2, capacity: project.Solution.Projects.Sum(p => p.MetadataReferences.Count)); var finder = new SymbolReferenceFinder( this, document, semanticModel, diagnosticId, node, symbolSearchService, searchReferenceAssemblies, packageSources, cancellationToken); // Look for exact matches first: var exactReferences = await FindResultsAsync(projectToAssembly, referenceToCompilation, project, maxResults, finder, exact: true, cancellationToken: cancellationToken).ConfigureAwait(false); if (exactReferences.Length > 0) { return exactReferences; } // No exact matches found. Fall back to fuzzy searching. // Only bother doing this for host workspaces. We don't want this for // things like the Interactive workspace as this will cause us to // create expensive bk-trees which we won't even be able to save for // future use. if (!IsHostOrRemoteWorkspace(project)) { return ImmutableArray<Reference>.Empty; } var fuzzyReferences = await FindResultsAsync(projectToAssembly, referenceToCompilation, project, maxResults, finder, exact: false, cancellationToken: cancellationToken).ConfigureAwait(false); return fuzzyReferences; } private static bool IsHostOrRemoteWorkspace(Project project) { return project.Solution.Workspace.Kind == WorkspaceKind.Host || project.Solution.Workspace.Kind == WorkspaceKind.RemoteWorkspace || project.Solution.Workspace.Kind == WorkspaceKind.RemoteTemporaryWorkspace; } private async Task<ImmutableArray<Reference>> FindResultsAsync( ConcurrentDictionary<Project, AsyncLazy<IAssemblySymbol>> projectToAssembly, ConcurrentDictionary<PortableExecutableReference, Compilation> referenceToCompilation, Project project, int maxResults, SymbolReferenceFinder finder, bool exact, CancellationToken cancellationToken) { using var _ = ArrayBuilder<Reference>.GetInstance(out var allReferences); // First search the current project to see if any symbols (source or metadata) match the // search string. await FindResultsInAllSymbolsInStartingProjectAsync( allReferences, maxResults, finder, exact, cancellationToken).ConfigureAwait(false); // Only bother doing this for host workspaces. We don't want this for // things like the Interactive workspace as we can't even add project // references to the interactive window. We could consider adding metadata // references with #r in the future. if (IsHostOrRemoteWorkspace(project)) { // Now search unreferenced projects, and see if they have any source symbols that match // the search string. await FindResultsInUnreferencedProjectSourceSymbolsAsync(projectToAssembly, project, allReferences, maxResults, finder, exact, cancellationToken).ConfigureAwait(false); // Finally, check and see if we have any metadata symbols that match the search string. await FindResultsInUnreferencedMetadataSymbolsAsync(referenceToCompilation, project, allReferences, maxResults, finder, exact, cancellationToken).ConfigureAwait(false); // We only support searching NuGet in an exact manner currently. if (exact) { await finder.FindNugetOrReferenceAssemblyReferencesAsync(allReferences, cancellationToken).ConfigureAwait(false); } } return allReferences.ToImmutable(); } private static async Task FindResultsInAllSymbolsInStartingProjectAsync( ArrayBuilder<Reference> allSymbolReferences, int maxResults, SymbolReferenceFinder finder, bool exact, CancellationToken cancellationToken) { var references = await finder.FindInAllSymbolsInStartingProjectAsync(exact, cancellationToken).ConfigureAwait(false); AddRange(allSymbolReferences, references, maxResults); } private static async Task FindResultsInUnreferencedProjectSourceSymbolsAsync( ConcurrentDictionary<Project, AsyncLazy<IAssemblySymbol>> projectToAssembly, Project project, ArrayBuilder<Reference> allSymbolReferences, int maxResults, SymbolReferenceFinder finder, bool exact, CancellationToken cancellationToken) { // If we didn't find enough hits searching just in the project, then check // in any unreferenced projects. if (allSymbolReferences.Count >= maxResults) { return; } var viableUnreferencedProjects = GetViableUnreferencedProjects(project); // Search all unreferenced projects in parallel. var findTasks = new HashSet<Task<ImmutableArray<SymbolReference>>>(); // Create another cancellation token so we can both search all projects in parallel, // but also stop any searches once we get enough results. using var nestedTokenSource = new CancellationTokenSource(); using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(nestedTokenSource.Token, cancellationToken); foreach (var unreferencedProject in viableUnreferencedProjects) { // Search in this unreferenced project. But don't search in any of its' // direct references. i.e. we don't want to search in its metadata references // or in the projects it references itself. We'll be searching those entities // individually. findTasks.Add(finder.FindInSourceSymbolsInProjectAsync( projectToAssembly, unreferencedProject, exact, linkedTokenSource.Token)); } await WaitForTasksAsync(allSymbolReferences, maxResults, findTasks, nestedTokenSource, cancellationToken).ConfigureAwait(false); } private async Task FindResultsInUnreferencedMetadataSymbolsAsync( ConcurrentDictionary<PortableExecutableReference, Compilation> referenceToCompilation, Project project, ArrayBuilder<Reference> allSymbolReferences, int maxResults, SymbolReferenceFinder finder, bool exact, CancellationToken cancellationToken) { if (allSymbolReferences.Count > 0) { // Only do this if none of the project searches produced any results. We may have a // lot of metadata to search through, and it would be good to avoid that if we can. return; } // Keep track of the references we've seen (so that we don't process them multiple times // across many sibling projects). Prepopulate it with our own metadata references since // we know we don't need to search in that. var seenReferences = new HashSet<PortableExecutableReference>(comparer: this); seenReferences.AddAll(project.MetadataReferences.OfType<PortableExecutableReference>()); var newReferences = GetUnreferencedMetadataReferences(project, seenReferences); // Search all metadata references in parallel. var findTasks = new HashSet<Task<ImmutableArray<SymbolReference>>>(); // Create another cancellation token so we can both search all projects in parallel, // but also stop any searches once we get enough results. using var nestedTokenSource = new CancellationTokenSource(); using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(nestedTokenSource.Token, cancellationToken); foreach (var (referenceProjectId, reference) in newReferences) { var compilation = referenceToCompilation.GetOrAdd( reference, r => CreateCompilation(project, r)); // Ignore netmodules. First, they're incredibly esoteric and barely used. // Second, the SymbolFinder API doesn't even support searching them. if (compilation.GetAssemblyOrModuleSymbol(reference) is IAssemblySymbol assembly) { findTasks.Add(finder.FindInMetadataSymbolsAsync( assembly, referenceProjectId, reference, exact, linkedTokenSource.Token)); } } await WaitForTasksAsync(allSymbolReferences, maxResults, findTasks, nestedTokenSource, cancellationToken).ConfigureAwait(false); } /// <summary> /// Returns the set of PEReferences in the solution that are not currently being referenced /// by this project. The set returned will be tuples containing the PEReference, and the project-id /// for the project we found the pe-reference in. /// </summary> private static ImmutableArray<(ProjectId, PortableExecutableReference)> GetUnreferencedMetadataReferences( Project project, HashSet<PortableExecutableReference> seenReferences) { var result = ArrayBuilder<(ProjectId, PortableExecutableReference)>.GetInstance(); var solution = project.Solution; foreach (var p in solution.Projects) { if (p == project) { continue; } foreach (var reference in p.MetadataReferences) { if (reference is PortableExecutableReference peReference && !IsInPackagesDirectory(peReference) && seenReferences.Add(peReference)) { result.Add((p.Id, peReference)); } } } return result.ToImmutableAndFree(); } private static async Task WaitForTasksAsync( ArrayBuilder<Reference> allSymbolReferences, int maxResults, HashSet<Task<ImmutableArray<SymbolReference>>> findTasks, CancellationTokenSource nestedTokenSource, CancellationToken cancellationToken) { try { while (findTasks.Count > 0) { // Keep on looping through the 'find' tasks, processing each when they finish. cancellationToken.ThrowIfCancellationRequested(); var doneTask = await Task.WhenAny(findTasks).ConfigureAwait(false); // One of the tasks finished. Remove it from the list we're waiting on. findTasks.Remove(doneTask); // Add its results to the final result set we're keeping. AddRange(allSymbolReferences, await doneTask.ConfigureAwait(false), maxResults); // Once we get enough, just stop. if (allSymbolReferences.Count >= maxResults) { return; } } } finally { // Cancel any nested work that's still happening. nestedTokenSource.Cancel(); } } /// <summary> /// We ignore references that are in a directory that contains the names /// "Packages", "packs", "NuGetFallbackFolder", or "NuGetPackages" /// These directories are most likely the ones produced by NuGet, and we don't want /// to offer to add .dll reference manually for dlls that are part of NuGet packages. /// /// Note that this is only a heuristic (though a good one), and we should remove this /// when we can get an API from NuGet that tells us if a reference is actually provided /// by a nuget packages. /// Tracking issue: https://github.com/dotnet/project-system/issues/5275 /// /// This heuristic will do the right thing in practically all cases for all. It /// prevents the very unpleasant experience of us offering to add a direct metadata /// reference to something that should only be referenced as a nuget package. /// /// It does mean that if the following is true: /// You have a project that has a non-nuget metadata reference to something in a "packages" /// directory, and you are in another project that uses a type name that would have matched /// an accessible type from that dll. then we will not offer to add that .dll reference to /// that other project. /// /// However, that would be an exceedingly uncommon case that is degraded. Whereas we're /// vastly improved in the common case. This is a totally acceptable and desirable outcome /// for such a heuristic. /// </summary> private static bool IsInPackagesDirectory(PortableExecutableReference reference) { return ContainsPathComponent(reference, "packages") || ContainsPathComponent(reference, "packs") || ContainsPathComponent(reference, "NuGetFallbackFolder") || ContainsPathComponent(reference, "NuGetPackages"); static bool ContainsPathComponent(PortableExecutableReference reference, string pathComponent) { return PathUtilities.ContainsPathComponent(reference.FilePath, pathComponent, ignoreCase: true); } } /// <summary> /// Called when we want to search a metadata reference. We create a dummy compilation /// containing just that reference and we search that. That way we can get actual symbols /// returned. /// /// We don't want to use the project that the reference is actually associated with as /// getting the compilation for that project may be extremely expensive. For example, /// in a large solution it may cause us to build an enormous amount of skeleton assemblies. /// </summary> private static Compilation CreateCompilation(Project project, PortableExecutableReference reference) { var compilationService = project.LanguageServices.GetRequiredService<ICompilationFactoryService>(); var compilation = compilationService.CreateCompilation("TempAssembly", compilationService.GetDefaultCompilationOptions()); return compilation.WithReferences(reference); } bool IEqualityComparer<PortableExecutableReference>.Equals(PortableExecutableReference? x, PortableExecutableReference? y) => StringComparer.OrdinalIgnoreCase.Equals(x?.FilePath ?? x?.Display, y?.FilePath ?? y?.Display); int IEqualityComparer<PortableExecutableReference>.GetHashCode(PortableExecutableReference obj) { var identifier = obj.FilePath ?? obj.Display; Contract.ThrowIfNull(identifier, "Either FilePath or Display must be non-null"); return StringComparer.OrdinalIgnoreCase.GetHashCode(identifier); } private static HashSet<Project> GetViableUnreferencedProjects(Project project) { var solution = project.Solution; var viableProjects = new HashSet<Project>(solution.Projects); // Clearly we can't reference ourselves. viableProjects.Remove(project); // We can't reference any project that transitively depends on us. Doing so would // cause a circular reference between projects. var dependencyGraph = solution.GetProjectDependencyGraph(); var projectsThatTransitivelyDependOnThisProject = dependencyGraph.GetProjectsThatTransitivelyDependOnThisProject(project.Id); viableProjects.RemoveAll(projectsThatTransitivelyDependOnThisProject.Select(id => solution.GetRequiredProject(id))); // We also aren't interested in any projects we're already directly referencing. viableProjects.RemoveAll(project.ProjectReferences.Select(r => solution.GetRequiredProject(r.ProjectId))); return viableProjects; } private static void AddRange<TReference>(ArrayBuilder<Reference> allSymbolReferences, ImmutableArray<TReference> proposedReferences, int maxResults) where TReference : Reference { allSymbolReferences.AddRange(proposedReferences.Take(maxResults - allSymbolReferences.Count)); } protected static bool IsViableExtensionMethod(IMethodSymbol method, ITypeSymbol receiver) { if (receiver == null || method == null) { return false; } // It's possible that the 'method' we're looking at is from a different language than // the language we're currently in. For example, we might find the extension method // in an unreferenced VB project while we're in C#. However, in order to 'reduce' // the extension method, the compiler requires both the method and receiver to be // from the same language. // // So, if they're not from the same language, we simply can't proceed. Now in this // case we decide that the method is not viable. But we could, in the future, decide // to just always consider such methods viable. if (receiver.Language != method.Language) { return false; } return method.ReduceExtensionMethod(receiver) != null; } private static bool NotGlobalNamespace(SymbolReference reference) { var symbol = reference.SymbolResult.Symbol; return symbol.IsNamespace ? !((INamespaceSymbol)symbol).IsGlobalNamespace : true; } private static bool NotNull(SymbolReference reference) => reference.SymbolResult.Symbol != null; public async Task<ImmutableArray<(Diagnostic Diagnostic, ImmutableArray<AddImportFixData> Fixes)>> GetFixesForDiagnosticsAsync( Document document, TextSpan span, ImmutableArray<Diagnostic> diagnostics, int maxResultsPerDiagnostic, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { // We might have multiple different diagnostics covering the same span. Have to // process them all as we might produce different fixes for each diagnostic. var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var placeSystemNamespaceFirst = documentOptions.GetOption(GenerationOptions.PlaceSystemNamespaceFirst); // Normally we don't allow generation into a hidden region in the file. However, if we have a // modern span mapper at our disposal, we do allow it as that host span mapper can handle mapping // our edit to their domain appropriate. var allowInHiddenRegions = document.CanAddImportsInHiddenRegions(); var fixesForDiagnosticBuilder = ArrayBuilder<(Diagnostic, ImmutableArray<AddImportFixData>)>.GetInstance(); foreach (var diagnostic in diagnostics) { var fixes = await GetFixesAsync( document, span, diagnostic.Id, maxResultsPerDiagnostic, placeSystemNamespaceFirst, allowInHiddenRegions, symbolSearchService, searchReferenceAssemblies, packageSources, cancellationToken).ConfigureAwait(false); fixesForDiagnosticBuilder.Add((diagnostic, fixes)); } return fixesForDiagnosticBuilder.ToImmutableAndFree(); } public ImmutableArray<CodeAction> GetCodeActionsForFixes( Document document, ImmutableArray<AddImportFixData> fixes, IPackageInstallerService installerService, int maxResults) { var codeActionsBuilder = ArrayBuilder<CodeAction>.GetInstance(); foreach (var fix in fixes) { var codeAction = TryCreateCodeAction(document, fix, installerService); codeActionsBuilder.AddIfNotNull(codeAction); if (codeActionsBuilder.Count >= maxResults) { break; } } return codeActionsBuilder.ToImmutableAndFree(); } private static CodeAction? TryCreateCodeAction(Document document, AddImportFixData fixData, IPackageInstallerService installerService) => fixData.Kind switch { AddImportFixKind.ProjectSymbol => new ProjectSymbolReferenceCodeAction(document, fixData), AddImportFixKind.MetadataSymbol => new MetadataSymbolReferenceCodeAction(document, fixData), AddImportFixKind.ReferenceAssemblySymbol => new AssemblyReferenceCodeAction(document, fixData), AddImportFixKind.PackageSymbol => !installerService.IsInstalled(document.Project.Solution.Workspace, document.Project.Id, fixData.PackageName) ? new ParentInstallPackageCodeAction(document, fixData, installerService) : null, _ => throw ExceptionUtilities.Unreachable, }; private static ITypeSymbol? GetAwaitInfo(SemanticModel semanticModel, ISyntaxFacts syntaxFactsService, SyntaxNode node) { var awaitExpression = FirstAwaitExpressionAncestor(syntaxFactsService, node); if (awaitExpression is null) return null; Debug.Assert(syntaxFactsService.IsAwaitExpression(awaitExpression)); var innerExpression = syntaxFactsService.GetExpressionOfAwaitExpression(awaitExpression); return semanticModel.GetTypeInfo(innerExpression).Type; } private static ITypeSymbol? GetCollectionExpressionType(SemanticModel semanticModel, ISyntaxFacts syntaxFactsService, SyntaxNode node) { var collectionExpression = FirstForeachCollectionExpressionAncestor(syntaxFactsService, node); if (collectionExpression is null) { return null; } return semanticModel.GetTypeInfo(collectionExpression).Type; } protected static bool AncestorOrSelfIsAwaitExpression(ISyntaxFacts syntaxFactsService, SyntaxNode node) => FirstAwaitExpressionAncestor(syntaxFactsService, node) != null; private static SyntaxNode? FirstAwaitExpressionAncestor(ISyntaxFacts syntaxFactsService, SyntaxNode node) => node.FirstAncestorOrSelf<SyntaxNode, ISyntaxFacts>((n, syntaxFactsService) => syntaxFactsService.IsAwaitExpression(n), syntaxFactsService); private static SyntaxNode? FirstForeachCollectionExpressionAncestor(ISyntaxFacts syntaxFactsService, SyntaxNode node) => node.FirstAncestorOrSelf<SyntaxNode, ISyntaxFacts>((n, syntaxFactsService) => syntaxFactsService.IsExpressionOfForeach(n), syntaxFactsService); } }
{ "content_hash": "17e2d725b4f2b9bada7e4a246ac403e9", "timestamp": "", "source": "github", "line_count": 578, "max_line_length": 228, "avg_line_length": 55.411764705882355, "alnum_prop": 0.6741288872236793, "repo_name": "stephentoub/roslyn", "id": "4e2a75a850a431b8c4394773d77b0a3764ed1c81", "size": "32030", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Features/Core/Portable/AddImport/AbstractAddImportFeatureService.cs", "mode": "33188", "license": "mit", "language": [ { "name": "1C Enterprise", "bytes": "257760" }, { "name": "Batchfile", "bytes": "8025" }, { "name": "C#", "bytes": "141577774" }, { "name": "C++", "bytes": "5602" }, { "name": "CMake", "bytes": "9153" }, { "name": "Dockerfile", "bytes": "2450" }, { "name": "F#", "bytes": "549" }, { "name": "PowerShell", "bytes": "242771" }, { "name": "Shell", "bytes": "94346" }, { "name": "Visual Basic .NET", "bytes": "71902552" } ], "symlink_target": "" }
using System; using System.ComponentModel; namespace EnumsNET.Tests.TestEnums { // Flag example [Flags] public enum ColorFlagEnum : sbyte { Black = 0, Red = 1, Green = 2, //Yellow = Red | Green, Blue = 4, //Magenta = Red | Blue, //Cyan = Green | Blue, //White = Red | Green | Blue, [Description("Ultra-Violet")] UltraViolet = 8, All = 15 } }
{ "content_hash": "f97bc9814ff5e087b448a62e25cc5418", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 37, "avg_line_length": 20.545454545454547, "alnum_prop": 0.5066371681415929, "repo_name": "TylerBrinkley/Enums.NET", "id": "0436178fde6e4bd71cca9dc2dab1e9c26846f9f6", "size": "454", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Src/Enums.NET.TestEnums/ColorFlagEnum.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1007930" }, { "name": "PowerShell", "bytes": "3303" } ], "symlink_target": "" }
package io.fabric8.maven.docker.util; import com.google.gson.JsonObject; import io.fabric8.maven.docker.access.AuthConfig; import org.apache.commons.codec.binary.Base64; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; /** * @author roland * @since 30.07.14 */ class AuthConfigTest { @Test void simpleConstructor() { Map<String,String> map = new HashMap<String,String>(); map.put(AuthConfig.AUTH_USERNAME,"roland"); map.put(AuthConfig.AUTH_PASSWORD,"#>secrets??"); map.put(AuthConfig.AUTH_EMAIL,"roland@jolokia.org"); AuthConfig config = new AuthConfig(map); check(config); } @Test void mapConstructor() { AuthConfig config = new AuthConfig("roland","#>secrets??","roland@jolokia.org",null); check(config); } @Test void dockerLoginConstructor() { AuthConfig config = new AuthConfig(Base64.encodeBase64String("roland:#>secrets??".getBytes()),"roland@jolokia.org"); check(config); } @Test void toJsonConfig() { AuthConfig config = new AuthConfig("king.roland", "12345", "king_roland@druidia.com", null); config.setRegistry("druidia.com/registry"); Assertions.assertEquals("{\"auths\":{\"druidia.com/registry\":{\"auth\":\"a2luZy5yb2xhbmQ6MTIzNDU=\"}}}", config.toJson()); } private void check(AuthConfig config) { // Since Base64.decodeBase64 handles URL-safe encoding, must explicitly check // the correct characters are used Assertions.assertEquals( "eyJ1c2VybmFtZSI6InJvbGFuZCIsInBhc3N3b3JkIjoiIz5zZWNyZXRzPz8iLCJlbWFpbCI6InJvbGFuZEBqb2xva2lhLm9yZyJ9", config.toHeaderValue() ); String header = new String(Base64.decodeBase64(config.toHeaderValue())); JsonObject data = JsonFactory.newJsonObject(header); Assertions.assertEquals("roland",data.get(AuthConfig.AUTH_USERNAME).getAsString()); Assertions.assertEquals("#>secrets??",data.get(AuthConfig.AUTH_PASSWORD).getAsString()); Assertions.assertEquals("roland@jolokia.org",data.get(AuthConfig.AUTH_EMAIL).getAsString()); Assertions.assertFalse(data.has(AuthConfig.AUTH_AUTH)); } }
{ "content_hash": "ab09fc42ff2162208a300fbf8e51a0b7", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 131, "avg_line_length": 35.8125, "alnum_prop": 0.6797556719022687, "repo_name": "vjuranek/docker-maven-plugin", "id": "79b694b986f444c146f960b587d308c8435310a4", "size": "2292", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/test/java/io/fabric8/maven/docker/util/AuthConfigTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "408" }, { "name": "CMake", "bytes": "997" }, { "name": "Dockerfile", "bytes": "2402" }, { "name": "Groovy", "bytes": "764" }, { "name": "Java", "bytes": "1730710" }, { "name": "Shell", "bytes": "9406" } ], "symlink_target": "" }
package org.appng.api; import org.appng.api.model.Application; import org.appng.api.model.Site; import org.appng.xml.platform.Action; import org.appng.xml.platform.Bean; import org.appng.xml.platform.BeanOption; import org.appng.xml.platform.Datasource; import org.appng.xml.platform.FieldDef; import org.appng.xml.platform.MetaData; /** * An {@link ActionProvider} usually performs a CRUD-action on a domain object. The implementing class needs to be * defined in the application's {@code beans.xml}. This bean is then being referenced in a concrete {@link Action}: * * <pre> * &lt;action id="update"> * &lt;config> * &lt;title id="issue.update" /> * &lt;params> * &lt;param name="form_action" /> * &lt;param name="issueName" /> * &lt;param name="edit" /> * &lt;/params> * &lt;/config> * &lt;condition expression="${form_action eq 'update' and not empty issueName}" /> * &lt;datasource id="issue"> * &lt;params> * &lt;param name="issueName">${issueName}&lt;/param> * &lt;param name="edit">${edit}&lt;/param> * &lt;/params> * &lt;/datasource> * &lt;bean id="issues"> * &lt;option name="action" id="update" issue="${issueName}" /> * &lt;/bean> * &lt;/action> * </pre> * * There is no need to implement one {@link ActionProvider} per {@link Action}, since the {@link Bean} can be * parameterized using different {@link BeanOption}s. So for example, the above defined bean could also be used for * creating a new domain object, using another {@link BeanOption}: * * <pre> * &lt;action id="create"> * &lt;config> * &lt;title id="issue.create" /> * &lt;/config> * &lt;condition expression="${form_action eq 'create'}" /> * &lt;datasource id="new_issue"> * &lt;params> * &lt;param name="form_action" /> * &lt;/params> * &lt;/datasource> * &lt;bean id="issues"> * &lt;option name="action" id="create" /> * &lt;/bean> * &lt;/action> * </pre> * * The distinction between create and update then can be done like this: * * <pre> * <code> * if ("create".equals(options.getOptionValue("action", "id"))) { * // create new domain object * } else if ("update".equals(options.getOptionValue("action", "id"))){ * // update existing domain object * }</code> * </pre> * * @author Matthias Müller * * @param <T> * the bean type for this {@link ActionProvider}s {@code perform(...)}-method. Must match * {@link MetaData#getBindClass()} of the {@link Datasource} used by the {@link Action} */ public interface ActionProvider<T> { /** * Performs an action on the given {@code formBean} * * @param site * the current {@link Site} * @param application * the current {@link Application} * @param environment * the current {@link Environment} * @param options * the {@link Options} for this {@link ActionProvider} * @param request * the current {@link Request} * @param formBean * the bean which has been created * @param fieldProcessor * the {@link FieldProcessor} containing all writable {@link FieldDef}initions for this action */ void perform(Site site, Application application, Environment environment, Options options, Request request, T formBean, FieldProcessor fieldProcessor); }
{ "content_hash": "d3227860eda8e955aaacf62ca70f3643", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 117, "avg_line_length": 35.2970297029703, "alnum_prop": 0.5997194950911641, "repo_name": "appNG/appng", "id": "df2048fc398efdeb490697bc96930b7842152dae", "size": "4185", "binary": false, "copies": "1", "ref": "refs/heads/appng-1.25.x", "path": "appng-api/src/main/java/org/appng/api/ActionProvider.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1448" }, { "name": "CSS", "bytes": "58943" }, { "name": "Dockerfile", "bytes": "2107" }, { "name": "FreeMarker", "bytes": "790" }, { "name": "HTML", "bytes": "30413" }, { "name": "Java", "bytes": "4204904" }, { "name": "Mustache", "bytes": "8550" }, { "name": "Shell", "bytes": "6527" }, { "name": "Standard ML", "bytes": "256" }, { "name": "TSQL", "bytes": "12467" }, { "name": "XSLT", "bytes": "8278" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "22be749d6e24c8facf7b2c77fd893dd4", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "168c5fc088ee6e70dbf3efe3bc475dc9de573ca1", "size": "176", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lamiaceae/Coleus/Coleus djalonensis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <!-- PROJECT --> <parent> <groupId>no.acntech.sandbox</groupId> <artifactId>spring-boot</artifactId> <version>1.0.0-SNAPSHOT</version> </parent> <artifactId>spring-boot-access-control-thymeleaf</artifactId> <packaging>war</packaging> <!-- PROPERTIES --> <properties> </properties> <!-- DEPENDENCIES --> <dependencies> <!-- Spring Framework --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <!-- Thymeleaf --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>nz.net.ultraq.thymeleaf</groupId> <artifactId>thymeleaf-layout-dialect</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity5</artifactId> </dependency> <!-- Security --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- WebJars --> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>webjars-locator</artifactId> </dependency> </dependencies> <!-- BUILD --> <build> <!-- PLUGINS --> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
{ "content_hash": "e59797027768511524ea198d2c18511a", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 108, "avg_line_length": 32.10126582278481, "alnum_prop": 0.5761041009463722, "repo_name": "acntech/acntech-sandbox", "id": "8e80e662c08cf3758f400f8d9874962da8c9740c", "size": "2536", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "spring-boot/access-control-thymeleaf/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2078" }, { "name": "HTML", "bytes": "103744" }, { "name": "Java", "bytes": "384700" }, { "name": "JavaScript", "bytes": "11114" }, { "name": "Kotlin", "bytes": "934" }, { "name": "Shell", "bytes": "3028" }, { "name": "TypeScript", "bytes": "10021" } ], "symlink_target": "" }
.class Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController$1; .super Ljava/lang/Object; .source "MuteAllSoundsPreferenceController.java" # interfaces .implements Landroid/content/DialogInterface$OnClickListener; # annotations .annotation system Ldalvik/annotation/EnclosingMethod; value = Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController;->showAccFeatureConfirmDialog(Landroid/support/v7/preference/Preference;)V .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x0 name = null .end annotation # instance fields .field final synthetic this$0:Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController; .field final synthetic val$checkbox:Landroid/widget/CheckBox; # direct methods .method constructor <init>(Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController;Landroid/widget/CheckBox;)V .locals 0 iput-object p1, p0, Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController$1;->this$0:Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController; iput-object p2, p0, Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController$1;->val$checkbox:Landroid/widget/CheckBox; invoke-direct {p0}, Ljava/lang/Object;-><init>()V return-void .end method # virtual methods .method public onClick(Landroid/content/DialogInterface;I)V .locals 9 const/4 v8, 0x2 const/4 v7, 0x1 iget-object v4, p0, Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController$1;->this$0:Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController; invoke-static {v4}, Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController;->-get0(Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController;)Landroid/content/Context; move-result-object v4 const-string/jumbo v5, "accessibility_feature_confirm_dialog" const/4 v6, 0x0 invoke-virtual {v4, v5, v6}, Landroid/content/Context;->getSharedPreferences(Ljava/lang/String;I)Landroid/content/SharedPreferences; move-result-object v3 invoke-interface {v3}, Landroid/content/SharedPreferences;->edit()Landroid/content/SharedPreferences$Editor; move-result-object v1 const-string/jumbo v4, "all_sound_off_key_dialog_do_not_show_again" iget-object v5, p0, Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController$1;->val$checkbox:Landroid/widget/CheckBox; invoke-virtual {v5}, Landroid/widget/CheckBox;->isChecked()Z move-result v5 invoke-interface {v1, v4, v5}, Landroid/content/SharedPreferences$Editor;->putBoolean(Ljava/lang/String;Z)Landroid/content/SharedPreferences$Editor; invoke-interface {v1}, Landroid/content/SharedPreferences$Editor;->apply()V new-instance v0, Landroid/content/Intent; const-string/jumbo v4, "android.settings.ALL_SOUND_MUTE" invoke-direct {v0, v4}, Landroid/content/Intent;-><init>(Ljava/lang/String;)V iget-object v4, p0, Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController$1;->this$0:Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController; invoke-static {v4}, Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController;->-get0(Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController;)Landroid/content/Context; move-result-object v4 invoke-static {v4}, Lcom/android/settings/Utils;->isTalkBackEnabled(Landroid/content/Context;)Z move-result v4 if-eqz v4, :cond_1 iget-object v4, p0, Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController$1;->this$0:Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController; invoke-static {v4}, Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController;->-wrap2(Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController;)V :cond_0 :goto_0 iget-object v4, p0, Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController$1;->this$0:Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController; invoke-static {v4}, Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController;->-get0(Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController;)Landroid/content/Context; move-result-object v4 sget-object v5, Landroid/os/UserHandle;->ALL:Landroid/os/UserHandle; invoke-virtual {v4, v0, v5}, Landroid/content/Context;->sendBroadcastAsUser(Landroid/content/Intent;Landroid/os/UserHandle;)V iget-object v4, p0, Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController$1;->this$0:Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController; invoke-static {v4}, Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController;->-get0(Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController;)Landroid/content/Context; move-result-object v4 iget-object v5, p0, Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController$1;->this$0:Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController; invoke-static {v5}, Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController;->-get0(Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController;)Landroid/content/Context; move-result-object v5 invoke-virtual {v5}, Landroid/content/Context;->getResources()Landroid/content/res/Resources; move-result-object v5 const v6, 0x7f0b007e invoke-virtual {v5, v6}, Landroid/content/res/Resources;->getInteger(I)I move-result v5 const/16 v6, 0x3e8 invoke-static {v6}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer; move-result-object v6 invoke-static {v4, v5, v6}, Lcom/android/settings/Utils;->insertEventwithDetailLog(Landroid/content/Context;ILjava/lang/Object;)V const-string/jumbo v4, "MuteAllSoundsController" const-string/jumbo v5, "All sound off broadcast" invoke-static {v4, v5}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I return-void :cond_1 iget-object v4, p0, Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController$1;->this$0:Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController; invoke-static {v4}, Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController;->-get0(Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController;)Landroid/content/Context; move-result-object v4 invoke-virtual {v4}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver; move-result-object v4 const-string/jumbo v5, "all_sound_off" invoke-static {v4, v5, v7}, Landroid/provider/Settings$System;->putInt(Landroid/content/ContentResolver;Ljava/lang/String;I)Z const-string/jumbo v4, "mute" invoke-virtual {v0, v4, v7}, Landroid/content/Intent;->putExtra(Ljava/lang/String;I)Landroid/content/Intent; iget-object v4, p0, Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController$1;->this$0:Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController; invoke-static {v4}, Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController;->-wrap0(Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController;)Z move-result v4 if-eqz v4, :cond_0 iget-object v4, p0, Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController$1;->this$0:Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController; invoke-static {v4}, Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController;->-get0(Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController;)Landroid/content/Context; move-result-object v4 invoke-virtual {v4}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver; move-result-object v4 const-string/jumbo v5, "callsettings_answer_memo" invoke-static {v4, v5, v8}, Landroid/provider/Settings$System;->getInt(Landroid/content/ContentResolver;Ljava/lang/String;I)I move-result v2 iget-object v4, p0, Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController$1;->this$0:Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController; invoke-static {v4, v2}, Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController;->-wrap1(Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController;I)V iget-object v4, p0, Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController$1;->this$0:Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController; invoke-static {v4}, Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController;->-get0(Lcom/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController;)Landroid/content/Context; move-result-object v4 invoke-virtual {v4}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver; move-result-object v4 const-string/jumbo v5, "callsettings_answer_memo" invoke-static {v4, v5, v8}, Landroid/provider/Settings$System;->putInt(Landroid/content/ContentResolver;Ljava/lang/String;I)Z goto :goto_0 .end method
{ "content_hash": "62028611f3c69e7eaa39bd15beb5074c", "timestamp": "", "source": "github", "line_count": 212, "max_line_length": 230, "avg_line_length": 47.221698113207545, "alnum_prop": 0.8024173409249825, "repo_name": "BatMan-Rom/ModdedFiles", "id": "06cc1f64a98b5475f3bc98ffa323e182dea6a8bb", "size": "10011", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SecSettings/smali/com/samsung/android/settings/accessibility/hearing/MuteAllSoundsPreferenceController$1.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GLSL", "bytes": "15069" }, { "name": "HTML", "bytes": "139176" }, { "name": "Smali", "bytes": "541934400" } ], "symlink_target": "" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__new_delete_array_struct_17.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__new_delete_array.label.xml Template File: sources-sinks-17.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: Allocate data using new * GoodSource: Allocate data using new [] * Sinks: * GoodSink: Deallocate data using delete * BadSink : Deallocate data using delete [] * Flow Variant: 17 Control flow: for loops * */ #include "std_testcase.h" namespace CWE762_Mismatched_Memory_Management_Routines__new_delete_array_struct_17 { #ifndef OMITBAD void bad() { int i,j; twoIntsStruct * data; /* Initialize data*/ data = NULL; for(i = 0; i < 1; i++) { /* POTENTIAL FLAW: Allocate memory with a function that requires delete to free the memory */ data = new twoIntsStruct; } for(j = 0; j < 1; j++) { /* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may * require a call to delete to deallocate the memory */ delete [] data; } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodB2G() - use badsource and goodsink in the for statements */ static void goodB2G() { int i,k; twoIntsStruct * data; /* Initialize data*/ data = NULL; for(i = 0; i < 1; i++) { /* POTENTIAL FLAW: Allocate memory with a function that requires delete to free the memory */ data = new twoIntsStruct; } for(k = 0; k < 1; k++) { /* FIX: Deallocate the memory using delete */ delete data; } } /* goodG2B() - use goodsource and badsink in the for statements */ static void goodG2B() { int h,j; twoIntsStruct * data; /* Initialize data*/ data = NULL; for(h = 0; h < 1; h++) { /* FIX: Allocate memory from the heap using new [] */ data = new twoIntsStruct[100]; } for(j = 0; j < 1; j++) { /* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may * require a call to delete to deallocate the memory */ delete [] data; } } void good() { goodB2G(); goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE762_Mismatched_Memory_Management_Routines__new_delete_array_struct_17; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
{ "content_hash": "ae8ad1bd529f0cc29d427565e191e652", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 134, "avg_line_length": 26.827868852459016, "alnum_prop": 0.615032080659945, "repo_name": "maurer/tiamat", "id": "141187707a280d725e06c7eb0b4c2c7ea2bdd537", "size": "3273", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "samples/Juliet/testcases/CWE762_Mismatched_Memory_Management_Routines/s06/CWE762_Mismatched_Memory_Management_Routines__new_delete_array_struct_17.cpp", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
%VGG_QPBO Binary MRF energy minimization on non-submodular graphs % % [L stats] = vgg_qpbo(UE, PI, PE, [TI, TE], [options]) % % Uses the Quadratic Pseudo-Boolean Optimization (QPBO - an extension of % graph cuts that solves the "roof duality" problem, allowing graphs with % submodular edges to be solved) to solve binary, pairwise and triple % clique MRF energy minimization problems. % % The algorithm can be viewed as fusing two labellings in such a way as to % minimize output labellings energy: % L = FUSE(L0, L1) % In particular the solution has these properties: % P1: Not all nodes are labelled. Nodes which are labelled form part of % an optimal labelling. % P2: If all unlabelled nodes in L are fixed to L0, then E(L) <= E(L0). % % This function also implements QPBO-P and QPBO-I. See "Optimizing binary % MRFs via extended roof duality", Rother et al., CVPR 2007, for more % details. % % This function uses mexified C++ code downloaded from www page of Vladimir % Kolmogorov. To acknowledge him/reference the correct papers, see his web % page for details. % % IN: % UE - 2xM matrix of unary terms for M nodes, or M = UE(1) if numel(UE) % == 1 (assumes all unary terms are zero). UE can be any type, but % PE and TE must be of the same type; also, optimality is not % guaranteed for non-integer types. % PI - {2,3}xN uint32 matrix, each column containing the following % information on an edge: [start_node end_node % [pairwise_energy_table_index]]. If there are only 2 rows then % pairwise_energy_table_index is assumed to be the column number, % therefore you must have N == P. % PE - 4xP pairwise energy table, each column containing the energies % [E00 E01 E10 E11] for a given edge. % TI - {3,4}xQ uint32 matrix, each column containing the following % information on a triple clique: [node1 node2 node3 % [triple_clique_energy_table_index]]. If there are only 3 rows then % triple_clique_energy_table_index is assumed to be the column % number, therefore you must have Q == R. % TE - 8xR triple clique energy table, each column containing the % energies [E000 E001 E010 E011 E100 E101 E110 E111] for a given % triple clique. % options - 2x1 cell array. options{1} is a 1x4 uint32 vector of optional % parameters: % FirstNNodes - Only labels of nodes 1:FirstNNodes will be output. % Also limits nodes considered in QPBO-P and QPBO-I. % Default: M. % ImproveMethod - 0: Unlabelled nodes not improved; 1: QPBO-I % employed, assuming preferred label is L0. 2: QPBO-I % employed, using user-defined labelling returned by % callback_func. % ContractIters - Number of iterations of QPBO-P to do. Default: 0. % LargerInternal - 0: input type also used internally; 1: code uses a % larger representation (i.e. more bits) for energies % than that provided, reducing the possibility of % edges becoming saturated. Default: 0. % options{2} - callback_func, a function name or handle which, % given the labelling L (the first output of this % function), returns a logical array of the same % size defining a labelling to be transfromed by % QPBO-I. % % OUT: % L - 1xFirstNNodes int32 matrix of the energy minimizing state of each % node. Labels {0,1} are the optimal label (in a weak sense), while % labels < 0 indicate unlabelled nodes. For unlabelled nodes, if L(x) % == L(y) then x and y are in the same "strongly connected region". % stats - 3x1 int32 vector of stats: % stats(1) - number of unlabelled pixels % stats(2) - number of strongly connected regions of unlabelled pixels % stats(3) - number of unlabelled pixels after running QPBO-P % $Id: vgg_qpbo.m,v 1.1 2007/12/07 11:27:56 ojw Exp $ function varargout = vgg_qpbo(varargin) funcName = mfilename; sd = 'qpbo/'; sourceList = {['-I' sd], [funcName '.cxx'], [sd 'QPBO.cpp'],... [sd 'QPBO_maxflow.cpp'], [sd 'QPBO_extra.cpp'],... [sd 'QPBO_postprocessing.cpp']}; vgg_mexcompile_script; % Compilation happens in this script return
{ "content_hash": "efbd63c24e5c764cd2ddb808ee1c50b0", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 75, "avg_line_length": 52.752941176470586, "alnum_prop": 0.6378233719892953, "repo_name": "batra-mlp-lab/divmbest", "id": "d7804333c5d60706844cecf46652b88ffa19ff8a", "size": "4484", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "intseg/utils/imrender/vgg/vgg_qpbo.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "130460" }, { "name": "C", "bytes": "2122655" }, { "name": "C++", "bytes": "1666810" }, { "name": "CSS", "bytes": "23115" }, { "name": "Clean", "bytes": "14936" }, { "name": "D", "bytes": "69811" }, { "name": "Erlang", "bytes": "1523" }, { "name": "FORTRAN", "bytes": "199327" }, { "name": "HTML", "bytes": "239285" }, { "name": "Java", "bytes": "97728" }, { "name": "JavaScript", "bytes": "12268" }, { "name": "M", "bytes": "48164" }, { "name": "Makefile", "bytes": "107939" }, { "name": "Matlab", "bytes": "2030727" }, { "name": "Objective-C", "bytes": "73135" }, { "name": "Perl", "bytes": "37972" }, { "name": "Prolog", "bytes": "2200" }, { "name": "Python", "bytes": "180656" }, { "name": "Ruby", "bytes": "566" }, { "name": "Scala", "bytes": "901" }, { "name": "Shell", "bytes": "39000" }, { "name": "Stata", "bytes": "13389" } ], "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_66) on Tue Mar 08 13:38:46 EST 2016 --> <title>Uses of Interface protos.Chaincode.ChaincodeIdentifierOrBuilder</title> <meta name="date" content="2016-03-08"> <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 Interface protos.Chaincode.ChaincodeIdentifierOrBuilder"; } } 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="../../protos/Chaincode.ChaincodeIdentifierOrBuilder.html" title="interface in protos">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-files/index-1.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../index.html?protos/class-use/Chaincode.ChaincodeIdentifierOrBuilder.html" target="_top">Frames</a></li> <li><a href="Chaincode.ChaincodeIdentifierOrBuilder.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 Interface protos.Chaincode.ChaincodeIdentifierOrBuilder" class="title">Uses of Interface<br>protos.Chaincode.ChaincodeIdentifierOrBuilder</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="../../protos/Chaincode.ChaincodeIdentifierOrBuilder.html" title="interface in protos">Chaincode.ChaincodeIdentifierOrBuilder</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="#protos">protos</a></td> <td class="colLast"> <div class="block">Contains the objects compiled with Google Protocol Buffer.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="protos"> <!-- --> </a> <h3>Uses of <a href="../../protos/Chaincode.ChaincodeIdentifierOrBuilder.html" title="interface in protos">Chaincode.ChaincodeIdentifierOrBuilder</a> in <a href="../../protos/package-summary.html">protos</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="../../protos/package-summary.html">protos</a> that implement <a href="../../protos/Chaincode.ChaincodeIdentifierOrBuilder.html" title="interface in protos">Chaincode.ChaincodeIdentifierOrBuilder</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>static class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../protos/Chaincode.ChaincodeIdentifier.html" title="class in protos">Chaincode.ChaincodeIdentifier</a></span></code> <div class="block">Protobuf type <code>protos.ChaincodeIdentifier</code></div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../protos/Chaincode.ChaincodeIdentifier.Builder.html" title="class in protos">Chaincode.ChaincodeIdentifier.Builder</a></span></code> <div class="block">Protobuf type <code>protos.ChaincodeIdentifier</code></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="../../protos/package-summary.html">protos</a> that return <a href="../../protos/Chaincode.ChaincodeIdentifierOrBuilder.html" title="interface in protos">Chaincode.ChaincodeIdentifierOrBuilder</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="../../protos/Chaincode.ChaincodeIdentifierOrBuilder.html" title="interface in protos">Chaincode.ChaincodeIdentifierOrBuilder</a></code></td> <td class="colLast"><span class="typeNameLabel">Chaincode.ChaincodeExecutionContextOrBuilder.</span><code><span class="memberNameLink"><a href="../../protos/Chaincode.ChaincodeExecutionContextOrBuilder.html#getChaincodeIdOrBuilder--">getChaincodeIdOrBuilder</a></span>()</code> <div class="block"><code>optional .protos.ChaincodeIdentifier ChaincodeId = 1;</code></div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../protos/Chaincode.ChaincodeIdentifierOrBuilder.html" title="interface in protos">Chaincode.ChaincodeIdentifierOrBuilder</a></code></td> <td class="colLast"><span class="typeNameLabel">Chaincode.ChaincodeExecutionContext.</span><code><span class="memberNameLink"><a href="../../protos/Chaincode.ChaincodeExecutionContext.html#getChaincodeIdOrBuilder--">getChaincodeIdOrBuilder</a></span>()</code> <div class="block"><code>optional .protos.ChaincodeIdentifier ChaincodeId = 1;</code></div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../protos/Chaincode.ChaincodeIdentifierOrBuilder.html" title="interface in protos">Chaincode.ChaincodeIdentifierOrBuilder</a></code></td> <td class="colLast"><span class="typeNameLabel">Chaincode.ChaincodeExecutionContext.Builder.</span><code><span class="memberNameLink"><a href="../../protos/Chaincode.ChaincodeExecutionContext.Builder.html#getChaincodeIdOrBuilder--">getChaincodeIdOrBuilder</a></span>()</code> <div class="block"><code>optional .protos.ChaincodeIdentifier ChaincodeId = 1;</code></div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../protos/Chaincode.ChaincodeIdentifierOrBuilder.html" title="interface in protos">Chaincode.ChaincodeIdentifierOrBuilder</a></code></td> <td class="colLast"><span class="typeNameLabel">Chaincode.ChaincodeRequestContextOrBuilder.</span><code><span class="memberNameLink"><a href="../../protos/Chaincode.ChaincodeRequestContextOrBuilder.html#getIdOrBuilder--">getIdOrBuilder</a></span>()</code> <div class="block"><code>optional .protos.ChaincodeIdentifier Id = 1;</code></div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../protos/Chaincode.ChaincodeIdentifierOrBuilder.html" title="interface in protos">Chaincode.ChaincodeIdentifierOrBuilder</a></code></td> <td class="colLast"><span class="typeNameLabel">Chaincode.ChaincodeRequestContext.</span><code><span class="memberNameLink"><a href="../../protos/Chaincode.ChaincodeRequestContext.html#getIdOrBuilder--">getIdOrBuilder</a></span>()</code> <div class="block"><code>optional .protos.ChaincodeIdentifier Id = 1;</code></div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../protos/Chaincode.ChaincodeIdentifierOrBuilder.html" title="interface in protos">Chaincode.ChaincodeIdentifierOrBuilder</a></code></td> <td class="colLast"><span class="typeNameLabel">Chaincode.ChaincodeRequestContext.Builder.</span><code><span class="memberNameLink"><a href="../../protos/Chaincode.ChaincodeRequestContext.Builder.html#getIdOrBuilder--">getIdOrBuilder</a></span>()</code> <div class="block"><code>optional .protos.ChaincodeIdentifier Id = 1;</code></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="../../protos/Chaincode.ChaincodeIdentifierOrBuilder.html" title="interface in protos">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-files/index-1.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../index.html?protos/class-use/Chaincode.ChaincodeIdentifierOrBuilder.html" target="_top">Frames</a></li> <li><a href="Chaincode.ChaincodeIdentifierOrBuilder.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "77f2841fbee20414f4668532511beb4a", "timestamp": "", "source": "github", "line_count": 219, "max_line_length": 284, "avg_line_length": 48.278538812785385, "alnum_prop": 0.7016929915823323, "repo_name": "quentinlesceller/OBC4J", "id": "3196bc932d8ac873cdf2c6dc5b9f7212a42e08cc", "size": "10573", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/protos/class-use/Chaincode.ChaincodeIdentifierOrBuilder.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "112946" }, { "name": "Protocol Buffer", "bytes": "19707" }, { "name": "Shell", "bytes": "616" } ], "symlink_target": "" }
<?php namespace Doctrine\Tests\DBAL\Schema\Synchronizer; use Doctrine\DBAL\DriverManager; use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\Synchronizer\SingleDatabaseSynchronizer; class SingleDatabaseSynchronizerTest extends \PHPUnit\Framework\TestCase { private $conn; private $synchronizer; protected function setUp() { $this->conn = DriverManager::getConnection(array( 'driver' => 'pdo_sqlite', 'memory' => true, )); $this->synchronizer = new SingleDatabaseSynchronizer($this->conn); } public function testGetCreateSchema() { $schema = new Schema(); $table = $schema->createTable('test'); $table->addColumn('id', 'integer'); $table->setPrimaryKey(array('id')); $sql = $this->synchronizer->getCreateSchema($schema); self::assertEquals(array('CREATE TABLE test (id INTEGER NOT NULL, PRIMARY KEY(id))'), $sql); } public function testGetUpdateSchema() { $schema = new Schema(); $table = $schema->createTable('test'); $table->addColumn('id', 'integer'); $table->setPrimaryKey(array('id')); $sql = $this->synchronizer->getUpdateSchema($schema); self::assertEquals(array('CREATE TABLE test (id INTEGER NOT NULL, PRIMARY KEY(id))'), $sql); } public function testGetDropSchema() { $schema = new Schema(); $table = $schema->createTable('test'); $table->addColumn('id', 'integer'); $table->setPrimaryKey(array('id')); $this->synchronizer->createSchema($schema); $sql = $this->synchronizer->getDropSchema($schema); self::assertEquals(array('DROP TABLE test'), $sql); } public function testGetDropAllSchema() { $schema = new Schema(); $table = $schema->createTable('test'); $table->addColumn('id', 'integer'); $table->setPrimaryKey(array('id')); $this->synchronizer->createSchema($schema); $sql = $this->synchronizer->getDropAllSchema(); self::assertEquals(array('DROP TABLE test'), $sql); } }
{ "content_hash": "ad11b06283975ef6749696a3982e9717", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 100, "avg_line_length": 29.625, "alnum_prop": 0.6150961087669948, "repo_name": "gencer/dbal", "id": "06b30e08d286879c06a57e52fbae8d03c07fb7b9", "size": "3114", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tests/Doctrine/Tests/DBAL/Schema/Synchronizer/SingleDatabaseSynchronizerTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "2525029" }, { "name": "Shell", "bytes": "1898" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>compcert: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.7.1+1 / compcert - 3.0.1</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> compcert <small> 3.0.1 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-11-12 06:37:06 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-12 06:37:06 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.7.1+1 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.04.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.04.2 Official 4.04.2 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Matej Košík &lt;matej.kosik@inria.fr&gt;&quot; homepage: &quot;http://compcert.inria.fr/&quot; dev-repo: &quot;git+https://github.com/AbsInt/CompCert.git&quot; bug-reports: &quot;https://github.com/AbsInt/CompCert/issues&quot; license: &quot;INRIA Non-Commercial License Agreement&quot; build: [ [ &quot;./configure&quot; &quot;ia32-linux&quot; {os = &quot;linux&quot;} &quot;ia32-macosx&quot; {os = &quot;macos&quot;} &quot;ia32-cygwin&quot; {os = &quot;cygwin&quot;} &quot;-bindir&quot; &quot;%{bin}%&quot; &quot;-libdir&quot; &quot;%{lib}%/compcert&quot; &quot;-clightgen&quot; ] [make &quot;-j%{jobs}%&quot;] ] install: [ [make &quot;install&quot;] ] remove: [ [&quot;rm&quot; &quot;%{bin}%/ccomp&quot;] [&quot;rm&quot; &quot;%{bin}%/clightgen&quot;] [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/compcert&quot;] [&quot;rm&quot; &quot;%{share}%/compcert.ini&quot;] ] depends: [ &quot;ocaml&quot; &quot;coq&quot; {= &quot;8.6&quot;} &quot;menhir&quot; {&gt;= &quot;20160303&quot; &amp; &lt; &quot;20180530&quot;} ] synopsis: &quot;The CompCert C compiler&quot; authors: &quot;Xavier Leroy &lt;xavier.leroy@inria.fr&gt;&quot; flags: light-uninstall url { src: &quot;https://github.com/AbsInt/CompCert/archive/v3.0.1.tar.gz&quot; checksum: &quot;md5=76af0b470261df6b19053a60474fc84a&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-compcert.3.0.1 coq.8.7.1+1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.7.1+1). The following dependencies couldn&#39;t be met: - coq-compcert -&gt; coq = 8.6 Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-compcert.3.0.1</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "f2af3462065a4ab26c51db4730e72da0", "timestamp": "", "source": "github", "line_count": 183, "max_line_length": 159, "avg_line_length": 39.049180327868854, "alnum_prop": 0.5348446683459278, "repo_name": "coq-bench/coq-bench.github.io", "id": "ea6e8f302f8362e914a9b90a04d8fd49adccab99", "size": "7173", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.04.2-2.0.5/released/8.7.1+1/compcert/3.0.1.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Calicium peraffine Speg. ### Remarks null
{ "content_hash": "145c62997ec4d3a7c666bc50ea366d7e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 24, "avg_line_length": 9.923076923076923, "alnum_prop": 0.7054263565891473, "repo_name": "mdoering/backbone", "id": "78547fb7f332f4fa1521df77661a7c62d477904d", "size": "211", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Lecanoromycetes/Teloschistales/Caliciaceae/Calicium/Calicium cinereorufescens/Calicium cinereorufescens peraffine/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import * as log4js from "log4js"; import * as util from "util"; import * as stream from "stream"; import * as marked from "marked"; const TerminalRenderer = require("marked-terminal"); const chalk = require("chalk"); export class Logger implements ILogger { private log4jsLogger: log4js.ILogger = null; private passwordRegex = /(password=).*?(['&,]|$)|(password["']?\s*:\s*["']).*?(["'])/i; private passwordReplacement = "$1$3*******$2$4"; private static LABEL = "[WARNING]:"; constructor($config: Config.IConfig, private $options: ICommonOptions) { const appenders: log4js.IAppender[] = []; if (!$config.CI_LOGGER) { appenders.push({ type: "console", layout: { type: "messagePassThrough" } }); } log4js.configure({ appenders: appenders }); this.log4jsLogger = log4js.getLogger(); if (this.$options.log) { this.log4jsLogger.setLevel(this.$options.log); } else { this.log4jsLogger.setLevel($config.DEBUG ? "TRACE" : "INFO"); } } setLevel(level: string): void { this.log4jsLogger.setLevel(level); } getLevel(): string { return this.log4jsLogger.level.toString(); } fatal(...args: string[]): void { this.log4jsLogger.fatal.apply(this.log4jsLogger, args); } error(...args: string[]): void { const message = util.format.apply(null, args); const colorizedMessage = message.red; this.log4jsLogger.error.apply(this.log4jsLogger, [colorizedMessage]); } warn(...args: string[]): void { const message = util.format.apply(null, args); const colorizedMessage = message.yellow; this.log4jsLogger.warn.apply(this.log4jsLogger, [colorizedMessage]); } warnWithLabel(...args: string[]): void { const message = util.format.apply(null, args); this.warn(`${Logger.LABEL} ${message}`); } info(...args: string[]): void { this.log4jsLogger.info.apply(this.log4jsLogger, args); } debug(...args: string[]): void { const encodedArgs: string[] = this.getPasswordEncodedArguments(args); this.log4jsLogger.debug.apply(this.log4jsLogger, encodedArgs); } trace(...args: string[]): void { const encodedArgs: string[] = this.getPasswordEncodedArguments(args); this.log4jsLogger.trace.apply(this.log4jsLogger, encodedArgs); } out(...args: string[]): void { console.log(util.format.apply(null, args)); } write(...args: string[]): void { process.stdout.write(util.format.apply(null, args)); } prepare(item: any): string { if (typeof item === "undefined" || item === null) { return "[no content]"; } if (typeof item === "string") { return item; } // do not try to read streams, because they may not be rewindable if (item instanceof stream.Readable) { return "[ReadableStream]"; } // There's no point in printing buffers if (item instanceof Buffer) { return "[Buffer]"; } return JSON.stringify(item); } public printInfoMessageOnSameLine(message: string): void { if (!this.$options.log || this.$options.log === "info") { this.write(message); } } public printMsgWithTimeout(message: string, timeout: number): Promise<void> { return new Promise<void>((resolve, reject) => { setTimeout(() => { this.printInfoMessageOnSameLine(message); resolve(); }, timeout); }); } public printMarkdown(...args: string[]): void { const opts = { unescape: true, link: chalk.red, tableOptions: { chars: { 'mid': '', 'left-mid': '', 'mid-mid': '', 'right-mid': '' }, style: { 'padding-left': 1, 'padding-right': 1, head: ['green', 'bold'], border: ['grey'], compact: false } } }; marked.setOptions({ renderer: new TerminalRenderer(opts) }); const formattedMessage = marked(util.format.apply(null, args)); this.write(formattedMessage); } private getPasswordEncodedArguments(args: string[]): string[] { return _.map(args, argument => { if (typeof argument === 'string' && !!argument.match(/password/i)) { argument = argument.replace(this.passwordRegex, this.passwordReplacement); } return argument; }); } } $injector.register("logger", Logger);
{ "content_hash": "2072dd3e182273bce6f9f5da093e2afc", "timestamp": "", "source": "github", "line_count": 159, "max_line_length": 88, "avg_line_length": 25.58490566037736, "alnum_prop": 0.6541297935103245, "repo_name": "telerik/mobile-cli-lib", "id": "c05504689c8aeccfccc376be6eb5356572d5007b", "size": "4068", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "logger.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "6099" }, { "name": "TypeScript", "bytes": "1025015" } ], "symlink_target": "" }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using NUnit.Framework; using osu.Framework.Platform; using osu.Game.IPC; using osu.Framework.Allocation; using osu.Framework.Extensions; using osu.Framework.Extensions.ObjectExtensions; using osu.Framework.Logging; using osu.Game.Beatmaps; using osu.Game.Database; using osu.Game.IO; using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Scoring; using osu.Game.Tests.Resources; using osu.Game.Tests.Scores.IO; using osu.Game.Users; using SharpCompress.Archives; using SharpCompress.Archives.Zip; using SharpCompress.Common; using SharpCompress.Writers.Zip; using FileInfo = System.IO.FileInfo; namespace osu.Game.Tests.Beatmaps.IO { [TestFixture] public class ImportBeatmapTest : ImportTest { [Test] public async Task TestImportWhenClosed() { // unfortunately for the time being we need to reference osu.Framework.Desktop for a game host here. using (HeadlessGameHost host = new CleanRunHeadlessGameHost(nameof(ImportBeatmapTest))) { try { await LoadOszIntoOsu(LoadOsuIntoHost(host)); } finally { host.Exit(); } } } [Test] public async Task TestImportThenDelete() { // unfortunately for the time being we need to reference osu.Framework.Desktop for a game host here. using (HeadlessGameHost host = new CleanRunHeadlessGameHost(nameof(ImportBeatmapTest))) { try { var osu = LoadOsuIntoHost(host); var imported = await LoadOszIntoOsu(osu); deleteBeatmapSet(imported, osu); } finally { host.Exit(); } } } [Test] public async Task TestImportThenDeleteFromStream() { // unfortunately for the time being we need to reference osu.Framework.Desktop for a game host here. using (HeadlessGameHost host = new CleanRunHeadlessGameHost(nameof(ImportBeatmapTest))) { try { var osu = LoadOsuIntoHost(host); var tempPath = TestResources.GetTestBeatmapForImport(); var manager = osu.Dependencies.Get<BeatmapManager>(); ILive<BeatmapSetInfo> importedSet; using (var stream = File.OpenRead(tempPath)) { importedSet = await manager.Import(new ImportTask(stream, Path.GetFileName(tempPath))); ensureLoaded(osu); } Assert.IsTrue(File.Exists(tempPath), "Stream source file somehow went missing"); File.Delete(tempPath); var imported = manager.GetAllUsableBeatmapSets().Find(beatmapSet => beatmapSet.ID == importedSet.Value.ID); deleteBeatmapSet(imported, osu); } finally { host.Exit(); } } } [Test] public async Task TestImportThenImport() { // unfortunately for the time being we need to reference osu.Framework.Desktop for a game host here. using (HeadlessGameHost host = new CleanRunHeadlessGameHost(nameof(ImportBeatmapTest))) { try { var osu = LoadOsuIntoHost(host); var imported = await LoadOszIntoOsu(osu); var importedSecondTime = await LoadOszIntoOsu(osu); // check the newly "imported" beatmap is actually just the restored previous import. since it matches hash. Assert.IsTrue(imported.ID == importedSecondTime.ID); Assert.IsTrue(imported.Beatmaps.First().ID == importedSecondTime.Beatmaps.First().ID); checkBeatmapSetCount(osu, 1); checkSingleReferencedFileCount(osu, 18); } finally { host.Exit(); } } } [Test] public async Task TestImportThenImportWithReZip() { using (HeadlessGameHost host = new CleanRunHeadlessGameHost(nameof(ImportBeatmapTest))) { try { var osu = LoadOsuIntoHost(host); var temp = TestResources.GetTestBeatmapForImport(); string extractedFolder = $"{temp}_extracted"; Directory.CreateDirectory(extractedFolder); try { var imported = await LoadOszIntoOsu(osu); string hashBefore = hashFile(temp); using (var zip = ZipArchive.Open(temp)) zip.WriteToDirectory(extractedFolder); using (var zip = ZipArchive.Create()) { zip.AddAllFromDirectory(extractedFolder); zip.SaveTo(temp, new ZipWriterOptions(CompressionType.Deflate)); } // zip files differ because different compression or encoder. Assert.AreNotEqual(hashBefore, hashFile(temp)); var importedSecondTime = await osu.Dependencies.Get<BeatmapManager>().Import(new ImportTask(temp)); ensureLoaded(osu); // but contents doesn't, so existing should still be used. Assert.IsTrue(imported.ID == importedSecondTime.Value.ID); Assert.IsTrue(imported.Beatmaps.First().ID == importedSecondTime.Value.Beatmaps.First().ID); } finally { Directory.Delete(extractedFolder, true); } } finally { host.Exit(); } } } [Test] public async Task TestImportThenImportWithChangedHashedFile() { using (HeadlessGameHost host = new CleanRunHeadlessGameHost(nameof(ImportBeatmapTest))) { try { var osu = LoadOsuIntoHost(host); var temp = TestResources.GetTestBeatmapForImport(); string extractedFolder = $"{temp}_extracted"; Directory.CreateDirectory(extractedFolder); try { var imported = await LoadOszIntoOsu(osu); await createScoreForBeatmap(osu, imported.Beatmaps.First()); using (var zip = ZipArchive.Open(temp)) zip.WriteToDirectory(extractedFolder); // arbitrary write to hashed file // this triggers the special BeatmapManager.PreImport deletion/replacement flow. using (var sw = new FileInfo(Directory.GetFiles(extractedFolder, "*.osu").First()).AppendText()) await sw.WriteLineAsync("// changed"); using (var zip = ZipArchive.Create()) { zip.AddAllFromDirectory(extractedFolder); zip.SaveTo(temp, new ZipWriterOptions(CompressionType.Deflate)); } var importedSecondTime = await osu.Dependencies.Get<BeatmapManager>().Import(new ImportTask(temp)); ensureLoaded(osu); // check the newly "imported" beatmap is not the original. Assert.IsTrue(imported.ID != importedSecondTime.Value.ID); Assert.IsTrue(imported.Beatmaps.First().ID != importedSecondTime.Value.Beatmaps.First().ID); } finally { Directory.Delete(extractedFolder, true); } } finally { host.Exit(); } } } [Test] [Ignore("intentionally broken by import optimisations")] public async Task TestImportThenImportWithChangedFile() { using (HeadlessGameHost host = new CleanRunHeadlessGameHost(nameof(ImportBeatmapTest))) { try { var osu = LoadOsuIntoHost(host); var temp = TestResources.GetTestBeatmapForImport(); string extractedFolder = $"{temp}_extracted"; Directory.CreateDirectory(extractedFolder); try { var imported = await LoadOszIntoOsu(osu); using (var zip = ZipArchive.Open(temp)) zip.WriteToDirectory(extractedFolder); // arbitrary write to non-hashed file using (var sw = new FileInfo(Directory.GetFiles(extractedFolder, "*.mp3").First()).AppendText()) await sw.WriteLineAsync("text"); using (var zip = ZipArchive.Create()) { zip.AddAllFromDirectory(extractedFolder); zip.SaveTo(temp, new ZipWriterOptions(CompressionType.Deflate)); } var importedSecondTime = await osu.Dependencies.Get<BeatmapManager>().Import(new ImportTask(temp)); ensureLoaded(osu); // check the newly "imported" beatmap is not the original. Assert.IsTrue(imported.ID != importedSecondTime.Value.ID); Assert.IsTrue(imported.Beatmaps.First().ID != importedSecondTime.Value.Beatmaps.First().ID); } finally { Directory.Delete(extractedFolder, true); } } finally { host.Exit(); } } } [Test] public async Task TestImportThenImportWithDifferentFilename() { using (HeadlessGameHost host = new CleanRunHeadlessGameHost(nameof(ImportBeatmapTest))) { try { var osu = LoadOsuIntoHost(host); var temp = TestResources.GetTestBeatmapForImport(); string extractedFolder = $"{temp}_extracted"; Directory.CreateDirectory(extractedFolder); try { var imported = await LoadOszIntoOsu(osu); using (var zip = ZipArchive.Open(temp)) zip.WriteToDirectory(extractedFolder); // change filename var firstFile = new FileInfo(Directory.GetFiles(extractedFolder).First()); firstFile.MoveTo(Path.Combine(firstFile.DirectoryName.AsNonNull(), $"{firstFile.Name}-changed{firstFile.Extension}")); using (var zip = ZipArchive.Create()) { zip.AddAllFromDirectory(extractedFolder); zip.SaveTo(temp, new ZipWriterOptions(CompressionType.Deflate)); } var importedSecondTime = await osu.Dependencies.Get<BeatmapManager>().Import(new ImportTask(temp)); ensureLoaded(osu); // check the newly "imported" beatmap is not the original. Assert.IsTrue(imported.ID != importedSecondTime.Value.ID); Assert.IsTrue(imported.Beatmaps.First().ID != importedSecondTime.Value.Beatmaps.First().ID); } finally { Directory.Delete(extractedFolder, true); } } finally { host.Exit(); } } } [Test] [Ignore("intentionally broken by import optimisations")] public async Task TestImportCorruptThenImport() { // unfortunately for the time being we need to reference osu.Framework.Desktop for a game host here. using (HeadlessGameHost host = new CleanRunHeadlessGameHost(nameof(ImportBeatmapTest))) { try { var osu = LoadOsuIntoHost(host); var imported = await LoadOszIntoOsu(osu); var firstFile = imported.Files.First(); var files = osu.Dependencies.Get<FileStore>(); long originalLength; using (var stream = files.Storage.GetStream(firstFile.FileInfo.StoragePath)) originalLength = stream.Length; using (var stream = files.Storage.GetStream(firstFile.FileInfo.StoragePath, FileAccess.Write, FileMode.Create)) stream.WriteByte(0); var importedSecondTime = await LoadOszIntoOsu(osu); using (var stream = files.Storage.GetStream(firstFile.FileInfo.StoragePath)) Assert.AreEqual(stream.Length, originalLength, "Corruption was not fixed on second import"); // check the newly "imported" beatmap is actually just the restored previous import. since it matches hash. Assert.IsTrue(imported.ID == importedSecondTime.ID); Assert.IsTrue(imported.Beatmaps.First().ID == importedSecondTime.Beatmaps.First().ID); checkBeatmapSetCount(osu, 1); checkSingleReferencedFileCount(osu, 18); } finally { host.Exit(); } } } [Test] public async Task TestRollbackOnFailure() { // unfortunately for the time being we need to reference osu.Framework.Desktop for a game host here. using (HeadlessGameHost host = new CleanRunHeadlessGameHost(nameof(ImportBeatmapTest))) { try { int itemAddRemoveFireCount = 0; int loggedExceptionCount = 0; Logger.NewEntry += l => { if (l.Target == LoggingTarget.Database && l.Exception != null) Interlocked.Increment(ref loggedExceptionCount); }; var osu = LoadOsuIntoHost(host); var manager = osu.Dependencies.Get<BeatmapManager>(); // ReSharper disable once AccessToModifiedClosure manager.ItemUpdated.BindValueChanged(_ => Interlocked.Increment(ref itemAddRemoveFireCount)); manager.ItemRemoved.BindValueChanged(_ => Interlocked.Increment(ref itemAddRemoveFireCount)); var imported = await LoadOszIntoOsu(osu); Assert.AreEqual(0, itemAddRemoveFireCount -= 1); imported.Hash += "-changed"; manager.Update(imported); Assert.AreEqual(0, itemAddRemoveFireCount -= 1); checkBeatmapSetCount(osu, 1); checkBeatmapCount(osu, 12); checkSingleReferencedFileCount(osu, 18); var brokenTempFilename = TestResources.GetTestBeatmapForImport(); MemoryStream brokenOsu = new MemoryStream(); MemoryStream brokenOsz = new MemoryStream(await File.ReadAllBytesAsync(brokenTempFilename)); File.Delete(brokenTempFilename); using (var outStream = File.Open(brokenTempFilename, FileMode.CreateNew)) using (var zip = ZipArchive.Open(brokenOsz)) { zip.AddEntry("broken.osu", brokenOsu, false); zip.SaveTo(outStream, CompressionType.Deflate); } // this will trigger purging of the existing beatmap (online set id match) but should rollback due to broken osu. try { await manager.Import(new ImportTask(brokenTempFilename)); } catch { } // no events should be fired in the case of a rollback. Assert.AreEqual(0, itemAddRemoveFireCount); checkBeatmapSetCount(osu, 1); checkBeatmapCount(osu, 12); checkSingleReferencedFileCount(osu, 18); Assert.AreEqual(1, loggedExceptionCount); File.Delete(brokenTempFilename); } finally { host.Exit(); } } } [Test] public async Task TestImportThenDeleteThenImport() { // unfortunately for the time being we need to reference osu.Framework.Desktop for a game host here. using (HeadlessGameHost host = new CleanRunHeadlessGameHost(nameof(ImportBeatmapTest))) { try { var osu = LoadOsuIntoHost(host); var imported = await LoadOszIntoOsu(osu); deleteBeatmapSet(imported, osu); var importedSecondTime = await LoadOszIntoOsu(osu); // check the newly "imported" beatmap is actually just the restored previous import. since it matches hash. Assert.IsTrue(imported.ID == importedSecondTime.ID); Assert.IsTrue(imported.Beatmaps.First().ID == importedSecondTime.Beatmaps.First().ID); } finally { host.Exit(); } } } [Test] public async Task TestImportThenDeleteThenImportWithOnlineIDsMissing() { // unfortunately for the time being we need to reference osu.Framework.Desktop for a game host here. using (HeadlessGameHost host = new CleanRunHeadlessGameHost($"{nameof(ImportBeatmapTest)}")) { try { var osu = LoadOsuIntoHost(host); var imported = await LoadOszIntoOsu(osu); foreach (var b in imported.Beatmaps) b.OnlineBeatmapID = null; osu.Dependencies.Get<BeatmapManager>().Update(imported); deleteBeatmapSet(imported, osu); var importedSecondTime = await LoadOszIntoOsu(osu); // check the newly "imported" beatmap has been reimported due to mismatch (even though hashes matched) Assert.IsTrue(imported.ID != importedSecondTime.ID); Assert.IsTrue(imported.Beatmaps.First().ID != importedSecondTime.Beatmaps.First().ID); } finally { host.Exit(); } } } [Test] public async Task TestImportWithDuplicateBeatmapIDs() { // unfortunately for the time being we need to reference osu.Framework.Desktop for a game host here. using (HeadlessGameHost host = new CleanRunHeadlessGameHost(nameof(ImportBeatmapTest))) { try { var osu = LoadOsuIntoHost(host); var metadata = new BeatmapMetadata { Artist = "SomeArtist", AuthorString = "SomeAuthor" }; var difficulty = new BeatmapDifficulty(); var toImport = new BeatmapSetInfo { OnlineBeatmapSetID = 1, Metadata = metadata, Beatmaps = new List<BeatmapInfo> { new BeatmapInfo { OnlineBeatmapID = 2, Metadata = metadata, BaseDifficulty = difficulty }, new BeatmapInfo { OnlineBeatmapID = 2, Metadata = metadata, Status = BeatmapSetOnlineStatus.Loved, BaseDifficulty = difficulty } } }; var manager = osu.Dependencies.Get<BeatmapManager>(); var imported = await manager.Import(toImport); Assert.NotNull(imported); Assert.AreEqual(null, imported.Value.Beatmaps[0].OnlineBeatmapID); Assert.AreEqual(null, imported.Value.Beatmaps[1].OnlineBeatmapID); } finally { host.Exit(); } } } [Test] [NonParallelizable] public void TestImportOverIPC() { using (HeadlessGameHost host = new CleanRunHeadlessGameHost($"{nameof(ImportBeatmapTest)}-host", true)) using (HeadlessGameHost client = new CleanRunHeadlessGameHost($"{nameof(ImportBeatmapTest)}-client", true)) { try { Assert.IsTrue(host.IsPrimaryInstance); Assert.IsFalse(client.IsPrimaryInstance); var osu = LoadOsuIntoHost(host); var temp = TestResources.GetTestBeatmapForImport(); var importer = new ArchiveImportIPCChannel(client); if (!importer.ImportAsync(temp).Wait(10000)) Assert.Fail(@"IPC took too long to send"); ensureLoaded(osu); waitForOrAssert(() => !File.Exists(temp), "Temporary still exists after IPC import", 5000); } finally { host.Exit(); } } } [Test] public async Task TestImportWhenFileOpen() { using (HeadlessGameHost host = new CleanRunHeadlessGameHost(nameof(ImportBeatmapTest))) { try { var osu = LoadOsuIntoHost(host); var temp = TestResources.GetTestBeatmapForImport(); using (File.OpenRead(temp)) await osu.Dependencies.Get<BeatmapManager>().Import(temp); ensureLoaded(osu); File.Delete(temp); Assert.IsFalse(File.Exists(temp), "We likely held a read lock on the file when we shouldn't"); } finally { host.Exit(); } } } [Test] public async Task TestImportWithDuplicateHashes() { using (HeadlessGameHost host = new CleanRunHeadlessGameHost(nameof(ImportBeatmapTest))) { try { var osu = LoadOsuIntoHost(host); var temp = TestResources.GetTestBeatmapForImport(); string extractedFolder = $"{temp}_extracted"; Directory.CreateDirectory(extractedFolder); try { using (var zip = ZipArchive.Open(temp)) zip.WriteToDirectory(extractedFolder); using (var zip = ZipArchive.Create()) { zip.AddAllFromDirectory(extractedFolder); zip.AddEntry("duplicate.osu", Directory.GetFiles(extractedFolder, "*.osu").First()); zip.SaveTo(temp, new ZipWriterOptions(CompressionType.Deflate)); } await osu.Dependencies.Get<BeatmapManager>().Import(temp); ensureLoaded(osu); } finally { Directory.Delete(extractedFolder, true); } } finally { host.Exit(); } } } [Test] public async Task TestImportNestedStructure() { using (HeadlessGameHost host = new CleanRunHeadlessGameHost(nameof(ImportBeatmapTest))) { try { var osu = LoadOsuIntoHost(host); var temp = TestResources.GetTestBeatmapForImport(); string extractedFolder = $"{temp}_extracted"; string subfolder = Path.Combine(extractedFolder, "subfolder"); Directory.CreateDirectory(subfolder); try { using (var zip = ZipArchive.Open(temp)) zip.WriteToDirectory(subfolder); using (var zip = ZipArchive.Create()) { zip.AddAllFromDirectory(extractedFolder); zip.SaveTo(temp, new ZipWriterOptions(CompressionType.Deflate)); } var imported = await osu.Dependencies.Get<BeatmapManager>().Import(new ImportTask(temp)); ensureLoaded(osu); Assert.IsFalse(imported.Value.Files.Any(f => f.Filename.Contains("subfolder")), "Files contain common subfolder"); } finally { Directory.Delete(extractedFolder, true); } } finally { host.Exit(); } } } [Test] public async Task TestImportWithIgnoredDirectoryInArchive() { using (HeadlessGameHost host = new CleanRunHeadlessGameHost(nameof(ImportBeatmapTest))) { try { var osu = LoadOsuIntoHost(host); var temp = TestResources.GetTestBeatmapForImport(); string extractedFolder = $"{temp}_extracted"; string dataFolder = Path.Combine(extractedFolder, "actual_data"); string resourceForkFolder = Path.Combine(extractedFolder, "__MACOSX"); string resourceForkFilePath = Path.Combine(resourceForkFolder, ".extracted"); Directory.CreateDirectory(dataFolder); Directory.CreateDirectory(resourceForkFolder); using (var resourceForkFile = File.CreateText(resourceForkFilePath)) { await resourceForkFile.WriteLineAsync("adding content so that it's not empty"); } try { using (var zip = ZipArchive.Open(temp)) zip.WriteToDirectory(dataFolder); using (var zip = ZipArchive.Create()) { zip.AddAllFromDirectory(extractedFolder); zip.SaveTo(temp, new ZipWriterOptions(CompressionType.Deflate)); } var imported = await osu.Dependencies.Get<BeatmapManager>().Import(new ImportTask(temp)); ensureLoaded(osu); Assert.IsFalse(imported.Value.Files.Any(f => f.Filename.Contains("__MACOSX")), "Files contain resource fork folder, which should be ignored"); Assert.IsFalse(imported.Value.Files.Any(f => f.Filename.Contains("actual_data")), "Files contain common subfolder"); } finally { Directory.Delete(extractedFolder, true); } } finally { host.Exit(); } } } [Test] public async Task TestUpdateBeatmapInfo() { using (HeadlessGameHost host = new CleanRunHeadlessGameHost(nameof(ImportBeatmapTest))) { try { var osu = LoadOsuIntoHost(host); var manager = osu.Dependencies.Get<BeatmapManager>(); var temp = TestResources.GetTestBeatmapForImport(); await osu.Dependencies.Get<BeatmapManager>().Import(temp); // Update via the beatmap, not the beatmap info, to ensure correct linking BeatmapSetInfo setToUpdate = manager.GetAllUsableBeatmapSets()[0]; Beatmap beatmapToUpdate = (Beatmap)manager.GetWorkingBeatmap(setToUpdate.Beatmaps.First(b => b.RulesetID == 0)).Beatmap; beatmapToUpdate.BeatmapInfo.Version = "updated"; manager.Update(setToUpdate); BeatmapInfo updatedInfo = manager.QueryBeatmap(b => b.ID == beatmapToUpdate.BeatmapInfo.ID); Assert.That(updatedInfo.Version, Is.EqualTo("updated")); } finally { host.Exit(); } } } [Test] public async Task TestUpdateBeatmapFile() { using (HeadlessGameHost host = new CleanRunHeadlessGameHost(nameof(ImportBeatmapTest))) { try { var osu = LoadOsuIntoHost(host); var manager = osu.Dependencies.Get<BeatmapManager>(); var temp = TestResources.GetTestBeatmapForImport(); await osu.Dependencies.Get<BeatmapManager>().Import(temp); BeatmapSetInfo setToUpdate = manager.GetAllUsableBeatmapSets()[0]; var beatmapInfo = setToUpdate.Beatmaps.First(b => b.RulesetID == 0); Beatmap beatmapToUpdate = (Beatmap)manager.GetWorkingBeatmap(setToUpdate.Beatmaps.First(b => b.RulesetID == 0)).Beatmap; BeatmapSetFileInfo fileToUpdate = setToUpdate.Files.First(f => beatmapToUpdate.BeatmapInfo.Path.Contains(f.Filename)); string oldMd5Hash = beatmapToUpdate.BeatmapInfo.MD5Hash; beatmapToUpdate.HitObjects.Clear(); beatmapToUpdate.HitObjects.Add(new HitCircle { StartTime = 5000 }); manager.Save(beatmapInfo, beatmapToUpdate); // Check that the old file reference has been removed Assert.That(manager.QueryBeatmapSet(s => s.ID == setToUpdate.ID).Files.All(f => f.ID != fileToUpdate.ID)); // Check that the new file is referenced correctly by attempting a retrieval Beatmap updatedBeatmap = (Beatmap)manager.GetWorkingBeatmap(manager.QueryBeatmap(b => b.ID == beatmapToUpdate.BeatmapInfo.ID)).Beatmap; Assert.That(updatedBeatmap.HitObjects.Count, Is.EqualTo(1)); Assert.That(updatedBeatmap.HitObjects[0].StartTime, Is.EqualTo(5000)); Assert.That(updatedBeatmap.BeatmapInfo.MD5Hash, Is.Not.EqualTo(oldMd5Hash)); } finally { host.Exit(); } } } [Test] public void TestCreateNewEmptyBeatmap() { using (HeadlessGameHost host = new CleanRunHeadlessGameHost(nameof(ImportBeatmapTest))) { try { var osu = LoadOsuIntoHost(host); var manager = osu.Dependencies.Get<BeatmapManager>(); var working = manager.CreateNew(new OsuRuleset().RulesetInfo, User.SYSTEM_USER); manager.Save(working.BeatmapInfo, working.Beatmap); var retrievedSet = manager.GetAllUsableBeatmapSets()[0]; // Check that the new file is referenced correctly by attempting a retrieval Beatmap updatedBeatmap = (Beatmap)manager.GetWorkingBeatmap(retrievedSet.Beatmaps[0]).Beatmap; Assert.That(updatedBeatmap.HitObjects.Count, Is.EqualTo(0)); } finally { host.Exit(); } } } [Test] public void TestCreateNewBeatmapWithObject() { using (HeadlessGameHost host = new CleanRunHeadlessGameHost(nameof(ImportBeatmapTest))) { try { var osu = LoadOsuIntoHost(host); var manager = osu.Dependencies.Get<BeatmapManager>(); var working = manager.CreateNew(new OsuRuleset().RulesetInfo, User.SYSTEM_USER); ((Beatmap)working.Beatmap).HitObjects.Add(new HitCircle { StartTime = 5000 }); manager.Save(working.BeatmapInfo, working.Beatmap); var retrievedSet = manager.GetAllUsableBeatmapSets()[0]; // Check that the new file is referenced correctly by attempting a retrieval Beatmap updatedBeatmap = (Beatmap)manager.GetWorkingBeatmap(retrievedSet.Beatmaps[0]).Beatmap; Assert.That(updatedBeatmap.HitObjects.Count, Is.EqualTo(1)); Assert.That(updatedBeatmap.HitObjects[0].StartTime, Is.EqualTo(5000)); } finally { host.Exit(); } } } public static async Task<BeatmapSetInfo> LoadQuickOszIntoOsu(OsuGameBase osu) { var temp = TestResources.GetQuickTestBeatmapForImport(); var manager = osu.Dependencies.Get<BeatmapManager>(); var importedSet = await manager.Import(new ImportTask(temp)).ConfigureAwait(false); ensureLoaded(osu); waitForOrAssert(() => !File.Exists(temp), "Temporary file still exists after standard import", 5000); return manager.GetAllUsableBeatmapSets().Find(beatmapSet => beatmapSet.ID == importedSet.Value.ID); } public static async Task<BeatmapSetInfo> LoadOszIntoOsu(OsuGameBase osu, string path = null, bool virtualTrack = false) { var temp = path ?? TestResources.GetTestBeatmapForImport(virtualTrack); var manager = osu.Dependencies.Get<BeatmapManager>(); var importedSet = await manager.Import(new ImportTask(temp)).ConfigureAwait(false); ensureLoaded(osu); waitForOrAssert(() => !File.Exists(temp), "Temporary file still exists after standard import", 5000); return manager.GetAllUsableBeatmapSets().Find(beatmapSet => beatmapSet.ID == importedSet.Value.ID); } private void deleteBeatmapSet(BeatmapSetInfo imported, OsuGameBase osu) { var manager = osu.Dependencies.Get<BeatmapManager>(); manager.Delete(imported); checkBeatmapSetCount(osu, 0); checkBeatmapSetCount(osu, 1, true); checkSingleReferencedFileCount(osu, 0); Assert.IsTrue(manager.QueryBeatmapSets(_ => true).First().DeletePending); } private static Task createScoreForBeatmap(OsuGameBase osu, BeatmapInfo beatmapInfo) { return ImportScoreTest.LoadScoreIntoOsu(osu, new ScoreInfo { OnlineScoreID = 2, BeatmapInfo = beatmapInfo, BeatmapInfoID = beatmapInfo.ID }, new ImportScoreTest.TestArchiveReader()); } private static void checkBeatmapSetCount(OsuGameBase osu, int expected, bool includeDeletePending = false) { var manager = osu.Dependencies.Get<BeatmapManager>(); Assert.AreEqual(expected, includeDeletePending ? manager.QueryBeatmapSets(_ => true).ToList().Count : manager.GetAllUsableBeatmapSets().Count); } private static string hashFile(string filename) { using (var s = File.OpenRead(filename)) return s.ComputeMD5Hash(); } private static void checkBeatmapCount(OsuGameBase osu, int expected) { Assert.AreEqual(expected, osu.Dependencies.Get<BeatmapManager>().QueryBeatmaps(_ => true).ToList().Count); } private static void checkSingleReferencedFileCount(OsuGameBase osu, int expected) { Assert.AreEqual(expected, osu.Dependencies.Get<FileStore>().QueryFiles(f => f.ReferenceCount == 1).Count()); } private static void ensureLoaded(OsuGameBase osu, int timeout = 60000) { IEnumerable<BeatmapSetInfo> resultSets = null; var store = osu.Dependencies.Get<BeatmapManager>(); waitForOrAssert(() => (resultSets = store.QueryBeatmapSets(s => s.OnlineBeatmapSetID == 241526)).Any(), @"BeatmapSet did not import to the database in allocated time.", timeout); // ensure we were stored to beatmap database backing... Assert.IsTrue(resultSets.Count() == 1, $@"Incorrect result count found ({resultSets.Count()} but should be 1)."); IEnumerable<BeatmapInfo> queryBeatmaps() => store.QueryBeatmaps(s => s.BeatmapSet.OnlineBeatmapSetID == 241526 && s.BaseDifficultyID > 0); IEnumerable<BeatmapSetInfo> queryBeatmapSets() => store.QueryBeatmapSets(s => s.OnlineBeatmapSetID == 241526); // if we don't re-check here, the set will be inserted but the beatmaps won't be present yet. waitForOrAssert(() => queryBeatmaps().Count() == 12, @"Beatmaps did not import to the database in allocated time", timeout); waitForOrAssert(() => queryBeatmapSets().Count() == 1, @"BeatmapSet did not import to the database in allocated time", timeout); int countBeatmapSetBeatmaps = 0; int countBeatmaps = 0; waitForOrAssert(() => (countBeatmapSetBeatmaps = queryBeatmapSets().First().Beatmaps.Count) == (countBeatmaps = queryBeatmaps().Count()), $@"Incorrect database beatmap count post-import ({countBeatmaps} but should be {countBeatmapSetBeatmaps}).", timeout); var set = queryBeatmapSets().First(); foreach (BeatmapInfo b in set.Beatmaps) Assert.IsTrue(set.Beatmaps.Any(c => c.OnlineBeatmapID == b.OnlineBeatmapID)); Assert.IsTrue(set.Beatmaps.Count > 0); var beatmap = store.GetWorkingBeatmap(set.Beatmaps.First(b => b.RulesetID == 0))?.Beatmap; Assert.IsTrue(beatmap?.HitObjects.Any() == true); beatmap = store.GetWorkingBeatmap(set.Beatmaps.First(b => b.RulesetID == 1))?.Beatmap; Assert.IsTrue(beatmap?.HitObjects.Any() == true); beatmap = store.GetWorkingBeatmap(set.Beatmaps.First(b => b.RulesetID == 2))?.Beatmap; Assert.IsTrue(beatmap?.HitObjects.Any() == true); beatmap = store.GetWorkingBeatmap(set.Beatmaps.First(b => b.RulesetID == 3))?.Beatmap; Assert.IsTrue(beatmap?.HitObjects.Any() == true); } private static void waitForOrAssert(Func<bool> result, string failureMessage, int timeout = 60000) { Task task = Task.Run(() => { while (!result()) Thread.Sleep(200); }); Assert.IsTrue(task.Wait(timeout), failureMessage); } } }
{ "content_hash": "baed5eb0d1a2a4efdafaad588d98e54a", "timestamp": "", "source": "github", "line_count": 1031, "max_line_length": 166, "avg_line_length": 40.11639185257032, "alnum_prop": 0.518931334622824, "repo_name": "peppy/osu-new", "id": "4cc71717ff3843bb86467360e5a97e6dc8f68e5e", "size": "41362", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "osu.Game.Tests/Beatmaps/IO/ImportBeatmapTest.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "281779" } ], "symlink_target": "" }
int main(int argc, char * argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([DAYAppDelegate class])); } }
{ "content_hash": "6b568ee23658bceaa33bd6bee2c524f8", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 93, "avg_line_length": 26.833333333333332, "alnum_prop": 0.6645962732919255, "repo_name": "benjipetit/dayly", "id": "9c058b4b955bf81a254c4f16ecc831956a56ffba", "size": "348", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dayly/main.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "72833" }, { "name": "Ruby", "bytes": "70" } ], "symlink_target": "" }
#ifndef HTTP_CLIENT_H #define HTTP_CLIENT_H #include "net.h" #include "http-response.h" struct http_response; struct http_client; struct http_client_request; enum http_client_request_error { HTTP_CLIENT_REQUEST_ERROR_ABORTED = 9000, HTTP_CLIENT_REQUEST_ERROR_HOST_LOOKUP_FAILED, HTTP_CLIENT_REQUEST_ERROR_CONNECT_FAILED, HTTP_CLIENT_REQUEST_ERROR_INVALID_REDIRECT, HTTP_CLIENT_REQUEST_ERROR_CONNECTION_LOST, HTTP_CLIENT_REQUEST_ERROR_BAD_RESPONSE, HTTP_CLIENT_REQUEST_ERROR_TIMED_OUT, }; enum http_request_state { HTTP_REQUEST_STATE_NEW = 0, HTTP_REQUEST_STATE_QUEUED, HTTP_REQUEST_STATE_PAYLOAD_OUT, HTTP_REQUEST_STATE_WAITING, HTTP_REQUEST_STATE_GOT_RESPONSE, HTTP_REQUEST_STATE_PAYLOAD_IN, HTTP_REQUEST_STATE_FINISHED, HTTP_REQUEST_STATE_ABORTED }; extern const char *http_request_state_names[]; struct http_client_settings { const char *dns_client_socket_path; const char *ssl_ca_dir, *ssl_ca_file, *ssl_ca; const char *ssl_crypto_device; bool ssl_allow_invalid_cert; /* user cert */ const char *ssl_cert, *ssl_key, *ssl_key_password; const char *rawlog_dir; unsigned int max_idle_time_msecs; /* maximum number of parallel connections per peer (default = 1) */ unsigned int max_parallel_connections; /* maximum number of pipelined requests per connection (default = 1) */ unsigned int max_pipelined_requests; /* maximum number of redirects for a request (default = 0; redirects refused) */ unsigned int max_redirects; /* maximum number of attempts for a request */ unsigned int max_attempts; /* response header limits */ struct http_header_limits response_hdr_limits; /* max time to wait for HTTP request to finish before retrying (default = unlimited) */ unsigned int request_timeout_msecs; /* max time to wait for connect() (and SSL handshake) to finish before retrying (default = request_timeout_msecs) */ unsigned int connect_timeout_msecs; /* time to wait for connect() (and SSL handshake) to finish for the first connection before trying the next IP in parallel (default = 0; wait until current connection attempt finishes) */ unsigned int soft_connect_timeout_msecs; bool debug; }; typedef void http_client_request_callback_t(const struct http_response *response, void *context); struct http_client *http_client_init(const struct http_client_settings *set); void http_client_deinit(struct http_client **_client); struct http_client_request * http_client_request(struct http_client *client, const char *method, const char *host, const char *target, http_client_request_callback_t *callback, void *context); #define http_client_request(client, method, host, target, callback, context) \ http_client_request(client, method, host, target + \ CALLBACK_TYPECHECK(callback, void (*)( \ const struct http_response *response, typeof(context))), \ (http_client_request_callback_t *)callback, context) void http_client_request_set_port(struct http_client_request *req, in_port_t port); void http_client_request_set_ssl(struct http_client_request *req, bool ssl); void http_client_request_set_urgent(struct http_client_request *req); void http_client_request_add_header(struct http_client_request *req, const char *key, const char *value); void http_client_request_set_date(struct http_client_request *req, time_t date); void http_client_request_set_payload(struct http_client_request *req, struct istream *input, bool sync); enum http_request_state http_client_request_get_state(struct http_client_request *req); void http_client_request_submit(struct http_client_request *req); bool http_client_request_try_retry(struct http_client_request *req); void http_client_request_abort(struct http_client_request **req); /* Call the specified callback when HTTP request is destroyed. */ void http_client_request_set_destroy_callback(struct http_client_request *req, void (*callback)(void *), void *context); /* submits request and blocks until provided payload is sent. Multiple calls are allowed; payload transmission is ended with http_client_request_finish_payload(). */ int http_client_request_send_payload(struct http_client_request **req, const unsigned char *data, size_t size); int http_client_request_finish_payload(struct http_client_request **req); void http_client_switch_ioloop(struct http_client *client); /* blocks until all currently submitted requests are handled */ void http_client_wait(struct http_client *client); /* Returns number of pending HTTP requests. */ unsigned int http_client_get_pending_request_count(struct http_client *client); #endif
{ "content_hash": "c4b443a9ef7f040fbc910cba3ffb9813", "timestamp": "", "source": "github", "line_count": 135, "max_line_length": 79, "avg_line_length": 34.37777777777778, "alnum_prop": 0.7463908640379229, "repo_name": "damoxc/dovecot", "id": "63327b6a8faa58683aa2628220daecd6fa63d7db", "size": "4641", "binary": false, "copies": "1", "ref": "refs/heads/mongodb-dict", "path": "src/lib-http/http-client.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "9553246" }, { "name": "C++", "bytes": "51249" }, { "name": "Objective-C", "bytes": "11776" }, { "name": "Perl", "bytes": "8159" }, { "name": "Python", "bytes": "1626" }, { "name": "Shell", "bytes": "10564" } ], "symlink_target": "" }
CREATE TABLE ntOoaHaplo ( bin smallint(5) unsigned not null, # index for browser speedup chrom varchar(255) not null, # Reference sequence chromosome chromStart int unsigned not null, # Start position in chromosome chromEnd int unsigned not null, # End position in chromosome name varchar(255) not null, # Qualitative assessment (OOA = out of africa, COS = cosmopolitan) score int unsigned not null, # For BED compatibility: Score from 0-1000 (placeholder = 0) strand char(1) not null, # For BED compatibility: + or - (placeholder = +) thickStart int unsigned not null, # For BED compatibility: Start of where display should be thick thickEnd int unsigned not null, # For BED compatibility: End of where display should be thick reserved int unsigned not null, # itemRgb color code st float not null, # Estimated ratio of OOA/African gene tree depth ooaTagFreq float not null, # Average frequency of tag in OOA clade am tinyint unsigned not null, # Neandertal (M)atches OOA-specific clade (Ancestral) dm tinyint unsigned not null, # Neandertal (M)atches OOA-specific clade (Derived) an tinyint unsigned not null, # Neandertal does (N)ot match OOA-specific clade (Ancestral) dn tinyint unsigned not null, # Neandertal does (N)ot match OOA-specific clade (Derived) #Indices INDEX chrom (chrom,bin) );
{ "content_hash": "23f6bd7866e9a2de963596c3a92023d3", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 101, "avg_line_length": 69.05, "alnum_prop": 0.7291817523533671, "repo_name": "hillerlab/GenomeAlignmentTools", "id": "4d08c9240a9e37353974de9bcf2967c9a22e891b", "size": "1750", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "kent/src/hg/lib/ntOoaHaplo.sql", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "1224" }, { "name": "AngelScript", "bytes": "434284" }, { "name": "C", "bytes": "14825208" }, { "name": "C++", "bytes": "81839" }, { "name": "CAP CDS", "bytes": "475" }, { "name": "Gnuplot", "bytes": "36237" }, { "name": "HTML", "bytes": "11954" }, { "name": "M4", "bytes": "7552" }, { "name": "Makefile", "bytes": "111088" }, { "name": "Perl", "bytes": "80546" }, { "name": "PostScript", "bytes": "2595" }, { "name": "Python", "bytes": "37076" }, { "name": "Roff", "bytes": "20366" }, { "name": "Shell", "bytes": "34162" }, { "name": "TSQL", "bytes": "2442" }, { "name": "q", "bytes": "218" } ], "symlink_target": "" }
<?php include_once('Admin.Fonts.php'); use utilities\MediaDirectory; class AdminFontIN extends AdminFonts{ private $internetRepository; private $coberturaRepository; private $fuente; private $urlLogo; public function __construct(){ $this->internetRepository = new InternetRepository(); $this->coberturaRepository = new CoberturaRepository(); $this->fuente = 'Internet'; $this->urlLogo = MediaDirectory::LOGO_FUENTES; } public function add(){ if( isset( $_SESSION['admin'] ) ){ ob_start(); require $this->adminviews . 'addFontIN.php'; $campos = ob_get_clean(); $this->addFont($campos, $this->fuente ); }else{ header( "Location: https://{$_SERVER["HTTP_HOST"]}/panel/login"); } } public function save(){ if( !empty($_POST) ){ $logo = $_FILES['logo']; $id_internet = $this->internetRepository->idFuenteIN(); $id_cobertura = $this->coberturaRepository->findIdByDescription($_POST['cobertura']); $_POST['tipoFuente'] = $id_internet; $_POST['cobertura'] = $id_cobertura; $adminColumn = new AdminColumns(); $guardarLogo = $adminColumn->saveImages( $logo, $this->urlLogo ); $_POST['logo'] = $guardarLogo['originName']; if(isset($_POST['activo'])){ $_POST['activo'] = 1; }else{ $_POST['activo'] = 0; } $alert = new stdClass(); if($this->internetRepository->addFontIN($_POST)){ $alert->tipo = 'alert-info'; $alert->mensaje = 'Se agrego la fuente <strong>' . $_POST['nombre'] . '</strong> Correctamente!!!'; $_SESSION['alerts']['fuentes'] = $alert; header('Location: /panel/fonts/show-list'); // echo 'Se ha agregado una fuente de TV correctamente'; }else{ $alert->tipo = 'alert-danger'; $alert->mensaje = 'No se agrego la fuente <strong>' . $_POST['nombre'] . '</strong> :('; $_SESSION['alerts']['fuentes'] = $alert; header( 'Location: ' . $_SERVER['HTTP_REFERER'] ); } }else{ header('Location: /panel/font/add/font-internet'); } } }
{ "content_hash": "31de071d1fbfd4378b5c0f6dd0f3d3f7", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 103, "avg_line_length": 27.602739726027398, "alnum_prop": 0.6178660049627791, "repo_name": "isaacBats/opemedios.cms.final", "id": "8c37716ed5b7ecf0853ce50f55850c6100ba31c5", "size": "2015", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "html/controllers/Admin.FontIN.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "999657" }, { "name": "HTML", "bytes": "10046820" }, { "name": "Hack", "bytes": "74980" }, { "name": "JavaScript", "bytes": "4623480" }, { "name": "PHP", "bytes": "18681224" }, { "name": "Shell", "bytes": "5484" }, { "name": "TSQL", "bytes": "828541" } ], "symlink_target": "" }
'use strict'; // Configuring the Cupones module angular.module('cupones').run(['Menus', function (Menus) { //Add the cupones dropdown item Menus.addMenuItem('topbar', { title: 'Cupones', state: 'cupones', type: 'dropdown', roles: ['*'] }); // Add the dropdown list item Menus.addSubMenuItem('topbar', 'cupones', { title: 'Listar Cupones', state: 'cupones.list' }); // Add the dropdown create item Menus.addSubMenuItem('topbar', 'cupones', { title: 'Crear Cupones', state: 'cupones.create', roles: ['user'] }); } ]);
{ "content_hash": "e061ff508c0f381531e89186c2f0cb9f", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 47, "avg_line_length": 22.703703703703702, "alnum_prop": 0.5758564437194127, "repo_name": "matamuchastegui/WebService", "id": "8d4f37f1c52825fd48217c25e5893617ea4c04f5", "size": "613", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/cupones/client/config/cupones.client.config.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1472" }, { "name": "HTML", "bytes": "41695" }, { "name": "JavaScript", "bytes": "240473" }, { "name": "Shell", "bytes": "685" } ], "symlink_target": "" }
"""The artifact knowledge base object. The knowledge base is filled by user provided input and the pre-processing phase. It is intended to provide successive phases, like the parsing and analysis phases, with essential information like the time zone and codepage of the source data. """ import codecs import pytz from plaso.containers import artifacts from plaso.engine import logger from plaso.helpers.windows import time_zones class KnowledgeBase(object): """The knowledge base.""" _DEFAULT_ACTIVE_SESSION = '00000000000000000000000000000000' def __init__(self): """Initializes a knowledge base.""" super(KnowledgeBase, self).__init__() self._active_session = self._DEFAULT_ACTIVE_SESSION self._available_time_zones = {} self._codepage = 'cp1252' self._environment_variables = {} self._hostnames = {} self._language = 'en-US' self._mount_path = None self._time_zone = pytz.UTC self._user_accounts = {} self._values = {} self._windows_eventlog_providers = {} @property def available_time_zones(self): """list[TimeZone]: available time zones of the current session.""" return self._available_time_zones.get(self._active_session, {}).values() @property def codepage(self): """str: codepage of the current session.""" return self.GetValue('codepage', default_value=self._codepage) @property def language(self): """str: language of the current session.""" return self.GetValue('language', default_value=self._language) @property def timezone(self): """datetime.tzinfo: time zone of the current session.""" return self._time_zone @property def user_accounts(self): """list[UserAccountArtifact]: user accounts of the current session.""" return self._user_accounts.get(self._active_session, {}).values() def AddAvailableTimeZone(self, time_zone): """Adds an available time zone. Args: time_zone (TimeZoneArtifact): time zone artifact. Raises: KeyError: if the time zone already exists. """ if self._active_session not in self._available_time_zones: self._available_time_zones[self._active_session] = {} available_time_zones = self._available_time_zones[self._active_session] if time_zone.name in available_time_zones: raise KeyError('Time zone: {0:s} already exists.'.format(time_zone.name)) available_time_zones[time_zone.name] = time_zone def AddEnvironmentVariable(self, environment_variable): """Adds an environment variable. Args: environment_variable (EnvironmentVariableArtifact): environment variable artifact. Raises: KeyError: if the environment variable already exists. """ name = environment_variable.name.upper() if name in self._environment_variables: raise KeyError('Environment variable: {0:s} already exists.'.format( environment_variable.name)) self._environment_variables[name] = environment_variable def AddUserAccount(self, user_account): """Adds an user account. Args: user_account (UserAccountArtifact): user account artifact. Raises: KeyError: if the user account already exists. """ if self._active_session not in self._user_accounts: self._user_accounts[self._active_session] = {} user_accounts = self._user_accounts[self._active_session] if user_account.identifier in user_accounts: raise KeyError('User account: {0:s} already exists.'.format( user_account.identifier)) user_accounts[user_account.identifier] = user_account def AddWindowsEventLogProvider(self, windows_eventlog_provider): """Adds a Windows Event Log provider. Args: windows_eventlog_provider (WindowsEventLogProviderArtifact): Windows Event Log provider. Raises: KeyError: if the Windows Event Log provider already exists. """ log_source = windows_eventlog_provider.log_source if log_source in self._windows_eventlog_providers: raise KeyError('Windows Event Log provider: {0:s} already exists.'.format( log_source)) # TODO: store on a per-volume basis? self._windows_eventlog_providers[log_source] = windows_eventlog_provider def GetEnvironmentVariable(self, name): """Retrieves an environment variable. Args: name (str): name of the environment variable. Returns: EnvironmentVariableArtifact: environment variable artifact or None if there was no value set for the given name. """ name = name.upper() return self._environment_variables.get(name, None) def GetEnvironmentVariables(self): """Retrieves the environment variables. Returns: list[EnvironmentVariableArtifact]: environment variable artifacts. """ return self._environment_variables.values() def GetHostname(self): """Retrieves the hostname related to the event. If the hostname is not stored in the event it is determined based on the preprocessing information that is stored inside the storage file. Returns: str: hostname. """ hostname_artifact = self._hostnames.get(self._active_session, None) if not hostname_artifact: return '' return hostname_artifact.name or '' def GetSystemConfigurationArtifact(self): """Retrieves the knowledge base as a system configuration artifact. Returns: SystemConfigurationArtifact: system configuration artifact. """ system_configuration = artifacts.SystemConfigurationArtifact() system_configuration.code_page = self.GetValue( 'codepage', default_value=self._codepage) system_configuration.hostname = self._hostnames.get( self._active_session, None) system_configuration.keyboard_layout = self.GetValue('keyboard_layout') system_configuration.language = self._language system_configuration.operating_system = self.GetValue('operating_system') system_configuration.operating_system_product = self.GetValue( 'operating_system_product') system_configuration.operating_system_version = self.GetValue( 'operating_system_version') time_zone = self._time_zone.zone if isinstance(time_zone, bytes): time_zone = time_zone.decode('ascii') system_configuration.time_zone = time_zone available_time_zones = self._available_time_zones.get( self._active_session, {}) # In Python 3 dict.values() returns a type dict_values, which will cause # the JSON serializer to raise a TypeError. system_configuration.available_time_zones = list( available_time_zones.values()) user_accounts = self._user_accounts.get(self._active_session, {}) # In Python 3 dict.values() returns a type dict_values, which will cause # the JSON serializer to raise a TypeError. system_configuration.user_accounts = list(user_accounts.values()) return system_configuration def GetUsernameByIdentifier(self, user_identifier): """Retrieves the username based on an user identifier. Args: user_identifier (str): user identifier, either a UID or SID. Returns: str: username. """ user_accounts = self._user_accounts.get(self._active_session, {}) user_account = user_accounts.get(user_identifier, None) if not user_account: return '' return user_account.username or '' def GetUsernameForPath(self, path): """Retrieves a username for a specific path. This is determining if a specific path is within a user's directory and returning the username of the user if so. Args: path (str): path. Returns: str: username or None if the path does not appear to be within a user's directory. """ path = path.lower() user_accounts = self._user_accounts.get(self._active_session, {}) for user_account in user_accounts.values(): if not user_account.user_directory: continue user_directory = user_account.user_directory.lower() if path.startswith(user_directory): return user_account.username return None def GetValue(self, identifier, default_value=None): """Retrieves a value by identifier. Args: identifier (str): case insensitive unique identifier for the value. default_value (object): default value. Returns: object: value or default value if not available. Raises: TypeError: if the identifier is not a string type. """ if not isinstance(identifier, str): raise TypeError('Identifier not a string type.') identifier = identifier.lower() return self._values.get(identifier, default_value) def GetWindowsEventLogProvider(self, log_source): """Retrieves a Windows EventLog provider by log source. Args: log_source (str): EventLog source, such as "Application Error". Returns: WindowsEventLogProviderArtifact: Windows EventLog provider artifact or None if not available. """ return self._windows_eventlog_providers.get(log_source, None) def GetWindowsEventLogProviders(self): """Retrieves the Windows EventLog providers. Returns: list[WindowsEventLogProviderArtifact]: Windows EventLog provider artifacts. """ return self._windows_eventlog_providers.values() def HasUserAccounts(self): """Determines if the knowledge base contains user accounts. Returns: bool: True if the knowledge base contains user accounts. """ return self._user_accounts.get(self._active_session, {}) != {} def ReadSystemConfigurationArtifact(self, system_configuration): """Reads the knowledge base values from a system configuration artifact. Note that this overwrites existing values in the knowledge base. Args: system_configuration (SystemConfigurationArtifact): system configuration artifact. """ if not system_configuration: return if system_configuration.code_page: try: self.SetCodepage(system_configuration.code_page) except ValueError: logger.warning( 'Unsupported codepage: {0:s}, defaulting to {1:s}'.format( system_configuration.code_page, self._codepage)) self._hostnames[self._active_session] = system_configuration.hostname self.SetValue('keyboard_layout', system_configuration.keyboard_layout) if system_configuration.language: self.SetLanguage(system_configuration.language) self.SetValue('operating_system', system_configuration.operating_system) self.SetValue( 'operating_system_product', system_configuration.operating_system_product) self.SetValue( 'operating_system_version', system_configuration.operating_system_version) # Set the available time zones before the system time zone so that localized # time zone names can be mapped to their corresponding Python time zone. self._available_time_zones[self._active_session] = { time_zone.name: time_zone for time_zone in system_configuration.available_time_zones} if system_configuration.time_zone: try: self.SetTimeZone(system_configuration.time_zone) except ValueError: logger.warning( 'Unsupported time zone: {0:s}, defaulting to {1:s}'.format( system_configuration.time_zone, self._time_zone.zone)) self._user_accounts[self._active_session] = { user_account.identifier: user_account for user_account in system_configuration.user_accounts} def SetActiveSession(self, session_identifier): """Sets the active session. Args: session_identifier (str): session identifier where None represents the default active session. """ self._active_session = session_identifier or self._DEFAULT_ACTIVE_SESSION def SetCodepage(self, codepage): """Sets the codepage. Args: codepage (str): codepage. Raises: ValueError: if the codepage is not supported. """ try: codecs.getencoder(codepage) self._codepage = codepage except LookupError: raise ValueError('Unsupported codepage: {0:s}'.format(codepage)) def SetEnvironmentVariable(self, environment_variable): """Sets an environment variable. Args: environment_variable (EnvironmentVariableArtifact): environment variable artifact. """ name = environment_variable.name.upper() self._environment_variables[name] = environment_variable def SetHostname(self, hostname): """Sets a hostname. Args: hostname (HostnameArtifact): hostname artifact. """ self._hostnames[self._active_session] = hostname def SetLanguage(self, language): """Sets the language. Args: language (str): language. """ self._language = language def SetTimeZone(self, time_zone): """Sets the time zone. Args: time_zone (str): time zone. Raises: ValueError: if the time zone is not supported. """ # Get the "normalized" name of a Windows time zone name. if time_zone.startswith('@tzres.dll,'): mui_form_time_zones = { time_zone_artifact.mui_form: time_zone_artifact.name for time_zone_artifact in self.available_time_zones} time_zone = mui_form_time_zones.get(time_zone, time_zone) else: localized_time_zones = { time_zone_artifact.localized_name: time_zone_artifact.name for time_zone_artifact in self.available_time_zones} time_zone = localized_time_zones.get(time_zone, time_zone) # Map a Windows time zone name to a Python time zone name. time_zone = time_zones.WINDOWS_TIME_ZONES.get(time_zone, time_zone) try: self._time_zone = pytz.timezone(time_zone) except pytz.UnknownTimeZoneError: raise ValueError('Unsupported time zone: {0!s}'.format(time_zone)) def SetValue(self, identifier, value): """Sets a value by identifier. Args: identifier (str): case insensitive unique identifier for the value. value (object): value. Raises: TypeError: if the identifier is not a string type. """ if not isinstance(identifier, str): raise TypeError('Identifier not a string type.') identifier = identifier.lower() self._values[identifier] = value
{ "content_hash": "90c51554daca68cd5f9170538e4e4426", "timestamp": "", "source": "github", "line_count": 452, "max_line_length": 80, "avg_line_length": 31.67920353982301, "alnum_prop": 0.6885257350373629, "repo_name": "joachimmetz/plaso", "id": "0cb5af0f5624e59e26326c5213d1f76397483b98", "size": "14343", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "plaso/engine/knowledge_base.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "4301" }, { "name": "Makefile", "bytes": "122" }, { "name": "PowerShell", "bytes": "1305" }, { "name": "Python", "bytes": "5345755" }, { "name": "Shell", "bytes": "27279" }, { "name": "YARA", "bytes": "507" } ], "symlink_target": "" }
namespace Problem_8_10 { using System; class TheMain { static void Main() { Matrix<int> matrix = new Matrix<int>(3, 3); Matrix<int> anotherMatrix = new Matrix<int>(3, 3); Matrix<int> multiplicationTestMatrix = new Matrix<int>(3, 2); Matrix<int> fakeMatrix = new Matrix<int>(2, 5); //Console.WriteLine(matrix); // only zero values //Console.WriteLine(doubleMatrix); // only zero values // matrix[10, 5] = 1; // throws Exception matrix[0, 0] = 1; matrix[0, 1] = 2; matrix[0, 2] = 3; matrix[1, 0] = 4; matrix[1, 1] = 5; matrix[1, 2] = 6; matrix[2, 0] = 7; matrix[2, 1] = 8; matrix[2, 2] = 9; Console.WriteLine(matrix); anotherMatrix[0, 0] = 11; anotherMatrix[0, 1] = 12; anotherMatrix[0, 2] = 13; anotherMatrix[1, 0] = 14; anotherMatrix[1, 1] = 15; anotherMatrix[1, 2] = 16; anotherMatrix[2, 0] = 17; anotherMatrix[2, 1] = 18; anotherMatrix[2, 2] = 19; multiplicationTestMatrix[0, 0] = 100; multiplicationTestMatrix[0, 1] = 200; multiplicationTestMatrix[1, 0] = 300; multiplicationTestMatrix[1, 1] = 400; multiplicationTestMatrix[2, 0] = 500; multiplicationTestMatrix[2, 1] = 600; Console.WriteLine(multiplicationTestMatrix); Console.WriteLine(matrix + anotherMatrix); //Console.WriteLine(matrix + fakeMatrix); // throws Exception Console.WriteLine(matrix - anotherMatrix); //Console.WriteLine(matrix - fakeMatrix); // throws Exception Console.WriteLine(matrix * anotherMatrix); //Console.WriteLine(matrix * fakeMatrix); // throws Exception Console.WriteLine(matrix * multiplicationTestMatrix); Matrix<double> doubleMatrix = new Matrix<double>(4, 4); if(doubleMatrix) // matrix contains only zero values { // Unreachable part of the code } doubleMatrix[0, 0] = 1; if (doubleMatrix) { Console.WriteLine("Matrix has at least one non-zero element"); } } } }
{ "content_hash": "31babd0c3237fde65c29da99546b585d", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 78, "avg_line_length": 32.74025974025974, "alnum_prop": 0.4962316541055137, "repo_name": "MarinMarinov/C-Sharp-OOP", "id": "437325c76e14490a7067248f40295916a2d19886", "size": "2523", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "HW02- Defining Classes - Part 2/Problem 8-10/TheMain.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "151139" } ], "symlink_target": "" }
<script src="{{ "/js/main.js" | prepend: site.baseurl }}"></script> {% if site.theme1.footer_text %} <footer class="site-footer"> <p class="text">{{ site.theme1.footer_text }}</p> </footer> {% endif %}
{ "content_hash": "a17c9bd703ef1b5d0962fff0f6bf84b8", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 67, "avg_line_length": 29.285714285714285, "alnum_prop": 0.6146341463414634, "repo_name": "FosterKizer/FosterKizer.github.io", "id": "46dca34cf6a84623b0eb0d578e26722ba8a7e24c", "size": "205", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_includes/footer.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9176" }, { "name": "HTML", "bytes": "11162" }, { "name": "JavaScript", "bytes": "739" } ], "symlink_target": "" }
<?php namespace Soccer\LandingBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class DefaultController extends Controller { public function indexAction($name) { return $this->render('SoccerLandingBundle:Default:index.html.twig', array('name' => $name)); } }
{ "content_hash": "d70abebbd807f2b7ecaaa1ab52b87c45", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 100, "avg_line_length": 23.76923076923077, "alnum_prop": 0.7378640776699029, "repo_name": "malioret/ConnectedSoccerApi", "id": "f7981f57d92a577da48eeb9528d0f9d98bfe87e2", "size": "309", "binary": false, "copies": "1", "ref": "refs/heads/origin2", "path": "src/Soccer/LandingBundle/Controller/DefaultController.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3606" }, { "name": "CSS", "bytes": "142021" }, { "name": "HTML", "bytes": "3898126" }, { "name": "JavaScript", "bytes": "67098" }, { "name": "PHP", "bytes": "272341" } ], "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> <title>Uses of Class org.apache.poi.hslf.record.ExAviMovie (POI API Documentation)</title> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.poi.hslf.record.ExAviMovie (POI API Documentation)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/poi/hslf/record/ExAviMovie.html" title="class in org.apache.poi.hslf.record">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>PREV</li> <li>NEXT</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/poi/hslf/record//class-useExAviMovie.html" target="_top">FRAMES</a></li> <li><a href="ExAviMovie.html" target="_top">NO FRAMES</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.poi.hslf.record.ExAviMovie" class="title">Uses of Class<br>org.apache.poi.hslf.record.ExAviMovie</h2> </div> <div class="classUseContainer">No usage of org.apache.poi.hslf.record.ExAviMovie</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/poi/hslf/record/ExAviMovie.html" title="class in org.apache.poi.hslf.record">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>PREV</li> <li>NEXT</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/poi/hslf/record//class-useExAviMovie.html" target="_top">FRAMES</a></li> <li><a href="ExAviMovie.html" target="_top">NO FRAMES</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <i>Copyright 2014 The Apache Software Foundation or its licensors, as applicable.</i> </small></p> </body> </html>
{ "content_hash": "30b4126d847500b7e81b9640b374b0ac", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 137, "avg_line_length": 36.47863247863248, "alnum_prop": 0.601921274601687, "repo_name": "RyoSaeba69/Bio-info", "id": "18881a68bb07e98a3e642d903f4febcb624950ec", "size": "4268", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "mylib/poi-3.11/docs/apidocs/org/apache/poi/hslf/record/class-use/ExAviMovie.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "23219" }, { "name": "HTML", "bytes": "75463818" }, { "name": "Java", "bytes": "98240" } ], "symlink_target": "" }
require 'test_helper' class OntologyExtensionWithSuggestedTypeTest < ActiveSupport::TestCase test "assay types from ontology cannot be edited or deleted" do Seek::Ontologies::AssayTypeReader.instance.class_hierarchy.hash_by_uri.each do |uri, clazz| User.current_user = Factory :user, :person => Factory(:admin) assert !clazz.can_edit? assert !clazz.can_destroy? User.current_user = Factory :user assert !clazz.can_edit? assert !clazz.can_destroy? end Seek::Ontologies::ModellingAnalysisTypeReader.instance.class_hierarchy.hash_by_uri.each do |uri, clazz| User.current_user = Factory :user, :person => Factory(:admin) assert !clazz.can_edit? assert !clazz.can_destroy? User.current_user = Factory :user assert !clazz.can_edit? assert !clazz.can_destroy? end end test "technology types from ontology cannot be edited or deleted" do Seek::Ontologies::TechnologyTypeReader.instance.class_hierarchy.hash_by_uri.each do |uri, clazz| User.current_user = Factory :user, :person => Factory(:admin) assert !clazz.can_edit? assert !clazz.can_destroy? User.current_user = Factory :user assert !clazz.can_edit? assert !clazz.can_destroy? end end end
{ "content_hash": "13aa5472cf4c23a064fdb4587e77cc23", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 112, "avg_line_length": 42.38235294117647, "alnum_prop": 0.6169326856349757, "repo_name": "stuzart/seek", "id": "245389b59e2894c772493827e49b346a47515d40", "size": "1441", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/unit/ontology_extension_with_suggested_type_test.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "38808" }, { "name": "JavaScript", "bytes": "244502" }, { "name": "Ruby", "bytes": "2868144" }, { "name": "Shell", "bytes": "12124" }, { "name": "XSLT", "bytes": "22416" } ], "symlink_target": "" }
/* * * This file was generated by LLRP Code Generator * see http://llrp-toolkit.cvs.sourceforge.net/llrp-toolkit/ * for more information * Generated on: Sun Apr 08 14:14:12 EDT 2012; * */ /* * Copyright 2007 ETH Zurich * * 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 org.llrp.ltk.generated.enumerations; import maximsblog.blogspot.com.llrpexplorer.Logger; import org.jdom2.Content; import org.jdom2.Element; import org.jdom2.Namespace; import org.jdom2.Text; import org.llrp.ltk.generated.LLRPConstants; import org.llrp.ltk.types.LLRPBitList; import org.llrp.ltk.types.LLRPEnumeration; import org.llrp.ltk.types.UnsignedByte; import org.llrp.ltk.types.UnsignedByte; import java.lang.IllegalArgumentException; import java.math.BigInteger; import java.util.LinkedList; import java.util.List; /** * AntennaEventType is Enumeration of Type UnsignedByte */ public class AntennaEventType extends UnsignedByte implements LLRPEnumeration { public static final int Antenna_Disconnected = 0; public static final int Antenna_Connected = 1; Logger logger = Logger.getLogger(AntennaEventType.class); public AntennaEventType() { super(0); } /** * Create new AntennaEventType by passing integer value. * * @throws IllegalArgumentException * if the value is not allowed for this enumeration * @param value an Integer value allowed - might check first * with isValidValue it it is an allowed value */ public AntennaEventType(int value) { super(value); if (!isValidValue(value)) { throw new IllegalArgumentException("Value not allowed"); } } /** * Create new AntennaEventType by passing jdom element. * * @throws IllegalArgumentException * if the value found in element is not allowed * for this enumeration. * @param element - jdom element where the child is a string * that is the name for a value of the enumeration. */ public AntennaEventType(final Element element) { this(element.getText()); } /** * Create new AntennaEventType by passing a string. * * @throws IllegalArgumentException * if the string does not stand for a valid value. */ public AntennaEventType(final String name) { if (!isValidName(name)) { throw new IllegalArgumentException("Name not allowed"); } this.value = getValue(name); signed = false; } /** * Create new AntennaEventType by passing LLRPBitList. * * @throws IllegalArgumentException * if the value found in the BitList is not allowed * for this enumeration. * @param list - LLRPBitList */ public AntennaEventType(final LLRPBitList list) { decodeBinary(list); if (!isValidValue(new Integer(toInteger()))) { throw new IllegalArgumentException("Value not allowed"); } } /** * set the current value of this enumeration to the * value identified by given string. * * @throws IllegalArgumentException * if the value found for given String is not allowed * for this enumeration. * @param name set this enumeration to hold one of the allowed values */ public final void set(final String name) { if (!isValidName(name)) { throw new IllegalArgumentException("name not allowed"); } this.value = getValue(name); } /** * set the current value of this enumeration to the * value given. * * @throws IllegalArgumentException * if the value is not allowed * for this enumeration. * @param value to be set */ public final void set(final int value) { if (!isValidValue(value)) { throw new IllegalArgumentException("value not allowed"); } this.value = value; } /** * {@inheritDoc} */ public Content encodeXML(final String name, Namespace ns) { Element element = new Element(name, ns); //Element element = new Element(name, Namespace.getNamespace("llrp",LLRPConstants.LLRPNAMESPACE)); element.setContent(new Text(toString())); return element; } /** * {@inheritDoc} */ public String toString() { return getName(toInteger()); } /** * {@inheritDoc} */ public boolean isValidValue(final int value) { switch (value) { case 0: return true; case 1: return true; default: return false; } } /** * {@inheritDoc} */ public final int getValue(final String name) { if (name.equalsIgnoreCase("Antenna_Disconnected")) { return 0; } if (name.equalsIgnoreCase("Antenna_Connected")) { return 1; } return -1; } /** * {@inheritDoc} */ public final String getName(final int value) { if (0 == value) { return "Antenna_Disconnected"; } if (1 == value) { return "Antenna_Connected"; } return ""; } /** * {@inheritDoc} */ public boolean isValidName(final String name) { if (name.equals("Antenna_Disconnected")) { return true; } if (name.equals("Antenna_Connected")) { return true; } return false; } /** * number of bits used to represent this type. * * @return Integer */ public static int length() { return UnsignedByte.length(); } /** * wrapper method for UnsignedIntegers that use BigIntegers to store value * */ private final String getName(final BigInteger value) { logger.warn("AntennaEventType must convert BigInteger " + value + " to Integer value " + value.intValue()); return getName(value.intValue()); } /** * wrapper method for UnsignedIntegers that use BigIntegers to store value * */ private final boolean isValidValue(final BigInteger value) { logger.warn("AntennaEventType must convert BigInteger " + value + " to Integer value " + value.intValue()); return isValidValue(value.intValue()); } }
{ "content_hash": "c9348a6b6a284da44c47a0c8bfc6f1a4", "timestamp": "", "source": "github", "line_count": 265, "max_line_length": 106, "avg_line_length": 25.871698113207547, "alnum_prop": 0.6225204200700116, "repo_name": "mksmbrtsh/LLRPexplorer", "id": "ea331703dc241f8d6d64eccb8faba815169c076d", "size": "6856", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/org/llrp/ltk/generated/enumerations/AntennaEventType.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "4576" }, { "name": "Java", "bytes": "3341909" } ], "symlink_target": "" }
namespace mnc { class ScoresTest : public ttest::TestBase { private: static const int MATE = Scores::PIECE_VALUES[Piece::KING]; TTEST_CASE("Positional values for players are mirrored.") { TTEST_EQUAL(Scores::POSITIONAL_PIECE_VALUES[Player::BLACK][Piece::PAWN][6 * 8 + 3], Scores::POSITIONAL_PIECE_VALUES[Player::WHITE][Piece::PAWN][1 * 8 + 3]); TTEST_EQUAL(Scores::POSITIONAL_PIECE_VALUES[Player::BLACK][Piece::BISHOP][5 * 8 + 6], Scores::POSITIONAL_PIECE_VALUES[Player::WHITE][Piece::BISHOP][2 * 8 + 6]); } TTEST_CASE("Positional value is increased by piece value.") { TTEST_EQUAL(Scores::POSITIONAL_PIECE_VALUES[Player::BLACK][Piece::KING][0 * 8 + 4], 100000005); } TTEST_CASE("getCheckMateScore()") { TTEST_EQUAL(Scores::getCheckMateScore(1), MATE - 1); TTEST_EQUAL(Scores::getCheckMateScore(-3), -MATE + 3); } TTEST_CASE("Score in floating point form has two decimals.") { TTEST_EQUAL(Scores::toStr(1510), "15.10"); TTEST_EQUAL(Scores::toStr(-12), "-0.12"); } TTEST_CASE("Mate score has correct string.") { TTEST_EQUAL(Scores::toStr(MATE - 1), "mate 1"); TTEST_EQUAL(Scores::toStr(MATE - 5), "mate 5"); TTEST_EQUAL(Scores::toStr(-MATE), "mate 0"); TTEST_EQUAL(Scores::toStr(-MATE + 3), "mate -3"); } }; }
{ "content_hash": "d0d35e8f21f82e3e313f6187a1d1cc3f", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 87, "avg_line_length": 28.795454545454547, "alnum_prop": 0.6677190213101816, "repo_name": "zekyll/Minace", "id": "fe0b00a64e7cecd2ca884516d4b2035200632cf8", "size": "1406", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Minace/tests/ScoresTest.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "77626" }, { "name": "C++", "bytes": "71729" }, { "name": "Objective-C", "bytes": "7175" }, { "name": "Shell", "bytes": "2876" } ], "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" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="generator" content="JsDoc Toolkit" /> <title>JsDoc Reference - AV.View</title> <style type="text/css"> /* default.css */ body { font: 12px "Lucida Grande", Tahoma, Arial, Helvetica, sans-serif; width: 800px; } .header { clear: both; background-color: #ccc; padding: 8px; } h1 { font-size: 150%; font-weight: bold; padding: 0; margin: 1em 0 0 .3em; } hr { border: none 0; border-top: 1px solid #7F8FB1; height: 1px; } pre.code { display: block; padding: 8px; border: 1px dashed #ccc; } #index { margin-top: 24px; float: left; width: 160px; position: absolute; left: 8px; background-color: #F3F3F3; padding: 8px; } #content { margin-left: 190px; width: 600px; } .classList { list-style-type: none; padding: 0; margin: 0 0 0 8px; font-family: arial, sans-serif; font-size: 1em; overflow: auto; } .classList li { padding: 0; margin: 0 0 8px 0; } .summaryTable { width: 100%; } h1.classTitle { font-size:170%; line-height:130%; } h2 { font-size: 110%; } caption, div.sectionTitle { background-color: #7F8FB1; color: #fff; font-size:130%; text-align: left; padding: 2px 6px 2px 6px; border: 1px #7F8FB1 solid; } div.sectionTitle { margin-bottom: 8px; } .summaryTable thead { display: none; } .summaryTable td { vertical-align: top; padding: 4px; border-bottom: 1px #7F8FB1 solid; border-right: 1px #7F8FB1 solid; } /*col#summaryAttributes {}*/ .summaryTable td.attributes { border-left: 1px #7F8FB1 solid; width: 140px; text-align: right; } td.attributes, .fixedFont { line-height: 15px; color: #002EBE; font-family: "Courier New",Courier,monospace; font-size: 13px; } .summaryTable td.nameDescription { text-align: left; font-size: 13px; line-height: 15px; } .summaryTable td.nameDescription, .description { line-height: 15px; padding: 4px; padding-left: 4px; } .summaryTable { margin-bottom: 8px; } ul.inheritsList { list-style: square; margin-left: 20px; padding-left: 0; } .detailList { margin-left: 20px; line-height: 15px; } .detailList dt { margin-left: 20px; } .detailList .heading { font-weight: bold; padding-bottom: 6px; margin-left: 0; } .light, td.attributes, .light a:link, .light a:visited { color: #777; font-style: italic; } .fineprint { text-align: right; font-size: 10px; } </style> </head> <body> <!-- ============================== header ================================= --> <!-- begin static/header.html --> <div id="header"> </div> <!-- end static/header.html --> <!-- ============================== classes index ============================ --> <div id="index"> <!-- begin publish.classesIndex --> <div align="center"><a href="../index.html">Class Index</a> | <a href="../files.html">File Index</a></div> <hr /> <h2>Classes</h2> <ul class="classList"> <li><i><a href="../symbols/_global_.html">_global_</a></i></li> <li><a href="../symbols/AV.html">AV</a></li> <li><a href="../symbols/AV.ACL.html">AV.ACL</a></li> <li><a href="../symbols/AV.Cloud.html">AV.Cloud</a></li> <li><a href="../symbols/AV.Cloud.AfterSaveRequest.html">AV.Cloud.AfterSaveRequest</a></li> <li><a href="../symbols/AV.Cloud.AfterUpdateRequest.html">AV.Cloud.AfterUpdateRequest</a></li> <li><a href="../symbols/AV.Cloud.BeforeDeleteRequest.html">AV.Cloud.BeforeDeleteRequest</a></li> <li><a href="../symbols/AV.Cloud.BeforeDeleteResponse.html">AV.Cloud.BeforeDeleteResponse</a></li> <li><a href="../symbols/AV.Cloud.BeforeSaveRequest.html">AV.Cloud.BeforeSaveRequest</a></li> <li><a href="../symbols/AV.Cloud.BeforeSaveResponse.html">AV.Cloud.BeforeSaveResponse</a></li> <li><a href="../symbols/AV.Cloud.FunctionRequest.html">AV.Cloud.FunctionRequest</a></li> <li><a href="../symbols/AV.Cloud.FunctionResponse.html">AV.Cloud.FunctionResponse</a></li> <li><a href="../symbols/AV.Collection.html">AV.Collection</a></li> <li><a href="../symbols/AV.Error.html">AV.Error</a></li> <li><a href="../symbols/AV.Events.html">AV.Events</a></li> <li><a href="../symbols/AV.FacebookUtils.html">AV.FacebookUtils</a></li> <li><a href="../symbols/AV.File.html">AV.File</a></li> <li><a href="../symbols/AV.GeoPoint.html">AV.GeoPoint</a></li> <li><a href="../symbols/AV.History.html">AV.History</a></li> <li><a href="../symbols/AV.InboxQuery.html">AV.InboxQuery</a></li> <li><a href="../symbols/AV.Insight.html">AV.Insight</a></li> <li><a href="../symbols/AV.Insight.JobQuery.html">AV.Insight.JobQuery</a></li> <li><a href="../symbols/AV.Object.html">AV.Object</a></li> <li><a href="../symbols/AV.Op.html">AV.Op</a></li> <li><a href="../symbols/AV.Op.Add.html">AV.Op.Add</a></li> <li><a href="../symbols/AV.Op.AddUnique.html">AV.Op.AddUnique</a></li> <li><a href="../symbols/AV.Op.Increment.html">AV.Op.Increment</a></li> <li><a href="../symbols/AV.Op.Relation.html">AV.Op.Relation</a></li> <li><a href="../symbols/AV.Op.Remove.html">AV.Op.Remove</a></li> <li><a href="../symbols/AV.Op.Set.html">AV.Op.Set</a></li> <li><a href="../symbols/AV.Op.Unset.html">AV.Op.Unset</a></li> <li><a href="../symbols/AV.Push.html">AV.Push</a></li> <li><a href="../symbols/AV.Query.html">AV.Query</a></li> <li><a href="../symbols/AV.Relation.html">AV.Relation</a></li> <li><a href="../symbols/AV.Role.html">AV.Role</a></li> <li><a href="../symbols/AV.Router.html">AV.Router</a></li> <li><a href="../symbols/AV.SearchQuery.html">AV.SearchQuery</a></li> <li><a href="../symbols/AV.SearchSortBuilder.html">AV.SearchSortBuilder</a></li> <li><a href="../symbols/AV.Status.html">AV.Status</a></li> <li><a href="../symbols/AV.User.html">AV.User</a></li> <li><a href="../symbols/AV.View.html">AV.View</a></li> <li><a href="../symbols/avosExpressCookieSession.html">avosExpressCookieSession</a></li> <li><a href="../symbols/avosExpressHttpsRedirect.html">avosExpressHttpsRedirect</a></li> </ul> <hr /> <!-- end publish.classesIndex --> </div> <div id="content"> <!-- ============================== class title ============================ --> <h1 class="classTitle"> Class AV.View </h1> <!-- ============================== class summary ========================== --> <p class="description"> <p>A fork of Backbone.View, provided for your convenience. If you use this class, you must also include jQuery, or another library that provides a jQuery-compatible $ function. For more information, see the <a href="http://documentcloud.github.com/backbone/#View">Backbone documentation</a>.</p> <p><strong><em>Available in the client SDK only.</em></strong></p> <br /><i>Defined in: </i> <a href="../symbols/src/lib_view.js.html">view.js</a>. </p> <!-- ============================== constructor summary ==================== --> <table class="summaryTable" cellspacing="0" summary="A summary of the constructor documented in the class AV.View."> <caption>Class Summary</caption> <thead> <tr> <th scope="col">Constructor Attributes</th> <th scope="col">Constructor Name and Description</th> </tr> </thead> <tbody> <tr> <td class="attributes">&nbsp;</td> <td class="nameDescription" > <div class="fixedFont"> <b><a href="../symbols/AV.View.html#constructor">AV.View</a></b>(options) </div> <div class="description">Creating a AV.View creates its initial element outside of the DOM, if an existing element is not provided.</div> </td> </tr> </tbody> </table> <!-- ============================== properties summary ===================== --> <!-- ============================== methods summary ======================== --> <table class="summaryTable" cellspacing="0" summary="A summary of the methods documented in the class AV.View."> <caption>Method Summary</caption> <thead> <tr> <th scope="col">Method Attributes</th> <th scope="col">Method Name and Description</th> </tr> </thead> <tbody> <tr> <td class="attributes">&nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/AV.View.html#$">$</a></b>(selector) </div> <div class="description">jQuery delegate for element lookup, scoped to DOM elements within the current view.</div> </td> </tr> <tr> <td class="attributes">&nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/AV.View.html#delegateEvents">delegateEvents</a></b>(events) </div> <div class="description">Set callbacks.</div> </td> </tr> <tr> <td class="attributes">&lt;static&gt; &nbsp;</td> <td class="nameDescription"> <div class="fixedFont">AV.View.<b><a href="../symbols/AV.View.html#.extend">extend</a></b>(instanceProps, classProps) </div> <div class="description"></div> </td> </tr> <tr> <td class="attributes">&nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/AV.View.html#initialize">initialize</a></b>() </div> <div class="description">Initialize is an empty function by default.</div> </td> </tr> <tr> <td class="attributes">&nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/AV.View.html#make">make</a></b>(tagName, attributes, content) </div> <div class="description">For small amounts of DOM Elements, where a full-blown template isn't needed, use **make** to manufacture elements, one at a time.</div> </td> </tr> <tr> <td class="attributes">&nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/AV.View.html#remove">remove</a></b>() </div> <div class="description">Remove this view from the DOM.</div> </td> </tr> <tr> <td class="attributes">&nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/AV.View.html#render">render</a></b>() </div> <div class="description">The core function that your view should override, in order to populate its element (`this.el`), with the appropriate HTML.</div> </td> </tr> <tr> <td class="attributes">&nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/AV.View.html#setElement">setElement</a></b>(element, delegate) </div> <div class="description">Changes the view's element (`this.el` property), including event re-delegation.</div> </td> </tr> <tr> <td class="attributes">&nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/AV.View.html#undelegateEvents">undelegateEvents</a></b>() </div> <div class="description">Clears all callbacks previously bound to the view with `delegateEvents`.</div> </td> </tr> </tbody> </table> <!-- ============================== events summary ======================== --> <!-- ============================== constructor details ==================== --> <div class="details"><a name="constructor"> </a> <div class="sectionTitle"> Class Detail </div> <div class="fixedFont"> <b>AV.View</b>(options) </div> <div class="description"> Creating a AV.View creates its initial element outside of the DOM, if an existing element is not provided... </div> <dl class="detailList"> <dt class="heading">Parameters:</dt> <dt> <b>options</b> </dt> <dd></dd> </dl> </div> <!-- ============================== field details ========================== --> <!-- ============================== method details ========================= --> <div class="sectionTitle"> Method Detail </div> <a name="$"> </a> <div class="fixedFont"> <b>$</b>(selector) </div> <div class="description"> jQuery delegate for element lookup, scoped to DOM elements within the current view. This should be prefered to global lookups where possible. </div> <dl class="detailList"> <dt class="heading">Parameters:</dt> <dt> <b>selector</b> </dt> <dd></dd> </dl> <hr /> <a name="delegateEvents"> </a> <div class="fixedFont"> <b>delegateEvents</b>(events) </div> <div class="description"> Set callbacks. <code>this.events</code> is a hash of <pre> *{"event selector": "callback"}* { 'mousedown .title': 'edit', 'click .button': 'save' 'click .open': function(e) { ... } } </pre> pairs. Callbacks will be bound to the view, with `this` set properly. Uses event delegation for efficiency. Omitting the selector binds the event to `this.el`. This only works for delegate-able events: not `focus`, `blur`, and not `change`, `submit`, and `reset` in Internet Explorer. </div> <dl class="detailList"> <dt class="heading">Parameters:</dt> <dt> <b>events</b> </dt> <dd></dd> </dl> <hr /> <a name=".extend"> </a> <div class="fixedFont">&lt;static&gt; <span class="light">{Class}</span> <span class="light">AV.View.</span><b>extend</b>(instanceProps, classProps) </div> <div class="description"> </div> <dl class="detailList"> <dt class="heading">Parameters:</dt> <dt> <span class="light fixedFont">{Object}</span> <b>instanceProps</b> </dt> <dd>Instance properties for the view.</dd> <dt> <span class="light fixedFont">{Object}</span> <b>classProps</b> </dt> <dd>Class properies for the view.</dd> </dl> <dl class="detailList"> <dt class="heading">Returns:</dt> <dd><span class="light fixedFont">{Class}</span> A new subclass of <code>AV.View</code>.</dd> </dl> <hr /> <a name="initialize"> </a> <div class="fixedFont"> <b>initialize</b>() </div> <div class="description"> Initialize is an empty function by default. Override it with your own initialization logic. </div> <hr /> <a name="make"> </a> <div class="fixedFont"> <b>make</b>(tagName, attributes, content) </div> <div class="description"> For small amounts of DOM Elements, where a full-blown template isn't needed, use **make** to manufacture elements, one at a time. <pre> var el = this.make('li', {'class': 'row'}, this.model.escape('title'));</pre> </div> <dl class="detailList"> <dt class="heading">Parameters:</dt> <dt> <b>tagName</b> </dt> <dd></dd> <dt> <b>attributes</b> </dt> <dd></dd> <dt> <b>content</b> </dt> <dd></dd> </dl> <hr /> <a name="remove"> </a> <div class="fixedFont"> <b>remove</b>() </div> <div class="description"> Remove this view from the DOM. Note that the view isn't present in the DOM by default, so calling this method may be a no-op. </div> <hr /> <a name="render"> </a> <div class="fixedFont"> <b>render</b>() </div> <div class="description"> The core function that your view should override, in order to populate its element (`this.el`), with the appropriate HTML. The convention is for **render** to always return `this`. </div> <hr /> <a name="setElement"> </a> <div class="fixedFont"> <b>setElement</b>(element, delegate) </div> <div class="description"> Changes the view's element (`this.el` property), including event re-delegation. </div> <dl class="detailList"> <dt class="heading">Parameters:</dt> <dt> <b>element</b> </dt> <dd></dd> <dt> <b>delegate</b> </dt> <dd></dd> </dl> <hr /> <a name="undelegateEvents"> </a> <div class="fixedFont"> <b>undelegateEvents</b>() </div> <div class="description"> Clears all callbacks previously bound to the view with `delegateEvents`. You usually don't need to use this, but may wish to if you have multiple Backbone views attached to the same DOM element. </div> <!-- ============================== event details ========================= --> <hr /> </div> <!-- ============================== footer ================================= --> <div class="fineprint" style="clear:both"> Documentation generated by <a href="http://code.google.com/p/jsdoc-toolkit/" target="_blank">JsDoc Toolkit</a> 2.4.0 on Fri Aug 28 2015 11:55:10 GMT+0800 (CST) </div> </body> </html>
{ "content_hash": "f83491678189c32a2b092a60b3c00d24", "timestamp": "", "source": "github", "line_count": 846, "max_line_length": 162, "avg_line_length": 22.138297872340427, "alnum_prop": 0.5265096908537562, "repo_name": "SK8-PTY-LTD/YunDa-Delivery", "id": "f94d0d1cc969f4c99a919a96b41e4fccc8daaacd", "size": "18729", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node_modules/leanengine/node_modules/avoscloud-sdk/dist/js-sdk-api-docs/symbols/AV.View.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "15560" }, { "name": "JavaScript", "bytes": "613791" } ], "symlink_target": "" }
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import './xf_button.js'; import './xf_circular_progress.js'; import {assert} from 'chrome://resources/js/assert.m.js'; import {html} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {str, util} from '../../common/js/util.js'; import {DisplayPanel} from './xf_display_panel.js'; /** @type {!HTMLTemplateElement} */ const htmlTemplate = html`{__html_template__}`; /** * A panel to display the status or progress of a file operation. * @extends HTMLElement */ export class PanelItem extends HTMLElement { constructor() { super(); const fragment = htmlTemplate.content.cloneNode(true); this.attachShadow({mode: 'open'}).appendChild(fragment); /** @private {Element} */ this.indicator_ = this.shadowRoot.querySelector('#indicator'); /** * TODO(crbug.com/947388) make this a closure enum. * @const */ this.panelTypeDefault = -1; this.panelTypeProgress = 0; this.panelTypeSummary = 1; this.panelTypeDone = 2; this.panelTypeError = 3; this.panelTypeInfo = 4; this.panelTypeFormatProgress = 5; this.panelTypeSyncProgress = 6; /** @private {number} */ this.panelType_ = this.panelTypeDefault; /** @private @type {?function(Event)} */ this.onclick = this.onClicked_.bind(this); /** @public {?DisplayPanel} */ this.parent = null; /** * Callback that signals events happening in the panel (e.g. click). * @private @type {!function(*)} */ this.signal_ = console.log; /** * User specific data, used as a reference to persist any custom * data that the panel user may want to use in the signal callback. * e.g. holding the file name(s) used in a copy operation. * @type {?Object} */ this.userData = null; } /** * Remove an element from the panel using it's id. * @return {?Element} * @private */ removePanelElementById_(id) { const element = this.shadowRoot.querySelector(id); if (element) { element.remove(); } return element; } /** * Sets up the different panel types. Panels have per-type configuration * templates, but can be further customized using individual attributes. * @param {number} type The enumerated panel type to set up. * @private */ setPanelType(type) { this.setAttribute('detailed-panel', 'detailed-panel'); if (this.panelType_ === type) { return; } // Remove the indicators/buttons that can change. this.removePanelElementById_('#indicator'); let element = this.removePanelElementById_('#primary-action'); if (element) { element.onclick = null; } element = this.removePanelElementById_('#secondary-action'); if (element) { element.onclick = null; } // Mark the indicator as empty so it recreates on setAttribute. this.setAttribute('indicator', 'empty'); const buttonSpacer = this.shadowRoot.querySelector('#button-gap'); // Default the text host to use an alert role. const textHost = assert(this.shadowRoot.querySelector('.xf-panel-text')); textHost.setAttribute('role', 'alert'); // Setup the panel configuration for the panel type. // TOOD(crbug.com/947388) Simplify this switch breaking out common cases. /** @type {?Element} */ let primaryButton = null; /** @type {?Element} */ let secondaryButton = null; switch (type) { case this.panelTypeProgress: this.setAttribute('indicator', 'progress'); secondaryButton = document.createElement('xf-button'); secondaryButton.id = 'secondary-action'; secondaryButton.onclick = assert(this.onclick); secondaryButton.dataset.category = 'cancel'; secondaryButton.setAttribute('aria-label', str('CANCEL_LABEL')); buttonSpacer.insertAdjacentElement('afterend', secondaryButton); break; case this.panelTypeSummary: this.setAttribute('indicator', 'largeprogress'); primaryButton = document.createElement('xf-button'); primaryButton.id = 'primary-action'; primaryButton.dataset.category = 'expand'; primaryButton.setAttribute('aria-label', str('FEEDBACK_EXPAND_LABEL')); // Remove the 'alert' role to stop screen readers repeatedly // reading each progress update. textHost.setAttribute('role', ''); buttonSpacer.insertAdjacentElement('afterend', primaryButton); break; case this.panelTypeDone: this.setAttribute('indicator', 'status'); this.setAttribute('status', 'success'); primaryButton = document.createElement('xf-button'); primaryButton.id = 'primary-action'; primaryButton.onclick = assert(this.onclick); primaryButton.dataset.category = 'dismiss'; buttonSpacer.insertAdjacentElement('afterend', primaryButton); break; case this.panelTypeError: this.setAttribute('indicator', 'status'); this.setAttribute('status', 'failure'); this.primaryText = str('FILE_ERROR_GENERIC'); this.secondaryText = ''; secondaryButton = document.createElement('xf-button'); secondaryButton.id = 'secondary-action'; secondaryButton.onclick = assert(this.onclick); secondaryButton.dataset.category = 'dismiss'; buttonSpacer.insertAdjacentElement('afterend', secondaryButton); break; case this.panelTypeInfo: break; case this.panelTypeFormatProgress: this.setAttribute('indicator', 'status'); this.setAttribute('status', 'hard-drive'); break; case this.panelTypeSyncProgress: this.setAttribute('indicator', 'progress'); break; } this.panelType_ = type; } /** * Registers this instance to listen to these attribute changes. * @private */ static get observedAttributes() { return [ 'count', 'errormark', 'indicator', 'panel-type', 'primary-text', 'progress', 'secondary-text', 'status', ]; } /** * Callback triggered by the browser when our attribute values change. * @param {string} name Attribute that's changed. * @param {?string} oldValue Old value of the attribute. * @param {?string} newValue New value of the attribute. * @private */ attributeChangedCallback(name, oldValue, newValue) { /** @type {Element} */ let indicator = null; /** @type {Element} */ let textNode; // TODO(adanilo) Chop out each attribute handler into a function. switch (name) { case 'count': if (this.indicator_) { this.indicator_.setAttribute('label', newValue || ''); } break; case 'errormark': if (this.indicator_) { this.indicator_.setAttribute('errormark', newValue || ''); } break; case 'indicator': // Get rid of any existing indicator const oldIndicator = this.shadowRoot.querySelector('#indicator'); if (oldIndicator) { oldIndicator.remove(); } switch (newValue) { case 'progress': case 'largeprogress': indicator = document.createElement('xf-circular-progress'); if (newValue === 'largeprogress') { indicator.setAttribute('radius', '14'); } else { indicator.setAttribute('radius', '10'); } break; case 'status': indicator = document.createElement('iron-icon'); const status = this.getAttribute('status'); if (status) { indicator.setAttribute('icon', `files36:${status}`); } break; } this.indicator_ = indicator; if (indicator) { const itemRoot = this.shadowRoot.querySelector('.xf-panel-item'); indicator.setAttribute('id', 'indicator'); itemRoot.prepend(indicator); } break; case 'panel-type': this.setPanelType(Number(newValue)); if (this.parent && this.parent.updateSummaryPanel) { this.parent.updateSummaryPanel(); } break; case 'progress': if (this.indicator_) { this.indicator_.progress = Number(newValue); if (this.parent && this.parent.updateProgress) { this.parent.updateProgress(); } } break; case 'status': if (this.indicator_) { this.indicator_.setAttribute('icon', `files36:${newValue}`); } break; case 'primary-text': textNode = this.shadowRoot.querySelector('.xf-panel-label-text'); if (textNode) { textNode.textContent = newValue; // Set the aria labels for the activity and cancel button. this.setAttribute('aria-label', /** @type {string} */ (newValue)); } break; case 'secondary-text': textNode = this.shadowRoot.querySelector('.xf-panel-secondary-text'); if (!textNode) { const parent = this.shadowRoot.querySelector('.xf-panel-text'); if (!parent) { return; } textNode = document.createElement('span'); textNode.setAttribute('class', 'xf-panel-secondary-text'); parent.appendChild(textNode); } // Remove the secondary text node if the text is empty if (newValue == '') { textNode.remove(); } else { textNode.textContent = newValue; } break; } } /** * DOM connected. * @private */ connectedCallback() { this.onclick = this.onClicked_.bind(this); // Set click event handler references. let button = this.shadowRoot.querySelector('#primary-action'); if (button) { button.onclick = this.onclick; } button = this.shadowRoot.querySelector('#secondary-action'); if (button) { button.onclick = this.onclick; } } /** * DOM disconnected. * @private */ disconnectedCallback() { // Replace references to any signal callback. this.signal_ = console.log; // Clear click event handler references. let button = this.shadowRoot.querySelector('#primary-action'); if (button) { button.onclick = null; } button = this.shadowRoot.querySelector('#secondary-action'); if (button) { button.onclick = null; } this.onclick = null; } /** * Handles 'click' events from our sub-elements and sends * signals to the |signal_| callback if needed. * @param {?Event} event * @private */ onClicked_(event) { event.stopImmediatePropagation(); event.preventDefault(); // Ignore clicks on the panel item itself. if (event.target === this) { return; } const id = assert(event.target.dataset.category); this.signal_(id); } /** * Sets the callback that triggers signals from events on the panel. * @param {?function(*)} signal */ set signalCallback(signal) { this.signal_ = signal || console.log; } /** * Set the visibility of the error marker. * @param {string} visibility Visibility value being set. */ set errorMarkerVisibility(visibility) { this.setAttribute('errormark', visibility); } /** * Getter for the visibility of the error marker. */ get errorMarkerVisibility() { // If we have an indicator on the panel, then grab the // visibility value from that. if (this.indicator_) { return this.indicator_.errorMarkerVisibility; } // If there's no indicator on the panel just return the // value of any attribute as a fallback. return this.getAttribute('errormark'); } /** * Setter to set the indicator type. * @param {string} indicator Progress (optionally large) or status. */ set indicator(indicator) { this.setAttribute('indicator', indicator); } /** * Getter for the progress indicator. */ get indicator() { return this.getAttribute('indicator'); } /** * Setter to set the success/failure indication. * @param {string} status Status value being set. */ set status(status) { this.setAttribute('status', status); } /** * Getter for the success/failure indication. */ get status() { return this.getAttribute('status'); } /** * Setter to set the progress property, sent to any child indicator. * @param {string} progress Progress value being set. * @public */ set progress(progress) { this.setAttribute('progress', progress); } /** * Getter for the progress indicator percentage. */ get progress() { return this.indicator_.progress || 0; } /** * Setter to set the primary text on the panel. * @param {string} text Text to be shown. */ set primaryText(text) { this.setAttribute('primary-text', text); } /** * Getter for the primary text on the panel. * @return {string} */ get primaryText() { return this.getAttribute('primary-text'); } /** * Setter to set the secondary text on the panel. * @param {string} text Text to be shown. */ set secondaryText(text) { this.setAttribute('secondary-text', text); } /** * Getter for the secondary text on the panel. * @return {string} */ get secondaryText() { return this.getAttribute('secondary-text'); } /** * Setter to set the panel type. * @param {number} type Enum value for the panel type. */ set panelType(type) { this.setAttribute('panel-type', type); } /** * Getter for the panel type. * TODO(crbug.com/947388) Add closure annotations to getters. */ get panelType() { return this.panelType_; } /** * Getter for the primary action button. */ get primaryButton() { return this.shadowRoot.querySelector('#primary-action'); } /** * Getter for the secondary action button. */ get secondaryButton() { return this.shadowRoot.querySelector('#secondary-action'); } /** * Getter for the panel text div. */ get textDiv() { return this.shadowRoot.querySelector('.xf-panel-text'); } /** * Setter to replace the default aria-label on any close button. * @param {string} text Text to set for the 'aria-label'. */ set closeButtonAriaLabel(text) { const action = this.shadowRoot.querySelector('#secondary-action'); if (action && action.dataset.category === 'cancel') { action.setAttribute('aria-label', text); } } } window.customElements.define('xf-panel-item', PanelItem); //# sourceURL=//ui/file_manager/file_manager/foreground/elements/xf_panel_item.js
{ "content_hash": "18925c5d5a7906426278abd60e7d734b", "timestamp": "", "source": "github", "line_count": 511, "max_line_length": 84, "avg_line_length": 29.025440313111545, "alnum_prop": 0.6198085221143473, "repo_name": "scheib/chromium", "id": "3eceaebed77d94d588e003c699b917775195743a", "size": "14832", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "ui/file_manager/file_manager/foreground/elements/xf_panel_item.js", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
require 'neows/models/base_model' module Neows module Models class EstimatedDiameterMinMax < Neows::Models::BaseModel # @!attribute [rw] # @return [Float] attribute :estimated_diameter_min, Float # @!attribute [rw] # @return [Integer] attribute :estimated_diameter_max, Float end end end
{ "content_hash": "a58af531e762be56662d3f724093e310", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 60, "avg_line_length": 22.533333333333335, "alnum_prop": 0.6538461538461539, "repo_name": "SpaceRocks/neows-ruby", "id": "021332b9ef4a27590020b48fc6becbdea6423ec0", "size": "338", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/neows/models/estimated_diameter_min_max.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "29259" } ], "symlink_target": "" }
"""Scraper for the 4th District Court of Appeals CourtID: ohioctap_4 Court Short Name: Ohio Dist Ct App 4 Author: Andrei Chelaru """ from juriscraper.opinions.united_states.state import ohio class Site(ohio.Site): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.court_id = self.__module__ self.court_index = 4
{ "content_hash": "0103c3cd8f30179631c2823942ff00e9", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 57, "avg_line_length": 26.357142857142858, "alnum_prop": 0.6612466124661247, "repo_name": "freelawproject/juriscraper", "id": "4dc81cded73bfeb7b9b61d9c52e6d2aff64e5edd", "size": "369", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "juriscraper/opinions/united_states/state/ohioctapp_4.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "HTML", "bytes": "63242956" }, { "name": "Jinja", "bytes": "2201" }, { "name": "Makefile", "bytes": "75" }, { "name": "Python", "bytes": "1059228" } ], "symlink_target": "" }
#include "e.h" /* local subsystem functions */ static void _e_config_dialog_free(E_Config_Dialog *cfd); static void _e_config_dialog_go(E_Config_Dialog *cfd, E_Config_Dialog_CFData_Type type); static Eina_Bool _e_config_dialog_cb_auto_apply_timer(void *data); static void _e_config_dialog_cb_dialog_del(void *obj); static void _e_config_dialog_cb_ok(void *data, E_Dialog *dia); static void _e_config_dialog_cb_apply(void *data, E_Dialog *dia); static void _e_config_dialog_cb_advanced(void *data, void *data2); static void _e_config_dialog_cb_basic(void *data, void *data2); static int _e_config_dialog_check_changed(E_Config_Dialog *cfd, unsigned char def); static void _e_config_dialog_cb_changed(void *data, Evas_Object *obj); static void _e_config_dialog_cb_close(void *data, E_Dialog *dia); /* local subsystem globals */ static Eina_List *_e_config_dialog_list = NULL; /* externally accessible functions */ /** * Creates a new dialog * * @param con the container the dialog will be added too * @param title to display for the dialog * @param name the name used to register the window in e * @param class the call used to register the window in e * @param icon the path to the icon file * @param icon_size is of the width and height of the icon * @param view the callbacks used to create the dialog and save the settings * @param data additional data to attach to the dialog, will be passed to the callbacks * @return returns the created dialog. Null on failure */ EAPI E_Config_Dialog * e_config_dialog_new(E_Container *con, const char *title, const char *name, const char *class, const char *icon, int icon_size, E_Config_Dialog_View *view, void *data) { E_Config_Dialog *cfd; cfd = E_OBJECT_ALLOC(E_Config_Dialog, E_CONFIG_DIALOG_TYPE, _e_config_dialog_free); cfd->view = view; cfd->con = con; cfd->title = eina_stringshare_add(title); cfd->name = eina_stringshare_add(name); cfd->class = eina_stringshare_add(class); if (icon) { cfd->icon = eina_stringshare_add(icon); cfd->icon_size = icon_size; } cfd->data = data; cfd->hide_buttons = 1; cfd->cfg_changed = 0; cfd->cfg_changed_auto = 1; if (cfd->view->override_auto_apply) { /* Dialog Requested To Not Auto-Apply */ if ((cfd->view->basic.apply_cfdata) || (cfd->view->advanced.apply_cfdata)) cfd->hide_buttons = 0; } else { /* Ok To Override, Or Not Specified. Use Config Value */ if (e_config->cfgdlg_auto_apply) cfd->hide_buttons = 1; else { if ((cfd->view->basic.apply_cfdata) || (cfd->view->advanced.apply_cfdata)) cfd->hide_buttons = 0; } } switch (e_config->cfgdlg_default_mode) { case E_CONFIG_DIALOG_CFDATA_TYPE_BASIC: if (cfd->view->basic.create_widgets) _e_config_dialog_go(cfd, E_CONFIG_DIALOG_CFDATA_TYPE_BASIC); break; case E_CONFIG_DIALOG_CFDATA_TYPE_ADVANCED: if (cfd->view->advanced.create_widgets) _e_config_dialog_go(cfd, E_CONFIG_DIALOG_CFDATA_TYPE_ADVANCED); else if (cfd->view->basic.create_widgets) _e_config_dialog_go(cfd, E_CONFIG_DIALOG_CFDATA_TYPE_BASIC); break; } _e_config_dialog_list = eina_list_append(_e_config_dialog_list, cfd); return cfd; } EAPI int e_config_dialog_find(const char *name, const char *class) { Eina_List *l; E_Config_Dialog *cfd; EINA_LIST_FOREACH(_e_config_dialog_list, l, cfd) { if ((!e_util_strcmp(name, cfd->name)) && (!e_util_strcmp(class, cfd->class))) { E_Zone *z; z = e_util_zone_current_get(e_manager_current_get()); e_border_uniconify(cfd->dia->win->border); e_win_raise(cfd->dia->win); if (z->container == cfd->dia->win->border->zone->container) e_border_desk_set(cfd->dia->win->border, e_desk_current_get(z)); else { if (!cfd->dia->win->border->sticky) e_desk_show(cfd->dia->win->border->desk); ecore_x_pointer_warp(cfd->dia->win->border->zone->container->win, cfd->dia->win->border->zone->x + (cfd->dia->win->border->zone->w / 2), cfd->dia->win->border->zone->y + (cfd->dia->win->border->zone->h / 2)); } e_border_unshade(cfd->dia->win->border, cfd->dia->win->border->shade.dir); if ((e_config->focus_setting == E_FOCUS_NEW_DIALOG) || (e_config->focus_setting == E_FOCUS_NEW_WINDOW)) e_border_focus_set(cfd->dia->win->border, 1, 1); return 1; } } return 0; } EAPI E_Config_Dialog * e_config_dialog_get(const char *name, const char *class) { Eina_List *l; E_Config_Dialog *cfd; EINA_LIST_FOREACH(_e_config_dialog_list, l, cfd) { if (!cfd) continue; if ((!e_util_strcmp(name, cfd->name)) && (!e_util_strcmp(class, cfd->class))) { return cfd; } } return NULL; } /* local subsystem functions */ static void _e_config_dialog_free(E_Config_Dialog *cfd) { _e_config_dialog_list = eina_list_remove(_e_config_dialog_list, cfd); if (cfd->auto_apply_timer) _e_config_dialog_cb_auto_apply_timer(cfd); if (cfd->title) eina_stringshare_del(cfd->title); if (cfd->name) eina_stringshare_del(cfd->name); if (cfd->class) eina_stringshare_del(cfd->class); if (cfd->icon) eina_stringshare_del(cfd->icon); if (cfd->view->free_cfdata) { cfd->view->free_cfdata(cfd, cfd->cfdata); cfd->cfdata = NULL; } if (cfd->dia) { e_object_del_attach_func_set(E_OBJECT(cfd->dia), NULL); e_object_del(E_OBJECT(cfd->dia)); cfd->dia = NULL; } E_FREE(cfd->view); E_FREE(cfd); } static void _e_config_dialog_go(E_Config_Dialog *cfd, E_Config_Dialog_CFData_Type type) { Evas *evas; E_Dialog *pdia; Evas_Object *o, *ob, *sf; Evas_Coord mw = 0, mh = 0; char buf[256]; void *cfdata; pdia = cfd->dia; /* FIXME: get name/class form new call and use here */ /* if (type == E_CONFIG_DIALOG_CFDATA_TYPE_BASIC) * snprintf(buf, sizeof(buf), "%s...%s", cfd->class, "BASIC"); * else * snprintf(buf, sizeof(buf), "%s...%s", cfd->class, "ADVANCED"); */ snprintf(buf, sizeof(buf), "_config::%s", cfd->class); if (!pdia) /* creating window for the first time */ { if ((cfd->view->normal_win) || (e_config->cfgdlg_normal_wins)) cfd->dia = e_dialog_normal_win_new(cfd->con, cfd->name, buf); else cfd->dia = e_dialog_new(cfd->con, cfd->name, buf); e_object_del_attach_func_set(E_OBJECT(cfd->dia), _e_config_dialog_cb_dialog_del); } /* window was created before - deleting content only */ else if (cfd->dia->content_object) evas_object_del(cfd->dia->content_object); cfd->view_type = type; cfd->dia->data = cfd; e_dialog_title_set(cfd->dia, cfd->title); cfdata = cfd->cfdata; if (cfd->view->create_cfdata && (!cfd->cfdata)) cfd->cfdata = cfd->view->create_cfdata(cfd); evas = e_win_evas_get(cfd->dia->win); if (type == E_CONFIG_DIALOG_CFDATA_TYPE_BASIC) { if (cfd->view->advanced.create_widgets) { o = e_widget_list_add(evas, 0, 0); ob = cfd->view->basic.create_widgets(cfd, evas, cfd->cfdata); if (cfd->view->scroll) { e_widget_size_min_resize(ob); sf = e_widget_scrollframe_simple_add(evas, ob); e_widget_list_object_append(o, sf, 1, 1, 0.0); } else e_widget_list_object_append(o, ob, 1, 1, 0.0); ob = e_widget_button_add(evas, _("Advanced"), "go-next", _e_config_dialog_cb_advanced, cfd, NULL); e_widget_list_object_append(o, ob, 0, 0, 1.0); } else { o = cfd->view->basic.create_widgets(cfd, evas, cfd->cfdata); if (cfd->view->scroll) { e_widget_size_min_resize(o); o = e_widget_scrollframe_simple_add(evas, o); } } } else { if (cfd->view->basic.create_widgets) { o = e_widget_list_add(evas, 0, 0); ob = cfd->view->advanced.create_widgets(cfd, evas, cfd->cfdata); if (cfd->view->scroll) { e_widget_size_min_resize(ob); sf = e_widget_scrollframe_simple_add(evas, ob); e_widget_list_object_append(o, sf, 1, 1, 0.0); } else e_widget_list_object_append(o, ob, 1, 1, 0.0); ob = e_widget_button_add(evas, _("Basic"), "go-next", _e_config_dialog_cb_basic, cfd, NULL); e_widget_list_object_append(o, ob, 0, 0, 1.0); } else { o = cfd->view->advanced.create_widgets(cfd, evas, cfd->cfdata); if (cfd->view->scroll) { e_widget_size_min_resize(o); o = e_widget_scrollframe_simple_add(evas, o); } } } e_widget_size_min_get(o, &mw, &mh); e_widget_on_change_hook_set(o, _e_config_dialog_cb_changed, cfd); e_dialog_content_set(cfd->dia, o, mw, mh); if (!pdia) /* dialog window was created in this function call - need to create buttons once */ { if (!cfd->hide_buttons) { e_dialog_button_add(cfd->dia, _("OK"), NULL, _e_config_dialog_cb_ok, cfd); e_dialog_button_add(cfd->dia, _("Apply"), NULL, _e_config_dialog_cb_apply, cfd); if (!cfd->cfg_changed) { e_dialog_button_disable_num_set(cfd->dia, 0, 1); e_dialog_button_disable_num_set(cfd->dia, 1, 1); } } e_dialog_button_add(cfd->dia, _("Close"), NULL, _e_config_dialog_cb_close, cfd); } if (cfdata && cfd->cfg_changed_auto) { int changed; changed = _e_config_dialog_check_changed(cfd, 0); e_config_dialog_changed_set(cfd, changed); } e_dialog_show(cfd->dia); if (cfd->icon) e_dialog_border_icon_set(cfd->dia, cfd->icon); } static Eina_Bool _e_config_dialog_cb_auto_apply_timer(void *data) { E_Config_Dialog *cfd; cfd = data; if (cfd->auto_apply_timer) ecore_timer_del(cfd->auto_apply_timer); cfd->auto_apply_timer = NULL; if (cfd->view_type == E_CONFIG_DIALOG_CFDATA_TYPE_BASIC) { if (cfd->view->basic.apply_cfdata) cfd->view->basic.apply_cfdata(cfd, cfd->cfdata); } else { if (cfd->view->advanced.apply_cfdata) cfd->view->advanced.apply_cfdata(cfd, cfd->cfdata); } return ECORE_CALLBACK_CANCEL; } static void _e_config_dialog_cb_dialog_del(void *obj) { E_Dialog *dia; E_Config_Dialog *cfd; dia = obj; cfd = dia->data; if (cfd->auto_apply_timer) _e_config_dialog_cb_auto_apply_timer(cfd); cfd->dia = NULL; e_object_del(E_OBJECT(cfd)); } static void _e_config_dialog_cb_ok(void *data __UNUSED__, E_Dialog *dia) { E_Config_Dialog *cfd; int ok = 0; cfd = dia->data; if (cfd->view_type == E_CONFIG_DIALOG_CFDATA_TYPE_BASIC) { if (cfd->view->basic.apply_cfdata) ok = cfd->view->basic.apply_cfdata(cfd, cfd->cfdata); } else { if (cfd->view->advanced.apply_cfdata) ok = cfd->view->advanced.apply_cfdata(cfd, cfd->cfdata); } if (ok) e_util_defer_object_del(E_OBJECT(cfd)); } static void _e_config_dialog_cb_apply(void *data __UNUSED__, E_Dialog *dia) { E_Config_Dialog *cfd; int ok = 0; cfd = dia->data; if (cfd->view_type == E_CONFIG_DIALOG_CFDATA_TYPE_BASIC) { if (cfd->view->basic.apply_cfdata) ok = cfd->view->basic.apply_cfdata(cfd, cfd->cfdata); } else { if (cfd->view->advanced.apply_cfdata) ok = cfd->view->advanced.apply_cfdata(cfd, cfd->cfdata); } if ((ok) && (!cfd->hide_buttons)) { cfd->cfg_changed = 0; e_dialog_button_disable_num_set(cfd->dia, 0, 1); e_dialog_button_disable_num_set(cfd->dia, 1, 1); } } static void _e_config_dialog_cb_advanced(void *data, void *data2 __UNUSED__) { E_Config_Dialog *cfd; cfd = data; if (cfd->auto_apply_timer) _e_config_dialog_cb_auto_apply_timer(cfd); _e_config_dialog_go(cfd, E_CONFIG_DIALOG_CFDATA_TYPE_ADVANCED); } static void _e_config_dialog_cb_basic(void *data, void *data2 __UNUSED__) { E_Config_Dialog *cfd; cfd = data; if (cfd->auto_apply_timer) _e_config_dialog_cb_auto_apply_timer(cfd); _e_config_dialog_go(cfd, E_CONFIG_DIALOG_CFDATA_TYPE_BASIC); } static void _e_config_dialog_changed(E_Config_Dialog *cfd) { if (!cfd->hide_buttons) { cfd->cfg_changed = 1; e_dialog_button_disable_num_set(cfd->dia, 0, 0); e_dialog_button_disable_num_set(cfd->dia, 1, 0); } else { if (cfd->auto_apply_timer) ecore_timer_del(cfd->auto_apply_timer); cfd->auto_apply_timer = NULL; cfd->auto_apply_timer = ecore_timer_add(0.5, _e_config_dialog_cb_auto_apply_timer, cfd); } } static void _e_config_dialog_unchanged(E_Config_Dialog *cfd) { if (!cfd->hide_buttons) { e_dialog_button_disable_num_set(cfd->dia, 0, 1); e_dialog_button_disable_num_set(cfd->dia, 1, 1); } else { if (cfd->auto_apply_timer) { ecore_timer_del(cfd->auto_apply_timer); cfd->auto_apply_timer = NULL; } } } static int _e_config_dialog_check_changed(E_Config_Dialog *cfd, unsigned char def) { int changed = 0; if (cfd->view_type == E_CONFIG_DIALOG_CFDATA_TYPE_BASIC) { if (cfd->view->basic.check_changed) changed = cfd->view->basic.check_changed(cfd, cfd->cfdata); else changed = def; } else if (cfd->view_type == E_CONFIG_DIALOG_CFDATA_TYPE_ADVANCED) { if (cfd->view->advanced.check_changed) changed = cfd->view->advanced.check_changed(cfd, cfd->cfdata); else changed = def; } return changed; } static void _e_config_dialog_cb_changed(void *data, Evas_Object *obj __UNUSED__) { E_Config_Dialog *cfd; int changed; cfd = data; if (!cfd->cfg_changed_auto) return; changed = _e_config_dialog_check_changed(cfd, 1); e_config_dialog_changed_set(cfd, changed); } static void _e_config_dialog_cb_close(void *data __UNUSED__, E_Dialog *dia) { E_Config_Dialog *cfd; int ok = 1; cfd = dia->data; if (cfd->auto_apply_timer) _e_config_dialog_cb_auto_apply_timer(cfd); if (cfd->view->close_cfdata) ok = cfd->view->close_cfdata(cfd, cfd->cfdata); if (ok) e_util_defer_object_del(E_OBJECT(cfd)); } EAPI void e_config_dialog_changed_auto_set(E_Config_Dialog *cfd, unsigned char value) { if (!cfd) return; cfd->cfg_changed_auto = !!value; } EAPI void e_config_dialog_changed_set(E_Config_Dialog *cfd, unsigned char value) { if (!cfd) return; cfd->cfg_changed = !!value; if (cfd->cfg_changed) _e_config_dialog_changed(cfd); else _e_config_dialog_unchanged(cfd); }
{ "content_hash": "95ef9f61f1073879e58f360919da2e81", "timestamp": "", "source": "github", "line_count": 508, "max_line_length": 166, "avg_line_length": 31.16732283464567, "alnum_prop": 0.561043390387166, "repo_name": "jordemort/e17", "id": "de549fc175ad5027465570b604ea09b82f212862", "size": "15833", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/bin/e_config_dialog.c", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "7982022" }, { "name": "C++", "bytes": "44106" }, { "name": "Objective-C", "bytes": "2788" }, { "name": "Shell", "bytes": "335991" } ], "symlink_target": "" }
'use strict'; var Socket = function (render) { var socket = io(); socket.on('channel', function (channel) { render.currChannel = channel; render.channel(render.currChannel); }); socket.on('nick', function (nick) { render.nick = nick; }); socket.on('users', function (users) { render.channel(render.currChannel); render.channels[render.currChannel].users = users.users; render.users(); }); socket.on('message', function (message) { render.channel(message.channel); render.message(message); }); } module.exports = Socket;
{ "content_hash": "166846c91ecf67028d34d55e3813f196", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 60, "avg_line_length": 20.607142857142858, "alnum_prop": 0.6481802426343154, "repo_name": "ednapiranha/norelay", "id": "aebdd99dc626c801052854df7bb6fcf047180f87", "size": "577", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/js/lib/socket.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "2350" }, { "name": "JavaScript", "bytes": "67300" } ], "symlink_target": "" }
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'musicassette' RSpec.configure do |config| config.expect_with :rspec do |c| c.syntax = [:should, :expect] end config.mock_with :rspec do |c| c.syntax = [:should, :expect] end config.before :each do Typhoeus::Expectation.clear end end
{ "content_hash": "371e7d6f57c7f0456cc3fc21f9e3d0a5", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 58, "avg_line_length": 23.285714285714285, "alnum_prop": 0.6595092024539877, "repo_name": "odcinek/musicassette", "id": "14990165e1c6261e011917bf05552aeff7449f5c", "size": "326", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/spec_helper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "4367" }, { "name": "Shell", "bytes": "115" } ], "symlink_target": "" }
<?php namespace Detail\Auth\Service; use Zend\Http\Request as HttpRequest; trait HttpRequestAwareTrait { /** * @var HttpRequest */ protected $request; /** * @return HttpRequest */ public function getRequest() { return $this->request; } /** * @param HttpRequest $request */ public function setRequest(HttpRequest $request) { $this->request = $request; } }
{ "content_hash": "156f0425d6fec05b616a1ad9ad4f5571", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 52, "avg_line_length": 15.379310344827585, "alnum_prop": 0.5762331838565022, "repo_name": "ivan-wolf/dfw-auth-module", "id": "b373780303618b8b955ed2466f2241bfad1beac2", "size": "446", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Service/HttpRequestAwareTrait.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "85074" } ], "symlink_target": "" }
using System.Web.Mvc; using Microsoft.VisualStudio.TestTools.UnitTesting; using WebApplication1.Controllers; namespace UnitTestProject1 { [TestClass] public class UnitTest1 { [TestMethod] public void TestHomeController() { HomeController ctl = new HomeController(); ViewResult res = ctl.About() as ViewResult; Assert.AreEqual("About PACKT Publishing", (dynamic) res.Model.ToString()); } } }
{ "content_hash": "bb94b7251af39348bad96d666eeecd9a", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 55, "avg_line_length": 25.842105263157894, "alnum_prop": 0.6313645621181263, "repo_name": "Dhiraj3005/Mastering-C-Sharp-and-.NET-Framework", "id": "f3160ef80bd8d576111bbd17d0cbade04d281a71", "size": "493", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Chapter09/WebApplication1/UnitTestProject1/UnitTest1.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "522" }, { "name": "C#", "bytes": "448327" }, { "name": "CSS", "bytes": "12183" }, { "name": "F#", "bytes": "6227" }, { "name": "HTML", "bytes": "41706" }, { "name": "JavaScript", "bytes": "5861533" }, { "name": "PowerShell", "bytes": "447357" }, { "name": "TypeScript", "bytes": "3374" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en" id="webstandardssherpa_com"> <head> <meta charset="utf-8"> <meta http-equiv="Content-Language" content="en"/> <title>Sign Up - Web Standards Sherpa</title> <meta name="robots" content="index,follow,archive" /> <meta name='description' content='Web Standards Sherpa&rsquo;s experts provide helpful, pragmatic and up-to-date advice on best practices for web professionals everywhere.' /> <meta name='DC.description' content='Web Standards Sherpa&rsquo;s experts provide helpful, pragmatic and up-to-date advice on best practices for web professionals everywhere.' /> <meta name='keywords' content='web standards,best practices,web design,web development' /> <meta name='DC.subject' content='web standards,best practices,web design,web development' /> <link rel="schema.DC" href="http://purl.org/dc/elements/1.1/" /> <link rel="schema.DCTERMS" href="http://purl.org/dc/terms/" /> <meta name="DC.title" content="Sign Up - Web Standards Sherpa" /> <meta name="DC.creator" content="Web Standards Sherpa" /> <meta name="DC.publisher" content="The Web Standards Project" /> <meta name="DC.date.created" scheme="DCTERMS.W3CDTF" content="2015-12-07T14:49:06-05:00" /> <meta name="DC.date.modified" scheme="DCTERMS.W3CDTF" content="1453-05-17T17:00:00-05:00" /> <meta name="DC.date.valid" scheme="DCTERMS.W3CDTF" content="2015-12-13T16:49:06-05:00" /> <meta name="DC.type" scheme="DCTERMS.DCMIType" content="Text" /> <meta name="DC.rights" scheme="DCTERMS.URI" content="(cc) Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License"> <meta name="Copyright" content="(cc) Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License"/> <meta name="DC.format" content="text/html" /> <meta name="DC.identifier" scheme="DCTERMS.URI" content="http://webstandardssherpa.com/sign-up" /> <meta name="MSSmartTagsPreventParsing" content="true"/> <meta name="Rating" content="General"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <link rel="home" href="../index.html"/> <link rel="copyright" href="index.html%3Freturn=%252Fask-the-sherpas%252Fframeworks-preprocessors-and-libraries%252F.html#license"/> <link rel="shortcut icon" type="image/png" href="../favicon.png"/> <link rel="author" type="text/plain" href="../humans.txt.html"/> <!--[if lte IE 8]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]--> <!--[if (lte IE 8)&(!IEMobile)]> <link rel="stylesheet" href="/c/old-ie.css" media="screen"> <![endif]--> <!--[if gt IE 8]><!--> <link rel="stylesheet" type="text/css" href="../c/main.css" media="screen"/> <!--<![endif]--> <!--[if IEMobile 7]> <link rel="stylesheet" href="/c/main.css" media="screen"> <link rel="stylesheet" href="/c/windows7-mobile.css" media="screen"> <![endif]--> <link rel="alternate" type="application/rss+xml" title="Web Standards Sherpa Reviews (Summary)" href="http://feeds.feedburner.com/Web-Standards-Sherpa-Reviews-Summary"/> <link rel="alternate" type="application/rss+xml" title="Web Standards Sherpa Reviews (Full Text)" href="http://feeds.feedburner.com/Web-Standards-Sherpa-Reviews"/> <link rel="alternate" type="application/rss+xml" title="Web Standards Sherpa Discussions" href="http://feeds.feedburner.com/Web-Standards-Sherpa-Discussions"/> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-176472-9']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <script type="text/javascript"> var WRInitTime=(new Date()).getTime(); </script> </head> <body id="sign-up" class="form"> <header role="banner" id="page-header"> <h4 id="logo"><a href="../index.html" title="Return to the homepage">Web Standards Sherpa</a></h4> </header> <nav id="nav-primary" role="navigation"> <ul><li id="nav-home"><a href="../index.html">Home</a></li><li id="nav-reviews"><a href="../reviews/index.html">Reviews</a></li><li id="nav-ask-the-sherpas"><a href="../ask-the-sherpas/index.html">Ask the Sherpas</a></li> </ul> </nav> <div id="content"> <nav id="crumbs"> <ol> <li><em>Sign Up</em></li> </ol> </nav> <article> <header> <h1>Sign Up</h1> </header> <p>In order to participate in discussions, you&rsquo;ll need to be registered on this site. Thankfully it&rsquo;s easy and you can do it one of several&nbsp;ways.</p> <p class="buttons" id="social-login"><a class="rpxnow" onclick="return false;" href="https://wasp.rpxnow.com/openid/v2/signin?token_url=http%3A%2F%2Fwebstandardssherpa.com%2Fopenid-login%2F%3Freturn%3DL2Fzay10aGUtc2hlcnBhcy9mcmFtZXdvcmtzLXByZXByb2Nlc3NvcnMtYW5kLWxpYnJhcmllcy8%2FcmVnaXN0ZXJlZD10cnVl"> Register using OpenID or oAuth </a><img src="../c/i/rpxnow.png" title="You can log in using and existing Twitter, Facebook, OpenID, Google, Yahoo, or AOL account" alt=""/></p> <p class="rule"><em>or</em></p> <form id="sa_member_register_form" method="post" action="../index.html" > <div class='hiddenFields'> <input type="hidden" name="ACT" value="29" /> <input type="hidden" name="RET" value="http://webstandardssherpa.com/ask-the-sherpas/frameworks-preprocessors-and-libraries/?registered=true" /> <input type="hidden" name="XID" value="df1c34a3c9763f5392f4c44e07c3a5b56722cff3" /> <input type="hidden" name="site_id" value="1" /> </div> <p>Create your own account on Web Standards Sherpa:</p> <p class="required-notice"><strong>All fields are required</strong></p> <fieldset> <ol> <li> <label for="signup-username">Username</label> <input type="text" id="signup-username" name="username" maxlength="32" required="required" aria-required="true" value=""/> <em class="notes">You&#8217;ll be able to sign in using this or your email.</em> </li> <li> <label for="signup-email">Email</label> <input type="email" id="signup-email" name="email" required="required" aria-required="true" value=""/> </li> <li> <label for="signup-password">Password</label> <input type="password" id="signup-password" name="password" required="required" aria-required="true" maxlength="32"/> <em class="notes">Your password must contain at least one uppercase character, one lowercase character, and one numeric character.</em> </li> <li> <label for="signup-password-confirm">Confirm Password</label> <input type="password" id="signup-password-confirm" name="password_confirm" required="required" aria-required="true" maxlength="32"/> </li> <li class="confirm"> <label for="signup-terms"><input type="checkbox" id="signup-terms" name="accept_terms" value="y" required="required" aria-required="true" /> I agree to the <a href="../terms-of-use/index.html">Terms of Use</a></label> </li> <li class="submit buttons"> <button type="submit" name="submit" value="Submit">Sign Up</button> </li> </ol> </fieldset> </form> </article> </div> <form style="display: none" id="search-form" method="post" action="../index.html" > <div class='hiddenFields'> <input type="hidden" name="ACT" value="6" /> <input type="hidden" name="XID" value="e2d81d25f1b1df32421438d5ce546b04c5a9c8ee" /> <input type="hidden" name="RES" value="10" /> <input type="hidden" name="meta" value="vJed+IEhaFn3W7jNVVY8C6VK4KKB0doGerxtt+3TXJkJkrK5M3OFhLNfv7UrH+uJhVYy/SM2Y8CEBzxS9ZAY+5Ry234MoWdF0KwpptDKKX/rJJg1NP4Y7SntDPwMKWd0mrV/+nbWgdpLXyGAXHtWDd/W8QMHWePL8qfhqCpJzaK4pU2LxFEhOj26ZDN4P+8d8hXffYqEVMiMRDrkUYAlZAa+r08a/igafmWKpfXqcmFAHWq/qsh+zoaTz9V6wiUJl2MMAdfHTEZ76nZbWvE5NUZpcvtxRexke8gSzhsFUK46dJJ8pJfmOvPccKB8bfwmBU4cgAZ668OleVhPUZRHiYhGfX21C2DodUFydLdhuEPR2Upj1jdw5RfdVF8nWXwA5G5T4DRd4xKMtKvVvr1BpJKZ37Gid+DBZjiqIcAhYCY=" /> <input type="hidden" name="site_id" value="1" /> </div> <p role="search"> <label for="query">Looking for something?</label> <input type="search" name="keywords" id="query" value=""/> <button type="submit">Search</button> </p> </form> <nav id="nav-account" style="display: none" role="navigation"> <ul class="buttons"> <li><a href="../log-in/index.html" style="display: none">Log in</a></li> </ul> </nav> <footer role="contentinfo" id="page-footer"> <div id="site-info"> <div id="elevator-pitch" class="footer-item"> <p>Web Standards Sherpa&rsquo;s experts provide helpful, pragmatic and up-to-date advice on best practices for web professionals everywhere.</p> <ul class="more"> <li><a href="../about/index.html">More about us</a></li> <li><a href="../contact/index.html" style="display: none">Contact us</a></li> </ul> </div> <nav id="nav-complete" role="navigation"> <section class="participate" style="display: none"> <h1>Participate</h1> <ul> <li><a href="../submit-a-site/index.html">Submit a site</a></li> <li><a href="../submit-a-question/index.html">Submit a question</a></li> <li><mark><a href="index.html" style="display: none">Sign up</a></mark><a href="../log-in/index.html" style="display: none">Log in</a></li> </ul> </section> <section class="learn"> <h1>Learn</h1> <ul> <li><a href="../reviews/index.html">Reviews</a></li> <li><a href="../ask-the-sherpas/index.html">Ask Sherpas</a></li> <li><a href="../about/authors/index.html">Authors</a></li> <li><a href="../glossary/index.html">Glossary</a></li> </ul> </section> </nav> <section id="sponsors" class="footer-item"> <h1>We thank our sponsors</h1> <ol class="partners"> <li> <a href="http://www.microsoft.com"><img src="../i/p/microsoft-mono.png" alt="Microsoft"/></a> </li> <li> <a href="http://mailchimp.com"><img src="../i/p/mc-mono.png" alt="MailChimp"/></a> </li> <li> <a href="http://developer.mozilla.org"><img src="../i/p/mozilla-mono.png" alt="Mozilla"/></a> </li> <li> <a href="http://mediatemple.net"><img src="../i/p/mt-mono.png" alt="Media Temple"/></a> </li> </ol> </section> </div> <div id="terms" class="source-org vcard"> <p id="ownership"><a xmlns:dct="http://purl.org/dc/terms/" href="../index.html" property="dct:title" rel="cc:attributionURL">Web Standards Sherpa</a> is an outreach effort by the <a class="org fn url" xmlns:cc="http://creativecommons.org/ns#" href="http://webstandards.org" property="cc:attributionName">Web Standards Project (WaSP)<img src="../i/WaSP-logo-mono.png" alt="" /></a>.</p> <!-- <p id="network">This site is a proud member of the <a rel="license" href="http://network.smashingmagazine.com/">Smashing Network<img src="/i/p/smashing-mono.png" alt="" /></a>.</p> --> <p id="license">The content of this site is licensed under <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/3.0/">Creative Commons<img src="../i/license.png" alt="" /></a>.</p> </div> </footer> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <script>window.jQuery || document.write("<script src='../j/jquery.js'>\x3C/script>")</script> <script src="../j/main.js"></script> <script src="../j/easy-validation.js"></script> <!-- Just to see if this works --> <!--[if lte IE 6]><script src="/j/ie6.js"></script><![endif]--> <script type="text/javascript"> var rpxJsHost = (("https:" == document.location.protocol) ? "https://" : "http://static."); document.write(unescape("%3Cscript src='" + rpxJsHost + "rpxnow.com/js/lib/rpx.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> RPXNOW.overlay = true; RPXNOW.language_preference = "en"; RPXNOW.init({appId: 'cdnifhbomckchfhfgbpl', xdReceiver: '/rpx_xdcomm.html'}); </script> <div id="ClickTaleDiv" style="display: none;"></div> <script type="text/javascript"> if ( document.location.protocol!='https:' ) { $.getScript('http://s.clicktale.net/WRb6.js',function(){ if ( typeof ClickTale=='function' ) {ClickTale(16473,0.1,"www02");} }); } </script> </body> </html>
{ "content_hash": "4c09aff12b492a65597cd1616c43c9c7", "timestamp": "", "source": "github", "line_count": 287, "max_line_length": 472, "avg_line_length": 43.65505226480836, "alnum_prop": 0.6625429004709075, "repo_name": "WebStandardsSherpa/webstandardssherpa.com", "id": "8210a8e47272b8782fbfb890c51953e02ee00760", "size": "12529", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sign-up/index.html?return=%2Fask-the-sherpas%2Fframeworks-preprocessors-and-libraries%2F.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "589844" }, { "name": "HTML", "bytes": "11527081" }, { "name": "JavaScript", "bytes": "17408" } ], "symlink_target": "" }
/*** * OUTPUTS : Digital outputs modules. Used to control relays. */ // TODO : HTTP API endpoints for timed and sequenced outputs modes // TODO : Add initial state to app section web page #define OUTPUT_NB_OUT 2 #define OUTPUT_MAX_SYNC 8 class outputModule : public Module { private: int pin[OUTPUT_NB_OUT]; bool output[OUTPUT_NB_OUT] = {false, false}; bool blinkEnabled[OUTPUT_NB_OUT] = {false, false}; long blinkOnDuration[OUTPUT_NB_OUT] = {0, 0}; long blinkOffDuration[OUTPUT_NB_OUT] = {0, 0}; long lastBlinkSwitch[OUTPUT_NB_OUT] = {0, 0}; String topicOutput[OUTPUT_NB_OUT] = {"outputs/1", "outputs/2"}; brickCommand *syncCommands[OUTPUT_NB_OUT][OUTPUT_MAX_SYNC]; int enabledSyncCommands[OUTPUT_NB_OUT]; public: outputModule(int pin1, int pin2) { this->pin[0] = pin1; this->pin[1] = pin2; } /*** * Outputs setup : set pins modes, and declare HTTP API endpoints */ void setup() { Log::Logln("[NFO] Outputs initialization"); for(int out=0; out<OUTPUT_NB_OUT; out++) { for (int i=0; i<OUTPUT_MAX_SYNC; i++) { this->syncCommands[out][i] = NULL; } this->enabledSyncCommands[out] = 0; pinMode(this->pin[out], OUTPUT); setOutput(out, false); } MainServer::server.on("/out/0/on", (std::bind(&outputModule::activateOutput1, this))); MainServer::server.on("/out/0/off", (std::bind(&outputModule::desactivateOutput1, this))); MainServer::server.on("/out/0/blink", (std::bind(&outputModule::blink1API, this))); MainServer::server.on("/out/0/addsync", (std::bind(&outputModule::addSync1, this))); MainServer::server.on("/out/0/remsync", (std::bind(&outputModule::remSync1, this))); MainServer::server.on("/out/1/on", (std::bind(&outputModule::activateOutput2, this))); MainServer::server.on("/out/1/off", (std::bind(&outputModule::desactivateOutput2, this))); MainServer::server.on("/out/1/blink", (std::bind(&outputModule::blink2API, this))); MainServer::server.on("/out/1/addsync", (std::bind(&outputModule::addSync2, this))); MainServer::server.on("/out/1/remsync", (std::bind(&outputModule::remSync2, this))); MainServer::server.on("/out/status", (std::bind(&outputModule::statusAPI, this))); } /*** * Outputs loop */ void loop() { for(int out=0; out<OUTPUT_NB_OUT; out++) blinkLoop(out); } /*** * HTTP JSON API to enable outputs */ void setOutput(unsigned short numOutput, bool activate) { digitalWrite(this->pin[numOutput], (activate)?HIGH:LOW); blinkEnabled[numOutput] = false; if (this->output[numOutput] != activate) { this->output[numOutput] = activate; #if defined(OPTION_MQTT) MQTT.publish(this->topicOutput[numOutput], (activate)?"1":"0"); #endif syncCommand(numOutput, (activate)?"on":"off"); } MainServer::ReturnOK(); } void activateOutput1() { setOutput(0, true); } void activateOutput2() { setOutput(1, true); } void desactivateOutput1() { setOutput(0, false); } void desactivateOutput2() { setOutput(1, false); } /** * HTTP API to add a sync'ed command to an output */ void addSync(unsigned char out) { bool toAdd = true; for (int i=0; i<this->enabledSyncCommands[out]; i++) { if (this->syncCommands[out][i]->url == MainServer::server.arg("url")) { toAdd = false; } } if (toAdd) { this->syncCommands[out][this->enabledSyncCommands[out]] = new brickCommand(MainServer::server.arg("name"), MainServer::server.arg("url")); this->enabledSyncCommands[out]++; MainServer::ReturnOK(); } else { Log::Logln("[ERR] Sync already present"); MainServer::ReturnKO("Sync already present"); } } void addSync1() { addSync(0); } void addSync2() { addSync(1); } /** * HTTP API to remove a sync'ed command of an output */ void remSync(unsigned char out) { bool isRemoved = false; for (int i=0; i<this->enabledSyncCommands[out]; i++) { if (isRemoved == true) { // If removed, we move others one place up Log::Logln("[NFO] Move " + this->syncCommands[out][i]->url + " from " + String(i) + " to " + String(i-1)); this->syncCommands[out][i-1] = new brickCommand(this->syncCommands[out][i]->name, this->syncCommands[out][i]->url); } else if(this->syncCommands[out][i]->url == MainServer::server.arg("url")) { Log::Logln("[NFO] " + this->syncCommands[out][i]->url + " removed"); isRemoved = true; } } this->enabledSyncCommands[out]--; } void remSync1() { remSync(0); } void remSync2() { remSync(1); } void syncCommand(unsigned short numOut, String command) { for (int i=0; i<this->enabledSyncCommands[numOut]; i++) { if (this->syncCommands[numOut][i]!=NULL) { Log::Logln("[EVT] Trigger synced command : " + syncCommands[numOut][i]->url ); HTTPClient cli; cli.begin(this->syncCommands[numOut][i]->url + command); cli.setTimeout(250); cli.GET(); yield(); } } } /*** * HTTP JSON API to send outputs statuses */ void statusAPI() { String JSONoutput = "{ "; for(int out=0; out<OUTPUT_NB_OUT; out++) { JSONoutput += "\"out"+String(out)+"\": \""; JSONoutput +=(this->output[out] ? "1" : "0"); JSONoutput +="\""; if (out<(OUTPUT_NB_OUT-1)) JSONoutput +=", "; } JSONoutput += "}\r\n"; MainServer::server.send(200, "application/json", JSONoutput); } /*** * App section for brick main web page */ // TODO : add buttons to control blink modes String mainWebPage(String actualPage) { actualPage.replace("<!-- %%APP_ZONE%% -->", SpiFfs::readFile("/app_outputs.html")); // Hide link buttons if no other commands if (discovery.commandsCount()<1) { Log::Logln("[NFO] Did not found any linkable command"); actualPage.replace("%%DISP_OUT_LINKS%%", "style=\"display:none\""); actualPage.replace("%%SYNC_COMMANDS_0%%", ""); actualPage.replace("%%SYNC_COMMANDS_1%%", ""); } else { actualPage.replace("%%DISP_OUT_LINKS%%", ""); actualPage.replace("%%SYNC_COMMANDS_0%%", this->commandsList(0)); actualPage.replace("%%SYNC_COMMANDS_1%%", this->commandsList(1)); } return actualPage; } /*** * Blink outputs loop */ void blinkLoop(unsigned short numOutput) { if (!this->blinkEnabled[numOutput]) return; long testDuration = 0; if (this->output[numOutput]) testDuration = this->blinkOnDuration[numOutput]; else testDuration = this->blinkOffDuration[numOutput]; if (millis() - this->lastBlinkSwitch[numOutput] > testDuration) { this->lastBlinkSwitch[numOutput] = millis(); if (this->output[numOutput]) { Log::Logln("[NFO] Output "+String(numOutput+1)+" blink OFF"); digitalWrite(this->pin[numOutput], LOW); this->output[numOutput] = false; } else { Log::Logln("[NFO] Output "+String(numOutput+1)+" blink ON"); digitalWrite(this->pin[numOutput], HIGH); this->output[numOutput] = true; } } } /** * Retruns a list of commands of all discovered bricks to replace "%%SYNC_COMMANDS%%" on app html files */ String commandsList(unsigned char numOut) { String tmp = ""; for (DiscoveredBrick *d = discoveredBricks; d; d = d->nextBrick) { for (int i=0; i<8; i++) { if (d->commands[i] != NULL) { tmp += "<li><label><input type=\"checkbox\" data-name=\""; tmp += String(d->commands[i]->name); tmp += "\" data-url=\""; tmp += String(d->commands[i]->url); tmp += "\" "; for (int c=0; c<this->enabledSyncCommands[numOut]; c++) { if (this->syncCommands[numOut][c]!=NULL) { if (syncCommands[numOut][c]->url == d->commands[i]->url) { tmp += "checked=\"checked\" "; break; } } } tmp += "/> "; tmp += String(d->commands[i]->name); tmp += " on "; tmp += String(d->name); tmp += "</label></li>"; } } } return tmp; } /*** * HTTP JSON API to blink outputs */ void blinkAPI(unsigned short numOutput) { this->blinkOnDuration[numOutput] = MainServer::server.arg("on").toInt(); // Parse on duration this->blinkOffDuration[numOutput] = MainServer::server.arg("off").toInt(); // Parse off duration if ((this->blinkOnDuration[numOutput]==0) || (this->blinkOffDuration[numOutput]==0)) { Log::Logln("[NFO] Output "+String(numOutput+1)+" blink mode stopped"); this->blinkEnabled[numOutput] = false; } else { Log::Logln("[NFO] Output "+String(numOutput+1)+" blink mode started : " + String(this->blinkOnDuration[numOutput]) + " / " + String(this->blinkOffDuration[numOutput])); this->blinkEnabled[numOutput] = true; this->lastBlinkSwitch[numOutput] = millis(); } MainServer::ReturnOK(); } void blink1API() { blinkAPI(0); } void blink2API() { blinkAPI(1); } };
{ "content_hash": "740e21603f3bc4c25942a952a604ffd5", "timestamp": "", "source": "github", "line_count": 252, "max_line_length": 184, "avg_line_length": 43.76190476190476, "alnum_prop": 0.49437794704388827, "repo_name": "36Bricks/Firmware", "id": "97c093ff94498eb81c3d0674a30910e0cfad7526", "size": "11028", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Outputs.h", "mode": "33188", "license": "mit", "language": [ { "name": "Arduino", "bytes": "7451" }, { "name": "C++", "bytes": "98019" }, { "name": "HTML", "bytes": "13327" }, { "name": "Objective-C", "bytes": "2039" } ], "symlink_target": "" }
package org.wso2.carbon.esb.tcp.transport.test; import org.apache.commons.lang.StringUtils; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.automation.engine.annotations.ExecutionEnvironment; import org.wso2.carbon.automation.engine.annotations.SetEnvironment; import org.wso2.carbon.esb.tcp.transport.test.util.NativeTCPClient; import org.wso2.esb.integration.common.utils.ESBIntegrationTest; import org.wso2.esb.integration.common.utils.common.ServerConfigurationManager; /** * Test TCP session persistance splitting by a special charachter. */ public class TCPSessionPersistenceSplitBySpecialCharacterTestCase extends ESBIntegrationTest { private ServerConfigurationManager serverConfigurationManager; private static String message = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap" + ".org/soap/envelope/\"><soapenv:Header/><soapenv:Body/></soapenv:Envelope>"; @BeforeClass(alwaysRun = true) public void setEnvironment() throws Exception { super.init(); loadESBConfigurationFromClasspath("/artifacts/ESB/tcp/transport/tcpProxy_splitBySpecialCharacter.xml"); } @SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE }) @Test(groups = "wso2.esb", description = "Tcp proxy service which configured to split by special character") public void tcpTransportSplitBySpecialCharacterProxy() throws Exception { int messageCount = 3; Character aByte = 0x03; NativeTCPClient tcpClient = new NativeTCPClient(NativeTCPClient.DelimiterTypeEnum.BYTE.getDelimiterType(), messageCount); tcpClient.setMessage(message); tcpClient.setByteDelimiter(aByte); tcpClient.sendToServer(); String[] responses = tcpClient.receiveCharactorTypeDelimiterResonse(); Assert.assertEquals(messageCount, responses.length); for(String response: responses) { Assert.assertNotNull(response, "Received a null response from the server"); Assert.assertNotEquals(StringUtils.EMPTY, response, "Received an empty response from the server"); } } @AfterClass(alwaysRun = true) public void destroy() throws Exception { super.cleanup(); } }
{ "content_hash": "1fd870513d1e066cf8b9ef6c5d31324d", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 129, "avg_line_length": 45.03846153846154, "alnum_prop": 0.7549103330486764, "repo_name": "milindaperera/product-ei", "id": "c27b601931d0ddf35d1b8ab97d57689f29b4b216", "size": "2984", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "integration/mediation-tests/tests-transport/src/test/java/org/wso2/carbon/esb/tcp/transport/test/TCPSessionPersistenceSplitBySpecialCharacterTestCase.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ballerina", "bytes": "22977" }, { "name": "Batchfile", "bytes": "147995" }, { "name": "CSS", "bytes": "233470" }, { "name": "HTML", "bytes": "110657" }, { "name": "Java", "bytes": "8882160" }, { "name": "JavaScript", "bytes": "5980272" }, { "name": "PLSQL", "bytes": "16634" }, { "name": "PLpgSQL", "bytes": "12825" }, { "name": "Ruby", "bytes": "11897" }, { "name": "Shell", "bytes": "378668" }, { "name": "TSQL", "bytes": "308110" }, { "name": "XSLT", "bytes": "38219" } ], "symlink_target": "" }
import six from unittest import TestCase from itertools import product from dark.aa import ( PROPERTIES, ALL_PROPERTIES, PROPERTY_NAMES, ACIDIC, ALIPHATIC, AROMATIC, BASIC_POSITIVE, HYDROPHILIC, HYDROPHOBIC, HYDROXYLIC, NEGATIVE, NONE, POLAR, SMALL, SULPHUR, TINY, NAMES, NAMES_TO_ABBREV1, ABBREV3, ABBREV3_TO_ABBREV1, CODONS, AA_LETTERS, find, AminoAcid, clustersForSequence, propertiesForSequence, PROPERTY_CLUSTERS, PROPERTY_DETAILS_RAW, START_CODON, STOP_CODONS, compareAaReads, matchToString) from dark.reads import AARead class TestAALetters(TestCase): """ Test the AA_LETTERS string in dark.aa """ def testExpectedAALetters(self): """ The AA_LETTERS value must be as expected. """ # From https://en.wikipedia.org/wiki/Amino_acid expected = sorted('ARNDCEQGHILKMFPSTWYV') self.assertEqual(expected, AA_LETTERS) class TestProperties(TestCase): """ Test the AA properties in dark.aa """ def testCorrectAAs(self): """ The PROPERTIES dict must have the correct AA keys. """ self.assertEqual(AA_LETTERS, sorted(PROPERTIES)) def testAllProperties(self): """ The ALL_PROPERTIES tuple must contain all known properties. """ expected = set([ ACIDIC, ALIPHATIC, AROMATIC, BASIC_POSITIVE, HYDROPHILIC, HYDROPHOBIC, HYDROXYLIC, NEGATIVE, NONE, POLAR, SMALL, SULPHUR, TINY]) self.assertEqual(set(ALL_PROPERTIES), expected) def testPropertyValuesDiffer(self): """ All individual property values must be different. """ self.assertEqual(len(ALL_PROPERTIES), len(set(ALL_PROPERTIES))) def testEachAAHasItsCorrectPropertiesAndNoOthers(self): """ Each amino acid must have the properties expected of it, and no others. """ expected = { 'A': set([HYDROPHOBIC, SMALL, TINY]), 'C': set([HYDROPHOBIC, SMALL, TINY, SULPHUR]), 'D': set([HYDROPHILIC, SMALL, POLAR, NEGATIVE]), 'E': set([HYDROPHILIC, NEGATIVE, ACIDIC]), 'F': set([HYDROPHOBIC, AROMATIC]), 'G': set([HYDROPHILIC, SMALL, TINY]), 'H': set([HYDROPHOBIC, AROMATIC, POLAR, BASIC_POSITIVE]), 'I': set([ALIPHATIC, HYDROPHOBIC]), 'K': set([HYDROPHOBIC, BASIC_POSITIVE, POLAR]), 'L': set([ALIPHATIC, HYDROPHOBIC]), 'M': set([HYDROPHOBIC, SULPHUR]), 'N': set([HYDROPHILIC, SMALL, POLAR, ACIDIC]), 'P': set([HYDROPHILIC, SMALL]), 'Q': set([HYDROPHILIC, POLAR, ACIDIC]), 'R': set([HYDROPHILIC, POLAR, BASIC_POSITIVE]), 'S': set([HYDROPHILIC, SMALL, POLAR, HYDROXYLIC]), 'T': set([HYDROPHOBIC, SMALL, HYDROXYLIC]), 'V': set([ALIPHATIC, HYDROPHOBIC, SMALL]), 'W': set([HYDROPHOBIC, AROMATIC, POLAR]), 'Y': set([HYDROPHOBIC, AROMATIC, POLAR]), } # Make sure our 'expected' dict (above) has properties for everything. self.assertEqual(AA_LETTERS, sorted(expected)) for aa in AA_LETTERS: for prop in ALL_PROPERTIES: if prop in expected[aa]: self.assertTrue(bool(PROPERTIES[aa] & prop)) else: self.assertFalse(bool(PROPERTIES[aa] & prop)) def testProperyNamesKeys(self): """ The PROPERTY_NAMES dict must have a key for each property. """ self.assertEqual(sorted(ALL_PROPERTIES), sorted(PROPERTY_NAMES)) def testProperyNamesValuesDiffer(self): """ The PROPERTY_NAMES dict must have different values for each key. """ self.assertEqual(len(PROPERTY_NAMES), len(set(PROPERTY_NAMES.values()))) class TestNames(TestCase): """ Test the NAMES dict in dark.aa """ def testCorrectAAs(self): """ The NAMES dict must have the correct AA keys. """ self.assertEqual(AA_LETTERS, sorted(NAMES)) def testValuesDiffer(self): """ All individual names must be different. """ names = list(NAMES.values()) self.assertEqual(len(names), len(set(names))) class TestNamesToAbbrev1(TestCase): """ Test the NAMES_TO_ABBREV1 dict in dark.aa """ def testCorrectAAs(self): """ The NAMES_TO_ABBREV1 dict must have the correct AA values. """ self.assertEqual(AA_LETTERS, sorted(NAMES_TO_ABBREV1.values())) class TestAbbrev3(TestCase): """ Test the ABBREV3 dict in dark.aa """ def testCorrectAAs(self): """ The ABBREV3 dict must have the correct AA keys. """ self.assertEqual(AA_LETTERS, sorted(ABBREV3)) def testValuesDiffer(self): """ All individual names must be different. """ names = list(ABBREV3.values()) self.assertEqual(len(names), len(set(names))) class TestAbbrev3ToAbbrev1(TestCase): """ Test the ABBREV3_TO_ABBREV1 dict in dark.aa """ def testCorrectAAs(self): """ The ABBREV3_TO_ABBREV1 dict must have the correct AA values. """ self.assertEqual(AA_LETTERS, sorted(ABBREV3_TO_ABBREV1.values())) class TestCodons(TestCase): """ Tests for the CODONS dict. """ def testCorrectAAs(self): """ The CODONS dict must have the correct AA keys. """ self.assertEqual(AA_LETTERS, sorted(CODONS)) def testNumberCodons(self): """ The table must contain 61 codons. This is 4^3 - 3. I.e., all possible combinations of 3 bases minus the three stop codons. """ self.assertEqual(61, sum(len(codons) for codons in CODONS.values())) def testCodonLength(self): """ All codons must be three bases long. """ for codons in CODONS.values(): self.assertTrue(all(len(codon) == 3 for codon in codons)) def testCodonContent(self): """ Codons must only contain the letters A, T, G, C. """ for codons in CODONS.values(): for codon in codons: self.assertTrue(all(letter in 'ACGT' for letter in codon)) def testCodonsAreNotAbbrev3s(self): """ No codon can be the same as an amino acid 3-letter abbreviation (or else our find function may not be unambiguous in what it returns). """ for codons in CODONS.values(): self.assertFalse( any(codon.title() in ABBREV3_TO_ABBREV1 for codon in codons)) def testDistinct(self): """ All nucleotide triples must be distinct. """ seen = set() for codons in CODONS.values(): for codon in codons: seen.add(codon) self.assertEqual(61, len(seen)) def testStartCodon(self): """ The start codon must have the expected value. """ self.assertEqual('ATG', START_CODON) def testStartCodonIsMethionine(self): """ The start codon is the same as Methionine. """ self.assertEqual((START_CODON,), CODONS['M']) def testStopCodons(self): """ The stop codons must have the expected value. """ self.assertEqual(('TAA', 'TAG', 'TGA'), STOP_CODONS) def testStopCodonsNotInCodonTable(self): """ The stop codons must not be in the main table. """ for stop in STOP_CODONS: for codons in CODONS.values(): self.assertNotIn(stop, codons) def testAllCodonsPresent(self): """ All possible codons must be present, as either coding for an AA or as a stop codon. """ combinations = set( ''.join(x) for x in product('ACGT', 'ACGT', 'ACGT')) for codons in CODONS.values(): for codon in codons: combinations.remove(codon) # Just the stop codons should be left. self.assertEqual(set(STOP_CODONS), combinations) class TestAminoAcid(TestCase): """ Test the AminoAcid class in dark.aa """ def testExpectedAttributes(self): """ An amino acid instance must have the expected attributes. """ properties = {} propertyDetails = {} codons = [] propertyClusters = {} aa = AminoAcid('Alanine', 'Ala', 'A', codons, properties, propertyDetails, propertyClusters) self.assertEqual('Alanine', aa.name) self.assertEqual('Ala', aa.abbrev3) self.assertEqual('A', aa.abbrev1) self.assertIs(codons, aa.codons) self.assertIs(properties, aa.properties) self.assertIs(propertyDetails, aa.propertyDetails) self.assertIs(propertyClusters, aa.propertyClusters) class TestFind(TestCase): """ Test the find function in dark.aa """ def testFindUnknown(self): """ find must return an empty generator when called with an unrecognized value. """ self.assertEqual([], list(find('silly'))) def testFindByAbbrev1(self): """ It must be possible to find an amino acid by its 1-letter abbreviation. """ aa = list(find('A'))[0] self.assertEqual('Alanine', aa.name) self.assertEqual('Ala', aa.abbrev3) self.assertEqual('A', aa.abbrev1) self.assertEqual(('GCA', 'GCC', 'GCG', 'GCT'), aa.codons) self.assertEqual(HYDROPHOBIC | SMALL | TINY, aa.properties) self.assertEqual( { 'aliphaticity': 0.305785123967, 'aromaticity': -0.550128534704, 'composition': -1.0, 'hydrogenation': 0.8973042362, 'hydropathy': 0.4, 'hydroxythiolation': -0.265160523187, 'iep': -0.191489361702, 'polar requirement': -0.463414634146, 'polarity': -0.20987654321, 'volume': -0.664670658683, }, aa.propertyDetails) self.assertEqual( { 'aliphaticity': 1, 'aromaticity': 1, 'composition': 1, 'hydrogenation': 1, 'hydropathy': 3, 'hydroxythiolation': 2, 'iep': 2, 'polar requirement': 2, 'polarity': 2, 'volume': 2, }, aa.propertyClusters) def testFindByAbbrev3(self): """ It must be possible to find an amino acid by its 3-letter abbreviation. """ aa = list(find('Ala'))[0] self.assertEqual('Alanine', aa.name) self.assertEqual('Ala', aa.abbrev3) self.assertEqual('A', aa.abbrev1) self.assertEqual(('GCA', 'GCC', 'GCG', 'GCT'), aa.codons) self.assertEqual(HYDROPHOBIC | SMALL | TINY, aa.properties) self.assertEqual( { 'aliphaticity': 0.305785123967, 'aromaticity': -0.550128534704, 'composition': -1.0, 'hydrogenation': 0.8973042362, 'hydropathy': 0.4, 'hydroxythiolation': -0.265160523187, 'iep': -0.191489361702, 'polar requirement': -0.463414634146, 'polarity': -0.20987654321, 'volume': -0.664670658683, }, aa.propertyDetails) self.assertEqual( { 'aliphaticity': 1, 'aromaticity': 1, 'composition': 1, 'hydrogenation': 1, 'hydropathy': 3, 'hydroxythiolation': 2, 'iep': 2, 'polar requirement': 2, 'polarity': 2, 'volume': 2, }, aa.propertyClusters) def testFindByCodon(self): """ It must be possible to find an amino acid by a 3-letter codon. """ aa = list(find('GCC'))[0] self.assertEqual('Alanine', aa.name) self.assertEqual('Ala', aa.abbrev3) self.assertEqual('A', aa.abbrev1) self.assertEqual(('GCA', 'GCC', 'GCG', 'GCT'), aa.codons) self.assertEqual(HYDROPHOBIC | SMALL | TINY, aa.properties) self.assertEqual( { 'aliphaticity': 0.305785123967, 'aromaticity': -0.550128534704, 'composition': -1.0, 'hydrogenation': 0.8973042362, 'hydropathy': 0.4, 'hydroxythiolation': -0.265160523187, 'iep': -0.191489361702, 'polar requirement': -0.463414634146, 'polarity': -0.20987654321, 'volume': -0.664670658683, }, aa.propertyDetails) self.assertEqual( { 'aliphaticity': 1, 'aromaticity': 1, 'composition': 1, 'hydrogenation': 1, 'hydropathy': 3, 'hydroxythiolation': 2, 'iep': 2, 'polar requirement': 2, 'polarity': 2, 'volume': 2, }, aa.propertyClusters) def testFindByName(self): """ It must be possible to find an amino acid by its name. """ aa = list(find('Alanine'))[0] self.assertEqual('Alanine', aa.name) self.assertEqual('Ala', aa.abbrev3) self.assertEqual('A', aa.abbrev1) self.assertEqual(('GCA', 'GCC', 'GCG', 'GCT'), aa.codons) self.assertEqual(HYDROPHOBIC | SMALL | TINY, aa.properties) self.assertEqual( { 'aliphaticity': 0.305785123967, 'aromaticity': -0.550128534704, 'composition': -1.0, 'hydrogenation': 0.8973042362, 'hydropathy': 0.4, 'hydroxythiolation': -0.265160523187, 'iep': -0.191489361702, 'polar requirement': -0.463414634146, 'polarity': -0.20987654321, 'volume': -0.664670658683, }, aa.propertyDetails) self.assertEqual( { 'aliphaticity': 1, 'aromaticity': 1, 'composition': 1, 'hydrogenation': 1, 'hydropathy': 3, 'hydroxythiolation': 2, 'iep': 2, 'polar requirement': 2, 'polarity': 2, 'volume': 2, }, aa.propertyClusters) def testFindByNameCaseIgnored(self): """ It must be possible to find an amino acid by its name when the name is given in mixed case. """ aa = list(find('alaNIne'))[0] self.assertEqual('Alanine', aa.name) self.assertEqual('Ala', aa.abbrev3) self.assertEqual('A', aa.abbrev1) self.assertEqual(('GCA', 'GCC', 'GCG', 'GCT'), aa.codons) self.assertEqual(HYDROPHOBIC | SMALL | TINY, aa.properties) self.assertEqual( { 'aliphaticity': 0.305785123967, 'aromaticity': -0.550128534704, 'composition': -1.0, 'hydrogenation': 0.8973042362, 'hydropathy': 0.4, 'hydroxythiolation': -0.265160523187, 'iep': -0.191489361702, 'polar requirement': -0.463414634146, 'polarity': -0.20987654321, 'volume': -0.664670658683, }, aa.propertyDetails) self.assertEqual( { 'aliphaticity': 1, 'aromaticity': 1, 'composition': 1, 'hydrogenation': 1, 'hydropathy': 3, 'hydroxythiolation': 2, 'iep': 2, 'polar requirement': 2, 'polarity': 2, 'volume': 2, }, aa.propertyClusters) def testFindByNameCaseIgnoredNameWithSpace(self): """ It must be possible to find an amino acid by its name when the name is given in mixed case, including if the name has a space in it. """ aa = list(find('asparTIC aCId'))[0] self.assertEqual('Aspartic acid', aa.name) self.assertEqual('Asp', aa.abbrev3) self.assertEqual('D', aa.abbrev1) self.assertEqual(('GAC', 'GAT'), aa.codons) self.assertEqual(HYDROPHILIC | SMALL | POLAR | NEGATIVE, aa.properties) self.assertEqual( { 'aliphaticity': -0.818181818182, 'aromaticity': -1.0, 'composition': 0.00363636363636, 'hydrogenation': -0.90243902439, 'hydropathy': -0.777777777778, 'hydroxythiolation': -0.348394768133, 'iep': -1.0, 'polar requirement': 1.0, 'polarity': 1.0, 'volume': -0.389221556886, }, aa.propertyDetails) self.assertEqual( { 'aliphaticity': 1, 'aromaticity': 1, 'composition': 2, 'hydrogenation': 1, 'hydropathy': 1, 'hydroxythiolation': 2, 'iep': 1, 'polar requirement': 4, 'polarity': 4, 'volume': 3, }, aa.propertyClusters) def testFindByPartialName(self): """ It must be possible to find an amino acid by a partial name. """ aa = list(find('nine'))[0] self.assertEqual('Alanine', aa.name) def testFindByPartialNameMixedCase(self): """ It must be possible to find an amino acid by a mixed-case partial name. """ aa = list(find('NiNe'))[0] self.assertEqual('Alanine', aa.name) def testFindMultipleMatches(self): """ It must be possible to find more than one matching amino acid. """ aa1, aa2 = list(find('acid')) self.assertEqual('Aspartic acid', aa1.name) self.assertEqual('Glutamic acid', aa2.name) class TestPropertyClusters(TestCase): """ Tests for the PROPERTY_CLUSTERS dict. """ def testPropertyClusterKeys(self): """ The PROPERTY_CLUSTERS dict must contain the right keys. """ self.assertEqual(AA_LETTERS, sorted(PROPERTY_CLUSTERS)) def testNumberOfValues(self): """ Each key in PROPERTY_CLUSTERS must have a dict with 10 elements in it as the value. """ for propertyNames in PROPERTY_CLUSTERS.values(): self.assertEqual([ 'aliphaticity', 'aromaticity', 'composition', 'hydrogenation', 'hydropathy', 'hydroxythiolation', 'iep', 'polar requirement', 'polarity', 'volume'], sorted(propertyNames)) def testAliphaticity(self): """ Aliphaticity must always be in cluster 1. """ for propertiesDict in PROPERTY_CLUSTERS.values(): self.assertEqual(1, propertiesDict['aliphaticity']) def testPermittedClustersOnly(self): """ All cluster numbers must be in {1, 2, 3, 4, 5}. """ for propertiesDict in PROPERTY_CLUSTERS.values(): for clusterNr in propertiesDict.values(): self.assertIn(clusterNr, {1, 2, 3, 4, 5}) class TestPropertyDetailsRaw(TestCase): """ Tests for the PROPERTY_DETAILS_RAW dict. """ def testPropertyDetailsRawKeys(self): """ The PROPERTY_DETAILS_RAW dict must contain the right keys. """ self.assertEqual(AA_LETTERS, sorted(PROPERTY_DETAILS_RAW)) def testNumberOfValues(self): """ Each key in PROPERTY_DETAILS_RAW must have a dict with 10 elements in it as the value. """ for propertyNames in PROPERTY_DETAILS_RAW.values(): self.assertEqual([ 'aliphaticity', 'aromaticity', 'composition', 'hydrogenation', 'hydropathy', 'hydroxythiolation', 'iep', 'polar requirement', 'polarity', 'volume'], sorted(propertyNames)) def testAliphaticity(self): """ Aliphaticity of Alanin must have the right value. """ self.assertEqual(0.239, PROPERTY_DETAILS_RAW['A']['aliphaticity']) def testValuesMustBeFloats(self): """ Each key in PROPERTY_DETAILS_RAW must have a dict whose values are all floats. """ for properties in PROPERTY_DETAILS_RAW.values(): self.assertTrue(all(type(v) is float for v in properties.values())) class TestPropertiesForSequence(TestCase): """ Tests for the propertiesForSequence function in aa.py """ def testUnknownProperty(self): """ A C{ValueError} must be raised if an unknown property name is passed. """ error = 'Unknown property: xxx' read = AARead('id', 'RRR') six.assertRaisesRegex(self, ValueError, error, propertiesForSequence, read, ['xxx']) def testNoProperties(self): """ If no properties are wanted, an empty dict must be returned. """ read = AARead('id', 'RRR') self.assertEqual({}, propertiesForSequence(read, [])) def testOnePropertyEmptySequence(self): """ If one property is wanted but the sequence is empty, a dict with the property must be returned, and have an empty list value. """ read = AARead('id', '') self.assertEqual( { 'hydropathy': [], }, propertiesForSequence(read, ['hydropathy'])) def testPropertyNameIsLowercased(self): """ The property name must be lower-cased in the result. """ read = AARead('id', '') self.assertTrue('hydropathy' in propertiesForSequence(read, ['HYDROPATHY'])) def testOneProperty(self): """ If one property is wanted, a dict with the property must be returned, and have the expected property values. """ read = AARead('id', 'AI') self.assertEqual( { 'hydropathy': [0.4, 1.0], }, propertiesForSequence(read, ['hydropathy'])) def testTwoProperties(self): """ If two properties are wanted, a dict with the properties must be returned, and have the expected property values. """ read = AARead('id', 'AI') self.assertEqual( { 'composition': [-1.0, -1.0], 'hydropathy': [0.4, 1.0], }, propertiesForSequence(read, ['composition', 'hydropathy'])) def testDuplicatedPropertyName(self): """ If a property name is mentioned more than once, a dict with the wanted properties must be returned, and have the expected property values. """ read = AARead('id', 'AI') self.assertEqual( { 'composition': [-1.0, -1.0], 'hydropathy': [0.4, 1.0], }, propertiesForSequence(read, ['composition', 'hydropathy', 'hydropathy'])) def testMissingAminoAcid(self): """ If an unknown amino acid appears in the sequence, its property value must be the default (-1.1). """ read = AARead('id', 'XX') self.assertEqual( { 'composition': [-1.1, -1.1], 'hydropathy': [-1.1, -1.1], }, propertiesForSequence(read, ['composition', 'hydropathy'])) def testMissingAminoAcidWithNonDefaultMissingValue(self): """ If an unknown amino acid appears in the sequence, its property value must be the missing AA value that was passed. """ read = AARead('id', 'XX') self.assertEqual( { 'composition': [-1.5, -1.5], 'hydropathy': [-1.5, -1.5], }, propertiesForSequence(read, ['composition', 'hydropathy'], missingAAValue=-1.5)) class TestClustersForSequence(TestCase): """ Tests for the clustersForSequence function in aa.py """ def testUnknownProperty(self): """ A C{ValueError} must be raised if an unknown property name is passed. """ error = 'Unknown property: xxx' read = AARead('id', 'RRR') six.assertRaisesRegex(self, ValueError, error, clustersForSequence, read, ['xxx']) def testNoProperties(self): """ If no properties are wanted, an empty dict must be returned. """ read = AARead('id', 'RRR') self.assertEqual({}, clustersForSequence(read, [])) def testOnePropertyEmptySequence(self): """ If one property is wanted but the sequence is empty, a dict with the property must be returned, and have an empty list value. """ read = AARead('id', '') self.assertEqual( { 'hydropathy': [], }, clustersForSequence(read, ['hydropathy'])) def testPropertyNameIsLowercased(self): """ The property name must be lower-cased in the result. """ read = AARead('id', '') self.assertTrue('hydropathy' in clustersForSequence(read, ['HYDROPATHY'])) def testOneProperty(self): """ If one property is wanted, a dict with the property must be returned, and have the expected property cluster number. """ read = AARead('id', 'AI') self.assertEqual( { 'hydropathy': [3, 4], }, clustersForSequence(read, ['hydropathy'])) def testTwoProperties(self): """ If two properties are wanted, a dict with the properties must be returned, and have the expected property cluster numbers. """ read = AARead('id', 'AI') self.assertEqual( { 'composition': [1, 1], 'hydropathy': [3, 4], }, clustersForSequence(read, ['composition', 'hydropathy'])) def testDuplicatedPropertyName(self): """ If a property name is mentioned more than once, a dict with the wanted properties must be returned, and have the expected property cluster numbers. """ read = AARead('id', 'AI') self.assertEqual( { 'composition': [1, 1], 'hydropathy': [3, 4], }, clustersForSequence(read, ['composition', 'hydropathy', 'hydropathy'])) def testMissingAminoAcid(self): """ If an unknown amino acid appears in the sequence, its property cluster must be the default (0). """ read = AARead('id', 'XX') self.assertEqual( { 'composition': [0, 0], 'hydropathy': [0, 0], }, clustersForSequence(read, ['composition', 'hydropathy'])) def testMissingAminoAcidWithNonDefaultMissingValue(self): """ If an unknown amino acid appears in the sequence, its property cluster must be the missing AA value that was passed. """ read = AARead('id', 'XX') self.assertEqual( { 'composition': [10, 10], 'hydropathy': [10, 10], }, clustersForSequence(read, ['composition', 'hydropathy'], missingAAValue=10)) class TestCompareAaReads(TestCase): """ Test the compareAaReads function. """ def testEmptySequences(self): """ Two empty sequences must compare as expected. """ self.assertEqual( { 'match': { 'matchCount': 0, 'gapMismatchCount': 0, 'gapGapMismatchCount': 0, 'nonGapMismatchCount': 0, }, 'read1': { 'extraCount': 0, 'gapOffsets': [], }, 'read2': { 'extraCount': 0, 'gapOffsets': [], }, }, compareAaReads(AARead('id1', ''), AARead('id2', ''))) def testExactMatch(self): """ Two sequences that match exactly must compare as expected. """ self.assertEqual( { 'match': { 'matchCount': 5, 'gapMismatchCount': 0, 'gapGapMismatchCount': 0, 'nonGapMismatchCount': 0, }, 'read1': { 'extraCount': 0, 'gapOffsets': [], }, 'read2': { 'extraCount': 0, 'gapOffsets': [], }, }, compareAaReads(AARead('id1', 'GALHN'), AARead('id2', 'GALHN'))) def testMismatch(self): """ If the sequences have mismatched bases, their count must be given correctly in the nonGapMismatchCount. """ self.assertEqual( { 'match': { 'matchCount': 3, 'gapMismatchCount': 0, 'gapGapMismatchCount': 0, 'nonGapMismatchCount': 2, }, 'read1': { 'extraCount': 0, 'gapOffsets': [], }, 'read2': { 'extraCount': 0, 'gapOffsets': [], }, }, compareAaReads(AARead('id1', 'GALYY'), AARead('id2', 'GALHN'))) def testNoOffsets(self): """ If an empty set of wanted offsets is passed, the result must be empty. """ self.assertEqual( { 'match': { 'matchCount': 0, 'gapMismatchCount': 0, 'gapGapMismatchCount': 0, 'nonGapMismatchCount': 0, }, 'read1': { 'extraCount': 0, 'gapOffsets': [], }, 'read2': { 'extraCount': 0, 'gapOffsets': [], }, }, compareAaReads(AARead('id1', 'GAL-N'), AARead('id2', 'G-LHN'), offsets=set())) def testOffsets(self): """ If a set of wanted offsets is passed, the result must be restricted to just those offsets. """ self.assertEqual( { 'match': { 'matchCount': 1, 'gapMismatchCount': 0, 'gapGapMismatchCount': 0, 'nonGapMismatchCount': 1, }, 'read1': { 'extraCount': 0, 'gapOffsets': [], }, 'read2': { 'extraCount': 0, 'gapOffsets': [], }, }, compareAaReads(AARead('id1', 'GAL-L'), AARead('id2', 'G-LHN'), offsets=set([0, 4]))) def testGapInFirst(self): """ A gap in the first sequence must be dealt with correctly. """ self.assertEqual( { 'match': { 'matchCount': 4, 'gapMismatchCount': 1, 'gapGapMismatchCount': 0, 'nonGapMismatchCount': 0, }, 'read1': { 'extraCount': 0, 'gapOffsets': [3], }, 'read2': { 'extraCount': 0, 'gapOffsets': [], }, }, compareAaReads(AARead('id1', 'GAL-N'), AARead('id2', 'GALHN'))) def testGapInSecond(self): """ A gap in the second sequence must be dealt with correctly. """ self.assertEqual( { 'match': { 'matchCount': 3, 'gapMismatchCount': 2, 'gapGapMismatchCount': 0, 'nonGapMismatchCount': 0, }, 'read1': { 'extraCount': 0, 'gapOffsets': [], }, 'read2': { 'extraCount': 0, 'gapOffsets': [1, 2], }, }, compareAaReads(AARead('id1', 'GALHN'), AARead('id2', 'G--HN'))) def testNonDefaultGapChars(self): """ We must be able to specify the gap characters. """ for gap in '+$': self.assertEqual( { 'match': { 'matchCount': 3, 'gapMismatchCount': 2, 'gapGapMismatchCount': 0, 'nonGapMismatchCount': 0, }, 'read1': { 'extraCount': 0, 'gapOffsets': [2], }, 'read2': { 'extraCount': 0, 'gapOffsets': [0], }, }, compareAaReads(AARead('id1', 'GA%sHN' % gap), AARead('id2', '%sALHN' % gap), gapChars='+$')) def testGapGap(self): """ Coinciding gaps in the sequences must be dealt with correctly """ self.assertEqual( { 'match': { 'matchCount': 2, 'gapMismatchCount': 2, 'gapGapMismatchCount': 1, 'nonGapMismatchCount': 0, }, 'read1': { 'extraCount': 0, 'gapOffsets': [2, 3], }, 'read2': { 'extraCount': 0, 'gapOffsets': [1, 2], }, }, compareAaReads(AARead('id1', 'GA--N'), AARead('id2', 'G--HN'))) def testExtraInFirst(self): """ If the first sequence has extra bases, they must be indicated in the extraCount. """ self.assertEqual( { 'match': { 'matchCount': 5, 'gapMismatchCount': 0, 'gapGapMismatchCount': 0, 'nonGapMismatchCount': 0, }, 'read1': { 'extraCount': 2, 'gapOffsets': [], }, 'read2': { 'extraCount': 0, 'gapOffsets': [], }, }, compareAaReads(AARead('id1', 'GALHNHN'), AARead('id2', 'GALHN'))) def testExtraInSecond(self): """ If the second sequence has extra bases, they must be indicated in the extraCount. """ self.assertEqual( { 'match': { 'matchCount': 5, 'gapMismatchCount': 0, 'gapGapMismatchCount': 0, 'nonGapMismatchCount': 0, }, 'read1': { 'extraCount': 0, 'gapOffsets': [], }, 'read2': { 'extraCount': 2, 'gapOffsets': [], }, }, compareAaReads(AARead('id1', 'GALHN'), AARead('id2', 'GALHNHN'))) class TestMatchToString(TestCase): """ Test the matchToString function. """ def testMismatchAndMatch(self): """ Two sequences containing matches and mismatches must compare as expected. """ read1 = AARead('id1', 'GALHNG') read2 = AARead('id2', 'GALHNA') match = compareAaReads(read1, read2) self.assertEqual( '''\ Matches: 5/6 (83.33%) Mismatches: 1/6 (16.67%) Not involving gaps (i.e., conflicts): 1/6 (16.67%) Involving a gap in one sequence: 0 Involving a gap in both sequences: 0 Id: id1 Length: 6 Gaps: 0 Id: id2 Length: 6 Gaps: 0''', matchToString(match, read1, read2) ) def testGapAndMatch(self): """ Two sequences containing matches and gaps must compare as expected. """ read1 = AARead('id1', 'GALHN-') read2 = AARead('id2', 'GALHNA') match = compareAaReads(read1, read2) self.assertEqual( '''\ Matches: 5/6 (83.33%) Mismatches: 1/6 (16.67%) Not involving gaps (i.e., conflicts): 0 Involving a gap in one sequence: 1/6 (16.67%) Involving a gap in both sequences: 0 Id: id1 Length: 6 Gaps: 1/6 (16.67%) Gap locations (1-based): 6 Id: id2 Length: 6 Gaps: 0''', matchToString(match, read1, read2) )
{ "content_hash": "3fd6294fcbc85a155ead6aca030dab28", "timestamp": "", "source": "github", "line_count": 1178, "max_line_length": 79, "avg_line_length": 32.44736842105263, "alnum_prop": 0.4935510033226068, "repo_name": "terrycojones/dark-matter", "id": "39cab3ceebeb8b4b9071a5b7ab1bef176461d262", "size": "38223", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/test_aa.py", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "3380" }, { "name": "Python", "bytes": "2143833" }, { "name": "Shell", "bytes": "10548" } ], "symlink_target": "" }
The log prints to terminal the: - unique commit id - metadata such as author - commit message
{ "content_hash": "745a0d22200a2386ba4da3a1f2ab07b2", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 31, "avg_line_length": 19, "alnum_prop": 0.7578947368421053, "repo_name": "Lionex/github-workshop", "id": "6f5cbbee83b30052ab1b6d5a7e263513ffba4000", "size": "95", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "slides/basic/history/log-entry.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7031" }, { "name": "HTML", "bytes": "14388" } ], "symlink_target": "" }
using System; using System.Threading.Tasks; using Microsoft.Extensions.Options; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Hosting; using Umbraco.Cms.Core.Mail; using Umbraco.Cms.Core.Models.Email; using Umbraco.Cms.Core.Services; using Umbraco.Extensions; namespace Umbraco.Cms.Core.HealthChecks.NotificationMethods { [HealthCheckNotificationMethod("email")] public class EmailNotificationMethod : NotificationMethodBase { private readonly ILocalizedTextService _textService; private readonly IHostingEnvironment _hostingEnvironment; private readonly IEmailSender _emailSender; private readonly IMarkdownToHtmlConverter _markdownToHtmlConverter; private readonly ContentSettings _contentSettings; public EmailNotificationMethod( ILocalizedTextService textService, IHostingEnvironment hostingEnvironment, IEmailSender emailSender, IOptions<HealthChecksSettings> healthChecksSettings, IOptions<ContentSettings> contentSettings, IMarkdownToHtmlConverter markdownToHtmlConverter) : base(healthChecksSettings) { var recipientEmail = Settings?["RecipientEmail"]; if (string.IsNullOrWhiteSpace(recipientEmail)) { Enabled = false; return; } RecipientEmail = recipientEmail; _textService = textService ?? throw new ArgumentNullException(nameof(textService)); _hostingEnvironment = hostingEnvironment; _emailSender = emailSender; _markdownToHtmlConverter = markdownToHtmlConverter; _contentSettings = contentSettings.Value ?? throw new ArgumentNullException(nameof(contentSettings)); } public string RecipientEmail { get; } public override async Task SendAsync(HealthCheckResults results) { if (ShouldSend(results) == false) { return; } if (string.IsNullOrEmpty(RecipientEmail)) { return; } var message = _textService.Localize("healthcheck","scheduledHealthCheckEmailBody", new[] { DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), _markdownToHtmlConverter.ToHtml(results, Verbosity) }); // Include the umbraco Application URL host in the message subject so that // you can identify the site that these results are for. var host = _hostingEnvironment.ApplicationMainUrl?.ToString(); var subject = _textService.Localize("healthcheck","scheduledHealthCheckEmailSubject", new[] { host }); var mailMessage = CreateMailMessage(subject, message); await _emailSender.SendAsync(mailMessage, Constants.Web.EmailTypes.HealthCheck); } private EmailMessage CreateMailMessage(string subject, string message) { var to = _contentSettings.Notifications.Email; if (string.IsNullOrWhiteSpace(subject)) subject = "Umbraco Health Check Status"; var isBodyHtml = message.IsNullOrWhiteSpace() == false && message.Contains("<") && message.Contains("</"); return new EmailMessage(to, RecipientEmail, subject, message, isBodyHtml); } } }
{ "content_hash": "29a47e30db8f83b147c857fe1fe18a55", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 118, "avg_line_length": 38.010989010989015, "alnum_prop": 0.6522116218560278, "repo_name": "dawoe/Umbraco-CMS", "id": "8de4cd8cc3ab90288e6b30379c186cb371491a1b", "size": "3459", "binary": false, "copies": "2", "ref": "refs/heads/v9/contrib", "path": "src/Umbraco.Core/HealthChecks/NotificationMethods/EmailNotificationMethod.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "16387240" }, { "name": "CSS", "bytes": "17972" }, { "name": "Dockerfile", "bytes": "2352" }, { "name": "HTML", "bytes": "1270928" }, { "name": "JavaScript", "bytes": "4585128" }, { "name": "Less", "bytes": "691390" }, { "name": "PowerShell", "bytes": "21984" }, { "name": "Shell", "bytes": "3572" }, { "name": "TSQL", "bytes": "371" }, { "name": "TypeScript", "bytes": "125776" } ], "symlink_target": "" }
/// Licensed to Ronnel Reposo under one or more agreements. /// Ronnel Reposo licenses this file to you under the MIT license. /// See the LICENSE file in the project root for more information. using System; using System.Linq; using static System.Diagnostics.Contracts.Contract; namespace lineal { /// <summary> /// Represents Linear Algebra Vector functions. /// </summary> public static class Vector { /// <summary> /// Vector operation. /// </summary> /// <typeparam name="T">Input Type</typeparam> /// <typeparam name="V">Output Type</typeparam> /// <param name="xs">Input vector.</param> /// <param name="f">The operation to be performed in each element.</param> /// <param name="acc">The Accumulator vector</param> /// <param name="i">index initialized to 0.</param> /// <returns>The accumulated vector.</returns> public static V[] VectorOperation<T,V> (this T[] vector, Func<T, V> f, V[] acc, int i = 0) { if ( i > ( vector.Length - 1 ) ) { return acc; } else { acc[i] = f(vector[i]); return vector.VectorOperation(f, acc, ( i + 1 )); } } /* end VectorOperation. */ /// <summary> /// Operation on two vectors using function (f). /// </summary> /// <typeparam name="T">Input Type</typeparam> /// <typeparam name="V">Output Type</typeparam> /// <param name="firstvector">First Vector.</param> /// <param name="secondVector">Second Vector.</param> /// <param name="mapper">The mapper function.</param> /// <param name="acc">Vector accumulator.</param> /// <param name="i">index initialized to 0.</param> /// <returns>The accumulated Vector.</returns> public static V[] VectorOperation2<T, V> (this T[] firstvector, T[] secondVector, Func<T, T, V> mapper, V[] acc, int i = 0) { if ( firstvector.Length != secondVector.Length ) { throw new Exception("Vectors are not in same length."); } if ( i > ( firstvector.Length - 1 ) ) { return acc; } else { acc[i] = mapper(firstvector[i], secondVector[i]); return firstvector.VectorOperation2(secondVector, mapper, acc, ( i + 1 )); } } /* end VectorOperation2. */ /// <summary> /// Projects a vector to another form. /// </summary> /// <typeparam name="T">Input Type</typeparam> /// <typeparam name="V">Output Type</typeparam> /// <param name="vector">The input vector.</param> /// <param name="mapper">The mapper function.</param> /// <returns>The accumulated projected vector.</returns> public static V[] VectorMap<T, V> (this T[] vector, Func<T, V> mapper) { /* Use Linq Select for code optimization. */ return vector.Select(mapper).ToArray(); } /// <summary> /// Vector Multiplication. /// </summary> /// <param name="firstVector">First Vector.</param> /// <param name="secondVector">Second Vector.</param> /// <returns>new Vector Product.</returns> public static double[] VectorMul (this double[] firstVector, double[] secondVector) { Func<double, double, double> mul = (x, y) => x * y; /* Use Linq Zip for code optimization. */ return firstVector.Zip(secondVector, mul).ToArray(); } /// <summary> /// Vector Addtion. /// </summary> /// <param name="firstVector">First Vector.</param> /// <param name="secondVector">Second Vector.</param> /// <returns>new Sum Vector.</returns> public static double[] VectorAdd (this double[] firstVector, double[] secondVector) { Func<double, double, double> add = (x, y) => x + y; /* Use Linq Zip for code optimization. */ return firstVector.Zip(secondVector, add).ToArray(); } /// <summary> /// The Dot Product of two Vectors. /// </summary> /// <param name="firstVector">First Vector.</param> /// <param name="secondVector">Second Vector.</param> /// <returns>The Dot Product.</returns> public static double VectorDotProduct (this double[] firstVector, double[] secondVector) { Requires(firstVector != null, "First Vector (xs) is not null."); Requires(secondVector != null, "Second Vector (ys) is not null."); /* Use Linq Sum for code optimization. */ return firstVector.VectorMul(secondVector).Sum(); } /// <summary> /// Determines the Dot Product of a given vector to each vector in a given matrix, /// and returns vector of accumulated Dot Product Vector. /// </summary> /// <param name="vector">The given Vector.</param> /// <param name="matrix">The given Matrix.</param> /// <param name="acc">The Vector accumulator.</param> /// <param name="i">index initialized to 0.</param> /// <returns>The accumulated Dot Product Vector.</returns> static double[] VectorDotProductMatrix (this double[] vector, double[][] matrix, double[] acc, int i = 0) { /* Scape code contracts. ---- */ if ( i > ( matrix.Length - 1 ) ) { return acc; } acc[i] = vector.VectorMul(matrix[i]).Sum(); return vector.VectorDotProductMatrix(matrix, acc, ( i + 1 )); } /// <summary> /// Determines the Dot Product of a given vector to each vector in a given matrix, /// and returns vector of Dot Product Vector. /// </summary> /// <param name="vector">The given Vector.</param> /// <param name="matrix">The given Matrix.</param> /// <returns>The accumulated Dot Product Vector.</returns> public static double[] VectorDotProductMatrix (this double[] vector, double[][] matrix) { Requires(vector != null, "The given vector should must not be null."); Requires(matrix != null, "The given matrix should must not be null."); return vector.VectorDotProductMatrix(matrix, new double[matrix.Length]); } } /* end class. */ }
{ "content_hash": "075906b0559cc27e975bc2645321ba51", "timestamp": "", "source": "github", "line_count": 155, "max_line_length": 131, "avg_line_length": 41.619354838709675, "alnum_prop": 0.5630134862811967, "repo_name": "ronnelreposo/cardiotocography", "id": "5d372b379b074fe1ad845491f2508ad89a3b513f", "size": "6453", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cardio/lineal/Vector.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "35467" }, { "name": "F#", "bytes": "11043" } ], "symlink_target": "" }
@interface NSString (NCCMD5Hash) - (NSString *)md5Hash; @end
{ "content_hash": "03f6b6ea5ec94fff5c2f932d9c106778", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 32, "avg_line_length": 12.6, "alnum_prop": 0.7142857142857143, "repo_name": "Browncoat/NCCUtilities", "id": "187a9ed6bc663dbe4de1861a25e98324054d52e2", "size": "1275", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Utilities/Utilities/NSString+NCCMD5Hash.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1400" }, { "name": "Objective-C", "bytes": "110588" } ], "symlink_target": "" }
An SDK for local LAN control of bulbs, using Python The script has only been designed to work on Python 2.
{ "content_hash": "3b45aedd7c12725687870e02aa9ef2fa", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 54, "avg_line_length": 27.25, "alnum_prop": 0.7706422018348624, "repo_name": "smarthall/python-lifx-sdk", "id": "1dd01ad52dc5159c8f6e157fdd5cd4ec27aa5307", "size": "127", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "197" }, { "name": "Python", "bytes": "51653" } ], "symlink_target": "" }
* rncparser-0.1 * PM file version 32.435 V10.0 ## Что это такое ## REST приложение выполняющее функции по парсингу PM файлов и загрузку в БД MySQL для дальнейшего анализа. Файлы представляют собой XML документ с результатами измерений от различных сетевых элементов (Radio Network). В составе приложения spring фреймоврк , jdbc-pooling connection, jetty в качестве http сервер, jersey в качестве REST ответчика ,log4j - логирование junit тесты выполнены с помощью glassfish.jersey.test-framework. Приложение использует BASIC авторизацию. Технически в директории e:\rnc-pm находится произвольное количество файлов. Парсер обрабатывает файлы по очерди, разбирая каждый файл с помощью SAX. На основе разбора динамически из структуры файла создает таблицы в БД RNC и так же динамики создает поля (кол-во полей в таблицы заранее не известно) ## Сборка ### ## Что потребуется ## * jdk 1.8 * maven * MySQL ## Основная сборка ## * Распаковать и перейти в папку проекта. Выполнить: ``` #!java mvn package assembly:single ``` * После окончания компиляции в папке targe/ должен лежать готовое к запуску приложение. rncparser-0.0.1-SNAPSHOT-bin.zip ### Подготовка к запуску ### Если запуск первый то необходимо создать первоначальные базы данных, для этого необходимо выполнить загрузку с помощью дампа rnc.dmp ``` #!sh mysql -u root -p <rnc.dmp ``` Где -u root имя пользователя с привилегиям для создания БД * RNC - хранится статистика измерений по сетевым элементам * RNC_CONFIG - база данных конфигурации приложения ### Таблицы RNC_CONFIG #### * LOG_FILES - хранится лог pзагруженных файлов в поле file_name , поле status=1 файл обработан status=0 файл обрабатывается , statuses_id ID ссылка на запись таблицы STATUSES * STATUSES - хранится запись о текущей загружаемой конфигурации поле disabled =0 загрузка включена -1 загрузка отключена,status - 1 признак что процесс по загрузке ещё выполняется 0- вся обработка файлов завершена , поле rnc_name указывает на имя конфигурации (произвольное) ### Настройка приложения ### * пока по умолчанию каталог с расположением файлов для загрузки расположен "e:\rnc_pm", изменить можно в классе SAXParsEngine ``` #!java File[] f = new GlobProvider().getFiles("e:/rnc-pm") ``` * опционально каталог для лог файла e:\log , изменить можно в src/resource/log4j.properties ``` #!java log4j.appender.file.File=e:\\log\\log4j-application.log ``` * Приложение использует BASIC авторизацию admin/guest зашитую пока в App.class ``` #!java context.setSecurityHandler(basicAuth("admin", "guest", "Private area")); ``` После внесения изменений необходимо пере собрать проект ### Запуск приложения ### * Распаковать rncparser-0.0.1-SNAPSHOT-bin.zip и запустить startup.bat или startup.sh в зависимости от операционной системы ### Управление ### * Управление осуществляется по средствам API запросов к REST службе расположенной по адресу http://localhost:9999/ ## API ## * /state - выводит текущие состояние БД и статус загрузки ответ : ``` #!json {"RNCName":"rnc1","id":1,"isDisabled":false,"processedFiles":70,"status":1,"totalFiles":70} ``` --------------------------------------------------------------------------------------------------------------------------------------------------------- * RNCName - имя конфигурации * id - ID конфигурации * isDisabled - признак, отключено ли приложение ? false- нет /true дв * processedFiles - кол-во загруженных файлов * totalFiles - общее кол-во файлов (в данной версии пока повторяет параметр processedFiles ) * status - статус загрузки , 1 - файлы в процессе /0 - процесс остановлен --------------------------------------------------------------------------------------------------------------------------------------------------------- * /state?start=1 - запуск процесса загрузки * /state?start=0 - остановка процесса загрузки
{ "content_hash": "c97239460f29d55fab58ca2bb7459815", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 301, "avg_line_length": 37.76470588235294, "alnum_prop": 0.6980789200415368, "repo_name": "svoiring/RNCParser", "id": "a5c9a22e81bed662235ad23bd3e81cc66c2b56b7", "size": "5734", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "39" }, { "name": "Java", "bytes": "31910" }, { "name": "Shell", "bytes": "7146" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <ruleset name="pcsg-generated-ruleset"> <description>PHP Code Sniffer for Package</description> <arg name="colors"/> <rule ref="PSR2"> <exclude name="PSR2.Classes.ClassDeclaration.CloseBraceAfterBody"/> </rule> <rule ref="Generic.CodeAnalysis.EmptyStatement"> <exclude name="Generic.CodeAnalysis.EmptyStatement.DetectedCATCH"/> </rule> <rule ref="Generic.CodeAnalysis.UselessOverridingMethod"/> <rule ref="Generic.CodeAnalysis.UnusedFunctionParameter"/> <rule ref="Generic.CodeAnalysis.JumbledIncrementer"/> <rule ref="Generic.CodeAnalysis.UnconditionalIfStatement"/> <rule ref="Generic.CodeAnalysis.UnnecessaryFinalModifier"/> <rule ref="Generic.ControlStructures.InlineControlStructure"/> <rule ref="Generic.Files.ByteOrderMark"/> <rule ref="Generic.Files.LineEndings"/> <rule ref="Generic.Formatting.DisallowMultipleStatements"/> <rule ref="Generic.Formatting.SpaceAfterCast.NoSpace"> <type>warning</type> </rule> <rule ref="Generic.Functions.CallTimePassByReference"/> <rule ref="Generic.Functions.FunctionCallArgumentSpacing"/> <rule ref="Generic.Metrics.NestingLevel"> <properties> <property name="nestingLevel" value="7"/> </properties> </rule> <rule ref="Generic.Metrics.CyclomaticComplexity"> <properties> <property name="complexity" value="20"/> <property name="absoluteComplexity" value="40"/> </properties> </rule> <rule ref="Generic.Metrics.CyclomaticComplexity.TooHigh"> <type>warning</type> </rule> <rule ref="Generic.Metrics.CyclomaticComplexity.MaxExceeded"> <type>warning</type> </rule> <rule ref="Generic.NamingConventions.ConstructorName"/> <rule ref="Generic.NamingConventions.UpperCaseConstantName"/> <rule ref="Generic.PHP.DeprecatedFunctions"/> <rule ref="Generic.PHP.DisallowShortOpenTag"/> <rule ref="Generic.PHP.ForbiddenFunctions"/> <rule ref="Generic.PHP.LowerCaseConstant"/> <rule ref="Generic.PHP.NoSilencedErrors"/> <rule ref="Generic.Strings.UnnecessaryStringConcat"/> <rule ref="Generic.WhiteSpace.DisallowTabIndent"/> <rule ref="Generic.WhiteSpace.ScopeIndent"/> <rule ref="Generic.Commenting.Todo.CommentFound"> <message>Please review this TODO comment: %s</message> <type>warning</type> </rule> <rule ref="Generic.Commenting.Fixme.TaskFound"> <message>Please review this FIXME comment: %s</message> <type>warning</type> </rule> <rule ref="Generic.Files.LineLength"> <properties> <property name="lineLimit" value="120"/> <property name="absoluteLineLimit" value="200"/> </properties> </rule> <rule ref="Generic.Files.LineLength"> <exclude name="Generic.Files.LineLength.MaxExceeded"/> <exclude name="Generic.Files.LineLength.TooLong"/> </rule> <!-- <rule ref="Generic.Files.LineLength.MaxExceeded"> <message>Line contains %s chars, which is longer than the max limit of %s</message> <type>warning</type> </rule> <rule ref="Generic.Files.LineLength.TooLong"> <message>Line longer than %s characters; contains %s characters</message> <type>warning</type> </rule> --> <rule ref="Generic.Classes.DuplicateClassName"/> <rule ref="PEAR.Commenting.InlineComment"/> <rule ref="PEAR.ControlStructures.MultiLineCondition"/> <rule ref="PEAR.WhiteSpace.ObjectOperatorIndent"/> <rule ref="MySource.PHP.EvalObjectFactory"/> <rule ref="MySource.PHP.GetRequestData"/> <!-- <rule ref="MySource.PHP.ReturnFunctionValue"/> --> <rule ref="Squiz.WhiteSpace.LogicalOperatorSpacing"/> <rule ref="Squiz.WhiteSpace.SemicolonSpacing"/> <rule ref="Squiz.WhiteSpace.SuperfluousWhitespace.EmptyLines"> <type>warning</type> </rule> <rule ref="Squiz.WhiteSpace.CastSpacing"/> <rule ref="Squiz.WhiteSpace.LanguageConstructSpacing"/> <!-- <rule ref="Squiz.WhiteSpace.MemberVarSpacing"/> --> <rule ref="Squiz.WhiteSpace.OperatorSpacing"/> <rule ref="Squiz.Scope.StaticThisUsage"/> </ruleset>
{ "content_hash": "acdcd1df0b196c3b4f811ea57918e23a", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 91, "avg_line_length": 35.00819672131148, "alnum_prop": 0.6757199719035355, "repo_name": "akalongman/laravel-platfourm", "id": "fb6c4a69dca755aae22f2603987b51af9fe5c84f", "size": "4271", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "phpcs.xml", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "239225" } ], "symlink_target": "" }
<div id="NamespaceSearchFriends"> <div class="background-white-01"> <div class="spacer-20"></div> <input ng-keyup="searchFriends(userData.id, friendsSearched)" ng-model="friendsSearched" placeholder="Cerca per nome o email" type="text" class="ipt-search"/> <i class="search-friends-icon fa fa-search"></i> <div class="spacer-20"></div> </div> <div ng-if="newFriends.length > 0" ng-repeat="newFriend in newFriends" ng-class="{'no-border-bottom': $last}" class="listview-three-column"> <div class="listview-three-column-image"> <figure ng-if="newFriend.image" style="background-image: url('{{newFriend.image}}');" class="header-profile"></figure> <figure ng-if="!newFriend.image" class="header-profile no-image"></figure> </div> <div id="friend_{{$index}}" class="listview-three-column-icon"> <i ng-click="addFriend(userData.id, newFriend, 'friend_' + $index)" class="icon-contact-add-2"></i> </div> <div class="listview-three-column-content"> <span> <b ng-if="newFriend.username" ng-bind="newFriend.username"></b> <p ng-bind-template="{{newFriend.firstname}} {{newFriend.lastname}}"></p> </span> </div> </div> </div>
{ "content_hash": "055d9e661a9876a577e1044ff78caa20", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 144, "avg_line_length": 44.096774193548384, "alnum_prop": 0.5779078273591807, "repo_name": "gabrielmayta/playground-milano-app-2.0", "id": "3a04116b67eb43bb1cd5ee15839487dc8ba1e0fd", "size": "1367", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "project/app/features/friends-tabs-search/_views/search.html", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "55767" }, { "name": "HTML", "bytes": "27778" }, { "name": "JavaScript", "bytes": "197521" } ], "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_102) on Thu Sep 29 16:37:40 CEST 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class energy.usef.dso.workflow.operate.DsoMonitorGridStepParameter (usef-root-pom 1.3.6 API)</title> <meta name="date" content="2016-09-29"> <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 energy.usef.dso.workflow.operate.DsoMonitorGridStepParameter (usef-root-pom 1.3.6 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="../../../../../../energy/usef/dso/workflow/operate/DsoMonitorGridStepParameter.html" title="class in energy.usef.dso.workflow.operate">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?energy/usef/dso/workflow/operate/class-use/DsoMonitorGridStepParameter.html" target="_top">Frames</a></li> <li><a href="DsoMonitorGridStepParameter.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 energy.usef.dso.workflow.operate.DsoMonitorGridStepParameter" class="title">Uses of Class<br>energy.usef.dso.workflow.operate.DsoMonitorGridStepParameter</h2> </div> <div class="classUseContainer">No usage of energy.usef.dso.workflow.operate.DsoMonitorGridStepParameter</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="../../../../../../energy/usef/dso/workflow/operate/DsoMonitorGridStepParameter.html" title="class in energy.usef.dso.workflow.operate">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?energy/usef/dso/workflow/operate/class-use/DsoMonitorGridStepParameter.html" target="_top">Frames</a></li> <li><a href="DsoMonitorGridStepParameter.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; 2016. All rights reserved.</small></p> </body> </html>
{ "content_hash": "161cd8b10527dba35d4aacfab1f5351f", "timestamp": "", "source": "github", "line_count": 126, "max_line_length": 183, "avg_line_length": 39.682539682539684, "alnum_prop": 0.61, "repo_name": "USEF-Foundation/ri.usef.energy", "id": "885644bff432dcc30bbda8fa02d1d1be420af536", "size": "5000", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "usef-javadoc/energy/usef/dso/workflow/operate/class-use/DsoMonitorGridStepParameter.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "25252" }, { "name": "CSS", "bytes": "13416" }, { "name": "HTML", "bytes": "33111187" }, { "name": "Java", "bytes": "6550058" }, { "name": "JavaScript", "bytes": "857" }, { "name": "PowerShell", "bytes": "6025" }, { "name": "Shell", "bytes": "18796" } ], "symlink_target": "" }
<?php // // Copyright (c) 2013, Zynga Inc. // https://github.com/zynga/saigon // Author: Matt West (https://github.com/mhwest13) // License: BSD 2-Clause // require HTML_HEADER; function isdefined ($hostinfo, $key, $split = false) { if (isset($hostinfo[$key]) && (!empty($hostinfo[$key]))) { if ($split === false) return $hostinfo[$key]; elseif (is_array($hostinfo[$key])) return implode(',', $hostinfo[$key]); else return preg_replace('/,/', ', ', $hostinfo[$key]); } return '<i>null or incl from template</i>'; } function onoffdefined ($hostinfo, $key) { if (isset($hostinfo[$key])) { if ($hostinfo[$key] == 0) return 'Off'; else return 'On'; } return '<i>null or incl from template</i>'; } $deployment = $viewData->deployment; $action = $viewData->action; if ($action == 'modify_write') { $modifyFlag = true; } $hostName = isdefined($viewData->hostInfo, 'name'); $hostAlias = isdefined($viewData->hostInfo, 'alias'); $hostUse = isdefined($viewData->hostInfo, 'use'); $hostChkCommand = isdefined($viewData->hostInfo, 'check_command'); $hostInitState = isdefined($viewData->hostInfo, 'initial_state'); $hostMaxChkAtts = isdefined($viewData->hostInfo, 'max_check_attempts'); $hostCheckInt = isdefined($viewData->hostInfo, 'check_interval'); $hostRetryInt = isdefined($viewData->hostInfo, 'retry_interval'); $hostActChks = onoffdefined($viewData->hostInfo, 'active_checks_enabled'); $hostPsvChks = onoffdefined($viewData->hostInfo, 'passive_checks_enabled'); $hostChkPeriod = isdefined($viewData->hostInfo, 'check_period'); $hostPPData = onoffdefined($viewData->hostInfo, 'process_perf_data'); $hostRetStatusInfo = onoffdefined($viewData->hostInfo, 'retain_status_information'); $hostRetNStatusInfo = onoffdefined($viewData->hostInfo, 'retain_nonstatus_information'); $hostContacts = isdefined($viewData->hostInfo, 'contacts', true); $hostContactGrps = isdefined($viewData->hostInfo, 'contact_groups', true); $hostNotifEn = onoffdefined($viewData->hostInfo, 'notifications_enabled'); $hostNotifInt = isdefined($viewData->hostInfo, 'notification_interval'); $hostNotifPeriod = isdefined($viewData->hostInfo, 'notification_period'); $hostNotifOpts = isdefined($viewData->hostInfo, 'notification_options', true); $hostNotesUrl = isdefined($viewData->hostInfo, 'notes_url'); ?> <link type="text/css" rel="stylesheet" href="static/css/tables.css" /> <body> <div id="host-template" style="border-width:2px;width:97%;left:5;top:5;position:absolute" class="admin_box_blue divCacGroup admin_border_black"> <table class="noderesults"> <thead> <?php if ($viewData->delFlag === true) { ?> <th colspan="2">Delete Host Template Information for <?php echo $hostName?> from <?php echo $deployment?></th> <?php } else { ?> <th colspan="2">View Host Template Information for <?php echo $hostName?> in <?php echo $deployment?></th> <?php } ?> </thead> <tr> <th style="width:35%;text-align:right;">Name:</th> <td style="text-align:left;"><?php echo $hostName?></td> </tr><tr> <th style="width:35%;text-align:right;">Alias:</th> <td style="text-align:left;"><?php echo $hostAlias?></td> </tr><tr> <th style="width:35%;text-align:right;">Template:</th> <td style="text-align:left;"><?php echo $hostUse?></td> </tr><tr> <th style="width:35%;text-align:right;">Check Command:</th> <td style="text-align:left;"><?php echo $hostChkCommand?></td> </tr><tr> <th style="width:35%;text-align:right;">Initial State:</th> <td style="text-align:left;"><?php echo $hostInitState?></td> </tr><tr> <th style="width:35%;text-align:right;">Max Check Attempts:<br /><font size="2">(# of check attempts before sending an alert)</font></th> <td style="text-align:left;"><?php echo $hostMaxChkAtts?></td> </tr><tr> <th style="width:35%;text-align:right;">Check Interval:<br /><font size="2">(amount of minutes between normal check scheduling)</font></th> <td style="text-align:left;"><?php echo $hostCheckInt?></td> </tr><tr> <th style="width:35%;text-align:right;">Check Retry Interval:<br /><font size="2">(amount of minutes between error check scheduling)</font></th> <td style="text-align:left;"><?php echo $hostRetryInt?></td> </tr><tr> <th style="width:35%;text-align:right;">Active Checks Enabled:</th> <td style="text-align:left;"><?php echo $hostActChks?></td> </tr><tr> <th style="width:35%;text-align:right;">Passive Checks Enabled:</th> <td style="text-align:left;"><?php echo $hostPsvChks?></td> </tr><tr> <th style="width:35%;text-align:right;">Check Period:</th> <td style="text-align:left;"><?php echo $hostChkPeriod?></td> </tr><tr> <th style="width:35%;text-align:right;">Process Performance Data:</th> <td style="text-align:left;"><?php echo $hostPPData?></td> </tr><tr> <th style="width:35%;text-align:right;">Retain Status Information:</th> <td style="text-align:left;"><?php echo $hostRetStatusInfo?></td> </tr><tr> <th style="width:35%;text-align:right;">Retain Non-Status Information:</th> <td style="text-align:left;"><?php echo $hostRetNStatusInfo?></td> </tr><tr> <th style="width:35%;text-align:right;">Contacts:</th> <td style="text-align:left;"><?php echo $hostContacts?></td> </tr><tr> <th style="width:35%;text-align:right;">Contact Groups:</th> <td style="text-align:left;"><?php echo $hostContactGrps?></td> </tr><tr> <th style="width:35%;text-align:right;">Notifications Enabled:</th> <td style="text-align:left;"><?php echo $hostNotifEn?></td> </tr><tr> <th style="width:35%;text-align:right;">Notification Interval:<br /><font size="2">(amount of minutes between sending alerts)</font></th> <td style="text-align:left;"><?php echo $hostNotifInt?></td> </tr><tr> <th style="width:35%;text-align:right;">Notification Period:</th> <td style="text-align:left;"><?php echo $hostNotifPeriod?></td> </tr><tr> <th style="width:35%;text-align:right;">Notification Options:</th> <td style="text-align:left;"><?php echo $hostNotifOpts?></td> </tr><tr> <th style="width:35%;text-align:right;">Notes Url:</th> <td style="text-align:left;"><?php echo $hostNotesUrl?></td> </tr> </table> <div class="divCacGroup"><!-- 5 Pixel Spacer --></div> <?php if ($viewData->delFlag === true) { ?> <a href="action.php?controller=hosttemp&action=<?php echo $action?>&deployment=<?php echo $deployment?>&hosttemp=<?php echo $hostName?>" class="deployBtn">Delete</a> <a href="action.php?controller=hosttemp&action=stage&deployment=<?php echo $deployment?>" class="deployBtn">Cancel</a> <?php } else { ?> <a href="action.php?controller=hosttemp&action=stage&deployment=<?php echo $deployment?>" class="deployBtn">Host Templates</a> <?php } ?> </div> <?php require HTML_FOOTER;
{ "content_hash": "4435607dd410807eeaa9884a4f638073", "timestamp": "", "source": "github", "line_count": 156, "max_line_length": 165, "avg_line_length": 45.28846153846154, "alnum_prop": 0.643170559094126, "repo_name": "mhwest13/saigon", "id": "aaf91c706e3df38f4d06af7348f1b93816ec5255", "size": "7065", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "views/host_template_view_stage.php", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "ApacheConf", "bytes": "85" }, { "name": "CSS", "bytes": "17181" }, { "name": "JavaScript", "bytes": "391721" }, { "name": "PHP", "bytes": "2720010" }, { "name": "Perl", "bytes": "71051" }, { "name": "Shell", "bytes": "2660" } ], "symlink_target": "" }
package com.gentics.mesh.core.data.job; import java.time.ZonedDateTime; import com.gentics.mesh.core.data.Project; import com.gentics.mesh.core.data.branch.HibBranch; import com.gentics.mesh.core.data.project.HibProject; import com.gentics.mesh.core.data.root.RootVertex; import com.gentics.mesh.core.data.schema.HibMicroschemaVersion; import com.gentics.mesh.core.data.schema.HibSchemaVersion; import com.gentics.mesh.core.data.user.HibUser; import io.reactivex.Completable; /** * Aggregation vertex for jobs. */ public interface JobRoot extends RootVertex<Job> { /** * Enqueue a new job with the given information. * * @param creator * @param branch * @param fromVersion * @param toVersion * @return Created job */ HibJob enqueueSchemaMigration(HibUser creator, HibBranch branch, HibSchemaVersion fromVersion, HibSchemaVersion toVersion); /** * Enqueue a branch migration job. * * @param creator * @param branch * @param fromVersion * @param toVersion * @return */ HibJob enqueueBranchMigration(HibUser creator, HibBranch branch, HibSchemaVersion fromVersion, HibSchemaVersion toVersion); /** * Enqueue a microschema migration. * * @param creator * @param branch * @param fromVersion * @param toVersion * @return */ HibJob enqueueMicroschemaMigration(HibUser creator, HibBranch branch, HibMicroschemaVersion fromVersion, HibMicroschemaVersion toVersion); /** * Enqueue a branch migration. * * @param creator * @param branch * @return */ HibJob enqueueBranchMigration(HibUser creator, HibBranch branch); /** * Enqueue a project version purge job that is limited to the given date. * * @param user * @param project * @param before * @return */ HibJob enqueueVersionPurge(HibUser user, HibProject project, ZonedDateTime before); /** * Enqueue a project version purge job. * @param user * @param project * @return */ HibJob enqueueVersionPurge(HibUser user, HibProject project); /** * Delete all the jobs referencing the provided project. * @param project */ void deleteByProject(Project project); /** * Purge all failed jobs from the job root. */ void purgeFailed(); /** * Delete all jobs. */ void clear(); }
{ "content_hash": "77a4cb6cb0703b81b62aa21ad104b0ff", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 139, "avg_line_length": 23.610526315789475, "alnum_prop": 0.7253678109674543, "repo_name": "gentics/mesh", "id": "374e68009af406d2d836f15acba84c375ab201b6", "size": "2243", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "mdm/orientdb-api/src/main/java/com/gentics/mesh/core/data/job/JobRoot.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "40221" }, { "name": "Dockerfile", "bytes": "5309" }, { "name": "Erlang", "bytes": "4651" }, { "name": "HTML", "bytes": "3848" }, { "name": "Handlebars", "bytes": "6515" }, { "name": "Java", "bytes": "9074233" }, { "name": "JavaScript", "bytes": "1130" }, { "name": "Shell", "bytes": "3757" } ], "symlink_target": "" }
package com.sportmonks.data.entity; import com.fasterxml.jackson.annotation.*; import java.util.HashMap; import java.util.Map; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"name", "league_id", "is_current_season", "current_round_id", "current_stage_id"}) public class SeasonAttributes { @JsonProperty("name") private String name; @JsonProperty("league_id") private Long leagueId; @JsonProperty("is_current_season") private Boolean isCurrentSeason; @JsonProperty("current_round_id") private Object currentRoundId; @JsonProperty("current_stage_id") private Object currentStageId; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); @JsonProperty("name") public String getName() { return name; } @JsonProperty("name") public void setName(String name) { this.name = name; } @JsonProperty("league_id") public Long getLeagueId() { return leagueId; } @JsonProperty("league_id") public void setLeagueId(Long leagueId) { this.leagueId = leagueId; } @JsonProperty("is_current_season") public Boolean getIsCurrentSeason() { return isCurrentSeason; } @JsonProperty("is_current_season") public void setIsCurrentSeason(Boolean isCurrentSeason) { this.isCurrentSeason = isCurrentSeason; } @JsonProperty("current_round_id") public Object getCurrentRoundId() { return currentRoundId; } @JsonProperty("current_round_id") public void setCurrentRoundId(Object currentRoundId) { this.currentRoundId = currentRoundId; } @JsonProperty("current_stage_id") public Object getCurrentStageId() { return currentStageId; } @JsonProperty("current_stage_id") public void setCurrentStageId(Object currentStageId) { this.currentStageId = currentStageId; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } }
{ "content_hash": "b793b51f9b765e0b0df7b51cd894ed9b", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 102, "avg_line_length": 26.094117647058823, "alnum_prop": 0.6816952209197475, "repo_name": "kevinsamyn/sportmonks-soccer", "id": "5bfed2e9d114145c275f490d438f9d4c6d208c4b", "size": "2218", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/sportmonks/data/entity/SeasonAttributes.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "297257" } ], "symlink_target": "" }
/* A Bison parser, made by GNU Bison 3.0.2. */ /* Bison interface for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2013 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ #ifndef YY_YY_YYSCRIPT_H_INCLUDED # define YY_YY_YYSCRIPT_H_INCLUDED /* Debug traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif #if YYDEBUG extern int yydebug; #endif /* Token type. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE enum yytokentype { PLUSEQ = 258, MINUSEQ = 259, MULTEQ = 260, DIVEQ = 261, LSHIFTEQ = 262, RSHIFTEQ = 263, ANDEQ = 264, OREQ = 265, OROR = 266, ANDAND = 267, EQ = 268, NE = 269, LE = 270, GE = 271, LSHIFT = 272, RSHIFT = 273, UNARY = 274, STRING = 275, QUOTED_STRING = 276, INTEGER = 277, ABSOLUTE = 278, ADDR = 279, ALIGN_K = 280, ALIGNOF = 281, ASSERT_K = 282, AS_NEEDED = 283, AT = 284, BIND = 285, BLOCK = 286, BYTE = 287, CONSTANT = 288, CONSTRUCTORS = 289, COPY = 290, CREATE_OBJECT_SYMBOLS = 291, DATA_SEGMENT_ALIGN = 292, DATA_SEGMENT_END = 293, DATA_SEGMENT_RELRO_END = 294, DEFINED = 295, DSECT = 296, ENTRY = 297, EXCLUDE_FILE = 298, EXTERN = 299, FILL = 300, FLOAT = 301, FORCE_COMMON_ALLOCATION = 302, GLOBAL = 303, GROUP = 304, HLL = 305, INCLUDE = 306, INHIBIT_COMMON_ALLOCATION = 307, INFO = 308, INPUT = 309, KEEP = 310, LEN = 311, LENGTH = 312, LOADADDR = 313, LOCAL = 314, LONG = 315, MAP = 316, MAX_K = 317, MEMORY = 318, MIN_K = 319, NEXT = 320, NOCROSSREFS = 321, NOFLOAT = 322, NOLOAD = 323, ONLY_IF_RO = 324, ONLY_IF_RW = 325, ORG = 326, ORIGIN = 327, OUTPUT = 328, OUTPUT_ARCH = 329, OUTPUT_FORMAT = 330, OVERLAY = 331, PHDRS = 332, PROVIDE = 333, PROVIDE_HIDDEN = 334, QUAD = 335, SEARCH_DIR = 336, SECTIONS = 337, SEGMENT_START = 338, SHORT = 339, SIZEOF = 340, SIZEOF_HEADERS = 341, SORT_BY_ALIGNMENT = 342, SORT_BY_NAME = 343, SPECIAL = 344, SQUAD = 345, STARTUP = 346, SUBALIGN = 347, SYSLIB = 348, TARGET_K = 349, TRUNCATE = 350, VERSIONK = 351, OPTION = 352, PARSING_LINKER_SCRIPT = 353, PARSING_VERSION_SCRIPT = 354, PARSING_DEFSYM = 355, PARSING_DYNAMIC_LIST = 356 }; #endif /* Tokens. */ #define PLUSEQ 258 #define MINUSEQ 259 #define MULTEQ 260 #define DIVEQ 261 #define LSHIFTEQ 262 #define RSHIFTEQ 263 #define ANDEQ 264 #define OREQ 265 #define OROR 266 #define ANDAND 267 #define EQ 268 #define NE 269 #define LE 270 #define GE 271 #define LSHIFT 272 #define RSHIFT 273 #define UNARY 274 #define STRING 275 #define QUOTED_STRING 276 #define INTEGER 277 #define ABSOLUTE 278 #define ADDR 279 #define ALIGN_K 280 #define ALIGNOF 281 #define ASSERT_K 282 #define AS_NEEDED 283 #define AT 284 #define BIND 285 #define BLOCK 286 #define BYTE 287 #define CONSTANT 288 #define CONSTRUCTORS 289 #define COPY 290 #define CREATE_OBJECT_SYMBOLS 291 #define DATA_SEGMENT_ALIGN 292 #define DATA_SEGMENT_END 293 #define DATA_SEGMENT_RELRO_END 294 #define DEFINED 295 #define DSECT 296 #define ENTRY 297 #define EXCLUDE_FILE 298 #define EXTERN 299 #define FILL 300 #define FLOAT 301 #define FORCE_COMMON_ALLOCATION 302 #define GLOBAL 303 #define GROUP 304 #define HLL 305 #define INCLUDE 306 #define INHIBIT_COMMON_ALLOCATION 307 #define INFO 308 #define INPUT 309 #define KEEP 310 #define LEN 311 #define LENGTH 312 #define LOADADDR 313 #define LOCAL 314 #define LONG 315 #define MAP 316 #define MAX_K 317 #define MEMORY 318 #define MIN_K 319 #define NEXT 320 #define NOCROSSREFS 321 #define NOFLOAT 322 #define NOLOAD 323 #define ONLY_IF_RO 324 #define ONLY_IF_RW 325 #define ORG 326 #define ORIGIN 327 #define OUTPUT 328 #define OUTPUT_ARCH 329 #define OUTPUT_FORMAT 330 #define OVERLAY 331 #define PHDRS 332 #define PROVIDE 333 #define PROVIDE_HIDDEN 334 #define QUAD 335 #define SEARCH_DIR 336 #define SECTIONS 337 #define SEGMENT_START 338 #define SHORT 339 #define SIZEOF 340 #define SIZEOF_HEADERS 341 #define SORT_BY_ALIGNMENT 342 #define SORT_BY_NAME 343 #define SPECIAL 344 #define SQUAD 345 #define STARTUP 346 #define SUBALIGN 347 #define SYSLIB 348 #define TARGET_K 349 #define TRUNCATE 350 #define VERSIONK 351 #define OPTION 352 #define PARSING_LINKER_SCRIPT 353 #define PARSING_VERSION_SCRIPT 354 #define PARSING_DEFSYM 355 #define PARSING_DYNAMIC_LIST 356 /* Value type. */ #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE YYSTYPE; union YYSTYPE { #line 53 "yyscript.y" /* yacc.c:1909 */ /* A string. */ struct Parser_string string; /* A number. */ uint64_t integer; /* An expression. */ Expression_ptr expr; /* An output section header. */ struct Parser_output_section_header output_section_header; /* An output section trailer. */ struct Parser_output_section_trailer output_section_trailer; /* A section constraint. */ enum Section_constraint constraint; /* A complete input section specification. */ struct Input_section_spec input_section_spec; /* A list of wildcard specifications, with exclusions. */ struct Wildcard_sections wildcard_sections; /* A single wildcard specification. */ struct Wildcard_section wildcard_section; /* A list of strings. */ String_list_ptr string_list; /* Information for a program header. */ struct Phdr_info phdr_info; /* Used for version scripts and within VERSION {}. */ struct Version_dependency_list* deplist; struct Version_expression_list* versyms; struct Version_tree* versnode; enum Script_section_type section_type; #line 286 "yyscript.h" /* yacc.c:1909 */ }; # define YYSTYPE_IS_TRIVIAL 1 # define YYSTYPE_IS_DECLARED 1 #endif int yyparse (void* closure); #endif /* !YY_YY_YYSCRIPT_H_INCLUDED */
{ "content_hash": "10206ae71b52659cfd482205e3b1fcf3", "timestamp": "", "source": "github", "line_count": 295, "max_line_length": 76, "avg_line_length": 24.538983050847456, "alnum_prop": 0.6897361514021274, "repo_name": "veritas-shine/minix3-rpi", "id": "945d59da7afe629665dc85f479437a983f9a1a4e", "size": "7239", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "external/gpl3/binutils/files/yyscript.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ada", "bytes": "89060" }, { "name": "Arc", "bytes": "2839" }, { "name": "Assembly", "bytes": "2791293" }, { "name": "Awk", "bytes": "39398" }, { "name": "Bison", "bytes": "137952" }, { "name": "C", "bytes": "45473316" }, { "name": "C#", "bytes": "55726" }, { "name": "C++", "bytes": "577647" }, { "name": "CLIPS", "bytes": "6933" }, { "name": "CSS", "bytes": "254" }, { "name": "Emacs Lisp", "bytes": "4528" }, { "name": "IGOR Pro", "bytes": "2975" }, { "name": "JavaScript", "bytes": "25168" }, { "name": "Logos", "bytes": "14672" }, { "name": "Lua", "bytes": "4385" }, { "name": "Makefile", "bytes": "669790" }, { "name": "Max", "bytes": "3667" }, { "name": "Objective-C", "bytes": "62068" }, { "name": "Pascal", "bytes": "40318" }, { "name": "Perl", "bytes": "100129" }, { "name": "Perl6", "bytes": "243" }, { "name": "Prolog", "bytes": "97" }, { "name": "R", "bytes": "764" }, { "name": "Rebol", "bytes": "738" }, { "name": "SAS", "bytes": "1711" }, { "name": "Shell", "bytes": "2207644" } ], "symlink_target": "" }
import ServerPacket from "../ServerPackets"; import { PacketIdentifier } from "../AbstractPacket"; interface IPublicChannel { name: string; mode: string; characters: number; } @PacketIdentifier("CHA") class PublicChannelListPacket extends ServerPacket { channels: IPublicChannel[]; } export { PublicChannelListPacket, PublicChannelListPacket as CHA, IPublicChannel };
{ "content_hash": "cdc2e0e4317e90d30794d7d4eba7ec35", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 83, "avg_line_length": 22.764705882352942, "alnum_prop": 0.7571059431524548, "repo_name": "RootElevation/Horizon", "id": "fc66960063951ee192ec70d04379a4e3e847136c", "size": "389", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Horizon/Scripts/common/packets/server/PublicChannelListPacket.ts", "mode": "33188", "license": "mit", "language": [ { "name": "TypeScript", "bytes": "22345" } ], "symlink_target": "" }
// Copyright Jim Bosch 2010-2012. // Copyright Stefan Seefeld 2016. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef boost_python_numpy_matrix_hpp_ #define boost_python_numpy_matrix_hpp_ /** * @brief Object manager for numpy.matrix. */ #include <boost/python.hpp> #include <boost/python/numpy/numpy_object_mgr_traits.hpp> #include <boost/python/numpy/ndarray.hpp> #include <boost/python/numpy/config.hpp> namespace boost { namespace python { namespace numpy { /** * @brief A boost.python "object manager" (subclass of object) for numpy.matrix. * * @internal numpy.matrix is defined in Python, so object_manager_traits<matrix>::get_pytype() * is implemented by importing numpy and getting the "matrix" attribute of the module. * We then just hope that doesn't get destroyed while we need it, because if we put * a dynamic python object in a static-allocated boost::python::object or handle<>, * bad things happen when Python shuts down. I think this solution is safe, but I'd * love to get that confirmed. */ class BOOST_NUMPY_DECL matrix : public ndarray { static object construct(object_cref obj, dtype const & dt, bool copy); static object construct(object_cref obj, bool copy); public: BOOST_PYTHON_FORWARD_OBJECT_CONSTRUCTORS(matrix, ndarray); /// @brief Equivalent to "numpy.matrix(obj,dt,copy)" in Python. explicit matrix(object const & obj, dtype const & dt, bool copy=true) : ndarray(extract<ndarray>(construct(obj, dt, copy))) {} /// @brief Equivalent to "numpy.matrix(obj,copy=copy)" in Python. explicit matrix(object const & obj, bool copy=true) : ndarray(extract<ndarray>(construct(obj, copy))) {} /// \brief Return a view of the matrix with the given dtype. matrix view(dtype const & dt) const; /// \brief Copy the scalar (deep for all non-object fields). matrix copy() const; /// \brief Transpose the matrix. matrix transpose() const; }; /** * @brief CallPolicies that causes a function that returns a numpy.ndarray to * return a numpy.matrix instead. */ template <typename Base = default_call_policies> struct as_matrix : Base { static PyObject * postcall(PyObject *, PyObject * result) { object a = object(handle<>(result)); numpy::matrix m(a, false); Py_INCREF(m.ptr()); return m.ptr(); } }; } // namespace boost::python::numpy namespace converter { NUMPY_OBJECT_MANAGER_TRAITS(numpy::matrix); }}} // namespace boost::python::converter #endif
{ "content_hash": "f3571d2cf83c1b2b8ab6388dc8fdaeed", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 97, "avg_line_length": 32.357142857142854, "alnum_prop": 0.6736571008094187, "repo_name": "Owldream/Ginseng", "id": "228b7d67e972c992da0740937afcd0de834bfb3b", "size": "2718", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/ginseng/3rd-party/boost/python/numpy/matrix.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2144" }, { "name": "C++", "bytes": "612615" }, { "name": "CMake", "bytes": "21889" }, { "name": "Objective-C++", "bytes": "398" } ], "symlink_target": "" }
var actions = function (tools) { return { get: function (id, callback) { tools._get('actions/' + id, function (err, data) { if (err) return callback(err) callback(null, data) }) }, list: function (callback) { tools._get('actions', function (err, data) { if (err) return callback(err) callback(null, data) }) } } } module.exports = actions
{ "content_hash": "6092519de0976e03e5b981e3552b55f7", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 56, "avg_line_length": 20.9, "alnum_prop": 0.5454545454545454, "repo_name": "getfyre/digio-api", "id": "f70c1d81aa874e002045b494de707e142176dac3", "size": "418", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/modules/actions.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "14440" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "05cf0c4cca1a65f04cf15d54fe24a7fd", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "d05988a03a27ca40e132482600e74576db0aa7ab", "size": "184", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Elleanthus/Elleanthus tovarensis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.bitcoinj.core; import org.libdohj.core.AltcoinNetworkParameters; import com.google.common.base.Preconditions; import javax.annotation.Nullable; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.math.BigInteger; import java.security.GeneralSecurityException; import java.util.BitSet; import java.util.List; import static org.bitcoinj.core.Coin.FIFTY_COINS; import org.libdohj.core.ScryptHash; import static org.libdohj.core.Utils.scryptDigest; import static org.bitcoinj.core.Utils.reverseBytes; import org.libdohj.core.AuxPoWNetworkParameters; /** * <p>A block is a group of transactions, and is one of the fundamental data structures of the Bitcoin system. * It records a set of {@link Transaction}s together with some data that links it into a place in the global block * chain, and proves that a difficult calculation was done over its contents. See * <a href="http://www.bitcoin.org/bitcoin.pdf">the Bitcoin technical paper</a> for * more detail on blocks. <p/> * * To get a block, you can either build one from the raw bytes you can get from another implementation, or request one * specifically using {@link Peer#getBlock(Sha256Hash)}, or grab one from a downloaded {@link BlockChain}. */ public class AltcoinBlock extends org.bitcoinj.core.Block { private static final int BYTE_BITS = 8; private boolean auxpowParsed = false; private boolean auxpowBytesValid = false; /** AuxPoW header element, if applicable. */ @Nullable private AuxPoW auxpow; /** * Whether the chain this block belongs to support AuxPoW, used to avoid * repeated instanceof checks. Initialised in parseTransactions() */ private boolean auxpowChain = false; private ScryptHash scryptHash; /** Special case constructor, used for the genesis node, cloneAsHeader and unit tests. * @param params NetworkParameters object. */ public AltcoinBlock(final NetworkParameters params, final long version) { super(params, version); } /** Special case constructor, used for the genesis node, cloneAsHeader and unit tests. * @param params NetworkParameters object. */ public AltcoinBlock(final NetworkParameters params, final byte[] payloadBytes) { this(params, payloadBytes, 0, params.getDefaultSerializer(), payloadBytes.length); } /** * Construct a block object from the Bitcoin wire format. * @param params NetworkParameters object. * @param serializer the serializer to use for this message. * @param length The length of message if known. Usually this is provided when deserializing of the wire * as the length will be provided as part of the header. If unknown then set to Message.UNKNOWN_LENGTH * @throws ProtocolException */ public AltcoinBlock(final NetworkParameters params, final byte[] payloadBytes, final int offset, final MessageSerializer serializer, final int length) throws ProtocolException { super(params, payloadBytes, offset, serializer, length); } public AltcoinBlock(NetworkParameters params, byte[] payloadBytes, int offset, Message parent, MessageSerializer serializer, int length) throws ProtocolException { super(params, payloadBytes, serializer, length); } /** * Construct a block initialized with all the given fields. * @param params Which network the block is for. * @param version This should usually be set to 1 or 2, depending on if the height is in the coinbase input. * @param prevBlockHash Reference to previous block in the chain or {@link Sha256Hash#ZERO_HASH} if genesis. * @param merkleRoot The root of the merkle tree formed by the transactions. * @param time UNIX time when the block was mined. * @param difficultyTarget Number which this block hashes lower than. * @param nonce Arbitrary number to make the block hash lower than the target. * @param transactions List of transactions including the coinbase. */ public AltcoinBlock(NetworkParameters params, long version, Sha256Hash prevBlockHash, Sha256Hash merkleRoot, long time, long difficultyTarget, long nonce, List<Transaction> transactions) { super(params, version, prevBlockHash, merkleRoot, time, difficultyTarget, nonce, transactions); } private ScryptHash calculateScryptHash() { try { ByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(HEADER_SIZE); writeHeader(bos); return new ScryptHash(reverseBytes(scryptDigest(bos.toByteArray()))); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } catch (GeneralSecurityException e) { throw new RuntimeException(e); // Cannot happen. } } public AuxPoW getAuxPoW() { return this.auxpow; } public void setAuxPoW(AuxPoW auxpow) { this.auxpow = auxpow; } /** * Returns the Scrypt hash of the block (which for a valid, solved block should be * below the target). Big endian. */ public ScryptHash getScryptHash() { if (scryptHash == null) scryptHash = calculateScryptHash(); return scryptHash; } /** * Returns the Scrypt hash of the block. */ public String getScryptHashAsString() { return getScryptHash().toString(); } @Override public Coin getBlockInflation(int height) { final AltcoinNetworkParameters altParams = (AltcoinNetworkParameters) params; return altParams.getBlockSubsidy(height); } /** * Get the chain ID (upper 16 bits) from an AuxPoW version number. */ public static long getChainID(final long rawVersion) { return rawVersion >> 16; } /** * Return chain ID from block version of an AuxPoW-enabled chain. */ public long getChainID() { return getChainID(this.getRawVersion()); } /** * Return flags from block version of an AuxPoW-enabled chain. * * @return flags as a bitset. */ public BitSet getVersionFlags() { final BitSet bitset = new BitSet(BYTE_BITS); final int bits = (int) (this.getRawVersion() & 0xff00) >> 8; for (int bit = 0; bit < BYTE_BITS; bit++) { if ((bits & (1 << bit)) > 0) { bitset.set(bit); } } return bitset; } /** * Return block version without applying any filtering (i.e. for AuxPoW blocks * which structure version differently to pack in additional data). */ public final long getRawVersion() { return super.getVersion(); } /** * Get the base version (i.e. Bitcoin-like version number) out of a packed * AuxPoW version number (i.e. one that contains chain ID and feature flags). */ public static long getBaseVersion(final long rawVersion) { return rawVersion & 0xff; } @Override public long getVersion() { // TODO: Can we cache the individual parts on parse? if (this.params instanceof AltcoinNetworkParameters) { // AuxPoW networks use the higher block version bits for flags and // chain ID. return getBaseVersion(super.getVersion()); } else { return super.getVersion(); } } protected void parseAuxPoW() throws ProtocolException { if (this.auxpowParsed) return; this.auxpow = null; if (this.auxpowChain) { final AuxPoWNetworkParameters auxpowParams = (AuxPoWNetworkParameters)this.params; if (auxpowParams.isAuxPoWBlockVersion(this.getRawVersion()) && payload.length >= 160) { // We have at least 2 headers in an Aux block. Workaround for StoredBlocks this.auxpow = new AuxPoW(params, payload, cursor, this, serializer); } } this.auxpowParsed = true; this.auxpowBytesValid = serializer.isParseRetainMode(); } @Override protected void parseTransactions(final int offset) { this.auxpowChain = params instanceof AuxPoWNetworkParameters; parseAuxPoW(); if (null != this.auxpow) { super.parseTransactions(offset + auxpow.getMessageSize()); optimalEncodingMessageSize += auxpow.getMessageSize(); } else { super.parseTransactions(offset); } } @Override void writeHeader(OutputStream stream) throws IOException { super.writeHeader(stream); if (null != this.auxpow) { this.auxpow.bitcoinSerialize(stream); } } /** Returns a copy of the block, but without any transactions. */ @Override public Block cloneAsHeader() { AltcoinBlock block = new AltcoinBlock(params, getRawVersion()); super.copyBitcoinHeaderTo(block); block.auxpow = auxpow; return block; } /** Returns true if the hash of the block is OK (lower than difficulty target). */ protected boolean checkProofOfWork(boolean throwException) throws VerificationException { if (params instanceof AltcoinNetworkParameters) { BigInteger target = getDifficultyTargetAsInteger(); if (params instanceof AuxPoWNetworkParameters) { final AuxPoWNetworkParameters auxParams = (AuxPoWNetworkParameters)this.params; if (auxParams.isAuxPoWBlockVersion(getRawVersion()) && null != auxpow) { return auxpow.checkProofOfWork(this.getHash(), target, throwException); } } final AltcoinNetworkParameters altParams = (AltcoinNetworkParameters)this.params; BigInteger h = altParams.getBlockDifficultyHash(this).toBigInteger(); if (h.compareTo(target) > 0) { // Proof of work check failed! if (throwException) throw new VerificationException("Hash is higher than target: " + getHashAsString() + " vs " + target.toString(16)); else return false; } return true; } else { return super.checkProofOfWork(throwException); } } /** * Checks the block data to ensure it follows the rules laid out in the network parameters. Specifically, * throws an exception if the proof of work is invalid, or if the timestamp is too far from what it should be. * This is <b>not</b> everything that is required for a block to be valid, only what is checkable independent * of the chain and without a transaction index. * * @throws VerificationException */ @Override public void verifyHeader() throws VerificationException { super.verifyHeader(); } }
{ "content_hash": "360ab05ff923b379074a59d697b70c75", "timestamp": "", "source": "github", "line_count": 290, "max_line_length": 123, "avg_line_length": 37.727586206896554, "alnum_prop": 0.6604515126588063, "repo_name": "patricklodder/libdohj", "id": "62e320cf5c4c8ff22b94b5c7076041900e1f823c", "size": "11572", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/bitcoinj/core/AltcoinBlock.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "155252" }, { "name": "JavaScript", "bytes": "7390" }, { "name": "Protocol Buffer", "bytes": "37903" }, { "name": "Python", "bytes": "3090" } ], "symlink_target": "" }
package com.amazonaws.services.elasticmapreduce; import org.w3c.dom.*; import java.net.*; import java.util.*; import java.util.Map.Entry; import org.apache.commons.logging.*; import com.amazonaws.*; import com.amazonaws.auth.*; import com.amazonaws.handlers.*; import com.amazonaws.http.*; import com.amazonaws.internal.*; import com.amazonaws.metrics.*; import com.amazonaws.regions.*; import com.amazonaws.transform.*; import com.amazonaws.util.*; import com.amazonaws.util.json.*; import com.amazonaws.util.AWSRequestMetrics.Field; import com.amazonaws.annotation.ThreadSafe; import com.amazonaws.services.elasticmapreduce.model.*; import com.amazonaws.services.elasticmapreduce.model.transform.*; /** * Client for accessing Amazon EMR. All service calls made using this client are * blocking, and will not return until the service call completes. * <p> * <p> * Amazon Elastic MapReduce (Amazon EMR) is a web service that makes it easy to * process large amounts of data efficiently. Amazon EMR uses Hadoop processing * combined with several AWS products to do tasks such as web indexing, data * mining, log file analysis, machine learning, scientific simulation, and data * warehousing. * </p> */ @ThreadSafe public class AmazonElasticMapReduceClient extends AmazonWebServiceClient implements AmazonElasticMapReduce { /** Provider for AWS credentials. */ private AWSCredentialsProvider awsCredentialsProvider; private static final Log log = LogFactory .getLog(AmazonElasticMapReduce.class); /** Default signing name for the service. */ private static final String DEFAULT_SIGNING_NAME = "elasticmapreduce"; /** The region metadata service name for computing region endpoints. */ private static final String DEFAULT_ENDPOINT_PREFIX = "elasticmapreduce"; /** * Client configuration factory providing ClientConfigurations tailored to * this client */ protected static final ClientConfigurationFactory configFactory = new ClientConfigurationFactory(); /** * List of exception unmarshallers for all Amazon EMR exceptions. */ protected List<JsonErrorUnmarshallerV2> jsonErrorUnmarshallers = new ArrayList<JsonErrorUnmarshallerV2>(); /** * Constructs a new client to invoke service methods on Amazon EMR. A * credentials provider chain will be used that searches for credentials in * this order: * <ul> * <li>Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_KEY</li> * <li>Java System Properties - aws.accessKeyId and aws.secretKey</li> * <li>Instance profile credentials delivered through the Amazon EC2 * metadata service</li> * </ul> * * <p> * All service calls made using this new client object are blocking, and * will not return until the service call completes. * * @see DefaultAWSCredentialsProviderChain */ public AmazonElasticMapReduceClient() { this(new DefaultAWSCredentialsProviderChain(), configFactory .getConfig()); } /** * Constructs a new client to invoke service methods on Amazon EMR. A * credentials provider chain will be used that searches for credentials in * this order: * <ul> * <li>Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_KEY</li> * <li>Java System Properties - aws.accessKeyId and aws.secretKey</li> * <li>Instance profile credentials delivered through the Amazon EC2 * metadata service</li> * </ul> * * <p> * All service calls made using this new client object are blocking, and * will not return until the service call completes. * * @param clientConfiguration * The client configuration options controlling how this client * connects to Amazon EMR (ex: proxy settings, retry counts, etc.). * * @see DefaultAWSCredentialsProviderChain */ public AmazonElasticMapReduceClient(ClientConfiguration clientConfiguration) { this(new DefaultAWSCredentialsProviderChain(), clientConfiguration); } /** * Constructs a new client to invoke service methods on Amazon EMR using the * specified AWS account credentials. * * <p> * All service calls made using this new client object are blocking, and * will not return until the service call completes. * * @param awsCredentials * The AWS credentials (access key ID and secret key) to use when * authenticating with AWS services. */ public AmazonElasticMapReduceClient(AWSCredentials awsCredentials) { this(awsCredentials, configFactory.getConfig()); } /** * Constructs a new client to invoke service methods on Amazon EMR using the * specified AWS account credentials and client configuration options. * * <p> * All service calls made using this new client object are blocking, and * will not return until the service call completes. * * @param awsCredentials * The AWS credentials (access key ID and secret key) to use when * authenticating with AWS services. * @param clientConfiguration * The client configuration options controlling how this client * connects to Amazon EMR (ex: proxy settings, retry counts, etc.). */ public AmazonElasticMapReduceClient(AWSCredentials awsCredentials, ClientConfiguration clientConfiguration) { super(clientConfiguration); this.awsCredentialsProvider = new StaticCredentialsProvider( awsCredentials); init(); } /** * Constructs a new client to invoke service methods on Amazon EMR using the * specified AWS account credentials provider. * * <p> * All service calls made using this new client object are blocking, and * will not return until the service call completes. * * @param awsCredentialsProvider * The AWS credentials provider which will provide credentials to * authenticate requests with AWS services. */ public AmazonElasticMapReduceClient( AWSCredentialsProvider awsCredentialsProvider) { this(awsCredentialsProvider, configFactory.getConfig()); } /** * Constructs a new client to invoke service methods on Amazon EMR using the * specified AWS account credentials provider and client configuration * options. * * <p> * All service calls made using this new client object are blocking, and * will not return until the service call completes. * * @param awsCredentialsProvider * The AWS credentials provider which will provide credentials to * authenticate requests with AWS services. * @param clientConfiguration * The client configuration options controlling how this client * connects to Amazon EMR (ex: proxy settings, retry counts, etc.). */ public AmazonElasticMapReduceClient( AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration) { this(awsCredentialsProvider, clientConfiguration, null); } /** * Constructs a new client to invoke service methods on Amazon EMR using the * specified AWS account credentials provider, client configuration options, * and request metric collector. * * <p> * All service calls made using this new client object are blocking, and * will not return until the service call completes. * * @param awsCredentialsProvider * The AWS credentials provider which will provide credentials to * authenticate requests with AWS services. * @param clientConfiguration * The client configuration options controlling how this client * connects to Amazon EMR (ex: proxy settings, retry counts, etc.). * @param requestMetricCollector * optional request metric collector */ public AmazonElasticMapReduceClient( AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration, RequestMetricCollector requestMetricCollector) { super(clientConfiguration, requestMetricCollector); this.awsCredentialsProvider = awsCredentialsProvider; init(); } private void init() { jsonErrorUnmarshallers .add(new JsonErrorUnmarshallerV2( com.amazonaws.services.elasticmapreduce.model.InternalServerException.class, "InternalServerException")); jsonErrorUnmarshallers .add(new JsonErrorUnmarshallerV2( com.amazonaws.services.elasticmapreduce.model.InternalServerErrorException.class, "InternalServerError")); jsonErrorUnmarshallers .add(new JsonErrorUnmarshallerV2( com.amazonaws.services.elasticmapreduce.model.InvalidRequestException.class, "InvalidRequestException")); jsonErrorUnmarshallers .add(JsonErrorUnmarshallerV2.DEFAULT_UNMARSHALLER); setServiceNameIntern(DEFAULT_SIGNING_NAME); setEndpointPrefix(DEFAULT_ENDPOINT_PREFIX); // calling this.setEndPoint(...) will also modify the signer accordingly setEndpoint("https://elasticmapreduce.amazonaws.com"); HandlerChainFactory chainFactory = new HandlerChainFactory(); requestHandler2s .addAll(chainFactory .newRequestHandlerChain("/com/amazonaws/services/elasticmapreduce/request.handlers")); requestHandler2s .addAll(chainFactory .newRequestHandler2Chain("/com/amazonaws/services/elasticmapreduce/request.handler2s")); } /** * <p> * AddInstanceGroups adds an instance group to a running cluster. * </p> * * @param addInstanceGroupsRequest * Input to an AddInstanceGroups call. * @return Result of the AddInstanceGroups operation returned by the * service. * @throws InternalServerErrorException * Indicates that an error occurred while processing the request and * that the request was not completed. * @sample AmazonElasticMapReduce.AddInstanceGroups */ @Override public AddInstanceGroupsResult addInstanceGroups( AddInstanceGroupsRequest addInstanceGroupsRequest) { ExecutionContext executionContext = createExecutionContext(addInstanceGroupsRequest); AWSRequestMetrics awsRequestMetrics = executionContext .getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<AddInstanceGroupsRequest> request = null; Response<AddInstanceGroupsResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new AddInstanceGroupsRequestMarshaller() .marshall(super .beforeMarshalling(addInstanceGroupsRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } JsonResponseHandler<AddInstanceGroupsResult> responseHandler = SdkJsonProtocolFactory .createResponseHandler( new AddInstanceGroupsResultJsonUnmarshaller(), false); responseHandler.setIsPayloadJson(true); response = invoke(request, responseHandler, executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } } /** * <p> * AddJobFlowSteps adds new steps to a running job flow. A maximum of 256 * steps are allowed in each job flow. * </p> * <p> * If your job flow is long-running (such as a Hive data warehouse) or * complex, you may require more than 256 steps to process your data. You * can bypass the 256-step limitation in various ways, including using the * SSH shell to connect to the master node and submitting queries directly * to the software running on the master node, such as Hive and Hadoop. For * more information on how to do this, go to <a href= * "http://docs.aws.amazon.com/ElasticMapReduce/latest/DeveloperGuide/AddMoreThan256Steps.html" * >Add More than 256 Steps to a Job Flow</a> in the <i>Amazon Elastic * MapReduce Developer's Guide</i>. * </p> * <p> * A step specifies the location of a JAR file stored either on the master * node of the job flow or in Amazon S3. Each step is performed by the main * function of the main class of the JAR file. The main class can be * specified either in the manifest of the JAR or by using the MainFunction * parameter of the step. * </p> * <p> * Elastic MapReduce executes each step in the order listed. For a step to * be considered complete, the main function must exit with a zero exit code * and all Hadoop jobs started while the step was running must have * completed and run successfully. * </p> * <p> * You can only add steps to a job flow that is in one of the following * states: STARTING, BOOTSTRAPPING, RUNNING, or WAITING. * </p> * * @param addJobFlowStepsRequest * The input argument to the <a>AddJobFlowSteps</a> operation. * @return Result of the AddJobFlowSteps operation returned by the service. * @throws InternalServerErrorException * Indicates that an error occurred while processing the request and * that the request was not completed. * @sample AmazonElasticMapReduce.AddJobFlowSteps */ @Override public AddJobFlowStepsResult addJobFlowSteps( AddJobFlowStepsRequest addJobFlowStepsRequest) { ExecutionContext executionContext = createExecutionContext(addJobFlowStepsRequest); AWSRequestMetrics awsRequestMetrics = executionContext .getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<AddJobFlowStepsRequest> request = null; Response<AddJobFlowStepsResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new AddJobFlowStepsRequestMarshaller().marshall(super .beforeMarshalling(addJobFlowStepsRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } JsonResponseHandler<AddJobFlowStepsResult> responseHandler = SdkJsonProtocolFactory .createResponseHandler( new AddJobFlowStepsResultJsonUnmarshaller(), false); responseHandler.setIsPayloadJson(true); response = invoke(request, responseHandler, executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } } /** * <p> * Adds tags to an Amazon EMR resource. Tags make it easier to associate * clusters in various ways, such as grouping clusters to track your Amazon * EMR resource allocation costs. For more information, see <a href= * "http://docs.aws.amazon.com/ElasticMapReduce/latest/DeveloperGuide/emr-plan-tags.html" * >Tagging Amazon EMR Resources</a>. * </p> * * @param addTagsRequest * This input identifies a cluster and a list of tags to attach. * @return Result of the AddTags operation returned by the service. * @throws InternalServerException * This exception occurs when there is an internal failure in the * EMR service. * @throws InvalidRequestException * This exception occurs when there is something wrong with user * input. * @sample AmazonElasticMapReduce.AddTags */ @Override public AddTagsResult addTags(AddTagsRequest addTagsRequest) { ExecutionContext executionContext = createExecutionContext(addTagsRequest); AWSRequestMetrics awsRequestMetrics = executionContext .getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<AddTagsRequest> request = null; Response<AddTagsResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new AddTagsRequestMarshaller().marshall(super .beforeMarshalling(addTagsRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } JsonResponseHandler<AddTagsResult> responseHandler = SdkJsonProtocolFactory .createResponseHandler(new AddTagsResultJsonUnmarshaller(), false); responseHandler.setIsPayloadJson(true); response = invoke(request, responseHandler, executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } } /** * <p> * Provides cluster-level details including status, hardware and software * configuration, VPC settings, and so on. For information about the cluster * steps, see <a>ListSteps</a>. * </p> * * @param describeClusterRequest * This input determines which cluster to describe. * @return Result of the DescribeCluster operation returned by the service. * @throws InternalServerException * This exception occurs when there is an internal failure in the * EMR service. * @throws InvalidRequestException * This exception occurs when there is something wrong with user * input. * @sample AmazonElasticMapReduce.DescribeCluster */ @Override public DescribeClusterResult describeCluster( DescribeClusterRequest describeClusterRequest) { ExecutionContext executionContext = createExecutionContext(describeClusterRequest); AWSRequestMetrics awsRequestMetrics = executionContext .getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<DescribeClusterRequest> request = null; Response<DescribeClusterResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new DescribeClusterRequestMarshaller().marshall(super .beforeMarshalling(describeClusterRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } JsonResponseHandler<DescribeClusterResult> responseHandler = SdkJsonProtocolFactory .createResponseHandler( new DescribeClusterResultJsonUnmarshaller(), false); responseHandler.setIsPayloadJson(true); response = invoke(request, responseHandler, executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } } /** * <p> * This API is deprecated and will eventually be removed. We recommend you * use <a>ListClusters</a>, <a>DescribeCluster</a>, <a>ListSteps</a>, * <a>ListInstanceGroups</a> and <a>ListBootstrapActions</a> instead. * </p> * <p> * DescribeJobFlows returns a list of job flows that match all of the * supplied parameters. The parameters can include a list of job flow IDs, * job flow states, and restrictions on job flow creation date and time. * </p> * <p> * Regardless of supplied parameters, only job flows created within the last * two months are returned. * </p> * <p> * If no parameters are supplied, then job flows matching either of the * following criteria are returned: * </p> * <ul> * <li>Job flows created and completed in the last two weeks</li> * <li>Job flows created within the last two months that are in one of the * following states: <code>RUNNING</code>, <code>WAITING</code>, * <code>SHUTTING_DOWN</code>, <code>STARTING</code></li> * </ul> * <p> * Amazon Elastic MapReduce can return a maximum of 512 job flow * descriptions. * </p> * * @param describeJobFlowsRequest * The input for the <a>DescribeJobFlows</a> operation. * @return Result of the DescribeJobFlows operation returned by the service. * @throws InternalServerErrorException * Indicates that an error occurred while processing the request and * that the request was not completed. * @sample AmazonElasticMapReduce.DescribeJobFlows */ @Override @Deprecated public DescribeJobFlowsResult describeJobFlows( DescribeJobFlowsRequest describeJobFlowsRequest) { ExecutionContext executionContext = createExecutionContext(describeJobFlowsRequest); AWSRequestMetrics awsRequestMetrics = executionContext .getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<DescribeJobFlowsRequest> request = null; Response<DescribeJobFlowsResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new DescribeJobFlowsRequestMarshaller() .marshall(super .beforeMarshalling(describeJobFlowsRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } JsonResponseHandler<DescribeJobFlowsResult> responseHandler = SdkJsonProtocolFactory .createResponseHandler( new DescribeJobFlowsResultJsonUnmarshaller(), false); responseHandler.setIsPayloadJson(true); response = invoke(request, responseHandler, executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } } @Override @Deprecated public DescribeJobFlowsResult describeJobFlows() { return describeJobFlows(new DescribeJobFlowsRequest()); } /** * <p> * Provides more detail about the cluster step. * </p> * * @param describeStepRequest * This input determines which step to describe. * @return Result of the DescribeStep operation returned by the service. * @throws InternalServerException * This exception occurs when there is an internal failure in the * EMR service. * @throws InvalidRequestException * This exception occurs when there is something wrong with user * input. * @sample AmazonElasticMapReduce.DescribeStep */ @Override public DescribeStepResult describeStep( DescribeStepRequest describeStepRequest) { ExecutionContext executionContext = createExecutionContext(describeStepRequest); AWSRequestMetrics awsRequestMetrics = executionContext .getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<DescribeStepRequest> request = null; Response<DescribeStepResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new DescribeStepRequestMarshaller().marshall(super .beforeMarshalling(describeStepRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } JsonResponseHandler<DescribeStepResult> responseHandler = SdkJsonProtocolFactory .createResponseHandler( new DescribeStepResultJsonUnmarshaller(), false); responseHandler.setIsPayloadJson(true); response = invoke(request, responseHandler, executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } } /** * <p> * Provides information about the bootstrap actions associated with a * cluster. * </p> * * @param listBootstrapActionsRequest * This input determines which bootstrap actions to retrieve. * @return Result of the ListBootstrapActions operation returned by the * service. * @throws InternalServerException * This exception occurs when there is an internal failure in the * EMR service. * @throws InvalidRequestException * This exception occurs when there is something wrong with user * input. * @sample AmazonElasticMapReduce.ListBootstrapActions */ @Override public ListBootstrapActionsResult listBootstrapActions( ListBootstrapActionsRequest listBootstrapActionsRequest) { ExecutionContext executionContext = createExecutionContext(listBootstrapActionsRequest); AWSRequestMetrics awsRequestMetrics = executionContext .getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<ListBootstrapActionsRequest> request = null; Response<ListBootstrapActionsResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new ListBootstrapActionsRequestMarshaller() .marshall(super .beforeMarshalling(listBootstrapActionsRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } JsonResponseHandler<ListBootstrapActionsResult> responseHandler = SdkJsonProtocolFactory .createResponseHandler( new ListBootstrapActionsResultJsonUnmarshaller(), false); responseHandler.setIsPayloadJson(true); response = invoke(request, responseHandler, executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } } /** * <p> * Provides the status of all clusters visible to this AWS account. Allows * you to filter the list of clusters based on certain criteria; for * example, filtering by cluster creation date and time or by status. This * call returns a maximum of 50 clusters per call, but returns a marker to * track the paging of the cluster list across multiple ListClusters calls. * </p> * * @param listClustersRequest * This input determines how the ListClusters action filters the list * of clusters that it returns. * @return Result of the ListClusters operation returned by the service. * @throws InternalServerException * This exception occurs when there is an internal failure in the * EMR service. * @throws InvalidRequestException * This exception occurs when there is something wrong with user * input. * @sample AmazonElasticMapReduce.ListClusters */ @Override public ListClustersResult listClusters( ListClustersRequest listClustersRequest) { ExecutionContext executionContext = createExecutionContext(listClustersRequest); AWSRequestMetrics awsRequestMetrics = executionContext .getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<ListClustersRequest> request = null; Response<ListClustersResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new ListClustersRequestMarshaller().marshall(super .beforeMarshalling(listClustersRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } JsonResponseHandler<ListClustersResult> responseHandler = SdkJsonProtocolFactory .createResponseHandler( new ListClustersResultJsonUnmarshaller(), false); responseHandler.setIsPayloadJson(true); response = invoke(request, responseHandler, executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } } @Override public ListClustersResult listClusters() { return listClusters(new ListClustersRequest()); } /** * <p> * Provides all available details about the instance groups in a cluster. * </p> * * @param listInstanceGroupsRequest * This input determines which instance groups to retrieve. * @return Result of the ListInstanceGroups operation returned by the * service. * @throws InternalServerException * This exception occurs when there is an internal failure in the * EMR service. * @throws InvalidRequestException * This exception occurs when there is something wrong with user * input. * @sample AmazonElasticMapReduce.ListInstanceGroups */ @Override public ListInstanceGroupsResult listInstanceGroups( ListInstanceGroupsRequest listInstanceGroupsRequest) { ExecutionContext executionContext = createExecutionContext(listInstanceGroupsRequest); AWSRequestMetrics awsRequestMetrics = executionContext .getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<ListInstanceGroupsRequest> request = null; Response<ListInstanceGroupsResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new ListInstanceGroupsRequestMarshaller() .marshall(super .beforeMarshalling(listInstanceGroupsRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } JsonResponseHandler<ListInstanceGroupsResult> responseHandler = SdkJsonProtocolFactory .createResponseHandler( new ListInstanceGroupsResultJsonUnmarshaller(), false); responseHandler.setIsPayloadJson(true); response = invoke(request, responseHandler, executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } } /** * <p> * Provides information about the cluster instances that Amazon EMR * provisions on behalf of a user when it creates the cluster. For example, * this operation indicates when the EC2 instances reach the Ready state, * when instances become available to Amazon EMR to use for jobs, and the IP * addresses for cluster instances, etc. * </p> * * @param listInstancesRequest * This input determines which instances to list. * @return Result of the ListInstances operation returned by the service. * @throws InternalServerException * This exception occurs when there is an internal failure in the * EMR service. * @throws InvalidRequestException * This exception occurs when there is something wrong with user * input. * @sample AmazonElasticMapReduce.ListInstances */ @Override public ListInstancesResult listInstances( ListInstancesRequest listInstancesRequest) { ExecutionContext executionContext = createExecutionContext(listInstancesRequest); AWSRequestMetrics awsRequestMetrics = executionContext .getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<ListInstancesRequest> request = null; Response<ListInstancesResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new ListInstancesRequestMarshaller().marshall(super .beforeMarshalling(listInstancesRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } JsonResponseHandler<ListInstancesResult> responseHandler = SdkJsonProtocolFactory .createResponseHandler( new ListInstancesResultJsonUnmarshaller(), false); responseHandler.setIsPayloadJson(true); response = invoke(request, responseHandler, executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } } /** * <p> * Provides a list of steps for the cluster. * </p> * * @param listStepsRequest * This input determines which steps to list. * @return Result of the ListSteps operation returned by the service. * @throws InternalServerException * This exception occurs when there is an internal failure in the * EMR service. * @throws InvalidRequestException * This exception occurs when there is something wrong with user * input. * @sample AmazonElasticMapReduce.ListSteps */ @Override public ListStepsResult listSteps(ListStepsRequest listStepsRequest) { ExecutionContext executionContext = createExecutionContext(listStepsRequest); AWSRequestMetrics awsRequestMetrics = executionContext .getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<ListStepsRequest> request = null; Response<ListStepsResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new ListStepsRequestMarshaller().marshall(super .beforeMarshalling(listStepsRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } JsonResponseHandler<ListStepsResult> responseHandler = SdkJsonProtocolFactory .createResponseHandler( new ListStepsResultJsonUnmarshaller(), false); responseHandler.setIsPayloadJson(true); response = invoke(request, responseHandler, executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } } /** * <p> * ModifyInstanceGroups modifies the number of nodes and configuration * settings of an instance group. The input parameters include the new * target instance count for the group and the instance group ID. The call * will either succeed or fail atomically. * </p> * * @param modifyInstanceGroupsRequest * Change the size of some instance groups. * @throws InternalServerErrorException * Indicates that an error occurred while processing the request and * that the request was not completed. * @sample AmazonElasticMapReduce.ModifyInstanceGroups */ @Override public void modifyInstanceGroups( ModifyInstanceGroupsRequest modifyInstanceGroupsRequest) { ExecutionContext executionContext = createExecutionContext(modifyInstanceGroupsRequest); AWSRequestMetrics awsRequestMetrics = executionContext .getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<ModifyInstanceGroupsRequest> request = null; Response<Void> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new ModifyInstanceGroupsRequestMarshaller() .marshall(super .beforeMarshalling(modifyInstanceGroupsRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } JsonResponseHandler<Void> responseHandler = SdkJsonProtocolFactory .createResponseHandler(null, false); responseHandler.setIsPayloadJson(true); invoke(request, responseHandler, executionContext); } finally { endClientExecution(awsRequestMetrics, request, response); } } @Override public void modifyInstanceGroups() { modifyInstanceGroups(new ModifyInstanceGroupsRequest()); } /** * <p> * Removes tags from an Amazon EMR resource. Tags make it easier to * associate clusters in various ways, such as grouping clusters to track * your Amazon EMR resource allocation costs. For more information, see <a * href= * "http://docs.aws.amazon.com/ElasticMapReduce/latest/DeveloperGuide/emr-plan-tags.html" * >Tagging Amazon EMR Resources</a>. * </p> * <p> * The following example removes the stack tag with value Prod from a * cluster: * </p> * * @param removeTagsRequest * This input identifies a cluster and a list of tags to remove. * @return Result of the RemoveTags operation returned by the service. * @throws InternalServerException * This exception occurs when there is an internal failure in the * EMR service. * @throws InvalidRequestException * This exception occurs when there is something wrong with user * input. * @sample AmazonElasticMapReduce.RemoveTags */ @Override public RemoveTagsResult removeTags(RemoveTagsRequest removeTagsRequest) { ExecutionContext executionContext = createExecutionContext(removeTagsRequest); AWSRequestMetrics awsRequestMetrics = executionContext .getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<RemoveTagsRequest> request = null; Response<RemoveTagsResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new RemoveTagsRequestMarshaller().marshall(super .beforeMarshalling(removeTagsRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } JsonResponseHandler<RemoveTagsResult> responseHandler = SdkJsonProtocolFactory .createResponseHandler( new RemoveTagsResultJsonUnmarshaller(), false); responseHandler.setIsPayloadJson(true); response = invoke(request, responseHandler, executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } } /** * <p> * RunJobFlow creates and starts running a new job flow. The job flow will * run the steps specified. Once the job flow completes, the cluster is * stopped and the HDFS partition is lost. To prevent loss of data, * configure the last step of the job flow to store results in Amazon S3. If * the <a>JobFlowInstancesConfig</a> * <code>KeepJobFlowAliveWhenNoSteps</code> parameter is set to * <code>TRUE</code>, the job flow will transition to the WAITING state * rather than shutting down once the steps have completed. * </p> * <p> * For additional protection, you can set the <a>JobFlowInstancesConfig</a> * <code>TerminationProtected</code> parameter to <code>TRUE</code> to lock * the job flow and prevent it from being terminated by API call, user * intervention, or in the event of a job flow error. * </p> * <p> * A maximum of 256 steps are allowed in each job flow. * </p> * <p> * If your job flow is long-running (such as a Hive data warehouse) or * complex, you may require more than 256 steps to process your data. You * can bypass the 256-step limitation in various ways, including using the * SSH shell to connect to the master node and submitting queries directly * to the software running on the master node, such as Hive and Hadoop. For * more information on how to do this, go to <a href= * "http://docs.aws.amazon.com/ElasticMapReduce/latest/DeveloperGuide/AddMoreThan256Steps.html" * >Add More than 256 Steps to a Job Flow</a> in the <i>Amazon Elastic * MapReduce Developer's Guide</i>. * </p> * <p> * For long running job flows, we recommend that you periodically store your * results. * </p> * * @param runJobFlowRequest * Input to the <a>RunJobFlow</a> operation. * @return Result of the RunJobFlow operation returned by the service. * @throws InternalServerErrorException * Indicates that an error occurred while processing the request and * that the request was not completed. * @sample AmazonElasticMapReduce.RunJobFlow */ @Override public RunJobFlowResult runJobFlow(RunJobFlowRequest runJobFlowRequest) { ExecutionContext executionContext = createExecutionContext(runJobFlowRequest); AWSRequestMetrics awsRequestMetrics = executionContext .getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<RunJobFlowRequest> request = null; Response<RunJobFlowResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new RunJobFlowRequestMarshaller().marshall(super .beforeMarshalling(runJobFlowRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } JsonResponseHandler<RunJobFlowResult> responseHandler = SdkJsonProtocolFactory .createResponseHandler( new RunJobFlowResultJsonUnmarshaller(), false); responseHandler.setIsPayloadJson(true); response = invoke(request, responseHandler, executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } } /** * <p> * SetTerminationProtection locks a job flow so the Amazon EC2 instances in * the cluster cannot be terminated by user intervention, an API call, or in * the event of a job-flow error. The cluster still terminates upon * successful completion of the job flow. Calling SetTerminationProtection * on a job flow is analogous to calling the Amazon EC2 * DisableAPITermination API on all of the EC2 instances in a cluster. * </p> * <p> * SetTerminationProtection is used to prevent accidental termination of a * job flow and to ensure that in the event of an error, the instances will * persist so you can recover any data stored in their ephemeral instance * storage. * </p> * <p> * To terminate a job flow that has been locked by setting * SetTerminationProtection to <code>true</code>, you must first unlock the * job flow by a subsequent call to SetTerminationProtection in which you * set the value to <code>false</code>. * </p> * <p> * For more information, go to <a href= * "http://docs.aws.amazon.com/ElasticMapReduce/latest/DeveloperGuide/UsingEMR_TerminationProtection.html" * >Protecting a Job Flow from Termination</a> in the <i>Amazon Elastic * MapReduce Developer's Guide.</i> * </p> * * @param setTerminationProtectionRequest * The input argument to the <a>TerminationProtection</a> operation. * @throws InternalServerErrorException * Indicates that an error occurred while processing the request and * that the request was not completed. * @sample AmazonElasticMapReduce.SetTerminationProtection */ @Override public void setTerminationProtection( SetTerminationProtectionRequest setTerminationProtectionRequest) { ExecutionContext executionContext = createExecutionContext(setTerminationProtectionRequest); AWSRequestMetrics awsRequestMetrics = executionContext .getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<SetTerminationProtectionRequest> request = null; Response<Void> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new SetTerminationProtectionRequestMarshaller() .marshall(super .beforeMarshalling(setTerminationProtectionRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } JsonResponseHandler<Void> responseHandler = SdkJsonProtocolFactory .createResponseHandler(null, false); responseHandler.setIsPayloadJson(true); invoke(request, responseHandler, executionContext); } finally { endClientExecution(awsRequestMetrics, request, response); } } /** * <p> * Sets whether all AWS Identity and Access Management (IAM) users under * your account can access the specified job flows. This action works on * running job flows. You can also set the visibility of a job flow when you * launch it using the <code>VisibleToAllUsers</code> parameter of * <a>RunJobFlow</a>. The SetVisibleToAllUsers action can be called only by * an IAM user who created the job flow or the AWS account that owns the job * flow. * </p> * * @param setVisibleToAllUsersRequest * The input to the SetVisibleToAllUsers action. * @throws InternalServerErrorException * Indicates that an error occurred while processing the request and * that the request was not completed. * @sample AmazonElasticMapReduce.SetVisibleToAllUsers */ @Override public void setVisibleToAllUsers( SetVisibleToAllUsersRequest setVisibleToAllUsersRequest) { ExecutionContext executionContext = createExecutionContext(setVisibleToAllUsersRequest); AWSRequestMetrics awsRequestMetrics = executionContext .getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<SetVisibleToAllUsersRequest> request = null; Response<Void> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new SetVisibleToAllUsersRequestMarshaller() .marshall(super .beforeMarshalling(setVisibleToAllUsersRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } JsonResponseHandler<Void> responseHandler = SdkJsonProtocolFactory .createResponseHandler(null, false); responseHandler.setIsPayloadJson(true); invoke(request, responseHandler, executionContext); } finally { endClientExecution(awsRequestMetrics, request, response); } } /** * <p> * TerminateJobFlows shuts a list of job flows down. When a job flow is shut * down, any step not yet completed is canceled and the EC2 instances on * which the job flow is running are stopped. Any log files not already * saved are uploaded to Amazon S3 if a LogUri was specified when the job * flow was created. * </p> * <p> * The maximum number of JobFlows allowed is 10. The call to * TerminateJobFlows is asynchronous. Depending on the configuration of the * job flow, it may take up to 5-20 minutes for the job flow to completely * terminate and release allocated resources, such as Amazon EC2 instances. * </p> * * @param terminateJobFlowsRequest * Input to the <a>TerminateJobFlows</a> operation. * @throws InternalServerErrorException * Indicates that an error occurred while processing the request and * that the request was not completed. * @sample AmazonElasticMapReduce.TerminateJobFlows */ @Override public void terminateJobFlows( TerminateJobFlowsRequest terminateJobFlowsRequest) { ExecutionContext executionContext = createExecutionContext(terminateJobFlowsRequest); AWSRequestMetrics awsRequestMetrics = executionContext .getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<TerminateJobFlowsRequest> request = null; Response<Void> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new TerminateJobFlowsRequestMarshaller() .marshall(super .beforeMarshalling(terminateJobFlowsRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } JsonResponseHandler<Void> responseHandler = SdkJsonProtocolFactory .createResponseHandler(null, false); responseHandler.setIsPayloadJson(true); invoke(request, responseHandler, executionContext); } finally { endClientExecution(awsRequestMetrics, request, response); } } /** * Returns additional metadata for a previously executed successful, * request, typically used for debugging issues where a service isn't acting * as expected. This data isn't considered part of the result data returned * by an operation, so it's available through this separate, diagnostic * interface. * <p> * Response metadata is only cached for a limited period of time, so if you * need to access this extra diagnostic information for an executed request, * you should use this method to retrieve it as soon as possible after * executing the request. * * @param request * The originally executed request * * @return The response metadata for the specified request, or null if none * is available. */ public ResponseMetadata getCachedResponseMetadata( AmazonWebServiceRequest request) { return client.getResponseMetadataForRequest(request); } /** * Normal invoke with authentication. Credentials are required and may be * overriden at the request level. **/ private <X, Y extends AmazonWebServiceRequest> Response<X> invoke( Request<Y> request, HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler, ExecutionContext executionContext) { executionContext.setCredentialsProvider(CredentialUtils .getCredentialsProvider(request.getOriginalRequest(), awsCredentialsProvider)); return doInvoke(request, responseHandler, executionContext); } /** * Invoke with no authentication. Credentials are not required and any * credentials set on the client or request will be ignored for this * operation. **/ private <X, Y extends AmazonWebServiceRequest> Response<X> anonymousInvoke( Request<Y> request, HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler, ExecutionContext executionContext) { return doInvoke(request, responseHandler, executionContext); } /** * Invoke the request using the http client. Assumes credentials (or lack * thereof) have been configured in the ExecutionContext beforehand. **/ private <X, Y extends AmazonWebServiceRequest> Response<X> doInvoke( Request<Y> request, HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler, ExecutionContext executionContext) { request.setEndpoint(endpoint); request.setTimeOffset(timeOffset); JsonErrorResponseHandlerV2 errorResponseHandler = SdkJsonProtocolFactory .createErrorResponseHandler(jsonErrorUnmarshallers, false); return client.execute(request, responseHandler, errorResponseHandler, executionContext); } }
{ "content_hash": "354b4109bb87e00421b6c03995909886", "timestamp": "", "source": "github", "line_count": 1323, "max_line_length": 112, "avg_line_length": 42.40362811791383, "alnum_prop": 0.6577896613190731, "repo_name": "mhurne/aws-sdk-java", "id": "1007bac941ed76bd2c82c3ed0443c93d864df5c3", "size": "56687", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-emr/src/main/java/com/amazonaws/services/elasticmapreduce/AmazonElasticMapReduceClient.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "FreeMarker", "bytes": "123790" }, { "name": "Java", "bytes": "110875821" }, { "name": "Scilab", "bytes": "3561" } ], "symlink_target": "" }
$(function () { $.ajaxSetup({ cache: false }); var waypts = []; var location_selected=[]; var map_routing=[]; var place_ordering=[]; /* initialize the calendar -----------------------------------------------------------------*/ //Date for the calendar events (dummy data) var date = new Date(); var d = date.getDate(), m = date.getMonth(), y = date.getFullYear(); $('#calendar').fullCalendar({ lang: 'th', timezone: 'Asia/Bangkok', header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, buttonText: { today: 'วันนี้', month: 'เดือน', week: 'สัปดาห์', day: 'วัน' }, eventClick: function(calEvent, jsEvent, view) { // ** load trip detail on modal *** // var trip_detail_url="<?=base_url('staff/calendar_trip_details/"+calEvent.id+"')?>"; $('.modal-trip-detail .modal-content').load(trip_detail_url,function(){ $('.modal-trip-detail').modal('show'); }); } , events: { url: "<?=base_url('staff/get_calendar_events')?>", }, loading: function(bool) { $('#loading').toggle(bool); }, eventRender: function(event, element) { element.find('.fc-title').append("<br/>" + event.description); } }) $('.modal-place-detail').on('hidden.bs.modal', function (e) { // do something... $(this).removeData(); }) $('.modal-trip-detail').on('shown.bs.modal', function (e) { waypts = []; location_selected=[]; map_routing=[]; place_ordering=[]; var directionsService = new google.maps.DirectionsService(); var map; // console.log($('.splace-location-point').val()); var directionsService = new google.maps.DirectionsService(); var map; // initialize(); // loadWayPoint(); function initialize() { directionsDisplay = new google.maps.DirectionsRenderer({ suppressMarkers: true }); var myOptions = { zoom: 3, mapTypeId: google.maps.MapTypeId.ROADMAP, } map = new google.maps.Map(document.getElementById("map-waypoint"), myOptions); directionsDisplay.setMap(map); /* var trafficLayer = new google.maps.TrafficLayer(); trafficLayer.setMap(map);*/ calcRoute(); //console.log(map_routing); } function calcRoute() { start = new google.maps.LatLng(7.005286399999999,100.49978550000003); end = new google.maps.LatLng(7.005286399999999,100.49978550000003); // createMarker(start,1); // createMarker(end); var request = { origin: start, destination: end, waypoints: waypts, optimizeWaypoints: false, //travelMode: google.maps.DirectionsTravelMode.DRIVING travelMode: 'DRIVING' }; var totaldistance=0; var totalduration=0; directionsService.route(request, function (response, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(response); var route = response.routes[0]; // var summaryPanel = document.getElementById('directions-panel'); var start_location_name; var end_location_name; // console.log(route.legs); // console.log(route.waypoint_order) // route.waypoint_order=[1,0,2]; // console.log(route.waypoint_order) $('#directions-panel').empty(); $('#directions-panel').append('<ul class="timeline">'); //summaryPanel.innerHTML+='<ul class="timeline">'; for (var i = 0; i < route.legs.length; i++) { start_address=route.legs[i].start_address; if(i==0) { if(start_address==='Unnamed Road, ตำบล คอหงส์ อำเภอ หาดใหญ่ สงขลา 90110 ประเทศไทย') { start_location_name='คณะทรัพยากรธรรมชาติ'; start_place_id=0; } } else { if(location_selected[route.waypoint_order[i-1]].location_address==start_address) { // console.log("ok"); start_location_name=location_selected[route.waypoint_order[i-1]].place_name; start_place_id=location_selected[route.waypoint_order[i-1]].place_id; } } end_address=route.legs[i].end_address; if(i==0) { if(end_address==='Unnamed Road, ตำบล คอหงส์ อำเภอ หาดใหญ่ สงขลา 90110 ประเทศไทย') { end_location_name='คณะทรัพยากรธรรมชาติ'; end_place_id=0; } if(route.waypoint_order.length>0){ end_location_name=location_selected[route.waypoint_order[i]].place_name; end_place_id=location_selected[route.waypoint_order[i]].place_id; } } else { //console.log(start_address); if(end_address==='Unnamed Road, ตำบล คอหงส์ อำเภอ หาดใหญ่ สงขลา 90110 ประเทศไทย') { end_location_name='คณะทรัพยากรธรรมชาติ'; end_place_id=0; } else if(location_selected[route.waypoint_order[i-1]].location_address==start_address) { end_location_name=location_selected[route.waypoint_order[i]].place_name; end_place_id=location_selected[route.waypoint_order[i]].place_id; } } totaldistance = totaldistance + route.legs[i].distance.value; totalduration=totalduration+route.legs[i].duration.value; createMarker(route.legs[i].end_location,i+1,end_location_name); place_ordering.push({"place_id":end_place_id,"place_name":end_location_name}); // display segment var routeSegment = i + 1; // calculate segment distance segment_distance=route.legs[i].distance.value; segment_distance=(segment_distance/1000); segment_distance=segment_distance.toFixed(1) + " กม."; // calculate segment duration segment_duration=secondsToDhms(route.legs[i].duration.value); $('#directions-panel ul.timeline').append('<li class="time-circle"><b>Segment: ' + routeSegment +'</b><span><i class="fa fa-fw fa-angle-double-right"></i>เวลา '+segment_duration+'</span><span><i class="fa fa-fw fa-angle-double-right"></i>ระยะทาง '+segment_distance+'</span></li>'); $('#directions-panel ul.timeline').append('<li><span>จาก<i class="fa fa-fw fa-angle-double-right"></i>'+start_location_name+'</span></li>'); $('#directions-panel ul.timeline').append('<li><span>ถึง<i class="fa fa-fw fa-angle-double-right"></i>'+end_location_name+'</span></li>'); // keep map routing pathway map_routing.push({"segment":routeSegment, "start_location":start_location_name, "end_location":end_location_name, "duration":route.legs[i].duration.value, "distance":route.legs[i].distance.value, "start_place_id":start_place_id, "end_place_id":end_place_id }); } $('#directions-panel').append('</ul>'); // keep map totatal routing map_routing.push({"total_duration":totalduration,"total_distance":totaldistance}); // display total trip routing totaldistance=(totaldistance/1000); $('#directions-panel').append('<h4>รวมระยะทาง '+totaldistance.toFixed(1) + " กม."+' ระยะเวลา '+secondsToDhms(totalduration)+'</h4>') //console.log(place_ordering); // update trip routing } }); } function createMarker(latlng,label,title) { // console.log(latlng); numberMarkerImg = { url: '<?=base_url()?>/images/map-maker.png', size: new google.maps.Size(42, 42), scaledSize: new google.maps.Size(42, 42), labelOrigin: new google.maps.Point(20,15) }; var marker = new google.maps.Marker({ position: latlng, map: map, label: { text: label.toString()}, title:title, icon: numberMarkerImg }); } function secondsToDhms(seconds) { seconds = Number(seconds); var d = Math.floor(seconds / (3600*24)); var h = Math.floor(seconds % (3600*24) / 3600); var m = Math.floor(seconds % 3600 / 60); var s = Math.floor(seconds % 3600 % 60); var dDisplay = d > 0 ? d + (d == 1 ? " วัน " : " วัน ") : ""; var hDisplay = h > 0 ? h + (h == 1 ? " ชั่วโมง " : " ชั่วโมง ") : ""; var mDisplay = m > 0 ? m + (m == 1 ? " นาที " : " นาที ") : ""; var sDisplay = s > 0 ? s + (s == 1 ? " วินาที" : " วินาที") : ""; if(seconds!=0) return dDisplay + hDisplay + mDisplay + sDisplay; else return 0+' นาที'; } function loadWayPoint() { $('.splace-location-point').each(function (i) { //console.log($(this).val()); var str=$(this).val(); var stop_location=str.split(':'); stop = new google.maps.LatLng(stop_location[0],stop_location[1]); //stop=stop_location[0]+','+stop_location[1]; waypts.push({ location: stop, stopover: true }); //test1=new google.maps.Lat(stop_location[0]); location_selected.push({"place_id":stop_location[2], "place_name":stop_location[3], //"place_location":stop, "location_address":stop_location[4] }); }); } $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { var target = $(e.target).attr("href") // activated tab if(target=='#placemap') { waypts = []; location_selected=[]; map_routing=[]; place_ordering=[]; initialize(); loadWayPoint(); } }); }) // end event show modal $('.modal-place-detail').on('shown.bs.modal', function (e) { $('.modal-trip-detail').modal('hide'); // do something... $(function () { var center = place_location; console.log(center); $('#gm-map') .gmap3({ center: center, zoom: 6, mapTypeId : google.maps.MapTypeId.ROADMAP }) .marker(function (map) { return { position: map.getCenter(), icon: 'https://maps.google.com/mapfiles/marker_green.png' }; }) .circle({ center: center, radius : 100, fillColor : "#FFAF9F", strokeColor : "#FF512F" }) .fit(); }); }) $('.modal-place-detail').on('hidden.bs.modal', function (e) { $('.modal-trip-detail').modal('show'); }) $('body').on('hidden.bs.modal', function () { if($('.modal.in').length > 0) { $('body').addClass('modal-open'); } }); });
{ "content_hash": "76a69c10f9822c2bf62f4562129d27b2", "timestamp": "", "source": "github", "line_count": 349, "max_line_length": 321, "avg_line_length": 45.92263610315186, "alnum_prop": 0.37087414987209083, "repo_name": "vthawat/study_outside", "id": "a530d96358e3b9dd04b958341e9690828bc76d5e", "size": "16565", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/modules/staff/views/js/calendar.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "899744" }, { "name": "HTML", "bytes": "5633" }, { "name": "Hack", "bytes": "687" }, { "name": "JavaScript", "bytes": "3264011" }, { "name": "PHP", "bytes": "2042320" } ], "symlink_target": "" }
<!DOCTYPE HTML> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by otm (version 3.0) on Wed May 18 15:17:48 EDT 2016 --> <title>Address_BldgRoom</title> <meta name="date" content="2016-05-18"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Address_BldgRoom"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li><a href="library-summary.html#Common_0_0_0">Library</a></li> <li class="navBarCell1Rev">Object</li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev Object</li> <li>Next Object</li> </ul> <ul class="navList"> <li><a href="../index.html?Common_0_0_0/Address_BldgRoom.html" target="_top">Frames</a></li> <li><a href="Address_BldgRoom.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"></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 ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">http://www.opentravel.org/OTM/Common/v0</div> <h2 title="ValueWithAttributes Address_BldgRoom" class="title">ValueWithAttributes Address_BldgRoom</h2> </div> <ul class="inheritance"> <li> <ul class="inheritance"> <li>http://www.opentravel.org/OTM/Common/v0:String</li> <li> <ul class="inheritance"> <li>http://www.opentravel.org/OTM/Common/v0:Address_BldgRoom</li> </ul> </li> </ul> </li> </ul> <div class="contentContainer"> <div class="summary"> <ul class="blockList"> <li class="blockList"> <div class="example"> <div> <h4>Example XML<span class="toggleButton imgOpen" id="XMLOpen" title="open" data-target="#exampleXML" data-toggle="collapsed" data-imgTarget="#XMLClosed"></span><span class="imgClosed" id="XMLClosed" title="closed" data-target="#exampleXML" data-toggle="collapsed" data-imgTarget="#XMLOpen"></span></h4> </div> <div id="exampleXML" class="collapsed"> <pre>&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;Address_BldgRoom buldingInd="true" xmlns="http://www.opentravel.org/OTM/Common/v0"&gt;Bldg H&lt;/Address_BldgRoom&gt; </pre> </div> <div> <h4>Example JSON<span class="toggleButton imgOpen" id="JSONOpen" title="open" data-target="#exampleJSON" data-toggle="collapsed" data-imgTarget="#JSONClosed"></span><span class="imgClosed" id="JSONClosed" title="closed" data-target="#exampleJSON" data-toggle="collapsed" data-imgTarget="#JSONOpen"></span></h4> </div> <div id="exampleJSON" class="collapsed"> <pre>{ "Address_BldgRoom" : { "value" : "Bldg H", "buldingInd" : true } }</pre> </div> </div> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"> <h3>Indicator Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Indicator Summary table, listing indicators, and an explanation"> <caption><span>Indicators</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Name</th> <th class="colLast" scope="col">Description</th> </tr> <tr class="rowColor"> <td class="colFirst"><code><strong>buldingInd</strong></code></td> <td class="colLast"> <div class="block">When true, the information is a building name.</div> </td> </tr> </table> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li><a href="library-summary.html#Common_0_0_0">Library</a></li> <li class="navBarCell1Rev">Object</li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev Object</li> <li>Next Object</li> </ul> <ul class="navList"> <li><a href="../index.html?Common_0_0_0/Address_BldgRoom.html" target="_top">Frames</a></li> <li><a href="Address_BldgRoom.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"></ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script type="text/javascript">$(document).ready(function(){ $('[data-toggle="collapsed"]').click(function(){ var target = $(this).data('target'); $(target).toggleClass('collapsed'); var imgTarget = $(this).data('imgtarget'); var img = $(imgTarget); img.addClass('toggleButton'); $(this).removeClass('toggleButton'); }); });</script> </html>
{ "content_hash": "9478f8ca923ef7d0f475b699b915803e", "timestamp": "", "source": "github", "line_count": 176, "max_line_length": 310, "avg_line_length": 31.84659090909091, "alnum_prop": 0.6540588760035683, "repo_name": "OpenTravel-Forum-2016/otaforum-mock-content", "id": "a09203059e405f854fc0f6ab8d00cbd86a0187b6", "size": "5605", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "untitled folder/jljandrew_CompilerOutput/documentation/Common_0_0_0/Address_BldgRoom.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1143" } ], "symlink_target": "" }
package me.shkschneider.skeleton.ui.transforms; import android.view.View; // <https://github.com/ToxicBakery/ViewPagerTransforms> public class DepthPageTransformer extends ABaseTransformer { private static final float MIN_SCALE = 0.75F; @Override protected void onTransform(final View view, final float position) { if (position <= 0F) { view.setTranslationX(0F); view.setScaleX(1F); view.setScaleY(1F); } else if (position <= 1F) { final float scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (1 - Math.abs(position)); view.setAlpha(1 - position); view.setPivotY(0.5F * view.getHeight()); view.setTranslationX(view.getWidth() * -position); view.setScaleX(scaleFactor); view.setScaleY(scaleFactor); } } @Override protected boolean isPagingEnabled() { return true; } }
{ "content_hash": "6695432fa1c0152341598bcc16eae00a", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 84, "avg_line_length": 25.5625, "alnum_prop": 0.7053789731051344, "repo_name": "EnterPrayz/android_Skeleton", "id": "37032d701775feab58015969becd3f7de059a32e", "size": "818", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "library/src/main/java/me/shkschneider/skeleton/ui/transforms/DepthPageTransformer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "340508" }, { "name": "Makefile", "bytes": "1856" }, { "name": "Shell", "bytes": "1914" } ], "symlink_target": "" }
var net = require('net'); var path = require('path'); var extend = require('extend'); var EventEmitter = require('events').EventEmitter; var inherits = require('util').inherits; var BaseTerminal = require('./pty').Terminal; var pty = require('../build/Release/pty.node'); // Counter of number of "pipes" created so far. var pipeIncr = 0; /** * Agent. Internal class. * * Everytime a new pseudo terminal is created it is contained * within agent.exe. When this process is started there are two * available named pipes (control and data socket). */ function Agent(file, args, env, cwd, cols, rows, debug) { var self = this; // Increment the number of pipes created. pipeIncr++; // Unique identifier per pipe created. var timestamp = Date.now(); // The data pipe is the direct connection to the forked terminal. this.dataPipe = '\\\\.\\pipe\\winpty-data-' + pipeIncr + '' + timestamp; // Dummy socket for awaiting `ready` event. this.ptySocket = new net.Socket(); // Create terminal pipe IPC channel and forward // to a local unix socket. this.ptyDataPipe = net.createServer(function (socket) { // Default socket encoding. socket.setEncoding('utf8'); // Pause until `ready` event is emitted. socket.pause(); // Sanitize input variable. file = file; args = args.join(' '); cwd = path.resolve(cwd); // Start terminal session. pty.startProcess(self.pid, file, args, env, cwd); // Emit ready event. self.ptySocket.emit('ready_datapipe', socket); }).listen(this.dataPipe); // Open pty session. var term = pty.open(self.dataPipe, cols, rows, debug); // Terminal pid. this.pid = term.pid; // Not available on windows. this.fd = term.fd; // Generated incremental number that has no real purpose besides // using it as a terminal id. this.pty = term.pty; } /** * Terminal */ /* var pty = require('./'); var term = pty.fork('cmd.exe', [], { name: 'Windows Shell', cols: 80, rows: 30, cwd: process.env.HOME, env: process.env, debug: true }); term.on('data', function(data) { console.log(data); }); */ function Terminal(file, args, opt) { var self = this, env, cwd, name, cols, rows, term, agent, debug; // Backward compatibility. if (typeof args === 'string') { opt = { name: arguments[1], cols: arguments[2], rows: arguments[3], cwd: process.env.HOME }; args = []; } // for 'close' this._internalee = new EventEmitter; // Arguments. args = args || []; file = file || 'cmd.exe'; opt = opt || {}; env = extend({}, opt.env); cols = opt.cols || 80; rows = opt.rows || 30; cwd = opt.cwd || process.cwd(); name = opt.name || env.TERM || 'Windows Shell'; debug = opt.debug || false; env.TERM = name; // Initialize environment variables. env = environ(env); // If the terminal is ready this.isReady = false; // Functions that need to run after `ready` event is emitted. this.deferreds = []; // Create new termal. this.agent = new Agent(file, args, env, cwd, cols, rows, debug); // The dummy socket is used so that we can defer everything // until its available. this.socket = this.agent.ptySocket; // The terminal socket when its available this.dataPipe = null; // Not available until `ready` event emitted. this.pid = this.agent.pid; this.fd = this.agent.fd; this.pty = this.agent.pty; // The forked windows terminal is not available // until `ready` event is emitted. this.socket.on('ready_datapipe', function (socket) { // Set terminal socket self.dataPipe = socket; // These events needs to be forwarded. ['connect', 'data', 'end', 'timeout', 'drain'].forEach(function(event) { self.dataPipe.on(event, function(data) { // Wait until the first data event is fired // then we can run deferreds. if(!self.isReady && event == 'data') { // Terminal is now ready and we can // avoid having to defer method calls. self.isReady = true; // Execute all deferred methods self.deferreds.forEach(function(fn) { // NB! In order to ensure that `this` has all // its references updated any variable that // need to be available in `this` before // the deferred is run has to be declared // above this forEach statement. fn.run(); }); // Reset self.deferreds = []; } // Emit to dummy socket self.socket.emit(event, data); }); }); // Resume socket. self.dataPipe.resume(); // Shutdown if `error` event is emitted. self.dataPipe.on('error', function (err) { // Close terminal session. self._close(); // EIO, happens when someone closes our child // process: the only process in the terminal. // node < 0.6.14: errno 5 // node >= 0.6.14: read EIO if (err.code) { if (~err.code.indexOf('errno 5') || ~err.code.indexOf('EIO')) return; } // Throw anything else. if (self.listeners('error').length < 2) { throw err; } }); // Cleanup after the socket is closed. self.dataPipe.on('close', function () { Terminal.total--; self.emit('exit', null); self._close(); }); }); this.file = file; this.name = name; this.cols = cols; this.rows = rows; this.readable = true; this.writable = true; Terminal.total++; } Terminal.fork = Terminal.spawn = Terminal.createTerminal = function (file, args, opt) { return new Terminal(file, args, opt); }; // Inherit from pty.js inherits(Terminal, BaseTerminal); // Keep track of the total // number of terminals for // the process. Terminal.total = 0; /** * Events */ /** * openpty */ Terminal.open = function () { throw new Error("open() not supported on windows, use Fork() instead."); }; /** * Events */ Terminal.prototype.write = function(data) { defer(this, function() { this.dataPipe.write(data); }); }; /** * TTY */ Terminal.prototype.resize = function (cols, rows) { defer(this, function() { cols = cols || 80; rows = rows || 24; this.cols = cols; this.rows = rows; pty.resize(this.pid, cols, rows); }); }; Terminal.prototype.destroy = function () { defer(this, function() { this.kill(); }); }; Terminal.prototype.kill = function (sig) { defer(this, function() { if (sig !== undefined) { throw new Error("Signals not supported on windows."); } this._close(); pty.kill(this.pid); }); }; Terminal.prototype.__defineGetter__('process', function () { return this.name; }); /** * Helpers */ function defer(terminal, deferredFn) { // Ensure that this method is only used within Terminal class. if (!(terminal instanceof Terminal)) { throw new Error("Must be instanceof Terminal"); } // If the terminal is ready, execute. if (terminal.isReady) { deferredFn.apply(terminal, null); return; } // Queue until terminal is ready. terminal.deferreds.push({ run: function() { // Run deffered. deferredFn.apply(terminal, null); } }); } function environ(env) { var keys = Object.keys(env || {}) , l = keys.length , i = 0 , pairs = []; for (; i < l; i++) { pairs.push(keys[i] + '=' + env[keys[i]]); } return pairs; } /** * Expose */ module.exports = exports = Terminal; exports.Terminal = Terminal; exports.native = pty;
{ "content_hash": "be743ffbc6d49cd1dd80eccdc058030c", "timestamp": "", "source": "github", "line_count": 355, "max_line_length": 77, "avg_line_length": 21.270422535211267, "alnum_prop": 0.605747583101576, "repo_name": "iiegor/pty.js", "id": "5738e34c6a0e6733cf7f46084fbbe42baccb5073", "size": "7647", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/pty_win.js", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "23928" }, { "name": "JavaScript", "bytes": "20550" }, { "name": "Makefile", "bytes": "344" }, { "name": "Python", "bytes": "1508" } ], "symlink_target": "" }
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.dialogflow.v3.model; /** * Represents session information communicated to and from the webhook. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Dialogflow API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleCloudDialogflowCxV3beta1SessionInfo extends com.google.api.client.json.GenericJson { /** * Optional for WebhookRequest. Optional for WebhookResponse. All parameters collected from forms * and intents during the session. Parameters can be created, updated, or removed by the webhook. * To remove a parameter from the session, the webhook should explicitly set the parameter value * to null in WebhookResponse. The map is keyed by parameters' display names. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.Map<String, java.lang.Object> parameters; /** * Always present for WebhookRequest. Ignored for WebhookResponse. The unique identifier of the * session. This field can be used by the webhook to identify a session. Format: * `projects//locations//agents//sessions/` or * `projects//locations//agents//environments//sessions/` if environment is specified. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String session; /** * Optional for WebhookRequest. Optional for WebhookResponse. All parameters collected from forms * and intents during the session. Parameters can be created, updated, or removed by the webhook. * To remove a parameter from the session, the webhook should explicitly set the parameter value * to null in WebhookResponse. The map is keyed by parameters' display names. * @return value or {@code null} for none */ public java.util.Map<String, java.lang.Object> getParameters() { return parameters; } /** * Optional for WebhookRequest. Optional for WebhookResponse. All parameters collected from forms * and intents during the session. Parameters can be created, updated, or removed by the webhook. * To remove a parameter from the session, the webhook should explicitly set the parameter value * to null in WebhookResponse. The map is keyed by parameters' display names. * @param parameters parameters or {@code null} for none */ public GoogleCloudDialogflowCxV3beta1SessionInfo setParameters(java.util.Map<String, java.lang.Object> parameters) { this.parameters = parameters; return this; } /** * Always present for WebhookRequest. Ignored for WebhookResponse. The unique identifier of the * session. This field can be used by the webhook to identify a session. Format: * `projects//locations//agents//sessions/` or * `projects//locations//agents//environments//sessions/` if environment is specified. * @return value or {@code null} for none */ public java.lang.String getSession() { return session; } /** * Always present for WebhookRequest. Ignored for WebhookResponse. The unique identifier of the * session. This field can be used by the webhook to identify a session. Format: * `projects//locations//agents//sessions/` or * `projects//locations//agents//environments//sessions/` if environment is specified. * @param session session or {@code null} for none */ public GoogleCloudDialogflowCxV3beta1SessionInfo setSession(java.lang.String session) { this.session = session; return this; } @Override public GoogleCloudDialogflowCxV3beta1SessionInfo set(String fieldName, Object value) { return (GoogleCloudDialogflowCxV3beta1SessionInfo) super.set(fieldName, value); } @Override public GoogleCloudDialogflowCxV3beta1SessionInfo clone() { return (GoogleCloudDialogflowCxV3beta1SessionInfo) super.clone(); } }
{ "content_hash": "e73ea3de1eb4f4cbc6843ec7c1629e6b", "timestamp": "", "source": "github", "line_count": 108, "max_line_length": 182, "avg_line_length": 44.388888888888886, "alnum_prop": 0.7450980392156863, "repo_name": "googleapis/google-api-java-client-services", "id": "d8357221fcbcc86ed85c035cad30132bfc8bfc74", "size": "4794", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "clients/google-api-services-dialogflow/v3/1.31.0/com/google/api/services/dialogflow/v3/model/GoogleCloudDialogflowCxV3beta1SessionInfo.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
namespace net { class AuthCredentials; class BoundNetLog; struct HttpRequestInfo; class HttpResponseInfo; class IOBuffer; class X509Certificate; // Represents a single HTTP transaction (i.e., a single request/response pair). // HTTP redirects are not followed and authentication challenges are not // answered. Cookies are assumed to be managed by the caller. class NET_EXPORT_PRIVATE HttpTransaction { public: // Stops any pending IO and destroys the transaction object. virtual ~HttpTransaction() {} // Starts the HTTP transaction (i.e., sends the HTTP request). // // Returns OK if the transaction could be started synchronously, which means // that the request was served from the cache. ERR_IO_PENDING is returned to // indicate that the CompletionCallback will be notified once response info is // available or if an IO error occurs. Any other return value indicates that // the transaction could not be started. // // Regardless of the return value, the caller is expected to keep the // request_info object alive until Destroy is called on the transaction. // // NOTE: The transaction is not responsible for deleting the callback object. // // Profiling information for the request is saved to |net_log| if non-NULL. virtual int Start(const HttpRequestInfo* request_info, const CompletionCallback& callback, const BoundNetLog& net_log) = 0; // Restarts the HTTP transaction, ignoring the last error. This call can // only be made after a call to Start (or RestartIgnoringLastError) failed. // Once Read has been called, this method cannot be called. This method is // used, for example, to continue past various SSL related errors. // // Not all errors can be ignored using this method. See error code // descriptions for details about errors that can be ignored. // // NOTE: The transaction is not responsible for deleting the callback object. // virtual int RestartIgnoringLastError(const CompletionCallback& callback) = 0; // Restarts the HTTP transaction with a client certificate. virtual int RestartWithCertificate(X509Certificate* client_cert, const CompletionCallback& callback) = 0; // Restarts the HTTP transaction with authentication credentials. virtual int RestartWithAuth(const AuthCredentials& credentials, const CompletionCallback& callback) = 0; // Returns true if auth is ready to be continued. Callers should check // this value anytime Start() completes: if it is true, the transaction // can be resumed with RestartWithAuth(L"", L"", callback) to resume // the automatic auth exchange. This notification gives the caller a // chance to process the response headers from all of the intermediate // restarts needed for authentication. virtual bool IsReadyToRestartForAuth() = 0; // Once response info is available for the transaction, response data may be // read by calling this method. // // Response data is copied into the given buffer and the number of bytes // copied is returned. ERR_IO_PENDING is returned if response data is not // yet available. The CompletionCallback is notified when the data copy // completes, and it is passed the number of bytes that were successfully // copied. Or, if a read error occurs, the CompletionCallback is notified of // the error. Any other negative return value indicates that the transaction // could not be read. // // NOTE: The transaction is not responsible for deleting the callback object. // If the operation is not completed immediately, the transaction must acquire // a reference to the provided buffer. // virtual int Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback) = 0; // Stops further caching of this request by the HTTP cache, if there is any. virtual void StopCaching() = 0; // Called to tell the transaction that we have successfully reached the end // of the stream. This is equivalent to performing an extra Read() at the end // that should return 0 bytes. This method should not be called if the // transaction is busy processing a previous operation (like a pending Read). virtual void DoneReading() = 0; // Returns the response info for this transaction or NULL if the response // info is not available. virtual const HttpResponseInfo* GetResponseInfo() const = 0; // Returns the load state for this transaction. virtual LoadState GetLoadState() const = 0; // Returns the upload progress in bytes. If there is no upload data, // zero will be returned. This does not include the request headers. virtual UploadProgress GetUploadProgress() const = 0; }; } // namespace net #endif // NET_HTTP_HTTP_TRANSACTION_H_
{ "content_hash": "d0d7245dc1236f673d7c407c68508704", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 80, "avg_line_length": 45.91428571428571, "alnum_prop": 0.7295166977805435, "repo_name": "junmin-zhu/chromium-rivertrail", "id": "bae9fdc74954077c63f6d7fe05f99962533ecc5f", "size": "5214", "binary": false, "copies": "5", "ref": "refs/heads/v8-binding", "path": "net/http/http_transaction.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "853" }, { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "1172794" }, { "name": "Awk", "bytes": "9519" }, { "name": "C", "bytes": "75806807" }, { "name": "C#", "bytes": "1132" }, { "name": "C++", "bytes": "145161929" }, { "name": "DOT", "bytes": "1559" }, { "name": "F#", "bytes": "381" }, { "name": "Java", "bytes": "1546515" }, { "name": "JavaScript", "bytes": "18675242" }, { "name": "Logos", "bytes": "4517" }, { "name": "Matlab", "bytes": "5234" }, { "name": "Objective-C", "bytes": "6981387" }, { "name": "PHP", "bytes": "97817" }, { "name": "Perl", "bytes": "926245" }, { "name": "Python", "bytes": "8088373" }, { "name": "R", "bytes": "262" }, { "name": "Ragel in Ruby Host", "bytes": "3239" }, { "name": "Shell", "bytes": "1513486" }, { "name": "Tcl", "bytes": "277077" }, { "name": "XML", "bytes": "13493" } ], "symlink_target": "" }
package com.microsoft.bingads.v12.api.test.entities.adgroup.read; import java.util.Arrays; import java.util.Collection; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import com.microsoft.bingads.internal.functionalinterfaces.Function; import com.microsoft.bingads.v12.api.test.entities.adgroup.BulkAdGroupTest; import com.microsoft.bingads.v12.bulk.entities.BulkAdGroup; import com.microsoft.bingads.v12.campaignmanagement.CoOpSetting; @RunWith(Parameterized.class) public class BulkAdGroupReadFromRowValuesCoOpMaximumBidTest extends BulkAdGroupTest { @Parameter public String datum; @Parameter(value = 1) public Double expectedResult; @Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ {"123.4", 123.4}, }); } @Test public void testRead() { this.<Double>testReadProperty("Maximum Bid", this.datum, this.expectedResult, new Function<BulkAdGroup, Double>() { @Override public Double apply(BulkAdGroup c) { CoOpSetting setting = (CoOpSetting) c.getSetting(CoOpSetting.class); return setting.getBidMaxValue(); } }); } }
{ "content_hash": "87807c913dfdeb9a134ffe544dfd7d3f", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 123, "avg_line_length": 31.86046511627907, "alnum_prop": 0.7153284671532847, "repo_name": "bing-ads-sdk/BingAds-Java-SDK", "id": "d78279ad2412765133cf132c7479cd5cb56a0b65", "size": "1370", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/com/microsoft/bingads/v12/api/test/entities/adgroup/read/BulkAdGroupReadFromRowValuesCoOpMaximumBidTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2059" }, { "name": "Java", "bytes": "9842387" } ], "symlink_target": "" }
Parallel Learning Example ========================= Here is an example for LightGBM to perform parallel learning for 2 machines. 1. Edit mlist.txt, write the ip of these 2 machines that you want to run application on. ``` machine1_ip 12400 machine2_ip 12400 ``` 2. Copy this folder and executable file to these 2 machines that you want to run application on. 3. Run command in this folder on both 2 machines: For Windows: ```lightgbm.exe config=train.conf``` For Linux: ```./lightgbm config=train.conf``` This parallel learning example is based on socket. LightGBM also support parallel learning based on mpi. For more details about the usage of parallel learning, please refer to [this](https://github.com/Microsoft/LightGBM/wiki/Parallel-Learning-Guide).
{ "content_hash": "d278cf225619b58a58400780dd602521", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 146, "avg_line_length": 35.40909090909091, "alnum_prop": 0.7329910141206675, "repo_name": "olofer/LightGBM", "id": "87b50e7886619f84e39c93401919de0bd431c5c9", "size": "779", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/parallel_learning/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "112901" }, { "name": "C++", "bytes": "896110" }, { "name": "CMake", "bytes": "4661" }, { "name": "Python", "bytes": "226843" }, { "name": "R", "bytes": "205716" }, { "name": "Shell", "bytes": "6143" } ], "symlink_target": "" }
<?php namespace Cmf\System; /** * @author Vital Leshchyk <vitalleshchyk@gmail.com> */ class Confirmation { /** @var string */ protected $title; /** @var string */ protected $message; /** @var array */ public $urlNo = []; public function __construct($title, $message = '', array $urlNo = []) { $this->title = $title; $this->message = $message; $this->urlNo = $urlNo; } /** * @return string */ public function getUrlYes() { $urlParams = Application::getRequest()->getVars(); $urlYes = array_merge($urlParams, ['start' => 1]); return Application::getUrlBuilder()->build($urlYes); } /** * @return string */ public function getUrlNo() { return Application::getUrlBuilder()->build($this->urlNo); } /** * @return string */ public function getTitle() { return $this->title; } /** * @return string */ public function getMessage() { return $this->message; } }
{ "content_hash": "8742b45b39379f7d0df839e2f5a2b1d0", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 73, "avg_line_length": 17.62295081967213, "alnum_prop": 0.5209302325581395, "repo_name": "itcreator/custom-cmf", "id": "1868d2edb36f9dcd9126dec66400316e603ef03d", "size": "1363", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Module/System/src/Cmf/System/Confirmation.php", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "992" }, { "name": "CSS", "bytes": "1122" }, { "name": "PHP", "bytes": "515002" } ], "symlink_target": "" }
const std::vector<Geodetic2D*>* GEO2DPolygonGeometry::getCoordinates() const { return _polygonData->getCoordinates(); } const std::vector<std::vector<Geodetic2D*>*>* GEO2DPolygonGeometry::getHolesCoordinatesArray() const { return _polygonData->getHolesCoordinatesArray(); } GEO2DPolygonGeometry::~GEO2DPolygonGeometry() { delete _polygonData; // const int coordinatesCount = _coordinates->size(); // for (int i = 0; i < coordinatesCount; i++) { // Geodetic2D* coordinate = _coordinates->at(i); // delete coordinate; // } // delete _coordinates; // // // if (_holesCoordinatesArray != NULL) { // const int holesCoordinatesArraySize = _holesCoordinatesArray->size(); // for (int j = 0; j < holesCoordinatesArraySize; j++) { // const std::vector<Geodetic2D*>* holeCoordinates = _holesCoordinatesArray->at(j); // // const int holeCoordinatesCount = holeCoordinates->size(); // for (int i =0; i < holeCoordinatesCount; i++) { // const Geodetic2D* holeCoordinate = holeCoordinates->at(i); // // delete holeCoordinate; // } // // delete holeCoordinates; // } // delete _holesCoordinatesArray; // } #ifdef JAVA_CODE super.dispose(); #endif } std::vector<GEOSymbol*>* GEO2DPolygonGeometry::createSymbols(const GEOSymbolizer* symbolizer) const { return symbolizer->createSymbols(this); }
{ "content_hash": "def73179000c02e30b5145b1d05f3929", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 102, "avg_line_length": 29.565217391304348, "alnum_prop": 0.6823529411764706, "repo_name": "milafrerichs/g3m_pod", "id": "4e5f922ab73ec42454837c3f179c85d696e284b2", "size": "1559", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Classes/ios/Commons/GEO/GEO2DPolygonGeometry.cpp", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "12272" }, { "name": "C++", "bytes": "1888496" }, { "name": "Objective-C", "bytes": "173890" }, { "name": "Ruby", "bytes": "19926" } ], "symlink_target": "" }
RSpec.configure do |config| config.filter_run focus: true unless Nenv.ci? config.run_all_when_everything_filtered = true config.disable_monkey_patching! config.profile_examples = 3 config.filter_gems_from_backtrace(*Specs::BACKTRACE_OMITTED) config.verbose_retry = true config.default_retry_count = Specs::ALLOW_RETRIES config.display_try_failure_messages = true config.default_sleep_interval = 1 config.exceptions_to_retry = [Timeout::Error, Celluloid::ThreadLeak] config.mock_with :rspec do |mocks| mocks.verify_doubled_constant_names = true mocks.verify_partial_doubles = true end config.before(:suite) do Specs.stub_out_class_method(Celluloid::Internals::Logger, :crash) do |*args| _name, ex = *args fail "Unstubbed Logger.crash() was called:\n crash(\n #{args.map(&:inspect).join(",\n ")})"\ "\nException backtrace: \n (#{ex.class}) #{ex.backtrace * "\n (#{ex.class}) "}" end end config.before(:each) do |example| @fake_logger = Specs::FakeLogger.new(Celluloid.logger, example.description) stub_const("Celluloid::Internals::Logger", @fake_logger) end config.around do |ex| # Needed because some specs mock/stub/expect on the logger Celluloid.logger = Specs.logger Celluloid.actor_system = nil Specs.reset_class_variables(ex.description) do Timeout.timeout(Specs::MAX_EXECUTION) { ex.run } end if @fake_logger.crashes? crashes = @fake_logger.crashes.map do |args, call_stack| msg, ex = *args "\n** Crash: #{msg.inspect}(#{ex.inspect})\n Backtrace:\n (crash) #{call_stack * "\n (crash) "}"\ "\n Exception Backtrace (#{ex.inspect}):\n (ex) #{ex.backtrace * "\n (ex) "}" end.join("\n") fail "Actor crashes occured (please stub/mock if these are expected): #{crashes}" end @fake_logger = nil Specs.assert_no_loose_threads!("after example: #{ex.description}") if Specs::CHECK_LOOSE_THREADS end config.around :each, library: :IO do |ex| Celluloid.init FileUtils.rm("/tmp/cell_sock") if File.exist?("/tmp/cell_sock") ex.run Celluloid.shutdown end config.around :each, library: :ZMQ do |ex| Celluloid::ZMQ.init(1) unless ex.metadata[:no_init] Celluloid.boot ex.run Celluloid.shutdown Celluloid::ZMQ.terminate end config.around :each, actor_system: :global do |ex| Celluloid.boot ex.run Celluloid.shutdown end config.around :each, actor_system: :within do |ex| Celluloid::Actor::System.new.within do ex.run end end end
{ "content_hash": "e898b5ec9cbecbcd1c624094e05bfcdf", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 112, "avg_line_length": 33.63636363636363, "alnum_prop": 0.6625482625482626, "repo_name": "kenichi/celluloid", "id": "d161dc09f1058d1a1f261871d05b20fe25c82869", "size": "2590", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spec/support/configure_rspec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "158470" } ], "symlink_target": "" }
package com.amazonaws.services.importexport.model.transform; import org.w3c.dom.Node; import javax.annotation.Generated; import com.amazonaws.AmazonServiceException; import com.amazonaws.transform.StandardErrorUnmarshaller; import com.amazonaws.services.importexport.model.InvalidManifestFieldException; @Generated("com.amazonaws:aws-java-sdk-code-generator") public class InvalidManifestFieldExceptionUnmarshaller extends StandardErrorUnmarshaller { public InvalidManifestFieldExceptionUnmarshaller() { super(InvalidManifestFieldException.class); } @Override public AmazonServiceException unmarshall(Node node) throws Exception { // Bail out if this isn't the right error code that this // marshaller understands String errorCode = parseErrorCode(node); if (errorCode == null || !errorCode.equals("InvalidManifestFieldException")) return null; InvalidManifestFieldException e = (InvalidManifestFieldException) super.unmarshall(node); return e; } }
{ "content_hash": "4503cdb86c984bb48081b7812faf54f3", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 97, "avg_line_length": 32.71875, "alnum_prop": 0.7631327602674307, "repo_name": "aws/aws-sdk-java", "id": "cff50c0a6ef714fcd85c2a3572aaa73925bc706b", "size": "1627", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-importexport/src/main/java/com/amazonaws/services/importexport/model/transform/InvalidManifestFieldExceptionUnmarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.apache.jena.commonsrdf.impl; import java.util.Objects; import java.util.Optional; import org.apache.commons.rdf.api.IRI; import org.apache.commons.rdf.api.Literal; import org.apache.jena.graph.Node; public class JCR_Literal extends JCR_Term implements Literal { /*package*/ JCR_Literal(Node node) { super(node); } @Override public String getLexicalForm() { return getNode().getLiteralLexicalForm(); } @Override public IRI getDatatype() { return JCR_Factory.createIRI(getNode().getLiteralDatatype().getURI()); } @Override public Optional<String> getLanguageTag() { String x = getNode().getLiteralLanguage(); if ( x == null || x.isEmpty() ) return Optional.empty(); return Optional.of(x); } @Override public int hashCode() { return Objects.hash(getLexicalForm(), getDatatype(), getLanguageTag()); } private static boolean equalsIgnoreCase(Optional<String> s1, Optional<String> s2) { if ( Objects.equals(s1, s2) ) return true; if ( s1.isEmpty() || s2.isEmpty() ) return false; return s1.get().equalsIgnoreCase(s2.get()); } @Override public boolean equals(Object other) { if ( other == this ) return true; if ( other == null ) return false; if ( ! ( other instanceof Literal ) ) return false; Literal literal = (Literal)other; return getLexicalForm().equals(literal.getLexicalForm()) && equalsIgnoreCase(getLanguageTag(), literal.getLanguageTag()) && getDatatype().equals(literal.getDatatype()); } }
{ "content_hash": "c64901dba683b8d48edbb2e6294189ae", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 87, "avg_line_length": 28.1, "alnum_prop": 0.6227758007117438, "repo_name": "afs/commonsrdf-jena", "id": "91d70b4b016b54ed3201ae02271bbcbd57f571ec", "size": "2492", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/apache/jena/commonsrdf/impl/JCR_Literal.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "59432" } ], "symlink_target": "" }
<? $_meta['name'] = 'GithubTags'; $_meta['callable'] = true; if( !$shutup ) : $_config->defaults( array( 'USERNAME' => 'donatj', 'REPOSITORY' => 'CorpusPHP', 'DATEFORMAT'=> DISPLAY_DATE_FORMAT ) ); $USERNAME = firstNotEmpty( $data['username'], $_config->USERNAME ); $REPOSITORY = firstNotEmpty( $data['repository'], $_config->REPOSITORY ); $opts = array( 'http' => array('header' => 'User-Agent: Github Sucks at APIs') ); $context = stream_context_create($opts); $feedUrl = "https://api.github.com/repos/{$USERNAME}/{$REPOSITORY}/git/refs/tags"; $cacheKey = md5($feedUrl); if( !$_cache->isExpired( $cacheKey ) ) { $feed = $_cache->$cacheKey; }else{ if( $feed = file_get_contents( $feedUrl, false, $context ) ) { $_cache->set( $cacheKey, $feed, 1, 'DAY', false ); }else{ $feed = $_cache->$cacheKey; $_ms->add('Error Communicating with Github API, Error ' . __LINE__, true); } } $github = json_decode($feed, true); $info = array('data' => array()); foreach( $github as $data ) { $feedUrl = $data['object']['url']; $tag = str_replace('refs/tags/', '', $data['ref']); $cacheKey = md5($feedUrl); if( !$_cache->isExpired( $cacheKey ) ) { $feed = $_cache->$cacheKey; }else{ if( $feed = @file_get_contents( $feedUrl ) ) { $_cache->set( $cacheKey, $feed, 1, 'MONTH', true ); }else{ $feed = $_cache->$cacheKey; $_ms->add('Error Communicating with Github API, Error ' . __LINE__ . ':' . $data['ref'] . ' - ' . $hash, true); } } $commit = json_decode($feed, true); $download_link = 'http://github.com/'. $USERNAME .'/' . $REPOSITORY . '/zipball/'. $tag; if($commit) { array_unshift($info['data'], array( $tag . '<br /><small><a href="' . $download_link .'" target="_blank">Download</a></small>', $commit['tagger']['date'] ? co::module('blog/date', strtotime($commit['tagger']['date']) ) : '', '<small>' . nl2br($commit['message']) . '</small>', )); } } $info['header'] = array('Build', 'Date', 'Message'); $info['params'] = 'class="datatable" style="width: 100%" cellpadding="0" cellspacing="0"'; echo co::module('table', $info); endif;
{ "content_hash": "b16eb341cbfef87cf4b6da066398ddc7", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 114, "avg_line_length": 28.486486486486488, "alnum_prop": 0.5868121442125237, "repo_name": "donatj/CorpusPHP", "id": "dc9ffca1e6509ac839433c412071ca5a9ba0911e", "size": "2108", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/corpus/modules/Github/tags.php", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "728" }, { "name": "CSS", "bytes": "9179" }, { "name": "Hack", "bytes": "766" }, { "name": "JavaScript", "bytes": "8160" }, { "name": "PHP", "bytes": "255587" }, { "name": "Ruby", "bytes": "912" }, { "name": "Shell", "bytes": "1018" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Nova Acta R. Soc. Scient. upsal. , Ser. 3 1: 91 (1851) #### Original name Polystictus comatus Fr. ### Remarks null
{ "content_hash": "61c504f53566bd261398b6cdd4990a91", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 54, "avg_line_length": 13.692307692307692, "alnum_prop": 0.6741573033707865, "repo_name": "mdoering/backbone", "id": "50f0cc77014db405761ca1efd5fbb6f3df353668", "size": "225", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Basidiomycota/Agaricomycetes/Hymenochaetales/Hymenochaetaceae/Coltricia/Polystictus comatus/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
namespace ApiProxy.Areas.HelpPage.ModelDescriptions { public class DictionaryModelDescription : KeyValuePairModelDescription { } }
{ "content_hash": "682de6f9186df1596933111d36b12533", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 74, "avg_line_length": 23.666666666666668, "alnum_prop": 0.7887323943661971, "repo_name": "ryanande/ApiProxy", "id": "314cfafe6132dec7d2c744a7c881368800a41e65", "size": "142", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ApiProxy/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "117" }, { "name": "C#", "bytes": "225570" }, { "name": "CSS", "bytes": "8656" }, { "name": "HTML", "bytes": "13750" }, { "name": "JavaScript", "bytes": "1651724" }, { "name": "Shell", "bytes": "49" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Sydowia 59(1): 78 (2007) #### Original name Conidiobolus caecilius S. Keller ### Remarks null
{ "content_hash": "f7d189f85bdc36d0866d28f4afb74eda", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 32, "avg_line_length": 12.076923076923077, "alnum_prop": 0.7006369426751592, "repo_name": "mdoering/backbone", "id": "fc5c02b4433ac9bfa1800f4941c3169e30a35b1f", "size": "213", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Zygomycota/Entomophthorales/Ancylistaceae/Conidiobolus/Conidiobolus caecilius/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using namespace Geometry; using namespace Meshing; //Produces a list of contacts as though the robot were standing on a plane. //tol is the tolerance with which minimum-distance points are generated. //All contacts are given zero friction and in the local frame of the robot. void GetFlatContacts(RobotWithGeometry& robot,Real tol,ContactFormation& contacts) { vector<AABB3D> bbs(robot.geometry.size()); vector<pair<Real,int> > order; robot.UpdateGeometry(); for(size_t i=0;i<robot.geometry.size();i++) if(!robot.geometry[i].Empty()) { AABB3D aabb = robot.geometry[i].GetAABB(); bbs[i] = aabb; order.push_back(pair<Real,int>(aabb.bmin.z,(int)i)); } sort(order.begin(),order.end()); Real best = Inf; for(size_t i=0;i<order.size();i++) { if(order[i].first > best) break; //done int k=order[i].second; switch(robot.geometry[k].type) { case AnyGeometry3D::Primitive: FatalError("Can't get flat contacts for primitives"); break; case AnyGeometry3D::ImplicitSurface: FatalError("Can't get flat contacts for implicit surfaces"); break; case AnyGeometry3D::Group: FatalError("Can't get flat contacts for geometry group"); break; case AnyGeometry3D::TriangleMesh: { const TriMesh* m=AnyCast<TriMesh>(&robot.geometry[k].data); for(size_t v=0;v<m->verts.size();v++) { Vector3 pw = robot.links[k].T_World*m->verts[v]; if(pw.z < best) best = pw.z; assert(pw.z >= order[i].first); } } break; case AnyGeometry3D::PointCloud: { const PointCloud3D* pc=AnyCast<PointCloud3D>(&robot.geometry[k].data); for(size_t v=0;v<pc->points.size();v++) { Vector3 pw = robot.links[k].T_World*pc->points[v]; if(pw.z < best) best = pw.z; assert(pw.z >= order[i].first); } } break; } } //got the plane height, now output the vertices ContactPoint cp; cp.kFriction = 0.0; contacts.links.resize(0); contacts.contacts.resize(0); for(size_t i=0;i<order.size();i++) { if(order[i].first > best+tol) break; //done int k=order[i].second; contacts.links.resize(contacts.links.size()+1); contacts.links.back()=k; contacts.contacts.resize(contacts.contacts.size()+1); vector<Vector3> pts; switch(robot.geometry[k].type) { case AnyGeometry3D::TriangleMesh: { const TriMesh* m=AnyCast<TriMesh>(&robot.geometry[k].data); for(size_t v=0;v<m->verts.size();v++) { Vector3 pw = robot.links[k].T_World*m->verts[v]; if(pw.z < best+tol) { pts.push_back(pw); } } } break; case AnyGeometry3D::PointCloud: { const PointCloud3D* pc=AnyCast<PointCloud3D>(&robot.geometry[k].data); for(size_t v=0;v<pc->points.size();v++) { Vector3 pw = robot.links[k].T_World*pc->points[v]; if(pw.z < best+tol) { pts.push_back(pw); } } } break; default: break; } //get the convex hull of those points vector<Vector2> pts2(pts.size()); vector<Vector2> hull(pts.size()); vector<int> hindex(pts.size()); for(size_t v=0;v<pts.size();v++) pts2[v].set(pts[v].x,pts[v].y); int num = ConvexHull2D_Chain_Unsorted( &pts2[0], pts2.size(), &hull[0], &hindex[0]); contacts.contacts.back().resize(num); for(int v=0;v<num;v++) { //local estimate robot.links[k].T_World.mulInverse(pts[hindex[v]],cp.x); robot.links[k].T_World.R.mulTranspose(Vector3(0,0,1),cp.n); contacts.contacts.back()[v] = cp; } if(contacts.contacts.back().empty()) { //bound was below threshold, but no contacts below threshold contacts.links.resize(contacts.links.size()-1); contacts.contacts.resize(contacts.contacts.size()-1); } } } void GetFlatContacts(RobotWithGeometry& robot,int link,Real tol,vector<ContactPoint>& contacts) { Real best = Inf; const vector<Vector3>* points = NULL; switch(robot.geometry[link].type) { case AnyGeometry3D::Primitive: FatalError("Can't get flat contacts for primitives"); break; case AnyGeometry3D::ImplicitSurface: FatalError("Can't get flat contacts for implicit surfaces"); break; case AnyGeometry3D::Group: FatalError("Can't get flat contacts for geometry group"); break; case AnyGeometry3D::TriangleMesh: points = &AnyCast<TriMesh>(&robot.geometry[link].data)->verts; break; case AnyGeometry3D::PointCloud: points = &AnyCast<PointCloud3D>(&robot.geometry[link].data)->points; break; } for(size_t v=0;v<points->size();v++) { Vector3 pw = robot.links[link].T_World*(*points)[v]; if(pw.z < best) best = pw.z; } //got the plane height, now output the vertices ContactPoint cp; cp.kFriction = 0.0; contacts.resize(0); vector<Vector3> pts; for(size_t v=0;v<points->size();v++) { Vector3 pw = robot.links[link].T_World*(*points)[v]; if(pw.z < best+tol) { pts.push_back(pw); } } //get the convex hull of those points vector<Vector2> pts2(pts.size()); vector<Vector2> hull(pts.size()); vector<int> hindex(pts.size()); for(size_t v=0;v<pts.size();v++) pts2[v].set(pts[v].x,pts[v].y); int num = ConvexHull2D_Chain_Unsorted( &pts2[0], pts2.size(), &hull[0], &hindex[0]); contacts.resize(num); for(int v=0;v<num;v++) { //local estimate robot.links[link].T_World.mulInverse(pts[hindex[v]],cp.x); robot.links[link].T_World.R.mulTranspose(Vector3(0,0,1),cp.n); contacts[v] = cp; } } void GetFlatStance(RobotWithGeometry& robot,Real tol,Stance& s,Real kFriction) { ContactFormation formation; GetFlatContacts(robot,tol,formation); LocalContactsToStance(formation,robot,s); for(Stance::iterator i=s.begin();i!=s.end();i++) for(size_t j=0;j<i->second.contacts.size();j++) i->second.contacts[j].kFriction = 0.25; } void LocalContactsToHold(const vector<ContactPoint>& contacts,int link,const RobotKinematics3D& robot,Hold& hold) { hold.link = link; hold.contacts = contacts; for(size_t i=0;i<contacts.size();i++) { hold.contacts[i].x = robot.links[link].T_World*hold.contacts[i].x; hold.contacts[i].n = robot.links[link].T_World.R*hold.contacts[i].n; } MomentRotation m; m.setMatrix(robot.links[link].T_World.R); hold.SetupIKConstraint(contacts[0].x,m); hold.ikConstraint.destLink = -1; } void LocalContactsToStance(const ContactFormation& contacts,const RobotKinematics3D& robot,Stance& stance) { stance.clear(); for(size_t i=0;i<contacts.contacts.size();i++) { Hold h; LocalContactsToHold(contacts.contacts[i],contacts.links[i],robot,h); if(!contacts.targets.empty()) h.ikConstraint.destLink = contacts.targets[i]; stance.insert(h); } } void ClusterContacts(vector<ContactPoint>& contacts,int numClusters,Real normalScale,Real frictionScale) { if((int)contacts.size() <= numClusters) return; vector<Vector> pts(contacts.size()); for(size_t i=0;i<pts.size();i++) { pts[i].resize(7); pts[i][0] = contacts[i].x.x; pts[i][1] = contacts[i].x.y; pts[i][2] = contacts[i].x.z; pts[i][3] = contacts[i].n.x*normalScale; pts[i][4] = contacts[i].n.y*normalScale; pts[i][5] = contacts[i].n.z*normalScale; pts[i][6] = contacts[i].kFriction*frictionScale; } Statistics::KMeans kmeans(pts,numClusters); kmeans.RandomInitialCenters(); int iters=20; kmeans.Iterate(iters); contacts.resize(kmeans.centers.size()); vector<int> degenerate; for(size_t i=0;i<contacts.size();i++) { contacts[i].x.x = kmeans.centers[i][0]; contacts[i].x.y = kmeans.centers[i][1]; contacts[i].x.z = kmeans.centers[i][2]; contacts[i].n.x = kmeans.centers[i][3]; contacts[i].n.y = kmeans.centers[i][4]; contacts[i].n.z = kmeans.centers[i][5]; Real len = contacts[i].n.length(); if(FuzzyZero(len) || !IsFinite(len)) { printf("ClusterContacts: Warning, clustered normal became zero/infinite\n"); //pick any in the cluster int found = -1; for(size_t k=0;k<kmeans.labels.size();k++) { if(kmeans.labels[k] == (int)i) { found = (int)k; break; } } if(found < 0) { //strange -- degenerate cluster? degenerate.push_back(i); continue; } contacts[i].x.x = pts[found][0]; contacts[i].x.y = pts[found][1]; contacts[i].x.z = pts[found][2]; contacts[i].n.x = pts[found][3]; contacts[i].n.y = pts[found][4]; contacts[i].n.z = pts[found][5]; Real len = contacts[i].n.length(); contacts[i].n /= len; contacts[i].kFriction = pts[found][6]/frictionScale; Assert(contacts[i].kFriction >= 0); continue; } contacts[i].n /= len; //cout<<"Clustered contact "<<contacts[i].pos[0]<<" "<<contacts[i].pos[1]<<" "<<contacts[i].pos[2]<<endl; //cout<<"Clustered normal "<<contacts[i].normal[0]<<" "<<contacts[i].normal[1]<<" "<<contacts[i].normal[2]<<endl; contacts[i].kFriction = kmeans.centers[i][6]/frictionScale; Assert(contacts[i].kFriction >= 0); } //erase backward down degenerate list reverse(degenerate.begin(),degenerate.end()); for(size_t i=0;i<degenerate.size();i++) { contacts.erase(contacts.begin()+degenerate[i]); } } void CHContactsPlane(vector<ContactPoint>& cp,const Vector3& n,const Vector3& ori,Real ntol,Real xtol) { Assert(!cp.empty()); Real ofs = dot(n,ori); //all points must be on a plane for(size_t i=0;i<cp.size();i++) { if(!cp[i].n.isEqual(n,ntol)) { cout<<"CHContactsPlane: Warning: non-equal normal"<<endl; } if(!FuzzyEquals(n.dot(cp[i].x),ofs,xtol)) { cout<<"CHContactsPlane: Warning: non-equal offset: "<<ofs<<" vs "<<n.dot(cp[i].x)<<endl; } } Vector3 x,y; GetCanonicalBasis(n,x,y); Point2D* planePts = new Point2D[cp.size()]; Point2D* chPts = new Point2D[cp.size()+1]; //project points on plane Real xofs = x.dot(ofs); Real yofs = y.dot(ofs); for(size_t i=0;i<cp.size();i++) { planePts[i].x = x.dot(cp[i].x)-xofs; planePts[i].y = y.dot(cp[i].x)-yofs; } int k=ConvexHull2D_Chain_Unsorted(planePts,cp.size(),chPts); Assert(k <= (int)cp.size()); Assert(k > 0); cp.resize(k); for(int i=0;i<k;i++) { cp[i].x.mul(n,ofs); cp[i].x.madd(x,chPts[i].x+xofs); cp[i].x.madd(y,chPts[i].y+yofs); } delete [] planePts; delete [] chPts; } void GetPlane(const vector<ContactPoint>& cp,Vector3& n,Vector3& origin) { //just a simple average... n.setZero(); origin.setZero(); for(size_t i=0;i<cp.size();i++) { n += cp[i].n; origin += cp[i].x; } origin /= cp.size(); n.inplaceNormalize(); } struct EqualCP { EqualCP(Real _xtol,Real _ntol) :xtol(_xtol),ntol(_ntol) {} bool operator()(const ContactPoint& a,const ContactPoint& b) const { if(a.x.isEqual(b.x,xtol)) { if(a.n.isEqual(b.n,ntol)) { if(FuzzyEquals(a.kFriction,b.kFriction,ntol)) { return true; } } } return false; } Real xtol,ntol; }; struct EqualPlane { EqualPlane(Real _ntol,Real _xtol) :ntol(_ntol),xtol(_xtol) {} bool operator()(const ContactPoint& a,const ContactPoint& b) const { if(a.n.isEqual(b.n,ntol)) { if(FuzzyEquals(a.n.dot(a.x),a.n.dot(b.x),xtol) && FuzzyEquals(b.n.dot(a.x),b.n.dot(b.x),xtol)) { return true; } } return false; } Real ntol,xtol; }; void CHContacts(vector<ContactPoint>& cp,Real ntol,Real xtol) { EqualPlane eq(ntol,xtol); //EqualNormal eq(ntol); vector<vector<int> > sets; EquivalenceMap(cp,sets,eq); vector<ContactPoint> newCp; for(size_t i=0;i<sets.size();i++) { //set temp = sets[i] vector<int>& s=sets[i]; vector<ContactPoint> temp(s.size()); for(size_t j=0;j<s.size();j++) { Assert(0<=s[j] && s[j]<(int)cp.size()); temp[j] = cp[s[j]]; } size_t oldSize = temp.size(); //average the plane Vector3 n,origin; GetPlane(temp,n,origin); CHContactsPlane(temp,n,origin,ntol,xtol); //append temp onto newCps oldSize=newCp.size(); newCp.resize(oldSize + temp.size()); //copy(temp.begin(),temp.end(),newCp.begin()+oldSize); copy_backward(temp.begin(),temp.end(),newCp.end()); } swap(cp,newCp); } void CleanupContacts(vector<ContactPoint>& cp,Real tol) { EqualCP eq(tol,tol*10.0); vector<vector<int> > sets; EquivalenceMap(cp,sets,eq); vector<ContactPoint> cpNew; cpNew.resize(sets.size()); for(size_t i=0;i<sets.size();i++) { vector<int>& avgPoints = sets[i]; Assert(!avgPoints.empty()); cpNew[i].x.setZero(); cpNew[i].n.setZero(); cpNew[i].kFriction = Zero; for(size_t j=0;j<avgPoints.size();j++) { cpNew[i].x += cp[avgPoints[j]].x; cpNew[i].n += cp[avgPoints[j]].n; cpNew[i].kFriction += cp[avgPoints[j]].kFriction; } cpNew[i].x /= avgPoints.size(); cpNew[i].n /= avgPoints.size(); cpNew[i].kFriction /= avgPoints.size(); cpNew[i].n.inplaceNormalize(); } swap(cp,cpNew); } int ClosestContact(const ContactPoint& p,const Meshing::TriMesh& mesh,ContactPoint& pclose,Real normalScale) { int closest = -1; Real closestDist2 = Inf; Triangle3D tri; Plane3D plane; for(size_t i=0;i<mesh.tris.size();i++) { mesh.GetTriangle(i,tri); //first check distance to supporting plane, since it's a lower bound tri.getPlane(plane); Real dxmin = plane.distance(p.x); Real dn = normalScale*plane.normal.distanceSquared(p.n); if(dn + Sqr(dxmin) < closestDist2) { //has potential to be closer than previous Vector3 cp = tri.closestPoint(p.x); Real d = cp.distanceSquared(p.x) + dn; if(d < closestDist2) { closest = (int)i; closestDist2 = d; pclose.x = cp; pclose.n = plane.normal; pclose.kFriction = p.kFriction; } } } return closest; }
{ "content_hash": "714bf4a04b1447c8b60731115eff5e34", "timestamp": "", "source": "github", "line_count": 460, "max_line_length": 117, "avg_line_length": 29.73913043478261, "alnum_prop": 0.6309941520467837, "repo_name": "stevekuznetsov/Klampt", "id": "42219e4a71fe6f713222349884ea4fd2cd7912ca", "size": "13857", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Contact/Utils.cpp", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "4484" }, { "name": "C++", "bytes": "4381537" }, { "name": "CMake", "bytes": "56295" }, { "name": "GLSL", "bytes": "28" }, { "name": "Makefile", "bytes": "5311" }, { "name": "Python", "bytes": "931058" }, { "name": "QMake", "bytes": "3587" }, { "name": "Shell", "bytes": "283" } ], "symlink_target": "" }
var _append = require('./internal/_append'); var _curry2 = require('./internal/_curry2'); var _foldl = require('./internal/_foldl'); /** * Splits a list into sub-lists stored in an object, based on the result of calling a String-returning function * on each element, and grouping the results according to values returned. * * @func * @memberOf R * @category List * @sig (a -> s) -> [a] -> {s: a} * @param {Function} fn Function :: a -> String * @param {Array} list The array to group * @return {Object} An object with the output of `fn` for keys, mapped to arrays of elements * that produced that key when passed to `fn`. * @example * * var byGrade = R.groupBy(function(student) { * var score = student.score; * return (score < 65) ? 'F' : (score < 70) ? 'D' : * (score < 80) ? 'C' : (score < 90) ? 'B' : 'A'; * }); * var students = [{name: 'Abby', score: 84}, * {name: 'Eddy', score: 58}, * // ... * {name: 'Jack', score: 69}]; * byGrade(students); * // { * // 'A': [{name: 'Dianne', score: 99}], * // 'B': [{name: 'Abby', score: 84}] * // // ..., * // 'F': [{name: 'Eddy', score: 58}] * // } */ module.exports = _curry2(function groupBy(fn, list) { return _foldl(function(acc, elt) { var key = fn(elt); acc[key] = _append(elt, acc[key] || (acc[key] = [])); return acc; }, {}, list); });
{ "content_hash": "91ac25fff39d7ad17d9156857ea9d3e9", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 111, "avg_line_length": 34.74418604651163, "alnum_prop": 0.5113788487282463, "repo_name": "stoeffel/ramda", "id": "7325aa0645460c1ad7f3ea4a6526b6f464aa0e77", "size": "1494", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/groupBy.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7587" }, { "name": "JavaScript", "bytes": "817438" }, { "name": "Makefile", "bytes": "1022" }, { "name": "Shell", "bytes": "639" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en-GB" xml:lang="en-GB" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title>Statistics of Tense in UD_Finnish-PUD</title> <link rel="root" href=""/> <!-- for JS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/> <link rel="stylesheet" type="text/css" href="../../css/style.css"/> <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/> <link rel="stylesheet" type="text/css" href="../../css/hint.css"/> <script type="text/javascript" src="../../lib/ext/head.load.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/anchor-js/3.2.2/anchor.min.js"></script> <script>document.addEventListener("DOMContentLoaded", function(event) {anchors.add();});</script> <!-- Set up this custom Google search at https://cse.google.com/cse/business/settings?cx=001145188882102106025:dl1mehhcgbo --> <!-- DZ 2021-01-22: I am temporarily hiding the search field to find out whether it slows down loading of the title page. <script> (function() { var cx = '001145188882102106025:dl1mehhcgbo'; var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true; gcse.src = 'https://cse.google.com/cse.js?cx=' + cx; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s); })(); </script> --> <!-- <link rel="shortcut icon" href="favicon.ico"/> --> </head> <body> <div id="main" class="center"> <div id="hp-header"> <table width="100%"><tr><td width="50%"> <span class="header-text"><a href="http://universaldependencies.org/#language-">home</a></span> <span class="header-text"><a href="https://github.com/universaldependencies/docs/edit/pages-source/treebanks/fi_pud/fi_pud-feat-Tense.md" target="#">edit page</a></span> <span class="header-text"><a href="https://github.com/universaldependencies/docs/issues">issue tracker</a></span> </td><td> <gcse:search></gcse:search> </td></tr></table> </div> <hr/> <div class="v2complete"> This page pertains to UD version 2. </div> <div id="content"> <noscript> <div id="noscript"> It appears that you have Javascript disabled. Please consider enabling Javascript for this page to see the visualizations. </div> </noscript> <!-- The content may include scripts and styles, hence we must load the shared libraries before the content. --> <script type="text/javascript"> console.time('loading libraries'); var root = '../../'; // filled in by jekyll head.js( // External libraries // DZ: Copied from embedding.html. I don't know which one is needed for what, so I'm currently keeping them all. root + 'lib/ext/jquery.min.js', root + 'lib/ext/jquery.svg.min.js', root + 'lib/ext/jquery.svgdom.min.js', root + 'lib/ext/jquery.timeago.js', root + 'lib/ext/jquery-ui.min.js', root + 'lib/ext/waypoints.min.js', root + 'lib/ext/jquery.address.min.js' ); </script> <h2 id="treebank-statistics-ud_finnish-pud-features-tense">Treebank Statistics: UD_Finnish-PUD: Features: <code class="language-plaintext highlighter-rouge">Tense</code></h2> <p>This feature is universal. It occurs with 2 different values: <code class="language-plaintext highlighter-rouge">Past</code>, <code class="language-plaintext highlighter-rouge">Pres</code>.</p> <p>1766 tokens (11%) have a non-empty value of <code class="language-plaintext highlighter-rouge">Tense</code>. 725 types (10%) occur at least once with a non-empty value of <code class="language-plaintext highlighter-rouge">Tense</code>. 418 lemmas (8%) occur at least once with a non-empty value of <code class="language-plaintext highlighter-rouge">Tense</code>. The feature is used with 2 part-of-speech tags: <tt><a href="fi_pud-pos-VERB.html">VERB</a></tt> (1158; 7% instances), <tt><a href="fi_pud-pos-AUX.html">AUX</a></tt> (608; 4% instances).</p> <h3 id="verb"><code class="language-plaintext highlighter-rouge">VERB</code></h3> <p>1158 <tt><a href="fi_pud-pos-VERB.html">VERB</a></tt> tokens (57% of all <code class="language-plaintext highlighter-rouge">VERB</code> tokens) have a non-empty value of <code class="language-plaintext highlighter-rouge">Tense</code>.</p> <p>The most frequent other feature values with which <code class="language-plaintext highlighter-rouge">VERB</code> and <code class="language-plaintext highlighter-rouge">Tense</code> co-occurred: <tt><a href="fi_pud-feat-Case.html">Case</a></tt><tt>=EMPTY</tt> (1158; 100%), <tt><a href="fi_pud-feat-InfForm.html">InfForm</a></tt><tt>=EMPTY</tt> (1158; 100%), <tt><a href="fi_pud-feat-Mood.html">Mood</a></tt><tt>=Ind</tt> (1158; 100%), <tt><a href="fi_pud-feat-PartForm.html">PartForm</a></tt><tt>=EMPTY</tt> (1158; 100%), <tt><a href="fi_pud-feat-VerbForm.html">VerbForm</a></tt><tt>=Fin</tt> (1158; 100%), <tt><a href="fi_pud-feat-Voice.html">Voice</a></tt><tt>=Act</tt> (944; 82%), <tt><a href="fi_pud-feat-Person.html">Person</a></tt><tt>=3</tt> (899; 78%), <tt><a href="fi_pud-feat-Number.html">Number</a></tt><tt>=Sing</tt> (721; 62%).</p> <p><code class="language-plaintext highlighter-rouge">VERB</code> tokens may have the following values of <code class="language-plaintext highlighter-rouge">Tense</code>:</p> <ul> <li><code class="language-plaintext highlighter-rouge">Past</code> (717; 62% of non-empty <code class="language-plaintext highlighter-rouge">Tense</code>): <em>sanoi, tuli, kertoi, alkoi, johti, sai, syntyi, teki, rakennettiin, käytettiin</em></li> <li><code class="language-plaintext highlighter-rouge">Pres</code> (441; 38% of non-empty <code class="language-plaintext highlighter-rouge">Tense</code>): <em>tulee, sanoo, auttaa, pidetään, kuuluvat, toimii, alkaa, haluaa, kuuluu, liittyy</em></li> <li><code class="language-plaintext highlighter-rouge">EMPTY</code> (857): <em>tehdä, liittyen, lukien, olemassa, tullut, johtaa, johtuen, käytetty, käyttämällä, nähdä</em></li> </ul> <table> <tr><th>Paradigm <i>tulla</i></th><th><tt>Pres</tt></th><th><tt>Past</tt></th></tr> <tr><td><tt><tt><a href="fi_pud-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="fi_pud-feat-Person.html">Person</a></tt><tt>=0</tt>|<tt><a href="fi_pud-feat-Voice.html">Voice</a></tt><tt>=Act</tt></tt></td><td><em>tulee</em></td><td></td></tr> <tr><td><tt><tt><a href="fi_pud-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="fi_pud-feat-Person.html">Person</a></tt><tt>=3</tt>|<tt><a href="fi_pud-feat-Voice.html">Voice</a></tt><tt>=Act</tt></tt></td><td><em>tulee</em></td><td><em>tuli</em></td></tr> <tr><td><tt><tt><a href="fi_pud-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="fi_pud-feat-Person.html">Person</a></tt><tt>=3</tt>|<tt><a href="fi_pud-feat-Voice.html">Voice</a></tt><tt>=Act</tt></tt></td><td><em>tulevat</em></td><td></td></tr> <tr><td><tt><tt><a href="fi_pud-feat-Voice.html">Voice</a></tt><tt>=Pass</tt></tt></td><td><em>tullaan</em></td><td></td></tr> </table> <h3 id="aux"><code class="language-plaintext highlighter-rouge">AUX</code></h3> <p>608 <tt><a href="fi_pud-pos-AUX.html">AUX</a></tt> tokens (74% of all <code class="language-plaintext highlighter-rouge">AUX</code> tokens) have a non-empty value of <code class="language-plaintext highlighter-rouge">Tense</code>.</p> <p>The most frequent other feature values with which <code class="language-plaintext highlighter-rouge">AUX</code> and <code class="language-plaintext highlighter-rouge">Tense</code> co-occurred: <tt><a href="fi_pud-feat-Mood.html">Mood</a></tt><tt>=Ind</tt> (608; 100%), <tt><a href="fi_pud-feat-Polarity.html">Polarity</a></tt><tt>=EMPTY</tt> (608; 100%), <tt><a href="fi_pud-feat-VerbForm.html">VerbForm</a></tt><tt>=Fin</tt> (608; 100%), <tt><a href="fi_pud-feat-Voice.html">Voice</a></tt><tt>=Act</tt> (567; 93%), <tt><a href="fi_pud-feat-Person.html">Person</a></tt><tt>=3</tt> (549; 90%), <tt><a href="fi_pud-feat-Number.html">Number</a></tt><tt>=Sing</tt> (470; 77%).</p> <p><code class="language-plaintext highlighter-rouge">AUX</code> tokens may have the following values of <code class="language-plaintext highlighter-rouge">Tense</code>:</p> <ul> <li><code class="language-plaintext highlighter-rouge">Past</code> (175; 29% of non-empty <code class="language-plaintext highlighter-rouge">Tense</code>): <em>oli, olivat, oliko, olin, täytyi, olivatkaan, piti, voikin, voitiin</em></li> <li><code class="language-plaintext highlighter-rouge">Pres</code> (433; 71% of non-empty <code class="language-plaintext highlighter-rouge">Tense</code>): <em>on, ovat, ole, voi, täytyy, voivat, olemme, olen, onko, pitää</em></li> <li><code class="language-plaintext highlighter-rouge">EMPTY</code> (218): <em>ei, ollut, eivät, olisi, voisi, eikä, en, olla, pitäisi, emme</em></li> </ul> <table> <tr><th>Paradigm <i>olla</i></th><th><tt>Pres</tt></th><th><tt>Past</tt></th></tr> <tr><td><tt><tt><a href="fi_pud-feat-Clitic.html">Clitic</a></tt><tt>=Kaan</tt>|<tt><a href="fi_pud-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="fi_pud-feat-Person.html">Person</a></tt><tt>=3</tt>|<tt><a href="fi_pud-feat-Voice.html">Voice</a></tt><tt>=Act</tt></tt></td><td><em>onkaan</em></td><td></td></tr> <tr><td><tt><tt><a href="fi_pud-feat-Clitic.html">Clitic</a></tt><tt>=Kaan</tt>|<tt><a href="fi_pud-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="fi_pud-feat-Person.html">Person</a></tt><tt>=3</tt>|<tt><a href="fi_pud-feat-Voice.html">Voice</a></tt><tt>=Act</tt></tt></td><td></td><td><em>olivatkaan</em></td></tr> <tr><td><tt><tt><a href="fi_pud-feat-Clitic.html">Clitic</a></tt><tt>=Kin</tt>|<tt><a href="fi_pud-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="fi_pud-feat-Person.html">Person</a></tt><tt>=3</tt>|<tt><a href="fi_pud-feat-Voice.html">Voice</a></tt><tt>=Act</tt></tt></td><td><em>onkin</em></td><td></td></tr> <tr><td><tt><tt><a href="fi_pud-feat-Clitic.html">Clitic</a></tt><tt>=Ko</tt>|<tt><a href="fi_pud-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="fi_pud-feat-Person.html">Person</a></tt><tt>=3</tt>|<tt><a href="fi_pud-feat-Voice.html">Voice</a></tt><tt>=Act</tt></tt></td><td><em>onko</em></td><td><em>oliko</em></td></tr> <tr><td><tt><tt><a href="fi_pud-feat-Connegative.html">Connegative</a></tt><tt>=Yes</tt></tt></td><td><em>ole</em></td><td></td></tr> <tr><td><tt><tt><a href="fi_pud-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="fi_pud-feat-Person.html">Person</a></tt><tt>=1</tt>|<tt><a href="fi_pud-feat-Voice.html">Voice</a></tt><tt>=Act</tt></tt></td><td><em>olen</em></td><td><em>olin</em></td></tr> <tr><td><tt><tt><a href="fi_pud-feat-Number.html">Number</a></tt><tt>=Sing</tt>|<tt><a href="fi_pud-feat-Person.html">Person</a></tt><tt>=3</tt>|<tt><a href="fi_pud-feat-Voice.html">Voice</a></tt><tt>=Act</tt></tt></td><td><em>on</em></td><td><em>oli</em></td></tr> <tr><td><tt><tt><a href="fi_pud-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="fi_pud-feat-Person.html">Person</a></tt><tt>=1</tt>|<tt><a href="fi_pud-feat-Voice.html">Voice</a></tt><tt>=Act</tt></tt></td><td><em>olemme</em></td><td></td></tr> <tr><td><tt><tt><a href="fi_pud-feat-Number.html">Number</a></tt><tt>=Plur</tt>|<tt><a href="fi_pud-feat-Person.html">Person</a></tt><tt>=3</tt>|<tt><a href="fi_pud-feat-Voice.html">Voice</a></tt><tt>=Act</tt></tt></td><td><em>ovat</em></td><td><em>olivat</em></td></tr> </table> <h2 id="relations-with-agreement-in-tense">Relations with Agreement in <code class="language-plaintext highlighter-rouge">Tense</code></h2> <p>The 10 most frequent relations where parent and child node agree in <code class="language-plaintext highlighter-rouge">Tense</code>: <tt>VERB –[<tt><a href="fi_pud-dep-conj.html">conj</a></tt>]–&gt; VERB</tt> (111; 71%), <tt>VERB –[<tt><a href="fi_pud-dep-acl-relcl.html">acl:relcl</a></tt>]–&gt; VERB</tt> (3; 60%), <tt>AUX –[<tt><a href="fi_pud-dep-acl-relcl.html">acl:relcl</a></tt>]–&gt; VERB</tt> (1; 100%), <tt>VERB –[<tt><a href="fi_pud-dep-csubj.html">csubj</a></tt>]–&gt; VERB</tt> (1; 100%).</p> </div> <!-- support for embedded visualizations --> <script type="text/javascript"> var root = '../../'; // filled in by jekyll head.js( // We assume that external libraries such as jquery.min.js have already been loaded outside! // (See _layouts/base.html.) // brat helper modules root + 'lib/brat/configuration.js', root + 'lib/brat/util.js', root + 'lib/brat/annotation_log.js', root + 'lib/ext/webfont.js', // brat modules root + 'lib/brat/dispatcher.js', root + 'lib/brat/url_monitor.js', root + 'lib/brat/visualizer.js', // embedding configuration root + 'lib/local/config.js', // project-specific collection data root + 'lib/local/collections.js', // Annodoc root + 'lib/annodoc/annodoc.js', // NOTE: non-local libraries 'https://spyysalo.github.io/conllu.js/conllu.js' ); var webFontURLs = [ // root + 'static/fonts/Astloch-Bold.ttf', root + 'static/fonts/PT_Sans-Caption-Web-Regular.ttf', root + 'static/fonts/Liberation_Sans-Regular.ttf' ]; var setupTimeago = function() { jQuery("time.timeago").timeago(); }; head.ready(function() { setupTimeago(); // mark current collection (filled in by Jekyll) Collections.listing['_current'] = ''; // perform all embedding and support functions Annodoc.activate(Config.bratCollData, Collections.listing); }); </script> <!-- google analytics --> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-55233688-1', 'auto'); ga('send', 'pageview'); </script> <div id="footer"> <p class="footer-text">&copy; 2014–2021 <a href="http://universaldependencies.org/introduction.html#contributors" style="color:gray">Universal Dependencies contributors</a>. Site powered by <a href="http://spyysalo.github.io/annodoc" style="color:gray">Annodoc</a> and <a href="http://brat.nlplab.org/" style="color:gray">brat</a></p>. </div> </div> </body> </html>
{ "content_hash": "f5ab4deee3c5cc77db6a0ce4b74932ff", "timestamp": "", "source": "github", "line_count": 220, "max_line_length": 847, "avg_line_length": 68.99090909090908, "alnum_prop": 0.6323626301225458, "repo_name": "UniversalDependencies/universaldependencies.github.io", "id": "ef8d5ca05e6779f8760977f1ba35aea1dd953e8f", "size": "15214", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "treebanks/fi_pud/fi_pud-feat-Tense.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "64420" }, { "name": "HTML", "bytes": "383191916" }, { "name": "JavaScript", "bytes": "687350" }, { "name": "Perl", "bytes": "7788" }, { "name": "Python", "bytes": "21203" }, { "name": "Shell", "bytes": "7253" } ], "symlink_target": "" }
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:id="@+id/container_toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <include android:id="@+id/toolbar" layout="@layout/toolbar" /> </LinearLayout> <FrameLayout android:id="@+id/container_body" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="0.77" android:background="#000000"> <RadioGroup android:id="@+id/activityRadioGroup" android:layout_width="fill_parent" android:layout_height="50dp" android:layout_gravity="bottom|center" android:background="@android:color/white" android:orientation="horizontal" android:weightSum="1"> <RadioButton android:id="@+id/walkRadioButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0.16" android:checked="false" android:text="Walk" /> - <RadioButton android:id="@+id/runRadioButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="false" android:layout_weight="0.16" android:text="Run" /> <RadioButton android:id="@+id/driveRadioButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="false" android:layout_weight="0.16" android:text="Drive" /> <RadioButton android:id="@+id/busRadioButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="false" android:layout_weight="0.16" android:text="Bus" /> <RadioButton android:id="@+id/bikeRadioButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="false" android:layout_weight="0.16" android:text="Bike" /> <RadioButton android:id="@+id/stillRadioButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="false" android:layout_weight="0.16" android:text="Still" /> </RadioGroup> </FrameLayout> </LinearLayout> <fragment android:id="@+id/fragment_navigation_drawer" android:name="com.uf.nomad.mobitrace.android_activity.FragmentDrawer" android:layout_width="@dimen/nav_drawer_width" android:layout_height="match_parent" android:layout_gravity="start" app:layout="@layout/fragment_navigation_drawer" tools:layout="@layout/fragment_navigation_drawer" /> </android.support.v4.widget.DrawerLayout>
{ "content_hash": "f5e8fccd4ec18c3d9d04c062390b312e", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 98, "avg_line_length": 37.074766355140184, "alnum_prop": 0.5288631207461558, "repo_name": "BabakAp/MobiTrace", "id": "d92c675b2fcba89e4e38503da693bf5ab9172c98", "size": "3967", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/layout/activity_main.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "128898" } ], "symlink_target": "" }
author: robmyers comments: true date: 2006-04-22 05:55:47+00:00 layout: post slug: relational-aesthetics-the-institutional-theory-suspension-of-judgement-radical-commitment-via-rhizome-raw title: Relational Aesthetics (The Institutional Theory + Suspension of Judgement - Radical Commitment) [via Rhizome RAW] wordpress_id: 899 categories: - Aesthetics --- The trained seal of approval that is Relational Aesthetics (The Institutional Theory + Suspension Of Judgement - Radical Commitment) is unlikely to get its coat based on the chinstroking of Octoberistas. Pointing out that there is someone behind the curtain doesn't help. That someone still has social relations. Despite Bourriaud's protestatations, RA is deeply, achingly, embarrasingly managerial. It is the managerial mode of regard embodied in materials that managers recognise: assets, particularly human assets. And RA is auratic. Because without the aura of management -uh- art, what differentiates the social and aesthetic incompetence of RA from just actual social and aesthetic incompetence? Both these qualities can only increase if people need their passports or whatever as part of the beautific images of managerialism that RA give us as works. Managers' egos will not be deflated by an "art" of ever stronger management of Real People in ever more tighly controlled additions (or revelations) of managerial value (or power) in social situations. [Bishop](http://roundtable.kein.org/node/202)'s assessment of British art criticism in the 1990s is depressingly accurate but there is an account of art from that time that gives us something to work with. Julian Stallabrass's concept of the Urban Pastoral (from "High Art Lite") is far too close to the bone of RA to leave unused.
{ "content_hash": "144a907cce261d1331de6fa78f5c5c22", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 360, "avg_line_length": 77.26086956521739, "alnum_prop": 0.7979741136747327, "repo_name": "robmyers/robmyers.org", "id": "55f91e8dd8809899cd5bde6a50a156b664b34a3e", "size": "1781", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2006-04-22-relational-aesthetics-the-institutional-theory-suspension-of-judgement-radical-commitment-via-rhizome-raw.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "18921" }, { "name": "HTML", "bytes": "14981" }, { "name": "JavaScript", "bytes": "62388" }, { "name": "PHP", "bytes": "30" }, { "name": "R", "bytes": "16999" }, { "name": "Ruby", "bytes": "2751" }, { "name": "Scheme", "bytes": "2307" } ], "symlink_target": "" }
<?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>paramz.caching</title> <link rel="stylesheet" href="epydoc.css" type="text/css" /> <script type="text/javascript" src="epydoc.js"></script> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="paramz-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar" width="100%"></th> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="100%"> <span class="breadcrumbs"> <a href="paramz-module.html">Package&nbsp;paramz</a> :: Module&nbsp;caching </span> </td> <td> <table cellpadding="0" cellspacing="0"> <!-- hide/show private --> <tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink" onclick="toggle_private();">hide&nbsp;private</a>]</span></td></tr> <tr><td align="right"><span class="options" >[<a href="frames.html" target="_top">frames</a >]&nbsp;|&nbsp;<a href="paramz.caching-module.html" target="_top">no&nbsp;frames</a>]</span></td></tr> </table> </td> </tr> </table> <!-- ==================== MODULE DESCRIPTION ==================== --> <h1 class="epydoc">Module caching</h1><p class="nomargin-top"><span class="codelink"><a href="paramz.caching-pysrc.html">source&nbsp;code</a></span></p> <!-- ==================== CLASSES ==================== --> <a name="section-Classes"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Classes</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-Classes" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="paramz.caching.Cacher-class.html" class="summary-name">Cacher</a> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="paramz.caching.FunctionCache-class.html" class="summary-name">FunctionCache</a> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="paramz.caching.Cache_this-class.html" class="summary-name">Cache_this</a><br /> A decorator which can be applied to bound methods in order to cache them </td> </tr> </table> <!-- ==================== VARIABLES ==================== --> <a name="section-Variables"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Variables</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-Variables" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="__package__"></a><span class="summary-name">__package__</span> = <code title="'paramz'"><code class="variable-quote">'</code><code class="variable-string">paramz</code><code class="variable-quote">'</code></code> </td> </tr> </table> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="paramz-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar" width="100%"></th> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%%"> <tr> <td align="left" class="footer"> Generated by Epydoc 3.0.1 on Tue Jul 4 11:59:27 2017 </td> <td align="right" class="footer"> <a target="mainFrame" href="http://epydoc.sourceforge.net" >http://epydoc.sourceforge.net</a> </td> </tr> </table> <script type="text/javascript"> <!-- // Private objects are initially displayed (because if // javascript is turned off then we want them to be // visible); but by default, we want to hide them. So hide // them unless we have a cookie that says to show them. checkCookie(); // --> </script> </body> </html>
{ "content_hash": "1e092e6f5c80198af160756bb76ad50b", "timestamp": "", "source": "github", "line_count": 170, "max_line_length": 229, "avg_line_length": 36.67058823529412, "alnum_prop": 0.5700994546037856, "repo_name": "sods/paramz", "id": "186974f5a466ad2cf3f959c9bf16871bb7963467", "size": "6234", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docs/paramz.caching-module.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Jupyter Notebook", "bytes": "55080" }, { "name": "Python", "bytes": "334334" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:buzz="http://www.vitrociset.it/schema/vitrociset-buzz" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:repo="http://www.springframework.org/schema/data/repository" xmlns:c="http://www.springframework.org/schema/c" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.vitrociset.it/schema/vitrociset-buzz http://www.vitrociset.it/schema/vitrociset-buzz.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <util:map id="profiles"> <entry key="person"> <buzz:profile id="person"> <buzz:attribute id="zonaallerta" name="zonaallerta" classType="INT"></buzz:attribute> <buzz:attribute id="campo2" name="campo2" classType="STRING"></buzz:attribute> <buzz:attribute id="campo3" name="campo3" classType="LONG"></buzz:attribute> <buzz:attribute id="campo4" name="campo4" classType="DATETIME"></buzz:attribute> <buzz:attribute id="campo5" name="campo5" classType="GEO"></buzz:attribute> <buzz:attribute id="campo6" name="campo6" classType="NUMBER"></buzz:attribute> </buzz:profile> </entry> </util:map> </beans>
{ "content_hash": "cf50e21b9bd0e1e2fa58b78e440ffd6c", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 120, "avg_line_length": 55.3, "alnum_prop": 0.7112718505123569, "repo_name": "Antonio90/Angular2", "id": "0dfec09ebc7605f6905d4e30ea07c362b37ad01c", "size": "1659", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "buzz-web/WEB-INF/spring/profiles.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "328399" }, { "name": "HTML", "bytes": "7453" }, { "name": "JavaScript", "bytes": "26041" }, { "name": "TypeScript", "bytes": "30657" } ], "symlink_target": "" }
![Open Existing Map App](open-existing-map.png) The Open Existing Map app demonstrates how to open an existing map as a ```PortalItem``` from a ```Portal```. The app opens with a web map from a portal displayed. You tap on the navigation drawer icon to see a list of pre-defined web maps. Select any of the web maps to close the drawer and open it up in the ```MapView```. ## Features * ArcGISMap * MapView * Portal * PortalItem ## Developer Pattern ```Portal``` objects represent information from a portal such as ArcGIS Online. ```PortalItem``` represents an item stored in a portal. We create a ```Map``` from a ```Portal``` & ```PortalItem``` objects then pass the ```Map``` to the ```MapView```. ```java // get the portal url for ArcGIS Online mPortal = new Portal(getResources().getString(R.string.portal_url)); // get the pre-defined portal id and portal url mPortalItem = new PortalItem(mPortal, getResources().getString(R.string.webmap_houses_with_mortgages_id)); // create a map from a PortalItem mMap = new Map(mPortalItem); // set the map to be displayed in this view mMapView.setMap(mMap); ```
{ "content_hash": "91d530dc2efeec0880de4a947dcfe190", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 326, "avg_line_length": 48.47826086956522, "alnum_prop": 0.7237668161434978, "repo_name": "Aaron-Benson/arcgis-runtime-samples-android-master", "id": "c8cb4e32bb88f43d640aa4f7db1aa7d712bd5963", "size": "1136", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "open-existing-map/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "619814" }, { "name": "Kotlin", "bytes": "4630" } ], "symlink_target": "" }
class MultiLogger attr_reader :level # Initialize the MultiLogger, specify the severity level for all loggers # and add one or more loggers. # # @param [Hash] args the options to create a message with. # @option args [Integer] :level (2) The severity level # @option args [Array<Logger>] :loggers ([]) The loggers that are initially to be added # @return the object def initialize(args = {}) @level = args[:level] || Logger::Severity::WARN @loggers = [] Array(args[:loggers]).each { |logger| add_logger(logger) } end # Add a logger to the MultiLogger and adjust its level to the MultiLogger's current level. # # @param [Logger] logger the logger to add to the MultiLogger instance def add_logger(logger) logger.level = level @loggers << logger end # Adjust the MultiLogger's current level. # # @param [Integer] level the severity level to apply to the MultiLogger instance def level=(level) @level = level @loggers.each { |logger| logger.level = level } end # Close each Logger of the MultiLogger instance def close @loggers.map(&:close) end Logger::Severity.constants.each do |level| define_method(level.downcase) do |*args| @loggers.each { |logger| logger.send(level.downcase, args) } end define_method("#{level.downcase}?".to_sym) do @level <= Logger::Severity.const_get(level) end end end
{ "content_hash": "0e3edf9de22aa39d179fca009a1156dd", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 92, "avg_line_length": 29.375, "alnum_prop": 0.6780141843971631, "repo_name": "stefan-kolb/nucleus", "id": "9006e0782c82449f71f59a32d73563c68912164e", "size": "1946", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/nucleus/core/common/logging/multi_logger.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "34" }, { "name": "CSS", "bytes": "93075" }, { "name": "HTML", "bytes": "5738" }, { "name": "JavaScript", "bytes": "2295478" }, { "name": "Ruby", "bytes": "668103" } ], "symlink_target": "" }