repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
etelic/sampleapp
src/GeneratorBase.MVC/Scripts/bootstrap.js
59195
/* NUGET: BEGIN LICENSE TEXT * * Microsoft grants you the right to use these script files for the sole * purpose of either: (i) interacting through your browser with the Microsoft * website or online service, subject to the applicable licensing or use * terms; or (ii) using the files as included with a Microsoft product subject * to that product's license terms. Microsoft reserves all other rights to the * files not expressly granted by Microsoft, whether by implication, estoppel * or otherwise. Insofar as a script file is dual licensed under GPL, * Microsoft neither took the code under GPL nor distributes it thereunder but * under the terms set out in this paragraph. All notices and licenses * below are for informational purposes only. * * NUGET: END LICENSE TEXT */ /** * bootstrap.js v3.0.0 by @fat and @mdo * Copyright 2013 Twitter Inc. * http://www.apache.org/licenses/LICENSE-2.0 */ if (!jQuery) { throw new Error("Bootstrap requires jQuery") } /* ======================================================================== * Bootstrap: transition.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#transitions * ======================================================================== * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/) // ============================================================ function transitionEnd() { var el = document.createElement('bootstrap') var transEndEventNames = { 'WebkitTransition' : 'webkitTransitionEnd' , 'MozTransition' : 'transitionend' , 'OTransition' : 'oTransitionEnd otransitionend' , 'transition' : 'transitionend' } for (var name in transEndEventNames) { if (el.style[name] !== undefined) { return { end: transEndEventNames[name] } } } } // http://blog.alexmaccaw.com/css-transitions $.fn.emulateTransitionEnd = function (duration) { var called = false, $el = this $(this).one($.support.transition.end, function () { called = true }) var callback = function () { if (!called) $($el).trigger($.support.transition.end) } setTimeout(callback, duration) return this } $(function () { $.support.transition = transitionEnd() }) }(window.jQuery); /* ======================================================================== * Bootstrap: alert.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#alerts * ======================================================================== * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // ALERT CLASS DEFINITION // ====================== var dismiss = '[data-dismiss="alert"]' var Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.prototype.close = function (e) { var $this = $(this) var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = $(selector) if (e) e.preventDefault() if (!$parent.length) { $parent = $this.hasClass('alert') ? $this : $this.parent() } $parent.trigger(e = $.Event('close.bs.alert')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { $parent.trigger('closed.bs.alert').remove() } $.support.transition && $parent.hasClass('fade') ? $parent .one($.support.transition.end, removeElement) .emulateTransitionEnd(150) : removeElement() } // ALERT PLUGIN DEFINITION // ======================= var old = $.fn.alert $.fn.alert = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.alert') if (!data) $this.data('bs.alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.alert.Constructor = Alert // ALERT NO CONFLICT // ================= $.fn.alert.noConflict = function () { $.fn.alert = old return this } // ALERT DATA-API // ============== $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close) }(window.jQuery); /* ======================================================================== * Bootstrap: button.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#buttons * ======================================================================== * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // BUTTON PUBLIC CLASS DEFINITION // ============================== var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, Button.DEFAULTS, options) } Button.DEFAULTS = { loadingText: 'loading...' } Button.prototype.setState = function (state) { var d = 'disabled' var $el = this.$element var val = $el.is('input') ? 'val' : 'html' var data = $el.data() state = state + 'Text' if (!data.resetText) $el.data('resetText', $el[val]()) $el[val](data[state] || this.options[state]) // push to event loop to allow forms to submit setTimeout(function () { state == 'loadingText' ? $el.addClass(d).attr(d, d) : $el.removeClass(d).removeAttr(d); }, 0) } Button.prototype.toggle = function () { var $parent = this.$element.closest('[data-toggle="buttons"]') if ($parent.length) { var $input = this.$element.find('input') .prop('checked', !this.$element.hasClass('active')) .trigger('change') if ($input.prop('type') === 'radio') $parent.find('.active').removeClass('active') } this.$element.toggleClass('active') } // BUTTON PLUGIN DEFINITION // ======================== var old = $.fn.button $.fn.button = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.button') var options = typeof option == 'object' && option if (!data) $this.data('bs.button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } $.fn.button.Constructor = Button // BUTTON NO CONFLICT // ================== $.fn.button.noConflict = function () { $.fn.button = old return this } // BUTTON DATA-API // =============== $(document).on('click.bs.button.data-api', '[data-toggle^=button]', function (e) { var $btn = $(e.target) if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') $btn.button('toggle') e.preventDefault() }) }(window.jQuery); /* ======================================================================== * Bootstrap: carousel.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#carousel * ======================================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // CAROUSEL CLASS DEFINITION // ========================= var Carousel = function (element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.paused = this.sliding = this.interval = this.$active = this.$items = null this.options.pause == 'hover' && this.$element .on('mouseenter', $.proxy(this.pause, this)) .on('mouseleave', $.proxy(this.cycle, this)) } Carousel.DEFAULTS = { interval: 5000 , pause: 'hover' , wrap: true } Carousel.prototype.cycle = function (e) { e || (this.paused = false) this.interval && clearInterval(this.interval) this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } Carousel.prototype.getActiveIndex = function () { this.$active = this.$element.find('.item.active') this.$items = this.$active.parent().children() return this.$items.index(this.$active) } Carousel.prototype.to = function (pos) { var that = this var activeIndex = this.getActiveIndex() if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) return this.$element.one('slid', function () { that.to(pos) }) if (activeIndex == pos) return this.pause().cycle() return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos])) } Carousel.prototype.pause = function (e) { e || (this.paused = true) if (this.$element.find('.next, .prev').length && $.support.transition.end) { this.$element.trigger($.support.transition.end) this.cycle(true) } this.interval = clearInterval(this.interval) return this } Carousel.prototype.next = function () { if (this.sliding) return return this.slide('next') } Carousel.prototype.prev = function () { if (this.sliding) return return this.slide('prev') } Carousel.prototype.slide = function (type, next) { var $active = this.$element.find('.item.active') var $next = next || $active[type]() var isCycling = this.interval var direction = type == 'next' ? 'left' : 'right' var fallback = type == 'next' ? 'first' : 'last' var that = this if (!$next.length) { if (!this.options.wrap) return $next = this.$element.find('.item')[fallback]() } this.sliding = true isCycling && this.pause() var e = $.Event('slide.bs.carousel', { relatedTarget: $next[0], direction: direction }) if ($next.hasClass('active')) return if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') this.$element.one('slid', function () { var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()]) $nextIndicator && $nextIndicator.addClass('active') }) } if ($.support.transition && this.$element.hasClass('slide')) { this.$element.trigger(e) if (e.isDefaultPrevented()) return $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) $active .one($.support.transition.end, function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger('slid') }, 0) }) .emulateTransitionEnd(600) } else { this.$element.trigger(e) if (e.isDefaultPrevented()) return $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger('slid') } isCycling && this.cycle() return this } // CAROUSEL PLUGIN DEFINITION // ========================== var old = $.fn.carousel $.fn.carousel = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.carousel') var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option) var action = typeof option == 'string' ? option : options.slide if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } $.fn.carousel.Constructor = Carousel // CAROUSEL NO CONFLICT // ==================== $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } // CAROUSEL DATA-API // ================= $(document).on('click.bs.carousel.data-api', '[data-slide], [data-slide-to]', function (e) { var $this = $(this), href var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 var options = $.extend({}, $target.data(), $this.data()) var slideIndex = $this.attr('data-slide-to') if (slideIndex) options.interval = false $target.carousel(options) if (slideIndex = $this.attr('data-slide-to')) { $target.data('bs.carousel').to(slideIndex) } e.preventDefault() }) $(window).on('load', function () { $('[data-ride="carousel"]').each(function () { var $carousel = $(this) $carousel.carousel($carousel.data()) }) }) }(window.jQuery); /* ======================================================================== * Bootstrap: collapse.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#collapse * ======================================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // COLLAPSE PUBLIC CLASS DEFINITION // ================================ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, Collapse.DEFAULTS, options) this.transitioning = null if (this.options.parent) this.$parent = $(this.options.parent) if (this.options.toggle) this.toggle() } Collapse.DEFAULTS = { toggle: true } Collapse.prototype.dimension = function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } Collapse.prototype.show = function () { if (this.transitioning || this.$element.hasClass('in')) return var startEvent = $.Event('show.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var actives = this.$parent && this.$parent.find('> .panel > .in') if (actives && actives.length) { var hasData = actives.data('bs.collapse') if (hasData && hasData.transitioning) return actives.collapse('hide') hasData || actives.data('bs.collapse', null) } var dimension = this.dimension() this.$element .removeClass('collapse') .addClass('collapsing') [dimension](0) this.transitioning = 1 var complete = function () { this.$element .removeClass('collapsing') .addClass('in') [dimension]('auto') this.transitioning = 0 this.$element.trigger('shown.bs.collapse') } if (!$.support.transition) return complete.call(this) var scrollSize = $.camelCase(['scroll', dimension].join('-')) this.$element .one($.support.transition.end, $.proxy(complete, this)) .emulateTransitionEnd(350) [dimension](this.$element[0][scrollSize]) } Collapse.prototype.hide = function () { if (this.transitioning || !this.$element.hasClass('in')) return var startEvent = $.Event('hide.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var dimension = this.dimension() this.$element [dimension](this.$element[dimension]()) [0].offsetHeight this.$element .addClass('collapsing') .removeClass('collapse') .removeClass('in') this.transitioning = 1 var complete = function () { this.transitioning = 0 this.$element .trigger('hidden.bs.collapse') .removeClass('collapsing') .addClass('collapse') } if (!$.support.transition) return complete.call(this) this.$element [dimension](0) .one($.support.transition.end, $.proxy(complete, this)) .emulateTransitionEnd(350) } Collapse.prototype.toggle = function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } // COLLAPSE PLUGIN DEFINITION // ========================== var old = $.fn.collapse $.fn.collapse = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.collapse') var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.collapse.Constructor = Collapse // COLLAPSE NO CONFLICT // ==================== $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } // COLLAPSE DATA-API // ================= $(document).on('click.bs.collapse.data-api', '[data-toggle=collapse]', function (e) { var $this = $(this), href var target = $this.attr('data-target') || e.preventDefault() || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7 var $target = $(target) var data = $target.data('bs.collapse') var option = data ? 'toggle' : $this.data() var parent = $this.attr('data-parent') var $parent = parent && $(parent) if (!data || !data.transitioning) { if ($parent) $parent.find('[data-toggle=collapse][data-parent="' + parent + '"]').not($this).addClass('collapsed') $this[$target.hasClass('in') ? 'addClass' : 'removeClass']('collapsed') } $target.collapse(option) }) }(window.jQuery); /* ======================================================================== * Bootstrap: dropdown.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#dropdowns * ======================================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // DROPDOWN CLASS DEFINITION // ========================= var backdrop = '.dropdown-backdrop' var toggle = '[data-toggle=dropdown]' var Dropdown = function (element) { var $el = $(element).on('click.bs.dropdown', this.toggle) } Dropdown.prototype.toggle = function (e) { var $this = $(this) if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') clearMenus() if (!isActive) { if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) { // if mobile we we use a backdrop because click events don't delegate $('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus) } $parent.trigger(e = $.Event('show.bs.dropdown')) if (e.isDefaultPrevented()) return $parent .toggleClass('open') .trigger('shown.bs.dropdown') $this.focus() } return false } Dropdown.prototype.keydown = function (e) { if (!/(38|40|27)/.test(e.keyCode)) return var $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') if (!isActive || (isActive && e.keyCode == 27)) { if (e.which == 27) $parent.find(toggle).focus() return $this.click() } var $items = $('[role=menu] li:not(.divider):visible a', $parent) if (!$items.length) return var index = $items.index($items.filter(':focus')) if (e.keyCode == 38 && index > 0) index-- // up if (e.keyCode == 40 && index < $items.length - 1) index++ // down if (!~index) index=0 $items.eq(index).focus() } function clearMenus() { $(backdrop).remove() $(toggle).each(function (e) { var $parent = getParent($(this)) if (!$parent.hasClass('open')) return $parent.trigger(e = $.Event('hide.bs.dropdown')) if (e.isDefaultPrevented()) return $parent.removeClass('open').trigger('hidden.bs.dropdown') }) } function getParent($this) { var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } var $parent = selector && $(selector) return $parent && $parent.length ? $parent : $this.parent() } // DROPDOWN PLUGIN DEFINITION // ========================== var old = $.fn.dropdown $.fn.dropdown = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('dropdown') if (!data) $this.data('dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.dropdown.Constructor = Dropdown // DROPDOWN NO CONFLICT // ==================== $.fn.dropdown.noConflict = function () { $.fn.dropdown = old return this } // APPLY TO STANDARD DROPDOWN ELEMENTS // =================================== $(document) .on('click.bs.dropdown.data-api', clearMenus) .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) .on('click.bs.dropdown.data-api' , toggle, Dropdown.prototype.toggle) .on('keydown.bs.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown) }(window.jQuery); /* ======================================================================== * Bootstrap: modal.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#modals * ======================================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // MODAL CLASS DEFINITION // ====================== var Modal = function (element, options) { this.options = options this.$element = $(element) this.$backdrop = this.isShown = null if (this.options.remote) this.$element.load(this.options.remote) } Modal.DEFAULTS = { backdrop: true , keyboard: true , show: true } Modal.prototype.toggle = function (_relatedTarget) { return this[!this.isShown ? 'show' : 'hide'](_relatedTarget) } Modal.prototype.show = function (_relatedTarget) { var that = this var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget }) this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.escape() this.$element.on('click.dismiss.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this)) this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(document.body) // don't move modals dom position } that.$element.show() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget }) transition ? that.$element.find('.modal-dialog') // wait for modal to slide in .one($.support.transition.end, function () { that.$element.focus().trigger(e) }) .emulateTransitionEnd(300) : that.$element.focus().trigger(e) }) } Modal.prototype.hide = function (e) { if (e) e.preventDefault() e = $.Event('hide.bs.modal') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() $(document).off('focusin.bs.modal') this.$element .removeClass('in') .attr('aria-hidden', true) .off('click.dismiss.modal') $.support.transition && this.$element.hasClass('fade') ? this.$element .one($.support.transition.end, $.proxy(this.hideModal, this)) .emulateTransitionEnd(300) : this.hideModal() } Modal.prototype.enforceFocus = function () { $(document) .off('focusin.bs.modal') // guard against infinite focus loop .on('focusin.bs.modal', $.proxy(function (e) { if (this.$element[0] !== e.target && !this.$element.has(e.target).length) { this.$element.focus() } }, this)) } Modal.prototype.escape = function () { if (this.isShown && this.options.keyboard) { this.$element.on('keyup.dismiss.bs.modal', $.proxy(function (e) { e.which == 27 && this.hide() }, this)) } else if (!this.isShown) { this.$element.off('keyup.dismiss.bs.modal') } } Modal.prototype.hideModal = function () { var that = this this.$element.hide() this.backdrop(function () { that.removeBackdrop() $(".modal-backdrop").remove(); that.$element.trigger('hidden.bs.modal') }) } Modal.prototype.removeBackdrop = function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } Modal.prototype.backdrop = function (callback) { var that = this var animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />') .appendTo(document.body) this.$element.on('click.dismiss.modal', $.proxy(function (e) { if (e.target !== e.currentTarget) return this.options.backdrop == 'static' ? this.$element[0].focus.call(this.$element[0]) : this.hide.call(this) }, this)) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop .one($.support.transition.end, callback) .emulateTransitionEnd(150) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') $.support.transition && this.$element.hasClass('fade')? this.$backdrop .one($.support.transition.end, callback) .emulateTransitionEnd(150) : callback() } else if (callback) { callback() } } // MODAL PLUGIN DEFINITION // ======================= var old = $.fn.modal $.fn.modal = function (option, _relatedTarget) { return this.each(function () { var $this = $(this) var data = $this.data('bs.modal') var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option](_relatedTarget) else if (options.show) data.show(_relatedTarget) }) } $.fn.modal.Constructor = Modal // MODAL NO CONFLICT // ================= $.fn.modal.noConflict = function () { $.fn.modal = old return this } // MODAL DATA-API // ============== $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) var href = $this.attr('href') var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7 var option = $target.data('modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data()) e.preventDefault() $target .modal(option, this) .one('hide', function () { $this.is(':visible') && $this.focus() }) }) $(document) .on('show.bs.modal', '.modal', function () { $(document.body).addClass('modal-open') }) .on('hidden.bs.modal', '.modal', function () { $(document.body).removeClass('modal-open') }) }(window.jQuery); /* ======================================================================== * Bootstrap: tooltip.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#tooltip * Inspired by the original jQuery.tipsy by Jason Frame * ======================================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // TOOLTIP PUBLIC CLASS DEFINITION // =============================== var Tooltip = function (element, options) { this.type = this.options = this.enabled = this.timeout = this.hoverState = this.$element = null this.init('tooltip', element, options) } Tooltip.DEFAULTS = { animation: true , placement: 'top' , selector: false , template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>' , trigger: 'hover focus' , title: '' , delay: 0 , html: false , container: false } Tooltip.prototype.init = function (type, element, options) { this.enabled = true this.type = type this.$element = $(element) this.options = this.getOptions(options) var triggers = this.options.trigger.split(' ') for (var i = triggers.length; i--;) { var trigger = triggers[i] if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { var eventIn = trigger == 'hover' ? 'mouseenter' : 'focus' var eventOut = trigger == 'hover' ? 'mouseleave' : 'blur' this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) } } this.options.selector ? (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) : this.fixTitle() } Tooltip.prototype.getDefaults = function () { return Tooltip.DEFAULTS } Tooltip.prototype.getOptions = function (options) { options = $.extend({}, this.getDefaults(), this.$element.data(), options) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay , hide: options.delay } } return options } Tooltip.prototype.getDelegateOptions = function () { var options = {} var defaults = this.getDefaults() this._options && $.each(this._options, function (key, value) { if (defaults[key] != value) options[key] = value }) return options } Tooltip.prototype.enter = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) clearTimeout(self.timeout) self.hoverState = 'in' if (!self.options.delay || !self.options.delay.show) return self.show() self.timeout = setTimeout(function () { if (self.hoverState == 'in') self.show() }, self.options.delay.show) } Tooltip.prototype.leave = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) clearTimeout(self.timeout) self.hoverState = 'out' if (!self.options.delay || !self.options.delay.hide) return self.hide() self.timeout = setTimeout(function () { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } Tooltip.prototype.show = function () { var e = $.Event('show.bs.'+ this.type) if (this.hasContent() && this.enabled) { this.$element.trigger(e) if (e.isDefaultPrevented()) return var $tip = this.tip() this.setContent() if (this.options.animation) $tip.addClass('fade') var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement var autoToken = /\s?auto?\s?/i var autoPlace = autoToken.test(placement) if (autoPlace) placement = placement.replace(autoToken, '') || 'top' $tip .detach() .css({ top: 0, left: 0, display: 'block' }) .addClass(placement) this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) var pos = this.getPosition() var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (autoPlace) { var $parent = this.$element.parent() var orgPlacement = placement var docScroll = document.documentElement.scrollTop || document.body.scrollTop var parentWidth = this.options.container == 'body' ? window.innerWidth : $parent.outerWidth() var parentHeight = this.options.container == 'body' ? window.innerHeight : $parent.outerHeight() var parentLeft = this.options.container == 'body' ? 0 : $parent.offset().left placement = placement == 'bottom' && pos.top + pos.height + actualHeight - docScroll > parentHeight ? 'top' : placement == 'top' && pos.top - docScroll - actualHeight < 0 ? 'bottom' : placement == 'right' && pos.right + actualWidth > parentWidth ? 'left' : placement == 'left' && pos.left - actualWidth < parentLeft ? 'right' : placement $tip .removeClass(orgPlacement) .addClass(placement) } var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight) this.applyPlacement(calculatedOffset, placement) this.$element.trigger('shown.bs.' + this.type) } } Tooltip.prototype.applyPlacement = function(offset, placement) { var replace var $tip = this.tip() var width = $tip[0].offsetWidth var height = $tip[0].offsetHeight // manually read margins because getBoundingClientRect includes difference var marginTop = parseInt($tip.css('margin-top'), 10) var marginLeft = parseInt($tip.css('margin-left'), 10) // we must check for NaN for ie 8/9 if (isNaN(marginTop)) marginTop = 0 if (isNaN(marginLeft)) marginLeft = 0 offset.top = offset.top + marginTop offset.left = offset.left + marginLeft $tip .offset(offset) .addClass('in') // check to see if placing tip in new offset caused the tip to resize itself var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (placement == 'top' && actualHeight != height) { replace = true offset.top = offset.top + height - actualHeight } if (/bottom|top/.test(placement)) { var delta = 0 if (offset.left < 0) { delta = offset.left * -2 offset.left = 0 $tip.offset(offset) actualWidth = $tip[0].offsetWidth actualHeight = $tip[0].offsetHeight } this.replaceArrow(delta - width + actualWidth, actualWidth, 'left') } else { this.replaceArrow(actualHeight - height, actualHeight, 'top') } if (replace) $tip.offset(offset) } Tooltip.prototype.replaceArrow = function(delta, dimension, position) { this.arrow().css(position, delta ? (50 * (1 - delta / dimension) + "%") : '') } Tooltip.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) $tip.removeClass('fade in top bottom left right') } Tooltip.prototype.hide = function () { var that = this var $tip = this.tip() var e = $.Event('hide.bs.' + this.type) function complete() { if (that.hoverState != 'in') $tip.detach() } this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') $.support.transition && this.$tip.hasClass('fade') ? $tip .one($.support.transition.end, complete) .emulateTransitionEnd(150) : complete() this.$element.trigger('hidden.bs.' + this.type) return this } Tooltip.prototype.fixTitle = function () { var $e = this.$element if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') { $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } } Tooltip.prototype.hasContent = function () { return this.getTitle() } Tooltip.prototype.getPosition = function () { var el = this.$element[0] return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : { width: el.offsetWidth , height: el.offsetHeight }, this.$element.offset()) } Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) { return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } : /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width } } Tooltip.prototype.getTitle = function () { var title var $e = this.$element var o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } Tooltip.prototype.tip = function () { return this.$tip = this.$tip || $(this.options.template) } Tooltip.prototype.arrow = function () { return this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow') } Tooltip.prototype.validate = function () { if (!this.$element[0].parentNode) { this.hide() this.$element = null this.options = null } } Tooltip.prototype.enable = function () { this.enabled = true } Tooltip.prototype.disable = function () { this.enabled = false } Tooltip.prototype.toggleEnabled = function () { this.enabled = !this.enabled } Tooltip.prototype.toggle = function (e) { var self = e ? $(e.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) : this self.tip().hasClass('in') ? self.leave(self) : self.enter(self) } Tooltip.prototype.destroy = function () { this.hide().$element.off('.' + this.type).removeData('bs.' + this.type) } // TOOLTIP PLUGIN DEFINITION // ========================= var old = $.fn.tooltip $.fn.tooltip = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tooltip') var options = typeof option == 'object' && option if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.tooltip.Constructor = Tooltip // TOOLTIP NO CONFLICT // =================== $.fn.tooltip.noConflict = function () { $.fn.tooltip = old return this } }(window.jQuery); /* ======================================================================== * Bootstrap: popover.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#popovers * ======================================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // POPOVER PUBLIC CLASS DEFINITION // =============================== var Popover = function (element, options) { this.init('popover', element, options) } if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js') Popover.DEFAULTS = $.extend({} , $.fn.tooltip.Constructor.DEFAULTS, { placement: 'right' , trigger: 'click' , content: '' , template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' }) // NOTE: POPOVER EXTENDS tooltip.js // ================================ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype) Popover.prototype.constructor = Popover Popover.prototype.getDefaults = function () { return Popover.DEFAULTS } Popover.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() var content = this.getContent() $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title) $tip.find('.popover-content')[this.options.html ? 'html' : 'text'](content) $tip.removeClass('fade top bottom left right in') // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do // this manually by checking the contents. if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide() } Popover.prototype.hasContent = function () { return this.getTitle() || this.getContent() } Popover.prototype.getContent = function () { var $e = this.$element var o = this.options return $e.attr('data-content') || (typeof o.content == 'function' ? o.content.call($e[0]) : o.content) } Popover.prototype.arrow = function () { return this.$arrow = this.$arrow || this.tip().find('.arrow') } Popover.prototype.tip = function () { if (!this.$tip) this.$tip = $(this.options.template) return this.$tip } // POPOVER PLUGIN DEFINITION // ========================= var old = $.fn.popover $.fn.popover = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.popover') var options = typeof option == 'object' && option if (!data) $this.data('bs.popover', (data = new Popover(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.popover.Constructor = Popover // POPOVER NO CONFLICT // =================== $.fn.popover.noConflict = function () { $.fn.popover = old return this } }(window.jQuery); /* ======================================================================== * Bootstrap: scrollspy.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#scrollspy * ======================================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // SCROLLSPY CLASS DEFINITION // ========================== function ScrollSpy(element, options) { var href var process = $.proxy(this.process, this) this.$element = $(element).is('body') ? $(window) : $(element) this.$body = $('body') this.$scrollElement = this.$element.on('scroll.bs.scroll-spy.data-api', process) this.options = $.extend({}, ScrollSpy.DEFAULTS, options) this.selector = (this.options.target || ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 || '') + ' .nav li > a' this.offsets = $([]) this.targets = $([]) this.activeTarget = null this.refresh() this.process() } ScrollSpy.DEFAULTS = { offset: 10 } ScrollSpy.prototype.refresh = function () { var offsetMethod = this.$element[0] == window ? 'offset' : 'position' this.offsets = $([]) this.targets = $([]) var self = this var $targets = this.$body .find(this.selector) .map(function () { var $el = $(this) var href = $el.data('target') || $el.attr('href') var $href = /^#\w/.test(href) && $(href) return ($href && $href.length && [[ $href[offsetMethod]().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href ]]) || null }) .sort(function (a, b) { return a[0] - b[0] }) .each(function () { self.offsets.push(this[0]) self.targets.push(this[1]) }) } ScrollSpy.prototype.process = function () { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset var scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight var maxScroll = scrollHeight - this.$scrollElement.height() var offsets = this.offsets var targets = this.targets var activeTarget = this.activeTarget var i if (scrollTop >= maxScroll) { return activeTarget != (i = targets.last()[0]) && this.activate(i) } for (i = offsets.length; i--;) { activeTarget != targets[i] && scrollTop >= offsets[i] && (!offsets[i + 1] || scrollTop <= offsets[i + 1]) && this.activate( targets[i] ) } } ScrollSpy.prototype.activate = function (target) { this.activeTarget = target $(this.selector) .parents('.active') .removeClass('active') var selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' var active = $(selector) .parents('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active .closest('li.dropdown') .addClass('active') } active.trigger('activate') } // SCROLLSPY PLUGIN DEFINITION // =========================== var old = $.fn.scrollspy $.fn.scrollspy = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.scrollspy') var options = typeof option == 'object' && option if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.scrollspy.Constructor = ScrollSpy // SCROLLSPY NO CONFLICT // ===================== $.fn.scrollspy.noConflict = function () { $.fn.scrollspy = old return this } // SCROLLSPY DATA-API // ================== $(window).on('load', function () { $('[data-spy="scroll"]').each(function () { var $spy = $(this) $spy.scrollspy($spy.data()) }) }) }(window.jQuery); /* ======================================================================== * Bootstrap: tab.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#tabs * ======================================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // TAB CLASS DEFINITION // ==================== var Tab = function (element) { this.element = $(element) } Tab.prototype.show = function () { var $this = this.element var $ul = $this.closest('ul:not(.dropdown-menu)') var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } if ($this.parent('li').hasClass('active')) return var previous = $ul.find('.active:last a')[0] var e = $.Event('show.bs.tab', { relatedTarget: previous }) $this.trigger(e) if (e.isDefaultPrevented()) return var $target = $(selector) this.activate($this.parent('li'), $ul) this.activate($target, $target.parent(), function () { $this.trigger({ type: 'shown.bs.tab' , relatedTarget: previous }) }) } Tab.prototype.activate = function (element, container, callback) { var $active = container.find('> .active') var transition = callback && $.support.transition && $active.hasClass('fade') function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') element.addClass('active') if (transition) { element[0].offsetWidth // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if (element.parent('.dropdown-menu')) { element.closest('li.dropdown').addClass('active') } callback && callback() } transition ? $active .one($.support.transition.end, next) .emulateTransitionEnd(150) : next() $active.removeClass('in') } // TAB PLUGIN DEFINITION // ===================== var old = $.fn.tab $.fn.tab = function ( option ) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tab') if (!data) $this.data('bs.tab', (data = new Tab(this))) if (typeof option == 'string') data[option]() }) } $.fn.tab.Constructor = Tab // TAB NO CONFLICT // =============== $.fn.tab.noConflict = function () { $.fn.tab = old return this } // TAB DATA-API // ============ $(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) { e.preventDefault() $(this).tab('show') }) }(window.jQuery); /* ======================================================================== * Bootstrap: affix.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#affix * ======================================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // AFFIX CLASS DEFINITION // ====================== var Affix = function (element, options) { this.options = $.extend({}, Affix.DEFAULTS, options) this.$window = $(window) .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this)) this.$element = $(element) this.affixed = this.unpin = null this.checkPosition() } Affix.RESET = 'affix affix-top affix-bottom' Affix.DEFAULTS = { offset: 0 } Affix.prototype.checkPositionWithEventLoop = function () { setTimeout($.proxy(this.checkPosition, this), 1) } Affix.prototype.checkPosition = function () { if (!this.$element.is(':visible')) return var scrollHeight = $(document).height() var scrollTop = this.$window.scrollTop() var position = this.$element.offset() var offset = this.options.offset var offsetTop = offset.top var offsetBottom = offset.bottom if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top() if (typeof offsetBottom == 'function') offsetBottom = offset.bottom() var affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false : offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' : offsetTop != null && (scrollTop <= offsetTop) ? 'top' : false if (this.affixed === affix) return if (this.unpin) this.$element.css('top', '') this.affixed = affix this.unpin = affix == 'bottom' ? position.top - scrollTop : null this.$element.removeClass(Affix.RESET).addClass('affix' + (affix ? '-' + affix : '')) if (affix == 'bottom') { this.$element.offset({ top: document.body.offsetHeight - offsetBottom - this.$element.height() }) } } // AFFIX PLUGIN DEFINITION // ======================= var old = $.fn.affix $.fn.affix = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.affix') var options = typeof option == 'object' && option if (!data) $this.data('bs.affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.affix.Constructor = Affix // AFFIX NO CONFLICT // ================= $.fn.affix.noConflict = function () { $.fn.affix = old return this } // AFFIX DATA-API // ============== $(window).on('load', function () { $('[data-spy="affix"]').each(function () { var $spy = $(this) var data = $spy.data() data.offset = data.offset || {} if (data.offsetBottom) data.offset.bottom = data.offsetBottom if (data.offsetTop) data.offset.top = data.offsetTop $spy.affix(data) }) }) }(window.jQuery);
mit
neermitt/ng2-highcharts
webpack.config.js
1613
'use strict'; var webpack = require('webpack'); var path = require('path'); var srcPath = path.join(__dirname, 'demo'); var production = -1 < process.argv.indexOf('--dist'); console.log('production', production); var outPath = production ? 'dist' : 'build'; var devtool = production ? 'source-map' : 'eval-source-map'; var config = { target: 'web', cache: true, entry: { app: path.join(srcPath, 'bootstrap.ts'), common: [ 'angular2/bundles/angular2-polyfills', 'jquery/dist/jquery', 'highcharts/highcharts' ] }, resolve: { root: srcPath, extensions: ['', '.js', '.ts'], modulesDirectories: ['node_modules'], alias: {} }, output: { path: path.join(__dirname, 'demo', outPath), publicPath: '', filename: '[name].js', pathInfo: true }, module: { noParse: [], loaders: [ { test: /\.ts$/, loader: 'ts' }, {test: /\.css$/, loader: 'style!raw'}, {test: /\.html/, loader: 'html'} ] }, ts: { configFileName: 'tsconfig.demo.json' }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: 'common', filename: 'common.js', minChunks: Infinity }), new webpack.NoErrorsPlugin() ], debug: true, devtool: devtool }; if (production) { // TODO: enable once I figure out how to stop it from erroring on my // raw TypeScript imports in the demo app. /*config.plugins.push(new webpack.optimize.UglifyJsPlugin({ mangle: false }));*/ //config.plugins.push(new webpack.optimize.OccurrenceOrderPlugin(true)); } module.exports = config;
mit
moqada/github-wiki-notifier
src/utils/env.js
215
const PREFIX = 'GHWIKINOTIFIER_'; /** * Get environment variables * * @param {string} name variable name * @return {string|undefined} */ export function get(name) { return process.env[`${PREFIX}${name}`]; }
mit
thorstenwagner/TraJ
src/main/java/de/biomedical_imaging/traJ/features/MeanSquaredDisplacmentFeature.java
4347
/* The MIT License (MIT) Copyright (c) 2015 Thorsten Wagner (wagner@biomedical-imaging.de) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package de.biomedical_imaging.traJ.features; import de.biomedical_imaging.traJ.Trajectory; import de.biomedical_imaging.traJ.TrajectoryValidIndexTimelagIterator; /** * Calculates the mean squared displacement * @author Thorsten Wagner (wagner at biomedical - imaging.de * */ public class MeanSquaredDisplacmentFeature extends AbstractTrajectoryFeature implements AbstractMeanSquaredDisplacmentEvaluator { private Trajectory t; private int timelag; private boolean overlap =false; /** * * @param t Trajectory for which the MSD is to be calculated. * @param timelag Timeleg for msd caluclation (>= 1) */ public MeanSquaredDisplacmentFeature(Trajectory t, int timelag) { this.t = t; this.timelag = timelag; } public void setTimelag(int timelag){ this.timelag = timelag; } public void setTrajectory(Trajectory t){ this.t = t; result =null; } /** * * Calculates the mean squared displacement (MSD). Further more it calculates * the relative variance of MSD according to: * S. Huet, E. Karatekin, V. S. Tran, I. Fanget, S. Cribier, and J.-P. Henry, * “Analysis of transient behavior in complex trajectories: application to secretory vesicle dynamics.,” * Biophys. J., vol. 91, no. 9, pp. 3542–3559, 2006. * * @param t Trajectory * @param timelag * @return */ private double[] getMeanSquaredDisplacment(Trajectory t, int timelag){ double msd = 0; double[] result = new double[3]; if(t.size()==1){ result[0] =0; result[1] =0; result[2] =1; return result; } if(timelag<1){ throw new IllegalArgumentException("Timelag can not be smaller than 1"); } TrajectoryValidIndexTimelagIterator it = new TrajectoryValidIndexTimelagIterator(t, timelag,overlap); int N = 0; while(it.hasNext()){ int i = it.next(); msd = msd + Math.pow(t.get(i).getX()-t.get(i+timelag).getX(),2) + Math.pow(t.get(i).getY()-t.get(i+timelag).getY(),2) + Math.pow(t.get(i).getZ()-t.get(i+timelag).getZ(),2); N++; } msd = msd/N; result[0] = msd; result[1] = (timelag*(2*timelag*timelag+1.0))/(N-timelag+1.0); //Variance result[2] = N; //Number of data points return result; } @Override /** * @return An double array with elements [0] = Mean squared displacment (in length unit squared), [1] = estimated variance, [2] = number of used datapoints */ public double[] evaluate() { // TODO Auto-generated method stub return getMeanSquaredDisplacment(t, timelag); } /** * * @return Return the relative variance of MSD according formula (6) of: * S. Huet, E. Karatekin, V. S. Tran, I. Fanget, S. Cribier, and J.-P. Henry, * “Analysis of transient behavior in complex trajectories: application to secretory vesicle dynamics.,” * Biophys. J., vol. 91, no. 9, pp. 3542–3559, 2006. */ public double getRelativeVariance() { return getMeanSquaredDisplacment(t, timelag)[1]; } @Override public String getName() { // TODO Auto-generated method stub return "Mean squared displacement-dt-"+timelag; } @Override public String getShortName() { // TODO Auto-generated method stub return "MSD"; } public void setOverlap(boolean overlap){ this.overlap = overlap; } }
mit
cloudteams/designs
src/views/user/dashboard/profile/index.php
630
<?php include("../partials/header.php"); ?> <section class="page page-user-dashboard-projects dashboard-page user-dashboard-page"> <div class="container"> <div class="content"> <div class="row"> <?php include("../partials/side-menu.php"); ?> <main> <header class="main-header"> <div class="vertical-align"> <div class="middle"> <i class="icon icon-profile"></i> <h1 class="header-large">Edit profile</h1> </div> </div> </header> <?php include("content.php"); ?> </main> </div> </div> </div> </section> <?php include("../partials/footer.php"); ?>
mit
avajs/eslint-plugin-ava
rules/prefer-power-assert.js
1694
'use strict'; const {isDeepStrictEqual} = require('util'); const espurify = require('espurify'); const {visitIf} = require('enhance-visitors'); const createAvaRule = require('../create-ava-rule'); const util = require('../util'); const notAllowed = [ 'truthy', 'true', 'falsy', 'false', 'is', 'not', 'regex', 'notRegex', 'ifError', ]; const assertionCalleeAst = methodName => ({ type: 'MemberExpression', object: { type: 'Identifier', name: 't', }, property: { type: 'Identifier', name: methodName, }, computed: false, }); const skippedAssertionCalleeAst = methodName => ({ type: 'MemberExpression', object: { type: 'MemberExpression', object: { type: 'Identifier', name: 't', }, property: { type: 'Identifier', name: 'skip', }, computed: false, }, property: { type: 'Identifier', name: methodName, }, computed: false, }); const isCalleeMatched = (callee, methodName) => isDeepStrictEqual(callee, assertionCalleeAst(methodName)) || isDeepStrictEqual(callee, skippedAssertionCalleeAst(methodName)); const create = context => { const ava = createAvaRule(); return ava.merge({ CallExpression: visitIf([ ava.isInTestFile, ava.isInTestNode, ])(node => { const callee = espurify(node.callee); if (callee.type === 'MemberExpression') { for (const methodName of notAllowed) { if (isCalleeMatched(callee, methodName)) { context.report({ node, message: 'Only asserts with no power-assert alternative are allowed.', }); } } } }), }); }; module.exports = { create, meta: { type: 'suggestion', docs: { url: util.getDocsUrl(__filename), }, schema: [], }, };
mit
msegers/ng2-blog
app/components/contact/contact.ts
858
import {Component, View, NgFor} from 'angular2/angular2'; //import {forms, required, formDirectives, materialDesign, FormBuilder} from 'angular2/forms'; @Component({ selector: 'contact', }) @View({ templateUrl: './components/contact/contact.html', directives: [NgFor] }) export class Contact { //contactForm:ControlGroup; // builder:FormBuilder; // constructor(b:FormBuilder) { // this.builder = b; // // this.myForm = b.group({ // name: ["", required], // required // email: ["", required] // optional // }); // // // save changes to Firebase as the form updates //// this.myForm.valueChanges.subscribe(function(value) { //// this.ref.set(value); //// }.bind(this)); // } } function zipCodeValidator(control) { if (! control.value.match(/\d\d\d\d\d(-\d\d\d\d)?/)){ return {invalidZipCode: true}; } }
mit
Teknikaali/BenchmarkDotNet
src/BenchmarkDotNet.Disassembler.x64/ClrSourceExtensions.cs
4888
using Microsoft.Diagnostics.Runtime; using Microsoft.Diagnostics.Runtime.Utilities; using Microsoft.Diagnostics.Runtime.Utilities.Pdb; using System; using System.Collections.Generic; using System.IO; namespace Microsoft.Diagnostics.RuntimeExt { // This is taken from the Samples\FileAndLineNumbers projects from microsoft/clrmd, // and replaces the previously-available SourceLocation functionality. public class SourceLocation { public string FilePath; public int LineNumber; public int LineNumberEnd; public int ColStart; public int ColEnd; } public static class ClrSourceExtensions { // TODO Not sure we want this to be a shared dictionary, especially without // any synchronization. Probably want to put this hanging off the Context // somewhere, or inside SymbolCache. static Dictionary<PdbInfo, PdbReader> s_pdbReaders = new Dictionary<PdbInfo, PdbReader>(); public static SourceLocation GetSourceLocation(this ClrMethod method, int ilOffset) { PdbReader reader = GetReaderForMethod(method); if (reader == null) return null; PdbFunction function = reader.GetFunctionFromToken(method.MetadataToken); return FindNearestLine(function, ilOffset); } public static SourceLocation GetSourceLocation(this ClrStackFrame frame) { PdbReader reader = GetReaderForMethod(frame.Method); if (reader == null) return null; PdbFunction function = reader.GetFunctionFromToken(frame.Method.MetadataToken); int ilOffset = FindIlOffset(frame); return FindNearestLine(function, ilOffset); } private static SourceLocation FindNearestLine(PdbFunction function, int ilOffset) { int distance = int.MaxValue; SourceLocation nearest = null; foreach (PdbSequencePointCollection sequenceCollection in function.SequencePoints) { foreach (PdbSequencePoint point in sequenceCollection.Lines) { int dist = (int)Math.Abs(point.Offset - ilOffset); if (dist < distance) { if (nearest == null) nearest = new SourceLocation(); nearest.FilePath = sequenceCollection.File.Name; nearest.LineNumber = (int)point.LineBegin; nearest.LineNumberEnd = (int)point.LineEnd; nearest.ColStart = (int)point.ColBegin; nearest.ColEnd = (int)point.ColEnd; distance = dist; } } } return nearest; } private static int FindIlOffset(ClrStackFrame frame) { ulong ip = frame.InstructionPointer; int last = -1; foreach (ILToNativeMap item in frame.Method.ILOffsetMap) { if (item.StartAddress > ip) return last; if (ip <= item.EndAddress) return item.ILOffset; last = item.ILOffset; } return last; } private static PdbReader GetReaderForMethod(ClrMethod method) { ClrModule module = method?.Type?.Module; PdbInfo info = module?.Pdb; PdbReader reader = null; if (info != null) { if (!s_pdbReaders.TryGetValue(info, out reader)) { SymbolLocator locator = GetSymbolLocator(module); string pdbPath = locator.FindPdb(info); if (pdbPath != null) { try { reader = new PdbReader(pdbPath); } catch (IOException) { // This will typically happen when trying to load information // from public symbols, or symbol files generated by some weird // compiler. We can ignore this, but there's no need to load // this PDB anymore, so we will put null in the dictionary and // be done with it. reader = null; } } s_pdbReaders[info] = reader; } } return reader; } private static SymbolLocator GetSymbolLocator(ClrModule module) { return module.Runtime.DataTarget.SymbolLocator; } } }
mit
robertlemke/flow-development-collection
TYPO3.Flow/Classes/TYPO3/Flow/Cache/Exception/ClassAlreadyLoadedException.php
634
<?php namespace TYPO3\Flow\Cache\Exception; /* * * This script belongs to the Flow framework. * * * * It is free software; you can redistribute it and/or modify it under * * the terms of the MIT license. * * */ /** * A "Class Already Loaded" exception * * @api */ class ClassAlreadyLoadedException extends \TYPO3\Flow\Cache\Exception { }
mit
galaxykate/Stellar2014
js/modules/shared/common/rect.js
4057
/** * @author Kate Compton */ // Reusable Vector class define(["./vector"], function(Vector) { var Rect = Class.extend({ // use as init(x, y, w, h) or init(position:Vector, dimensions:Vector) init : function() { if (arguments.length == 4) { this.x = arguments[0]; this.y = arguments[1]; this.w = arguments[2]; this.h = arguments[3]; } else if (arguments.length === 2) { this.x = arguments[0].x; this.y = arguments[0].y; this.w = arguments[1].x; this.h = arguments[1].y; } else { this.w = 0; this.h = 0; } }, clone : function() { return new Rect(this.x, this.y, this.w, this.h); }, setPosition : function(p) { if (arguments.length == 2) { this.x = arguments[0]; this.y = arguments[1]; } else { this.x = p.x; this.y = p.y; } }, setDimensions : function(p) { if (arguments.length == 2) { this.w = arguments[0]; this.h = arguments[1]; } else { this.w = p.x; this.h = p.y; } }, // return the Vectors of the corners getCorners : function(ccw) { var x0 = this.x + this.w; var x1 = this.x; var y0 = this.y; var y1 = this.y + this.h; if (ccw) return [new Vector(x0, y0), new Vector(x1, y0), new Vector(x1, y1), new Vector(x0, y1)]; return [new Vector(x0, y0), new Vector(x0, y1), new Vector(x1, y1), new Vector(x1, y0)]; }, stretchToContainBox : function(b) { var box = this; var c = b.getCorners(); $.each(c, function(index, corner) { box.stretchToContainPoint(corner); }); }, stretchToContainPoint : function(pt) { if (this.x === undefined) this.x = pt.x; if (this.y === undefined) this.y = pt.y; if (pt.x < this.x) { this.w += this.x - pt.x; this.x = pt.x; } if (pt.y < this.y) { this.h += this.y - pt.y; this.y = pt.y; } this.w = Math.max(this.w, pt.x - this.x); this.h = Math.max(this.h, pt.y - this.y); }, getRandomPosition : function(border) { var x = this.x + border + Math.random() * (this.w - border * 2); var y = this.y + border + Math.random() * (this.h - border * 2); return new Vector(x, y); }, getSidePosition : function(side, sidePos, outset) { var x = sidePos; if (side === "left") { x = outset; } if (side === "right") { x = this.w - outset; } var y = sidePos; if (side === "top") { y = outset; } if (side === "bottom") { y = this.h - outset; } var p = new Vector(x + this.x, y + this.y); return p; }, centerTransform : function(g) { g.translate(-this.x + -this.w / 2, -this.y + -this.h / 2) }, draw : function(g) { g.rect(this.x, this.y, this.w, this.h); }, toCSS : function() { return { width : this.w + "px", height : this.h + "px", top : this.y + "px", left : this.x + "px", } }, toString : function() { return "[(" + this.x.toFixed(2) + "," + this.y.toFixed(2) + "), " + this.w.toFixed(2) + "x" + this.h.toFixed(2) + "]"; } }); return Rect; });
mit
next0/gtd
src/js/gtd.js
352
'use strict'; // imports var $ = require('jquery'), TableGTDView = require('./views/table-gtd'), StickersCollection = require('./collections/stickers'); // code var collection = new StickersCollection(); var table = new TableGTDView({ el: $('[data-ui="grid"]'), collection: collection }); collection.fetch();
mit
wcmatthysen/android-filechooser
code/src/group/pals/android/lib/ui/filechooser/utils/ui/GestureUtils.java
7345
/* * Copyright (c) 2012 Hai Bison * * See the file LICENSE at the root directory of this project for copying * permission. */ package group.pals.android.lib.ui.filechooser.utils.ui; import group.pals.android.lib.ui.filechooser.BuildConfig; import android.graphics.Rect; import android.util.Log; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.widget.AbsListView; /** * Utilities for user's gesture. * * @author Hai Bison * @since v5.1 beta * */ public class GestureUtils { public static final String _ClassName = GestureUtils.class.getName(); /** * The fling direction. * * @author Hai Bison * @since v5.1 beta * */ public static enum FlingDirection { LeftToRight, RightToLeft, Unknown }// FlingDirection /** * Calculates fling direction from two {@link MotionEvent} and their * velocity. * * @param e1 * {@link MotionEvent} * @param e2 * {@link MotionEvent} * @param velocityX * the X velocity. * @param velocityY * the Y velocity. * @return {@link FlingDirection} */ public static FlingDirection calcFlingDirection(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (e1 == null || e2 == null) return FlingDirection.Unknown; final int _max_y_distance = 19;// 10 is too short :-D final int _min_x_distance = 80; final int _min_x_velocity = 200; if (Math.abs(e1.getY() - e2.getY()) < _max_y_distance && Math.abs(e1.getX() - e2.getX()) > _min_x_distance && Math.abs(velocityX) > _min_x_velocity) { return velocityX <= 0 ? FlingDirection.LeftToRight : FlingDirection.RightToLeft; } return FlingDirection.Unknown; }// calcFlingDirection() /** * Interface for user's gesture. * * @author Hai Bison * @since v5.1 beta * */ public static interface OnGestureListener { /** * Will be called after the user did a single tap. * * @param view * the selected view. * @param data * the data. * @return {@code true} if you want to handle the event, otherwise * {@code false}. */ boolean onSingleTapConfirmed(View view, Object data); /** * Will be notified after the user flung the view. * * @param view * the selected view. * @param data * the data. * @param flingDirection * {@link FlingDirection}. * @return {@code true} if you handled this event, {@code false} if you * want to let default handler handle it. */ boolean onFling(View view, Object data, FlingDirection flingDirection); }// OnGestureListener /** * An adapter of {@link OnGestureListener}. * * @since v5.1 beta * @author Hai Bison * */ public static class SimpleOnGestureListener implements OnGestureListener { @Override public boolean onSingleTapConfirmed(View view, Object data) { return false; } @Override public boolean onFling(View view, Object data, FlingDirection flingDirection) { return false; } }// SimpleOnGestureListener /** * Adds a gesture listener to {@code listView}. * * @param listView * {@link AbsListView}. * @param listener * {@link OnGestureListener}. */ public static void setupGestureDetector(final AbsListView listView, final OnGestureListener listener) { final GestureDetector _gestureDetector = new GestureDetector(listView.getContext(), new GestureDetector.SimpleOnGestureListener() { private Object getData(float x, float y) { int i = getSubViewId(x, y); if (i >= 0) return listView.getItemAtPosition(listView.getFirstVisiblePosition() + i); return null; }// getSubView() private View getSubView(float x, float y) { int i = getSubViewId(x, y); if (i >= 0) return listView.getChildAt(i); return null; }// getSubView() private int getSubViewId(float x, float y) { Rect r = new Rect(); for (int i = 0; i < listView.getChildCount(); i++) { listView.getChildAt(i).getHitRect(r); if (r.contains((int) x, (int) y)) { if (BuildConfig.DEBUG) Log.d(_ClassName, String.format( "getSubViewId() -- left-top-right-bottom = %d-%d-%d-%d", r.left, r.top, r.right, r.bottom)); return i; } } return -1; }// getSubViewId() @Override public boolean onSingleTapConfirmed(MotionEvent e) { if (BuildConfig.DEBUG) Log.d(_ClassName, String.format("onSingleTapConfirmed() -- x = %.2f -- y = %.2f", e.getX(), e.getY())); return listener == null ? false : listener.onSingleTapConfirmed(getSubView(e.getX(), e.getY()), getData(e.getX(), e.getY())); }// onSingleTapConfirmed() @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (listener == null || e1 == null || e2 == null) return false; FlingDirection fd = calcFlingDirection(e1, e2, velocityX, velocityY); if (!FlingDirection.Unknown.equals(fd)) { if (listener.onFling(getSubView(e1.getX(), e1.getY()), getData(e1.getX(), e1.getY()), fd)) { MotionEvent cancelEvent = MotionEvent.obtain(e1); cancelEvent.setAction(MotionEvent.ACTION_CANCEL); listView.onTouchEvent(cancelEvent); } } /* * Always return false to let the default handler draw * the item properly. */ return false; }// onFling() });// _gestureDetector listView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return _gestureDetector.onTouchEvent(event); } }); }// setupGestureDetector() }
mit
octoblu/redis-interval-work-queue
main.go
420
package main import ( "log" "os" "github.com/codegangsta/cli" ) func main() { app := cli.NewApp() app.Name = "redis-interval-work-queue" app.Usage = "Run the work queue" app.Action = processQueue app.Run(os.Args) } func processQueue(context *cli.Context) { queue := NewProcessQueue() for { if err := queue.Process(); err != nil { log.Fatalf("Error occured: %v", err.Error()) } } }
mit
difaharashta/SKRIPSI
admin/login-cek.php
504
<?php session_start(); include 'connect.php'; $username = $_POST['username']; $password = $_POST['password']; $query = "select * from admin where username='$username' and password=md5('$password')"; $rows = mysql_num_rows(mysql_query($query)); if($rows>0){ $data = mysql_fetch_array(mysql_query($query)); $_SESSION['username'] = $username; $_SESSION['name'] = $data['name']; header("location:index.php"); }else{ header("location:login.php?error=Username atau Password Salah"); } ?>
mit
mdouchement/iosupport
storage_service.go
4175
package iosupport //go:generate codecgen -u -o codec.go -r TsvLine tsv_indexer.go import ( "bytes" "fmt" "strings" "sync" "github.com/oxtoacart/bpool" "github.com/peterbourgon/diskv" "github.com/ugorji/go/codec" ) // A StorageService allows to store blobs type StorageService interface { // Marshal writes the blob encoding of v to the given key. Marshal(key string, v interface{}) error // Unmarshal parses the blob-encoded data and stores the result in the value pointed to by v. Unmarshal(key string, v interface{}) error // EraseAll removes all stored data. EraseAll() error } // A HDDStorageService allows to reads and writes blobs on filesystem. type HDDStorageService struct { disk *diskv.Diskv pool *bpool.BufferPool } // NewHDDStorageService instanciates a new HDDStorageService. func NewHDDStorageService(basepath string) *HDDStorageService { return &HDDStorageService{ pool: bpool.NewBufferPool(4), disk: diskv.New(diskv.Options{ BasePath: basepath, Compression: diskv.NewGzipCompression(), Transform: func(s string) []string { return strings.Split(s, "-") }, CacheSizeMax: 0, }), } } // Marshal writes the blob encoding of v to the given key. func (s *HDDStorageService) Marshal(key string, v interface{}) error { buf := s.pool.Get() defer s.pool.Put(buf) enc := codec.NewEncoder(buf, &codec.CborHandle{}) if err := enc.Encode(v); err != nil { return fmt.Errorf("StorageService: Marshal: %s", err.Error()) } if err := s.disk.Write(key, buf.Bytes()); err != nil { return fmt.Errorf("StorageService: Marshal: %s", err.Error()) } return nil } // Unmarshal parses the blob-encoded data and stores the result in the value pointed to by v. func (s *HDDStorageService) Unmarshal(key string, v interface{}) error { rc, err := s.disk.ReadStream(key, true) if err != nil { return fmt.Errorf("StorageService: Unmarshal: %s", err.Error()) } defer rc.Close() dec := codec.NewDecoder(rc, &codec.CborHandle{}) if err := dec.Decode(v); err != nil { return fmt.Errorf("StorageService: Unmarshal: %s", err.Error()) } return nil } // EraseAll removes all stored data. func (s *HDDStorageService) EraseAll() error { err := s.disk.EraseAll() if err != nil { return fmt.Errorf("StorageService: EraseAll: %s", err.Error()) } return nil } // ------------------ // // MemStorageService // // ------------------ // // A MemStorageService allows to reads and writes blobs in memory. type MemStorageService struct { sync.RWMutex compression diskv.Compression registry map[string][]byte pool *bpool.BufferPool } // NewMemStorageService instanciates a new MemStorageService. func NewMemStorageService() *MemStorageService { return &MemStorageService{ pool: bpool.NewBufferPool(4), compression: diskv.NewGzipCompression(), registry: make(map[string][]byte, 0), } } // Marshal writes the blob encoding of v to the given key. func (s *MemStorageService) Marshal(key string, v interface{}) error { buf := s.pool.Get() defer s.pool.Put(buf) // Attach compression bufc, err := s.compression.Writer(buf) if err != nil { return fmt.Errorf("MemStorageService: Marshal: %s", err.Error()) } enc := codec.NewEncoder(bufc, &codec.CborHandle{}) if err := enc.Encode(v); err != nil { return fmt.Errorf("MemStorageService: Marshal: %s", err.Error()) } bufc.Close() s.Lock() defer s.Unlock() s.registry[key] = buf.Bytes() return nil } // Unmarshal parses the blob-encoded data and stores the result in the value pointed to by v. func (s *MemStorageService) Unmarshal(key string, v interface{}) error { s.RLock() defer s.RUnlock() bufc := bytes.NewBuffer(s.registry[key]) buf, err := s.compression.Reader(bufc) if err != nil { return fmt.Errorf("MemStorageService: Unmarshal: %s", err.Error()) } defer buf.Close() dec := codec.NewDecoder(buf, &codec.CborHandle{}) if err := dec.Decode(v); err != nil { return fmt.Errorf("MemStorageService: Unmarshal: %s", err.Error()) } return nil } // EraseAll removes all stored data. func (s *MemStorageService) EraseAll() error { s.registry = nil s.registry = make(map[string][]byte, 0) return nil }
mit
jawher/mow.cli
internal/matcher/matchers.go
698
package matcher /* Matcher is used to parse and consume the args and populate the ParseContext */ type Matcher interface { /* Match examines the provided args and: - likes it, fills the parse context and returns true and the remaining args it didn't consume - doesn't like it, returns false and the remaining args it didn't consume */ Match(args []string, c *ParseContext) (bool, []string) // Priority used to sort matchers. the lower the returned number, the higher the priority of the matcher Priority() int } // IsShortcut is a helper to determine whether a given matcher is a Shortcut (always matches) func IsShortcut(matcher Matcher) bool { _, ok := matcher.(shortcut) return ok }
mit
isliliye/CES-Wordpess-site
functions.php
17644
<?php /* * Author: Todd Motto | @toddmotto * URL: html5blank.com | @html5blank * Custom functions, support, custom post types and more. */ /*------------------------------------*\ External Modules/Files \*------------------------------------*/ // Load any external files you have here /*------------------------------------*\ Theme Support \*------------------------------------*/ if (!isset($content_width)) { $content_width = 900; } if (function_exists('add_theme_support')) { // Add Menu Support add_theme_support('menus'); // Add Thumbnail Theme Support add_theme_support('post-thumbnails'); add_image_size('large', 700, '', true); // Large Thumbnail add_image_size('medium', 250, '', true); // Medium Thumbnail add_image_size('small', 120, '', true); // Small Thumbnail add_image_size('full', 700, 500, true); // Custom Thumbnail Size call using the_post_thumbnail('custom-size'); // Add Support for Custom Backgrounds - Uncomment below if you're going to use /*add_theme_support('custom-background', array( 'default-color' => 'FFF', 'default-image' => get_template_directory_uri() . '/img/bg.jpg' ));*/ // Add Support for Custom Header - Uncomment below if you're going to use /*add_theme_support('custom-header', array( 'default-image' => get_template_directory_uri() . '/img/headers/default.jpg', 'header-text' => false, 'default-text-color' => '000', 'width' => 1000, 'height' => 198, 'random-default' => false, 'wp-head-callback' => $wphead_cb, 'admin-head-callback' => $adminhead_cb, 'admin-preview-callback' => $adminpreview_cb ));*/ // Enables post and comment RSS feed links to head add_theme_support('automatic-feed-links'); // Localisation Support load_theme_textdomain('html5blank', get_template_directory() . '/languages'); } /*------------------------------------*\ Functions \*------------------------------------*/ // HTML5 Blank navigation function html5blank_nav() { wp_nav_menu( array( 'theme_location' => 'header-menu', 'menu' => '', 'container' => 'div', 'container_class' => 'menu-{menu slug}-container', 'container_id' => '', 'menu_class' => 'menu', 'menu_id' => '', 'echo' => true, 'fallback_cb' => 'wp_page_menu', 'before' => '', 'after' => '', 'link_before' => '', 'link_after' => '', 'items_wrap' => '<ul>%3$s</ul>', 'depth' => 0, 'walker' => '' ) ); } // Load HTML5 Blank scripts (header.php) function html5blank_header_scripts() { if ($GLOBALS['pagenow'] != 'wp-login.php' && !is_admin()) { wp_register_script('conditionizr', get_template_directory_uri() . '/js/lib/conditionizr-4.3.0.min.js', array(), '4.3.0'); // Conditionizr wp_enqueue_script('conditionizr'); // Enqueue it! wp_register_script('modernizr', get_template_directory_uri() . '/js/lib/modernizr-2.7.1.min.js', array(), '2.7.1'); // Modernizr wp_enqueue_script('modernizr'); // Enqueue it! wp_register_script('html5blankscripts', get_template_directory_uri() . '/js/scripts.js', array('jquery'), '1.0.0'); // Custom scripts wp_enqueue_script('html5blankscripts'); // Enqueue it! } } // Load HTML5 Blank conditional scripts function html5blank_conditional_scripts() { if (is_page('pagenamehere')) { wp_register_script('scriptname', get_template_directory_uri() . '/js/scriptname.js', array('jquery'), '1.0.0'); // Conditional script(s) wp_enqueue_script('scriptname'); // Enqueue it! } } // Load HTML5 Blank styles function html5blank_styles() { wp_register_style('normalize', get_template_directory_uri() . '/normalize.css', array(), '1.0', 'all'); wp_enqueue_style('normalize'); // Enqueue it! wp_register_style('html5blank', get_template_directory_uri() . '/style.css', array(), '1.0', 'all'); wp_enqueue_style('html5blank'); // Enqueue it! } // Register HTML5 Blank Navigation function register_html5_menu() { register_nav_menus(array( // Using array to specify more menus if needed 'header-menu' => __('Header Menu', 'html5blank'), // Main Navigation 'sidebar-menu' => __('Sidebar Menu', 'html5blank'), // Sidebar Navigation 'extra-menu' => __('Extra Menu', 'html5blank') // Extra Navigation if needed (duplicate as many as you need!) )); } // Remove the <div> surrounding the dynamic navigation to cleanup markup function my_wp_nav_menu_args($args = '') { $args['container'] = false; return $args; } // Remove Injected classes, ID's and Page ID's from Navigation <li> items function my_css_attributes_filter($var) { return is_array($var) ? array() : ''; } // Remove invalid rel attribute values in the categorylist function remove_category_rel_from_category_list($thelist) { return str_replace('rel="category tag"', 'rel="tag"', $thelist); } // Add page slug to body class, love this - Credit: Starkers Wordpress Theme function add_slug_to_body_class($classes) { global $post; if (is_home()) { $key = array_search('blog', $classes); if ($key > -1) { unset($classes[$key]); } } elseif (is_page()) { $classes[] = sanitize_html_class($post->post_name); } elseif (is_singular()) { $classes[] = sanitize_html_class($post->post_name); } return $classes; } // If Dynamic Sidebar Exists if (function_exists('register_sidebar')) { // Define Sidebar Widget Area 1 register_sidebar(array( 'name' => __('Widget Area 1', 'html5blank'), 'description' => __('Description for this widget-area...', 'html5blank'), 'id' => 'widget-area-1', 'before_widget' => '<div id="%1$s" class="%2$s">', 'after_widget' => '</div>', 'before_title' => '<h3>', 'after_title' => '</h3>' )); // Define Sidebar Widget Area 2 register_sidebar(array( 'name' => __('Widget Area 2', 'html5blank'), 'description' => __('Description for this widget-area...', 'html5blank'), 'id' => 'widget-area-2', 'before_widget' => '<div id="%1$s" class="%2$s">', 'after_widget' => '</div>', 'before_title' => '<h3>', 'after_title' => '</h3>' )); } // Remove wp_head() injected Recent Comment styles function my_remove_recent_comments_style() { global $wp_widget_factory; remove_action('wp_head', array( $wp_widget_factory->widgets['WP_Widget_Recent_Comments'], 'recent_comments_style' )); } // Pagination for paged posts, Page 1, Page 2, Page 3, with Next and Previous Links, No plugin function html5wp_pagination() { global $wp_query; $big = 999999999; echo paginate_links(array( 'base' => str_replace($big, '%#%', get_pagenum_link($big)), 'format' => '?paged=%#%', 'current' => max(1, get_query_var('paged')), 'total' => $wp_query->max_num_pages )); } // Custom Excerpts function html5wp_index($length) // Create 20 Word Callback for Index page Excerpts, call using html5wp_excerpt('html5wp_index'); { return 20; } // Create 40 Word Callback for Custom Post Excerpts, call using html5wp_excerpt('html5wp_custom_post'); function html5wp_custom_post($length) { return 20; } // Create the Custom Excerpts callback function html5wp_excerpt($length_callback = '', $more_callback = '') { global $post; if (function_exists($length_callback)) { add_filter('excerpt_length', $length_callback); } if (function_exists($more_callback)) { add_filter('excerpt_more', $more_callback); } $output = get_the_excerpt(); $output = apply_filters('wptexturize', $output); $output = apply_filters('convert_chars', $output); $output = '<p>' . $output . '</p>'; echo $output; } // Custom View Article link to Post function html5_blank_view_article($more) { global $post; return '... <a class="view-article" href="' . get_permalink($post->ID) . '">' . __('Read More', 'html5blank') . '</a>'; } // Remove Admin bar function remove_admin_bar() { return false; } // Remove 'text/css' from our enqueued stylesheet function html5_style_remove($tag) { return preg_replace('~\s+type=["\'][^"\']++["\']~', '', $tag); } // Remove thumbnail width and height dimensions that prevent fluid images in the_thumbnail function remove_thumbnail_dimensions( $html ) { $html = preg_replace('/(width|height)=\"\d*\"\s/', "", $html); return $html; } // Custom Gravatar in Settings > Discussion function html5blankgravatar ($avatar_defaults) { $myavatar = get_template_directory_uri() . '/img/gravatar.jpg'; $avatar_defaults[$myavatar] = "Custom Gravatar"; return $avatar_defaults; } // Threaded Comments function enable_threaded_comments() { if (!is_admin()) { if (is_singular() AND comments_open() AND (get_option('thread_comments') == 1)) { wp_enqueue_script('comment-reply'); } } } // Custom Comments Callback function html5blankcomments($comment, $args, $depth) { $GLOBALS['comment'] = $comment; extract($args, EXTR_SKIP); if ( 'div' == $args['style'] ) { $tag = 'div'; $add_below = 'comment'; } else { $tag = 'li'; $add_below = 'div-comment'; } ?> <!-- heads up: starting < for the html tag (li or div) in the next line: --> <?php echo $tag ?> <?php comment_class(empty( $args['has_children'] ) ? '' : 'parent') ?> id="comment-<?php comment_ID() ?>"> <?php if ( 'div' != $args['style'] ) : ?> <div id="div-comment-<?php comment_ID() ?>" class="comment-body"> <?php endif; ?> <div class="comment-author vcard"> <?php if ($args['avatar_size'] != 0) echo get_avatar( $comment, $args['180'] ); ?> <?php printf(__('<cite class="fn">%s</cite> <span class="says">says:</span>'), get_comment_author_link()) ?> </div> <?php if ($comment->comment_approved == '0') : ?> <em class="comment-awaiting-moderation"><?php _e('Your comment is awaiting moderation.') ?></em> <br /> <?php endif; ?> <div class="comment-meta commentmetadata"><a href="<?php echo htmlspecialchars( get_comment_link( $comment->comment_ID ) ) ?>"> <?php printf( __('%1$s at %2$s'), get_comment_date(), get_comment_time()) ?></a><?php edit_comment_link(__('(Edit)'),' ','' ); ?> </div> <?php comment_text() ?> <div class="reply"> <?php comment_reply_link(array_merge( $args, array('add_below' => $add_below, 'depth' => $depth, 'max_depth' => $args['max_depth']))) ?> </div> <?php if ( 'div' != $args['style'] ) : ?> </div> <?php endif; ?> <?php } /*------------------------------------*\ Actions + Filters + ShortCodes \*------------------------------------*/ // Add Actions add_action('init', 'html5blank_header_scripts'); // Add Custom Scripts to wp_head add_action('wp_print_scripts', 'html5blank_conditional_scripts'); // Add Conditional Page Scripts add_action('get_header', 'enable_threaded_comments'); // Enable Threaded Comments add_action('wp_enqueue_scripts', 'html5blank_styles'); // Add Theme Stylesheet add_action('init', 'register_html5_menu'); // Add HTML5 Blank Menu add_action('init', 'create_post_type_html5'); // Add our HTML5 Blank Custom Post Type add_action('widgets_init', 'my_remove_recent_comments_style'); // Remove inline Recent Comment Styles from wp_head() add_action('init', 'html5wp_pagination'); // Add our HTML5 Pagination // Remove Actions remove_action('wp_head', 'feed_links_extra', 3); // Display the links to the extra feeds such as category feeds remove_action('wp_head', 'feed_links', 2); // Display the links to the general feeds: Post and Comment Feed remove_action('wp_head', 'rsd_link'); // Display the link to the Really Simple Discovery service endpoint, EditURI link remove_action('wp_head', 'wlwmanifest_link'); // Display the link to the Windows Live Writer manifest file. remove_action('wp_head', 'index_rel_link'); // Index link remove_action('wp_head', 'parent_post_rel_link', 10, 0); // Prev link remove_action('wp_head', 'start_post_rel_link', 10, 0); // Start link remove_action('wp_head', 'adjacent_posts_rel_link', 10, 0); // Display relational links for the posts adjacent to the current post. remove_action('wp_head', 'wp_generator'); // Display the XHTML generator that is generated on the wp_head hook, WP version remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0); remove_action('wp_head', 'rel_canonical'); remove_action('wp_head', 'wp_shortlink_wp_head', 10, 0); // Add Filters add_filter('avatar_defaults', 'html5blankgravatar'); // Custom Gravatar in Settings > Discussion add_filter('body_class', 'add_slug_to_body_class'); // Add slug to body class (Starkers build) add_filter('widget_text', 'do_shortcode'); // Allow shortcodes in Dynamic Sidebar add_filter('widget_text', 'shortcode_unautop'); // Remove <p> tags in Dynamic Sidebars (better!) add_filter('wp_nav_menu_args', 'my_wp_nav_menu_args'); // Remove surrounding <div> from WP Navigation // add_filter('nav_menu_css_class', 'my_css_attributes_filter', 100, 1); // Remove Navigation <li> injected classes (Commented out by default) // add_filter('nav_menu_item_id', 'my_css_attributes_filter', 100, 1); // Remove Navigation <li> injected ID (Commented out by default) // add_filter('page_css_class', 'my_css_attributes_filter', 100, 1); // Remove Navigation <li> Page ID's (Commented out by default) add_filter('the_category', 'remove_category_rel_from_category_list'); // Remove invalid rel attribute add_filter('the_excerpt', 'shortcode_unautop'); // Remove auto <p> tags in Excerpt (Manual Excerpts only) add_filter('the_excerpt', 'do_shortcode'); // Allows Shortcodes to be executed in Excerpt (Manual Excerpts only) add_filter('excerpt_more', 'html5_blank_view_article'); // Add 'View Article' button instead of [...] for Excerpts add_filter('show_admin_bar', 'remove_admin_bar'); // Remove Admin bar add_filter('style_loader_tag', 'html5_style_remove'); // Remove 'text/css' from enqueued stylesheet add_filter('post_thumbnail_html', 'remove_thumbnail_dimensions', 10); // Remove width and height dynamic attributes to thumbnails add_filter('image_send_to_editor', 'remove_thumbnail_dimensions', 10); // Remove width and height dynamic attributes to post images // Remove Filters remove_filter('the_excerpt', 'wpautop'); // Remove <p> tags from Excerpt altogether // Shortcodes add_shortcode('html5_shortcode_demo', 'html5_shortcode_demo'); // You can place [html5_shortcode_demo] in Pages, Posts now. add_shortcode('html5_shortcode_demo_2', 'html5_shortcode_demo_2'); // Place [html5_shortcode_demo_2] in Pages, Posts now. // Shortcodes above would be nested like this - // [html5_shortcode_demo] [html5_shortcode_demo_2] Here's the page title! [/html5_shortcode_demo_2] [/html5_shortcode_demo] /*------------------------------------*\ Custom Post Types \*------------------------------------*/ // Create 1 Custom Post type for a Demo, called HTML5-Blank function create_post_type_html5() { register_taxonomy_for_object_type('category', 'html5-blank'); // Register Taxonomies for Category register_taxonomy_for_object_type('post_tag', 'html5-blank'); register_post_type('html5-blank', // Register Custom Post Type array( 'labels' => array( 'name' => __('HTML5 Blank Custom Post', 'html5blank'), // Rename these to suit 'singular_name' => __('HTML5 Blank Custom Post', 'html5blank'), 'add_new' => __('Add New', 'html5blank'), 'add_new_item' => __('Add New HTML5 Blank Custom Post', 'html5blank'), 'edit' => __('Edit', 'html5blank'), 'edit_item' => __('Edit HTML5 Blank Custom Post', 'html5blank'), 'new_item' => __('New HTML5 Blank Custom Post', 'html5blank'), 'view' => __('View HTML5 Blank Custom Post', 'html5blank'), 'view_item' => __('View HTML5 Blank Custom Post', 'html5blank'), 'search_items' => __('Search HTML5 Blank Custom Post', 'html5blank'), 'not_found' => __('No HTML5 Blank Custom Posts found', 'html5blank'), 'not_found_in_trash' => __('No HTML5 Blank Custom Posts found in Trash', 'html5blank') ), 'public' => true, 'hierarchical' => true, // Allows your posts to behave like Hierarchy Pages 'has_archive' => true, 'supports' => array( 'title', 'editor', 'excerpt', 'thumbnail' ), // Go to Dashboard Custom HTML5 Blank post for supports 'can_export' => true, // Allows export in Tools > Export 'taxonomies' => array( 'post_tag', 'category' ) // Add Category and Post Tags support )); } /*------------------------------------*\ ShortCode Functions \*------------------------------------*/ // Shortcode Demo with Nested Capability function html5_shortcode_demo($atts, $content = null) { return '<div class="shortcode-demo">' . do_shortcode($content) . '</div>'; // do_shortcode allows for nested Shortcodes } // Shortcode Demo with simple <h2> tag function html5_shortcode_demo_2($atts, $content = null) // Demo Heading H2 shortcode, allows for nesting within above element. Fully expandable. { return '<h2>' . $content . '</h2>'; } // Add custom post type on home page/front-page.php // add_filter( 'pre_get_posts', 'my_get_posts' ); // function my_get_posts( $query ) { // if ( is_home() && $query->is_main_query() ) // $query->set( 'post_type', array( 'post' ) ); // // $query->set( 'posts_per_page', 4 ); // return $query; // } ?>
mit
nossas/vivos-em-nos
src/views/components/form/upload-multiples-field.js
1082
import { h, Component } from 'preact' /** @jsx h */ import { Field } from 'redux-form' import { FormGroup, UploadField } from '~src/views/components/form' export default class UploadMultiplesField extends Component { componentDidMount() { this.props.fields.push() } render() { const { fields, label, meta, formGroupClassName } = this.props return ( <FormGroup className={formGroupClassName} meta={meta}> <div className="components--upload-multiples-field"> {label && <span className="label">{label}</span>} <div className="images"> {fields && fields.map((field, index) => ( <Field id={`${field.name}-${index}`} name={`${field}.assetUrl`} component={UploadField} onFinish={() => fields.push()} iconDefault="icon-plus" iconAfterUpload="icon-trash" onClickWhenFilled={() => fields.remove(index)} /> ))} </div> </div> </FormGroup> ) } }
mit
rmc00/gsf
Source/Libraries/GSF.TimeSeries/UI/WPF/UserControls/AdapterUserControl.xaml.cs
12066
//****************************************************************************************************** // AdapterUserControl.xaml.cs - Gbtc // // Copyright © 2010, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may // not use this file except in compliance with the License. You may obtain a copy of the License at: // // http://www.opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 05/05/2011 - Mehulbhai P Thakkar // Generated original version of source code. // //****************************************************************************************************** using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using GSF.Reflection; using GSF.TimeSeries.Adapters; using GSF.TimeSeries.UI.DataModels; using FolderBrowserDialog = System.Windows.Forms.FolderBrowserDialog; namespace GSF.TimeSeries.UI.UserControls { /// <summary> /// Interaction logic for AdapterUserControl.xaml /// </summary> public partial class AdapterUserControl : UserControl { #region [ Members ] private readonly ViewModels.Adapters m_dataContext; private DataGridColumn m_sortColumn; private string m_sortMemberPath; private ListSortDirection m_sortDirection; #endregion #region [ Constructor ] /// <summary> /// Creates an instance of <see cref="AdapterUserControl"/> class. /// </summary> public AdapterUserControl(AdapterType adapterType) { InitializeComponent(); m_dataContext = new ViewModels.Adapters(7, adapterType); m_dataContext.PropertyChanged += ViewModel_PropertyChanged; this.DataContext = m_dataContext; } #endregion #region [ Methods ] /// <summary> /// Handles PreviewKeyDown event on the datagrid. /// </summary> /// <param name="sender">Source of the event.</param> /// <param name="e">Arguments for the event.</param> private void DataGrid_PreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Delete) { DataGrid dataGrid = sender as DataGrid; if (dataGrid.SelectedItems.Count > 0) { if (MessageBox.Show("Are you sure you want to delete " + dataGrid.SelectedItems.Count + " selected item(s)?", "Delete Selected Items", MessageBoxButton.YesNo) == MessageBoxResult.No) e.Handled = true; } } } private void DataGridEnabledCheckBox_Click(object sender, RoutedEventArgs e) { // Get a reference to the enabled checkbox that was clicked CheckBox enabledCheckBox = sender as CheckBox; if ((object)enabledCheckBox != null) { // Get the runtime ID of the currently selected adapter string runtimeID = m_dataContext.RuntimeID; if (!string.IsNullOrWhiteSpace(runtimeID)) { try { // Auto-save changes to the adapter m_dataContext.ProcessPropertyChange(); if (m_dataContext.CanSave) { if (enabledCheckBox.IsChecked.GetValueOrDefault()) CommonFunctions.SendCommandToService("Initialize " + runtimeID); else CommonFunctions.SendCommandToService("ReloadConfig"); } } catch (Exception ex) { if ((object)ex.InnerException != null) CommonFunctions.LogException(null, "Adapter Autosave", ex.InnerException); else CommonFunctions.LogException(null, "Adapter Autosave", ex); } } } } /// <summary> /// Handles Click event on the button labeled "Browse..." /// </summary> /// <param name="sender">Source of the event.</param> /// <param name="e">Arguments for the event.</param> private void Browse_Click(object sender, RoutedEventArgs e) { FolderBrowserDialog browser = new FolderBrowserDialog(); browser.SelectedPath = SearchDirectoryTextBox.Text; if (browser.ShowDialog() == System.Windows.Forms.DialogResult.OK) SearchDirectoryTextBox.Text = browser.SelectedPath; } /// <summary> /// Handles Click event on the button labeled "Default". /// </summary> /// <param name="sender">Source of the event.</param> /// <param name="e">Arguments for the event.</param> private void Default_Click(object sender, RoutedEventArgs e) { ViewModels.Adapters dataContext = this.DataContext as ViewModels.Adapters; if (dataContext != null && dataContext.SelectedParameter != null) { Dictionary<string, string> settings = dataContext.CurrentItem.ConnectionString.ToNonNullString().ParseKeyValuePairs(); settings.Remove(dataContext.SelectedParameter.Name); dataContext.CurrentItem.ConnectionString = settings.JoinKeyValuePairs(); } } private void DataGrid_Sorting(object sender, DataGridSortingEventArgs e) { if (e.Column.SortMemberPath != m_sortMemberPath) m_sortDirection = ListSortDirection.Ascending; else if (m_sortDirection == ListSortDirection.Ascending) m_sortDirection = ListSortDirection.Descending; else m_sortDirection = ListSortDirection.Ascending; m_sortColumn = e.Column; m_sortMemberPath = e.Column.SortMemberPath; m_dataContext.SortData(m_sortMemberPath, m_sortDirection); } private void ViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "ItemsSource") Dispatcher.BeginInvoke(new Action(SortDataGrid)); } private void SortDataGrid() { if ((object)m_sortColumn != null) { m_sortColumn.SortDirection = m_sortDirection; DataGridList.Items.SortDescriptions.Clear(); DataGridList.Items.SortDescriptions.Add(new SortDescription(m_sortMemberPath, m_sortDirection)); DataGridList.Items.Refresh(); } } private void GridDetailView_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { if (m_dataContext.IsNewRecord) DataGridList.SelectedIndex = -1; } private void ButtonOpenCustomConfiguration_Click(object sender, RoutedEventArgs e) { CustomConfigurationEditorAttribute customConfigurationEditorAttribute; UIElement customConfigurationElement; int adapterTypeIndex; try { adapterTypeIndex = m_dataContext.AdapterTypeSelectedIndex; if (adapterTypeIndex >= 0) { CustomConfigurationPanel.Children.Clear(); if (m_dataContext.AdapterTypeList[adapterTypeIndex].Item1.TryGetAttribute(out customConfigurationEditorAttribute)) { if ((object)customConfigurationEditorAttribute.ConnectionString != null) customConfigurationElement = Activator.CreateInstance(customConfigurationEditorAttribute.EditorType, m_dataContext.CurrentItem, customConfigurationEditorAttribute.ConnectionString) as UIElement; else customConfigurationElement = Activator.CreateInstance(customConfigurationEditorAttribute.EditorType, m_dataContext.CurrentItem) as UIElement; if ((object)customConfigurationElement != null) { CustomConfigurationPanel.Children.Insert(0, customConfigurationElement); CustomConfigurationPopup.IsOpen = true; } } } } catch (Exception ex) { string message = string.Format("Unable to open custom configuration control due to exception: {0}", ex.Message); m_dataContext.Popup(message, "Custom Configuration Error", MessageBoxImage.Error); } } private void ButtonOpenParameterConfiguration_Click(object sender, RoutedEventArgs e) { CustomConfigurationEditorAttribute customConfigurationEditorAttribute; UIElement customConfigurationElement; int adapterTypeIndex; try { adapterTypeIndex = m_dataContext.AdapterTypeSelectedIndex; if (adapterTypeIndex >= 0) { CustomConfigurationPanel.Children.Clear(); customConfigurationEditorAttribute = m_dataContext.SelectedParameter.Info.GetCustomAttribute<CustomConfigurationEditorAttribute>(); if ((object)customConfigurationEditorAttribute != null) { if ((object)customConfigurationEditorAttribute.ConnectionString != null) customConfigurationElement = Activator.CreateInstance(customConfigurationEditorAttribute.EditorType, m_dataContext.CurrentItem, m_dataContext.SelectedParameter.Name, customConfigurationEditorAttribute.ConnectionString) as UIElement; else customConfigurationElement = Activator.CreateInstance(customConfigurationEditorAttribute.EditorType, m_dataContext.CurrentItem, m_dataContext.SelectedParameter.Name) as UIElement; if ((object)customConfigurationElement != null) { CustomConfigurationPanel.Children.Add(customConfigurationElement); CustomConfigurationPopup.IsOpen = true; } } } } catch (Exception ex) { string message = string.Format("Unable to open custom configuration control due to exception: {0}", ex.Message); m_dataContext.Popup(message, "Custom Configuration Error", MessageBoxImage.Error); } } private void CustomConfigurationPopup_ButtonClick(object sender, RoutedEventArgs e) { Button originalSource = e.OriginalSource as Button; if ((object)originalSource != null && (originalSource.IsDefault || originalSource.IsCancel)) CustomConfigurationPopup.IsOpen = false; } private void UserControl_Unloaded(object sender, RoutedEventArgs e) { m_dataContext.Unload(); } #endregion } }
mit
sheplu/LiveDemo
SUPINFO/Tamagocci.js - base 1/src/tamagocci.js
293
function Tamagocci() { this.weight = 5; this.happiness = 5; this.age = 0; this.minWeight = 1; this.maxWeight = 10; this.eat = function() { this.weight += 2; }; this.play = function() { this.weight--; this.happiness++; } }
mit
PaulNoth/hackerrank
practice/algorithms/implementation/cats_and_a_mouse/CatsAndMouse.java
1016
import java.util.*; public class CatsAndMouse { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int tests = Integer.parseInt(stdin.nextLine()); for(int i = 0; i < tests; i++) { String line = stdin.nextLine(); String[] abmString = line.split(" "); int[] abm = new int[3]; for(int j = 0; j < 3; j++) { abm[j] = Integer.parseInt(abmString[j]); } int a = abm[0]; int b = abm[1]; int m = abm[2]; int catACatchMouseSteps = Math.abs(a - m); int catBCatchMouseSteps = Math.abs(b - m); if(catACatchMouseSteps == catBCatchMouseSteps) { System.out.println("Mouse C"); } else if(catACatchMouseSteps < catBCatchMouseSteps) { System.out.println("Cat A"); } else { System.out.println("Cat B"); } } stdin.close(); } }
mit
chilts/rustle
lib/epoch.js
428
function toEpoch(d) { if ( d instanceof Date ) { return Math.floor(d.valueOf() / 1000); } if ( typeof d === 'string' ) { return Math.floor((Date.parse(d)).valueOf() / 1000); } if ( typeof d === 'number' ) { return Math.floor((new Date(+(d + '000'))).valueOf() / 1000); } throw new Error("Unknown format for converting to Epoch : " + typeof d); } module.exports = toEpoch;
mit
mprinc/KnAllEdge
src/frontend/dev_puzzles/flow/audit/lib/colabo-flow-audit.service.ts
8687
const MODULE_NAME: string = "@colabo-flow/f-audit"; import { Injectable, Inject } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { catchError, map, tap } from 'rxjs/operators'; import { AuditedAction, AuditedActionClass } from '@colabo-flow/i-audit'; import { Observable, of } from 'rxjs'; import { GetPuzzle, GetGeneral } from '@colabo-utils/i-config'; import * as moment from 'moment'; @Injectable() export class ColaboFlowAuditService{ // RESTfull backend API url static serverAP: string = GetGeneral('serverUrl'); protected _isActive:boolean = true; protected puzzleConfig: any; constructor( private http: HttpClient ) { this.puzzleConfig = GetPuzzle(MODULE_NAME); this.init(); } /** * Initializes service */ init() { if(!this._isActive) return; // initialize } //TODO: to remove this, we are scaling it in the component: get timeDivider():number{ return this.puzzleConfig.timeDivider; } /** * Handle Http operation that failed. * Let the app continue. * @param operation - name of the operation that failed * @param result - optional value to return as the observable result */ protected handleError<T>(operation = 'operation', result?: T) { return (error: any): Observable<T> => { // TODO: send the error to remote logging infrastructure console.error(error); // log to console instead window.alert('error: ' + error); // TODO: better job of transforming error for user consumption //this.log(`${operation} failed: ${error.message}`); // Let the app keep running by returning an empty result. return of(result as T); }; } getStatisticsMockup():Observable<any>{ let items:any = { "searchUser": { "parameters": { "count": 10, "duration": 3, "success": 11 } }, "checkCache": { "parameters": { "count": 20, "duration": 25, "success": 4 } }, "start": { "parameters": { "count": 50, "duration": 15, "success": 8 } }, "end": { "parameters": { "count": 40, "duration": 5, "success": 7 } }, "parseResponse": { "parameters": { "count": 30, "duration": 15, "success": 16 } } }; return of(items); } getStatistics(sessionIds:string[],flowId:string=null):Observable<any> { let url: string; console.log('[getStatistics] sessionIds', sessionIds); let idsStr:string = '' if(sessionIds.length>0){ idsStr = sessionIds.join(',')+'/'; } let searchQuery: string = 'get-stats/sessions/'; // this.http.get<ServerData>(this.apiUrl+'id_in/'+this.defaultAction+'/'+idsStr+'.json') url = ColaboFlowAuditService.serverAP + '/colabo-flow/audit/' + searchQuery + idsStr + (flowId == null ? '' : flowId) + '.json'; const result: Observable<any[]> = this.http.get<any>(url) .pipe( map(statsFromServer => this.processStatsFromServer(statsFromServer.data)), // map(auditsFromServer => CFService.processAuditedActionsVOs(nodesFromServer, KNode)), catchError(this.handleError('ColaboFlowAuditService::getStatistics', null)) ); // result.subscribe(audits => { // console.log('[ColaboFlowAuditService::loadSounds] audits: ', audits); // }); // if (callback) { // result.subscribe(audits => callback(audits)); // } return result; } processStatsFromServer(statsFromServer:any[] ): any[] { let statFromServer:any = null; let name:string; // let newStatFromServer:any = null; for(let i:number=0; i<statsFromServer.length; i++){ statFromServer = statsFromServer[i]; name = statFromServer['_id']; // statFromServer['avgTime'] = statFromServer['avgTime'] / this.timeDivider; delete statFromServer['_id']; statsFromServer[i] = {'name': name, 'stats': JSON.parse(JSON.stringify(statFromServer))}; } return statsFromServer; } getActions(sessionIds:string[],flowId:string=null): Observable<AuditedAction[]> { // return this.getActionsMockup(); let searchQuery: string = 'get-audits/sessions-flow/'; // let searchQuery: string = 'get-stats/sessions/'; let url: string; // url = ColaboFlowAuditService.serverAP + '/colabo-flow/audit/' + searchQuery + '.json'; let sessionIdsStr:string = ''; if(sessionIds.length>0){ sessionIdsStr = sessionIds.join(',')+'/'; } url = ColaboFlowAuditService.serverAP + '/colabo-flow/audit/' + searchQuery + sessionIdsStr + (flowId == null ? '' : flowId) + '.json'; const result: Observable<any[]> = this.http.get<any>(url) .pipe( map(auditsFromServer => this.processAuditedActionsVOs(auditsFromServer)), // map(auditsFromServer => CFService.processAuditedActionsVOs(nodesFromServer, KNode)), catchError(this.handleError('ColaboFlowAuditService::loadSounds', null)) ); // result.subscribe(audits => { // console.log('[ColaboFlowAuditService::loadSounds] audits: ', audits); // }); // if (callback) { // result.subscribe(audits => callback(audits)); // } return result; } processAuditedActionsVOs(resultFull: any): AuditedAction[] { const audits: AuditedAction[] = []; let auditsFromServer:any[] = resultFull.data; console.log("[processAuditedActionsVOs] auditsFromServer: ", auditsFromServer); for (let auditId = 0; auditId < auditsFromServer.length; auditId++) { const auditFromServer:any = auditsFromServer[auditId]; const auditVo: AuditedActionClass = new AuditedActionClass(); auditVo.id = auditFromServer.id; if (!auditVo.id) auditVo.id = auditFromServer._id; auditVo.time = auditFromServer.time; auditVo.bpmn_type = auditFromServer.bpmn_type; auditVo.bpmn_subtype = auditFromServer.bpmn_subtype; auditVo.bpmn_subsubtype = auditFromServer.bpmn_subsubtype; auditVo.flowId = auditFromServer.flowId; auditVo.name = auditFromServer.name; auditVo.userId = auditFromServer.userId; auditVo.sessionId = auditFromServer.sessionId; auditVo.flowInstanceId = auditFromServer.flowInstanceId; auditVo.implementationId = auditFromServer.implementationId; auditVo.implementerId = auditFromServer.implementerId; auditVo.createdAt = moment(auditFromServer.createdAt).format("dddd, MMMM Do YYYY, h:mm:ss a"); auditVo.updatedAt = moment(auditFromServer.updatedAt).format("dddd, MMMM Do YYYY, h:mm:ss a"); audits.push(auditVo); } console.log("[processAuditedActionsVOs] audits: ", audits); return audits; } getActionsMockup():Observable<AuditedAction[]>{ let items:AuditedAction[] = []; items.push(({ id: "ad30", name: "start", flowId: "searchSoundsNoCache", flowInstanceId: "ff01" }) as AuditedAction); items.push(({ id: "ad31", name: "parseRequest", flowId: "searchSoundsNoCache", flowInstanceId: "ff01" }) as AuditedAction); items.push(({ id: "ad32", name: "parseResponse", flowId: "searchSoundsNoCache", flowInstanceId: "ff01" }) as AuditedAction); items.push(({ id: "ad3a", name: "end", flowId: "searchSoundsNoCache", flowInstanceId: "ff01" }) as AuditedAction); // flow ff02 items.push(({ id: "ad40", name: "start", flowId: "searchSoundsNoCache", flowInstanceId: "ff02" }) as AuditedAction); items.push(({ id: "ad41", name: "parseRequest", flowId: "searchSoundsNoCache", flowInstanceId: "ff02" }) as AuditedAction); items.push(({ id: "ad42", name: "parseResponse", flowId: "searchSoundsNoCache", flowInstanceId: "ff02" }) as AuditedAction); items.push(({ id: "ad4a", name: "end", flowId: "searchSoundsNoCache", flowInstanceId: "ff02" }) as AuditedAction); // flow ff03 items.push(({ id: "ad50", name: "start", flowId: "searchSoundsWithCache", flowInstanceId: "ff03" }) as AuditedAction); items.push(({ id: "ad50", name: "parseRequest", flowId: "searchSoundsWithCache", flowInstanceId: "ff03" }) as AuditedAction); items.push(({ id: "ad5a", name: "end", flowId: "searchSoundsWithCache", flowInstanceId: "ff03" }) as AuditedAction); return of(items); } }
mit
moeadham/ripple-simple
js/util/base58.js
2881
var Base58Utils = (function () { var alphabets = { 'ripple': "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz", 'bitcoin': "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" }; var SHA256 = function (bytes) { return sjcl.codec.bytes.fromBits(sjcl.hash.sha256.hash(sjcl.codec.bytes.toBits(bytes))); }; return { // --> input: big-endian array of bytes. // <-- string at least as long as input. encode_base: function (input, alphabetName) { var alphabet = alphabets[alphabetName || 'ripple'], base = new sjcl.bn(alphabet.length), bi = sjcl.bn.fromBits(sjcl.codec.bytes.toBits(input)), buffer = []; console.log(bi); while (bi.greaterEquals(base)) { var mod = bi.mod(base); buffer.push(alphabet[mod.limbs[0]]); bi = bi.div(base); } buffer.push(alphabet[bi.limbs[0]]); // Convert leading zeros too. for (var i = 0; i != input.length && !input[i]; i += 1) { buffer.push(alphabet[0]); } return buffer.reverse().join(""); }, // --> input: String // <-- array of bytes or undefined. decode_base: function (input, alphabetName) { var alphabet = alphabets[alphabetName || 'ripple'], base = new sjcl.bn(alphabet.length), bi = new sjcl.bn(0); var i; while (i != input.length && input[i] === alphabet[0]) { i += 1; } for (i = 0; i != input.length; i += 1) { var v = alphabet.indexOf(input[i]); if (v < 0) { return null; } bi = bi.mul(base).addM(v); } var bytes = sjcl.codec.bytes.fromBits(bi.toBits()).reverse(); // Remove leading zeros while(bytes[bytes.length-1] === 0) { bytes.pop(); } // Add the right number of leading zeros for (i = 0; input[i] === alphabet[0]; i++) { bytes.push(0); } bytes.reverse(); return bytes; }, // --> input: Array // <-- String encode_base_check: function (version, input, alphabet) { var buffer = [].concat(version, input); var check = SHA256(SHA256(buffer)).slice(0, 4); return Base58Utils.encode_base([].concat(buffer, check), alphabet); }, // --> input : String // <-- NaN || BigInteger decode_base_check: function (version, input, alphabet) { var buffer = Base58Utils.decode_base(input, alphabet); if (!buffer || buffer[0] !== version || buffer.length < 5) { return NaN; } var computed = SHA256(SHA256(buffer.slice(0, -4))).slice(0, 4), checksum = buffer.slice(-4); var i; for (i = 0; i != 4; i += 1) if (computed[i] !== checksum[i]) return NaN; return buffer.slice(1, -4); } }; })(); //module.exports = Base58Utils;
mit
towski/disc-jockey
node_modules/mongodb/lib/mongodb/index.js
912
var sys = require('sys') // // Add both the BSON Pure classes and the native ones var BSONPure = exports.BSONPure = require('./bson/bson'); var BSONNative = null try { BSONNative = exports.BSONNative = require('../../external-libs/bson/bson'); } catch(err) { } [ 'bson/binary_parser', 'commands/base_command', 'commands/db_command', 'commands/delete_command', 'commands/get_more_command', 'commands/insert_command', 'commands/kill_cursor_command', 'commands/query_command', 'commands/update_command', 'responses/mongo_reply', 'admin', 'collection', 'connections/server', 'connections/server_pair', 'connections/server_cluster', 'connections/repl_set_servers', 'connection', 'cursor', 'db', 'goog/math/integer', 'goog/math/long', 'crypto/md5', 'gridfs/chunk', 'gridfs/gridstore' ].forEach(function(path){ var module = require('./' + path); for (var i in module) exports[i] = module[i]; });
mit
eripa/rtelldus
lib/rtelldus/version.rb
40
module Rtelldus VERSION = "1.0.1" end
mit
InsertCleverNameHere/cleverjobhunter
src/components/list-companies/company-detail/edit-company/edit-company.js
763
import template from './edit-company.html'; export default { template, bindings: { companyToEdit: '<company' }, controller }; controller.$inject = ['$mdDialog', 'companyService', '$state']; function controller($mdDialog, companyService, $state){ this.company = angular.copy(this.companyToEdit); //get users companies to populate the drop down // companyService.getByUser() // .then(companies => { // this.companies = companies; // }) // .catch(err => console.log(err)); this.cancel = () => { $mdDialog.hide(); }; this.save = () => { this.company._id = $state.params.companyId; companyService.update(this.company) .then(updatedCompany => { $mdDialog.hide(updatedCompany); }); }; }
mit
ShowingCloud/Elnath
config/environment.rb
196
# Load the Rails application. require File.expand_path('../application', __FILE__) require_relative 'initializers/arel_patch' # Initialize the Rails application. Elnath::Application.initialize!
mit
waynesayonara/imperium
lib/engine/map/tile_sets.rb
1098
module Engine module Map class TileSets def initialize(data, data_dir) @data = data @tilesets = {} @data.each do |t| tileset = Gosu::Image.load_tiles( $window, File.join(data_dir, t.image), t.tilewidth, t.tileheight, true) @tilesets[t.firstgid] = { 'data' => t, 'tiles' => tileset } end end def size @data.size end def get(index) return empty_tile if index == 0 || index.nil? key = closest_key(index) @tilesets[key]['tiles'][index - key] end def properties(index) return {} if index == 0 key = closest_key(index) props = @tilesets[key]['data']['tileproperties'] return {} unless props props[(index - key).to_s] end private def empty_tile @empty_tile ||= EmptyTile.new end def closest_key(index) @tilesets.keys.select { |k| k <= index }.max end end class EmptyTile def draw end end end end
mit
gilcierweb/CMS-Rails
db/migrate/20150712203840_devise_create_users.rb
1361
class DeviseCreateUsers < ActiveRecord::Migration[5.2] def change create_table(:users) do |t| ## Database authenticatable t.string :email, null: false, default: "" t.string :encrypted_password, null: false, default: "" ## Recoverable t.string :reset_password_token t.datetime :reset_password_sent_at ## Rememberable t.datetime :remember_created_at ## Trackable t.integer :sign_in_count, default: 0, null: false t.datetime :current_sign_in_at t.datetime :last_sign_in_at t.string :current_sign_in_ip t.string :last_sign_in_ip ## Confirmable # t.string :confirmation_token # t.datetime :confirmed_at # t.datetime :confirmation_sent_at # t.string :unconfirmed_email # Only if using reconfirmable ## Lockable # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts # t.string :unlock_token # Only if unlock strategy is :email or :both # t.datetime :locked_at t.timestamps null: false end add_index :users, :email, unique: true add_index :users, :reset_password_token, unique: true # add_index :users, :confirmation_token, unique: true # add_index :users, :unlock_token, unique: true end end
mit
keefekwan/symfony2_forms
src/KK/FormsBundle/Entity/Account.php
1441
<?php // src/KK/FormsBundle/Entity/Account.php namespace KK\FormsBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Account * * @ORM\Table() * @ORM\Entity(repositoryClass="KK\FormsBundle\Repository\AccountRepository") */ class Account { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="name", type="string", length=255) */ private $name; /** * @ORM\ManyToOne(targetEntity="City") */ protected $city; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set name * * @param string $name * @return Account */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set city * * @param \KK\FormsBundle\Entity\City $city * @return Account */ public function setCity(City $city = null) { $this->city = $city; return $this; } /** * Get city * * @return \KK\FormsBundle\Entity\City */ public function getCity() { return $this->city; } }
mit
gazzlab/LSL-gazzlab-branch
liblsl/external/lslboost/fusion/adapted/boost_array/detail/size_impl.hpp
866
/*============================================================================= Copyright (c) 2001-2011 Joel de Guzman Copyright (c) 2005-2006 Dan Marsden Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.lslboost.org/LICENSE_1_0.txt) ==============================================================================*/ #if !defined(BOOST_FUSION_SIZE_IMPL_27122005_1251) #define BOOST_FUSION_SIZE_IMPL_27122005_1251 namespace lslboost { namespace fusion { struct lslboost_array_tag; namespace extension { template<typename T> struct size_impl; template<> struct size_impl<lslboost_array_tag> { template<typename Sequence> struct apply : mpl::int_<Sequence::static_size> {}; }; } }} #endif
mit
thedersen/UnityConfiguration
src/UnityConfiguration.Tests/CustomConventionTests.cs
946
using System; using NUnit.Framework; using Unity; using UnityConfiguration.Services; namespace UnityConfiguration { [TestFixture] public class CustomConventionTests { [Test] public void Can_create_custom_conventions() { var container = new UnityContainer(); container.Configure(x => x.Scan(scan => { scan.AssemblyContaining<FooRegistry>(); scan.With<CustomConvention>(); })); Assert.That(container.Resolve<IFooService>("Custom"), Is.InstanceOf<FooService>()); } } public class CustomConvention : IAssemblyScannerConvention { void IAssemblyScannerConvention.Process(Type type, IUnityRegistry registry) { if (type == typeof(FooService)) registry.Register<IFooService, FooService>().WithName("Custom"); } } }
mit
hrgdavor/java-hipster-sql
processor/src/main/java/hr/hrg/hipster/processor/GenDelta.java
642
package hr.hrg.hipster.processor; import static hr.hrg.javapoet.PoetUtil.*; import com.squareup.javapoet.*; public class GenDelta { public TypeSpec.Builder gen2(EntityDef def) { TypeSpec.Builder cp = classBuilder(PUBLIC(), def.typeDelta); // cp.superclass(parametrized(EnumGetterUpdateDelta.class, def.typeImmutable, def.typeEnum)); MethodSpec.Builder constr = constructorBuilder(PUBLIC()); addParameter(constr, long.class, "changeSet"); addParameter(constr, def.typeImmutable, "obj"); constr.addCode("super(changeSet, obj, $T.COLUMN_ARRAY);", def.typeMeta); cp.addMethod(constr.build()); return cp; } }
mit
lache/RacingKingLee
server/core/nancy/Nancy/Routing/Trie/TrieNodeFactory.cs
2724
namespace Nancy.Routing.Trie { using System.Linq; using System.Collections.Generic; using Nancy.Routing.Constraints; using Nancy.Routing.Trie.Nodes; /// <summary> /// Factory for creating the correct type of TrieNode /// </summary> public class TrieNodeFactory : ITrieNodeFactory { private readonly IEnumerable<IRouteSegmentConstraint> routeSegmentConstraints; public TrieNodeFactory(IEnumerable<IRouteSegmentConstraint> routeSegmentConstraints) { this.routeSegmentConstraints = routeSegmentConstraints; } /// <summary> /// Gets the correct Trie node type for the given segment /// </summary> /// <param name="parent">Parent node</param> /// <param name="segment">Segment</param> /// <returns>TrieNode instance</returns> public virtual TrieNode GetNodeForSegment(TrieNode parent, string segment) { if (parent == null) { return new RootNode(this); } var chars = segment.ToCharArray(); var start = chars[0]; var end = chars[chars.Length - 1]; if (start == '(' && end == ')') { return new RegExNode(parent, segment, this); } if (start == '{' && end == '}' && chars.Count(c => c == '{' || c == '}') == 2) { return this.GetCaptureNode(parent, segment); } if (segment.StartsWith("^(") && (segment.EndsWith(")") || segment.EndsWith(")$"))) { return new GreedyRegExCaptureNode(parent, segment, this); } if (CaptureNodeWithMultipleParameters.IsMatch(segment)) { return new CaptureNodeWithMultipleParameters(parent, segment, this, routeSegmentConstraints); } return new LiteralNode(parent, segment, this); } private TrieNode GetCaptureNode(TrieNode parent, string segment) { if (segment.Contains(":")) { return new CaptureNodeWithConstraint(parent, segment, this, routeSegmentConstraints); } if (segment.EndsWith("?}")) { return new OptionalCaptureNode(parent, segment, this); } if (segment.EndsWith("*}")) { return new GreedyCaptureNode(parent, segment, this); } if (segment.Contains("?")) { return new CaptureNodeWithDefaultValue(parent, segment, this); } return new CaptureNode(parent, segment, this); } } }
mit
akshaydewan/qbittorrent-remote
PhoneApp1/StorageWrapper.cs
2035
using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.IO.IsolatedStorage; namespace PhoneApp1 { public class StorageWrapper { private IsolatedStorageSettings _storage; public StorageWrapper(IsolatedStorageSettings storage) { _storage = storage; } public String LoadIfExists(string propertyName) { if (_storage.Contains(propertyName)) { return _storage[propertyName] as string; } else { return String.Empty; } } public void AddOrReplace(string propertyName, object value) { if (_storage.Contains(propertyName)) { _storage.Remove(propertyName); } _storage.Add(propertyName, value); } public AuthSettings LoadAuthSettings() { var AuthSettings = new AuthSettings(); AuthSettings.Host = LoadIfExists("auth_host"); String portString = LoadIfExists("auth_port"); int result; if (int.TryParse(portString, out result)) { AuthSettings.Port = result; } else { AuthSettings.Port = 8080; } AuthSettings.Username = LoadIfExists("auth_username"); AuthSettings.Password = LoadIfExists("auth_password"); return AuthSettings; } public void SaveAuthSettings(AuthSettings authSettings) { AddOrReplace("auth_host", authSettings.Host); AddOrReplace("auth_port", authSettings.Port.ToString()); AddOrReplace("auth_username", authSettings.Username); AddOrReplace("auth_password", authSettings.Password); } } }
mit
SantiMA10/HomePi
src/module/sensor/impl/RestSensor.ts
797
import { ReadData } from "../read" import * as requestPromise from "request-promise"; import {Configuration, RestOptions} from "../../../util/RestUtil"; export interface RestSensorConfig{ param : RestOptions, url : string } export class RestSensor implements ReadData{ param : RestOptions; options : Configuration; constructor(config : RestSensorConfig){ this.options = { "url" : config.url, "transform" : (body) => { return JSON.parse(body); } }; this.param = config.param; } get() : any { let ctx = this; return requestPromise(ctx.options) .then(body => { return body[ctx.param.ok]; }) .error(body => { return body[ctx.param.error]; }); } }
mit
coma/svg-reactify
src/index.js
3411
import { basename } from 'path'; import { transform as babel } from 'babel-core'; import react from 'babel-preset-react'; import SVGO from 'svgo'; import through from 'through2'; import camelCase from 'lodash.camelcase'; import kebabCase from 'lodash.kebabcase'; import template from './template'; const SVG_REGEX = /\.svg$/i; const SVG_ATTRS = [ 'accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'x-height' ]; const ATTR_REGEX = new RegExp(`(class|${SVG_ATTRS.join('|')})=`, 'g'); const svgo = new SVGO({ plugins: [ {convertStyleToAttrs: true}, {removeAttrs: {attrs: 'style'}}, {removeViewBox: false}, {removeUselessStrokeAndFill: false} ] }); const babelOptions = { presets: [react] }; function camelizeAttrs (code) { return code.replace(ATTR_REGEX, (line, attr) => { return attr !== 'class' ? camelCase(attr) + '=' : 'className=' }); } function transform (code) { return babel(camelizeAttrs(code), babelOptions).code; } function createTransformer (filename, template) { const name = kebabCase(basename(filename, '.svg')); let buffer = ''; function handleStream (chunk, encoding, next) { buffer += chunk.toString(); next(); } function finishStream (next) { svgo.optimize(buffer, svg => { this.push(template(name, transform(svg.data))); next(); }); } return through(handleStream, finishStream); } module.exports = (filename, options = {}) => { if (!SVG_REGEX.test(filename)) { return through(); } const type = Object .keys(template) .find(t => options[t] && (new RegExp(options[t])).test(filename)); return createTransformer(filename, template[type || options.default || 'icon']); };
mit
bokuweb/react-resizable-box
src/index.tsx
30190
import * as React from 'react'; import { Resizer, Direction } from './resizer'; import memoize from 'fast-memoize'; const DEFAULT_SIZE = { width: 'auto', height: 'auto', }; export type ResizeDirection = Direction; export interface Enable { top?: boolean; right?: boolean; bottom?: boolean; left?: boolean; topRight?: boolean; bottomRight?: boolean; bottomLeft?: boolean; topLeft?: boolean; } export interface HandleStyles { top?: React.CSSProperties; right?: React.CSSProperties; bottom?: React.CSSProperties; left?: React.CSSProperties; topRight?: React.CSSProperties; bottomRight?: React.CSSProperties; bottomLeft?: React.CSSProperties; topLeft?: React.CSSProperties; } export interface HandleClassName { top?: string; right?: string; bottom?: string; left?: string; topRight?: string; bottomRight?: string; bottomLeft?: string; topLeft?: string; } export interface Size { width: string | number; height: string | number; } export interface NumberSize { width: number; height: number; } export interface HandleComponent { top?: React.ReactElement<any>; right?: React.ReactElement<any>; bottom?: React.ReactElement<any>; left?: React.ReactElement<any>; topRight?: React.ReactElement<any>; bottomRight?: React.ReactElement<any>; bottomLeft?: React.ReactElement<any>; topLeft?: React.ReactElement<any>; } export type ResizeCallback = ( event: MouseEvent | TouchEvent, direction: Direction, elementRef: HTMLElement, delta: NumberSize, ) => void; export type ResizeStartCallback = ( e: React.MouseEvent<HTMLElement> | React.TouchEvent<HTMLElement>, dir: Direction, elementRef: HTMLElement, ) => void | boolean; export interface ResizableProps { as?: string | React.ComponentType<any>; style?: React.CSSProperties; className?: string; grid?: [number, number]; snap?: { x?: number[]; y?: number[]; }; snapGap?: number; bounds?: 'parent' | 'window' | HTMLElement; boundsByDirection?: boolean; size?: Size; minWidth?: string | number; minHeight?: string | number; maxWidth?: string | number; maxHeight?: string | number; lockAspectRatio?: boolean | number; lockAspectRatioExtraWidth?: number; lockAspectRatioExtraHeight?: number; enable?: Enable; handleStyles?: HandleStyles; handleClasses?: HandleClassName; handleWrapperStyle?: React.CSSProperties; handleWrapperClass?: string; handleComponent?: HandleComponent; children?: React.ReactNode; onResizeStart?: ResizeStartCallback; onResize?: ResizeCallback; onResizeStop?: ResizeCallback; defaultSize?: Size; scale?: number; resizeRatio?: number; } interface State { isResizing: boolean; direction: Direction; original: { x: number; y: number; width: number; height: number; }; width: number | string; height: number | string; backgroundStyle: React.CSSProperties; flexBasis?: string | number; } const clamp = memoize((n: number, min: number, max: number): number => Math.max(Math.min(n, max), min)); const snap = memoize((n: number, size: number): number => Math.round(n / size) * size); const hasDirection = memoize((dir: 'top' | 'right' | 'bottom' | 'left', target: string): boolean => new RegExp(dir, 'i').test(target), ); // INFO: In case of window is a Proxy and does not porxy Events correctly, use isTouchEvent & isMouseEvent to distinguish event type instead of `instanceof`. const isTouchEvent = (event: MouseEvent | TouchEvent): event is TouchEvent => { return Boolean((event as TouchEvent).touches && (event as TouchEvent).touches.length); }; const isMouseEvent = (event: MouseEvent | TouchEvent): event is MouseEvent => { return Boolean( ((event as MouseEvent).clientX || (event as MouseEvent).clientX === 0) && ((event as MouseEvent).clientY || (event as MouseEvent).clientY === 0), ); }; const findClosestSnap = memoize((n: number, snapArray: number[], snapGap: number = 0): number => { const closestGapIndex = snapArray.reduce( (prev, curr, index) => (Math.abs(curr - n) < Math.abs(snapArray[prev] - n) ? index : prev), 0, ); const gap = Math.abs(snapArray[closestGapIndex] - n); return snapGap === 0 || gap < snapGap ? snapArray[closestGapIndex] : n; }); const endsWith = memoize( (str: string, searchStr: string): boolean => str.substr(str.length - searchStr.length, searchStr.length) === searchStr, ); const getStringSize = memoize((n: number | string): string => { n = n.toString(); if (n === 'auto') { return n; } if (endsWith(n, 'px')) { return n; } if (endsWith(n, '%')) { return n; } if (endsWith(n, 'vh')) { return n; } if (endsWith(n, 'vw')) { return n; } if (endsWith(n, 'vmax')) { return n; } if (endsWith(n, 'vmin')) { return n; } return `${n}px`; }); const getPixelSize = ( size: undefined | string | number, parentSize: number, innerWidth: number, innerHeight: number, ) => { if (size && typeof size === 'string') { if (endsWith(size, 'px')) { return Number(size.replace('px', '')); } if (endsWith(size, '%')) { const ratio = Number(size.replace('%', '')) / 100; return parentSize * ratio; } if (endsWith(size, 'vw')) { const ratio = Number(size.replace('vw', '')) / 100; return innerWidth * ratio; } if (endsWith(size, 'vh')) { const ratio = Number(size.replace('vh', '')) / 100; return innerHeight * ratio; } } return size; }; const calculateNewMax = memoize( ( parentSize: { width: number; height: number }, innerWidth: number, innerHeight: number, maxWidth?: string | number, maxHeight?: string | number, minWidth?: string | number, minHeight?: string | number, ) => { maxWidth = getPixelSize(maxWidth, parentSize.width, innerWidth, innerHeight); maxHeight = getPixelSize(maxHeight, parentSize.height, innerWidth, innerHeight); minWidth = getPixelSize(minWidth, parentSize.width, innerWidth, innerHeight); minHeight = getPixelSize(minHeight, parentSize.height, innerWidth, innerHeight); return { maxWidth: typeof maxWidth === 'undefined' ? undefined : Number(maxWidth), maxHeight: typeof maxHeight === 'undefined' ? undefined : Number(maxHeight), minWidth: typeof minWidth === 'undefined' ? undefined : Number(minWidth), minHeight: typeof minHeight === 'undefined' ? undefined : Number(minHeight), }; }, ); const definedProps = [ 'as', 'style', 'className', 'grid', 'snap', 'bounds', 'boundsByDirection', 'size', 'defaultSize', 'minWidth', 'minHeight', 'maxWidth', 'maxHeight', 'lockAspectRatio', 'lockAspectRatioExtraWidth', 'lockAspectRatioExtraHeight', 'enable', 'handleStyles', 'handleClasses', 'handleWrapperStyle', 'handleWrapperClass', 'children', 'onResizeStart', 'onResize', 'onResizeStop', 'handleComponent', 'scale', 'resizeRatio', 'snapGap', ]; // HACK: This class is used to calculate % size. const baseClassName = '__resizable_base__'; declare global { interface Window { MouseEvent: typeof MouseEvent; TouchEvent: typeof TouchEvent; } } interface NewSize { newHeight: number | string; newWidth: number | string; } export class Resizable extends React.PureComponent<ResizableProps, State> { flexDir?: 'row' | 'column'; get parentNode(): HTMLElement | null { if (!this.resizable) { return null; } return this.resizable.parentNode as HTMLElement; } get window(): Window | null { if (!this.resizable) { return null; } if (!this.resizable.ownerDocument) { return null; } return this.resizable.ownerDocument.defaultView as Window; } get propsSize(): Size { return this.props.size || this.props.defaultSize || DEFAULT_SIZE; } get size(): NumberSize { let width = 0; let height = 0; if (this.resizable && this.window) { const orgWidth = this.resizable.offsetWidth; const orgHeight = this.resizable.offsetHeight; // HACK: Set position `relative` to get parent size. // This is because when re-resizable set `absolute`, I can not get base width correctly. const orgPosition = this.resizable.style.position; if (orgPosition !== 'relative') { this.resizable.style.position = 'relative'; } // INFO: Use original width or height if set auto. width = this.resizable.style.width !== 'auto' ? this.resizable.offsetWidth : orgWidth; height = this.resizable.style.height !== 'auto' ? this.resizable.offsetHeight : orgHeight; // Restore original position this.resizable.style.position = orgPosition; } return { width, height }; } get sizeStyle(): { width: string; height: string } { const { size } = this.props; const getSize = (key: 'width' | 'height'): string => { if (typeof this.state[key] === 'undefined' || this.state[key] === 'auto') { return 'auto'; } if (this.propsSize && this.propsSize[key] && endsWith(this.propsSize[key].toString(), '%')) { if (endsWith(this.state[key].toString(), '%')) { return this.state[key].toString(); } const parentSize = this.getParentSize(); const value = Number(this.state[key].toString().replace('px', '')); const percent = (value / parentSize[key]) * 100; return `${percent}%`; } return getStringSize(this.state[key]); }; const width = size && typeof size.width !== 'undefined' && !this.state.isResizing ? getStringSize(size.width) : getSize('width'); const height = size && typeof size.height !== 'undefined' && !this.state.isResizing ? getStringSize(size.height) : getSize('height'); return { width, height }; } public static defaultProps = { as: 'div', onResizeStart: () => {}, onResize: () => {}, onResizeStop: () => {}, enable: { top: true, right: true, bottom: true, left: true, topRight: true, bottomRight: true, bottomLeft: true, topLeft: true, }, style: {}, grid: [1, 1], lockAspectRatio: false, lockAspectRatioExtraWidth: 0, lockAspectRatioExtraHeight: 0, scale: 1, resizeRatio: 1, snapGap: 0, }; ratio = 1; resizable: HTMLElement | null = null; // For parent boundary parentLeft = 0; parentTop = 0; // For boundary resizableLeft = 0; resizableRight = 0; resizableTop = 0; resizableBottom = 0; // For target boundary targetLeft = 0; targetTop = 0; constructor(props: ResizableProps) { super(props); this.state = { isResizing: false, width: typeof (this.propsSize && this.propsSize.width) === 'undefined' ? 'auto' : this.propsSize && this.propsSize.width, height: typeof (this.propsSize && this.propsSize.height) === 'undefined' ? 'auto' : this.propsSize && this.propsSize.height, direction: 'right', original: { x: 0, y: 0, width: 0, height: 0, }, backgroundStyle: { height: '100%', width: '100%', backgroundColor: 'rgba(0,0,0,0)', cursor: 'auto', opacity: 0, position: 'fixed', zIndex: 9999, top: '0', left: '0', bottom: '0', right: '0', }, flexBasis: undefined, }; this.onResizeStart = this.onResizeStart.bind(this); this.onMouseMove = this.onMouseMove.bind(this); this.onMouseUp = this.onMouseUp.bind(this); } getParentSize(): { width: number; height: number } { if (!this.parentNode) { if (!this.window) { return { width: 0, height: 0 }; } return { width: this.window.innerWidth, height: this.window.innerHeight }; } const base = this.appendBase(); if (!base) { return { width: 0, height: 0 }; } // INFO: To calculate parent width with flex layout let wrapChanged = false; const wrap = this.parentNode.style.flexWrap; if (wrap !== 'wrap') { wrapChanged = true; this.parentNode.style.flexWrap = 'wrap'; // HACK: Use relative to get parent padding size } base.style.position = 'relative'; base.style.minWidth = '100%'; const size = { width: base.offsetWidth, height: base.offsetHeight, }; if (wrapChanged) { this.parentNode.style.flexWrap = wrap; } this.removeBase(base); return size; } bindEvents() { if (this.window) { this.window.addEventListener('mouseup', this.onMouseUp); this.window.addEventListener('mousemove', this.onMouseMove); this.window.addEventListener('mouseleave', this.onMouseUp); this.window.addEventListener('touchmove', this.onMouseMove, { capture: true, passive: false, }); this.window.addEventListener('touchend', this.onMouseUp); } } unbindEvents() { if (this.window) { this.window.removeEventListener('mouseup', this.onMouseUp); this.window.removeEventListener('mousemove', this.onMouseMove); this.window.removeEventListener('mouseleave', this.onMouseUp); this.window.removeEventListener('touchmove', this.onMouseMove, true); this.window.removeEventListener('touchend', this.onMouseUp); } } componentDidMount() { if (!this.resizable || !this.window) { return; } const computedStyle = this.window.getComputedStyle(this.resizable); this.setState({ width: this.state.width || this.size.width, height: this.state.height || this.size.height, flexBasis: computedStyle.flexBasis !== 'auto' ? computedStyle.flexBasis : undefined, }); } appendBase = () => { if (!this.resizable || !this.window) { return null; } const parent = this.parentNode; if (!parent) { return null; } const element = this.window.document.createElement('div'); element.style.width = '100%'; element.style.height = '100%'; element.style.position = 'absolute'; element.style.transform = 'scale(0, 0)'; element.style.left = '0'; element.style.flex = '0'; if (element.classList) { element.classList.add(baseClassName); } else { element.className += baseClassName; } parent.appendChild(element); return element; }; removeBase = (base: HTMLElement) => { const parent = this.parentNode; if (!parent) { return; } parent.removeChild(base); }; componentWillUnmount() { if (this.window) { this.unbindEvents(); } } createSizeForCssProperty(newSize: number | string, kind: 'width' | 'height'): number | string { const propsSize = this.propsSize && this.propsSize[kind]; return this.state[kind] === 'auto' && this.state.original[kind] === newSize && (typeof propsSize === 'undefined' || propsSize === 'auto') ? 'auto' : newSize; } calculateNewMaxFromBoundary(maxWidth?: number, maxHeight?: number) { const { boundsByDirection } = this.props; const { direction } = this.state; const widthByDirection = boundsByDirection && hasDirection('left', direction); const heightByDirection = boundsByDirection && hasDirection('top', direction); let boundWidth; let boundHeight; if (this.props.bounds === 'parent') { const parent = this.parentNode; if (parent) { boundWidth = widthByDirection ? this.resizableRight - this.parentLeft : parent.offsetWidth + (this.parentLeft - this.resizableLeft); boundHeight = heightByDirection ? this.resizableBottom - this.parentTop : parent.offsetHeight + (this.parentTop - this.resizableTop); } } else if (this.props.bounds === 'window') { if (this.window) { boundWidth = widthByDirection ? this.resizableRight : this.window.innerWidth - this.resizableLeft; boundHeight = heightByDirection ? this.resizableBottom : this.window.innerHeight - this.resizableTop; } } else if (this.props.bounds) { boundWidth = widthByDirection ? this.resizableRight - this.targetLeft : this.props.bounds.offsetWidth + (this.targetLeft - this.resizableLeft); boundHeight = heightByDirection ? this.resizableBottom - this.targetTop : this.props.bounds.offsetHeight + (this.targetTop - this.resizableTop); } if (boundWidth && Number.isFinite(boundWidth)) { maxWidth = maxWidth && maxWidth < boundWidth ? maxWidth : boundWidth; } if (boundHeight && Number.isFinite(boundHeight)) { maxHeight = maxHeight && maxHeight < boundHeight ? maxHeight : boundHeight; } return { maxWidth, maxHeight }; } calculateNewSizeFromDirection(clientX: number, clientY: number) { const scale = this.props.scale || 1; const resizeRatio = this.props.resizeRatio || 1; const { direction, original } = this.state; const { lockAspectRatio, lockAspectRatioExtraHeight, lockAspectRatioExtraWidth } = this.props; let newWidth = original.width; let newHeight = original.height; const extraHeight = lockAspectRatioExtraHeight || 0; const extraWidth = lockAspectRatioExtraWidth || 0; if (hasDirection('right', direction)) { newWidth = original.width + ((clientX - original.x) * resizeRatio) / scale; if (lockAspectRatio) { newHeight = (newWidth - extraWidth) / this.ratio + extraHeight; } } if (hasDirection('left', direction)) { newWidth = original.width - ((clientX - original.x) * resizeRatio) / scale; if (lockAspectRatio) { newHeight = (newWidth - extraWidth) / this.ratio + extraHeight; } } if (hasDirection('bottom', direction)) { newHeight = original.height + ((clientY - original.y) * resizeRatio) / scale; if (lockAspectRatio) { newWidth = (newHeight - extraHeight) * this.ratio + extraWidth; } } if (hasDirection('top', direction)) { newHeight = original.height - ((clientY - original.y) * resizeRatio) / scale; if (lockAspectRatio) { newWidth = (newHeight - extraHeight) * this.ratio + extraWidth; } } return { newWidth, newHeight }; } calculateNewSizeFromAspectRatio( newWidth: number, newHeight: number, max: { width?: number; height?: number }, min: { width?: number; height?: number }, ) { const { lockAspectRatio, lockAspectRatioExtraHeight, lockAspectRatioExtraWidth } = this.props; const computedMinWidth = typeof min.width === 'undefined' ? 10 : min.width; const computedMaxWidth = typeof max.width === 'undefined' || max.width < 0 ? newWidth : max.width; const computedMinHeight = typeof min.height === 'undefined' ? 10 : min.height; const computedMaxHeight = typeof max.height === 'undefined' || max.height < 0 ? newHeight : max.height; const extraHeight = lockAspectRatioExtraHeight || 0; const extraWidth = lockAspectRatioExtraWidth || 0; if (lockAspectRatio) { const extraMinWidth = (computedMinHeight - extraHeight) * this.ratio + extraWidth; const extraMaxWidth = (computedMaxHeight - extraHeight) * this.ratio + extraWidth; const extraMinHeight = (computedMinWidth - extraWidth) / this.ratio + extraHeight; const extraMaxHeight = (computedMaxWidth - extraWidth) / this.ratio + extraHeight; const lockedMinWidth = Math.max(computedMinWidth, extraMinWidth); const lockedMaxWidth = Math.min(computedMaxWidth, extraMaxWidth); const lockedMinHeight = Math.max(computedMinHeight, extraMinHeight); const lockedMaxHeight = Math.min(computedMaxHeight, extraMaxHeight); newWidth = clamp(newWidth, lockedMinWidth, lockedMaxWidth); newHeight = clamp(newHeight, lockedMinHeight, lockedMaxHeight); } else { newWidth = clamp(newWidth, computedMinWidth, computedMaxWidth); newHeight = clamp(newHeight, computedMinHeight, computedMaxHeight); } return { newWidth, newHeight }; } setBoundingClientRect() { // For parent boundary if (this.props.bounds === 'parent') { const parent = this.parentNode; if (parent) { const parentRect = parent.getBoundingClientRect(); this.parentLeft = parentRect.left; this.parentTop = parentRect.top; } } // For target(html element) boundary if (this.props.bounds && typeof this.props.bounds !== 'string') { const targetRect = this.props.bounds.getBoundingClientRect(); this.targetLeft = targetRect.left; this.targetTop = targetRect.top; } // For boundary if (this.resizable) { const { left, top, right, bottom } = this.resizable.getBoundingClientRect(); this.resizableLeft = left; this.resizableRight = right; this.resizableTop = top; this.resizableBottom = bottom; } } onResizeStart(event: React.MouseEvent<HTMLElement> | React.TouchEvent<HTMLElement>, direction: Direction) { if (!this.resizable || !this.window) { return; } let clientX = 0; let clientY = 0; if (event.nativeEvent && isMouseEvent(event.nativeEvent)) { clientX = event.nativeEvent.clientX; clientY = event.nativeEvent.clientY; // When user click with right button the resize is stuck in resizing mode // until users clicks again, dont continue if right click is used. // HACK: MouseEvent does not have `which` from flow-bin v0.68. if (event.nativeEvent.which === 3) { return; } } else if (event.nativeEvent && isTouchEvent(event.nativeEvent)) { clientX = (event.nativeEvent as TouchEvent).touches[0].clientX; clientY = (event.nativeEvent as TouchEvent).touches[0].clientY; } if (this.props.onResizeStart) { if (this.resizable) { const startResize = this.props.onResizeStart(event, direction, this.resizable); if (startResize === false) { return; } } } // Fix #168 if (this.props.size) { if (typeof this.props.size.height !== 'undefined' && this.props.size.height !== this.state.height) { this.setState({ height: this.props.size.height }); } if (typeof this.props.size.width !== 'undefined' && this.props.size.width !== this.state.width) { this.setState({ width: this.props.size.width }); } } // For lockAspectRatio case this.ratio = typeof this.props.lockAspectRatio === 'number' ? this.props.lockAspectRatio : this.size.width / this.size.height; let flexBasis; const computedStyle = this.window.getComputedStyle(this.resizable); if (computedStyle.flexBasis !== 'auto') { const parent = this.parentNode; if (parent) { const dir = this.window.getComputedStyle(parent).flexDirection; this.flexDir = dir.startsWith('row') ? 'row' : 'column'; flexBasis = computedStyle.flexBasis; } } // For boundary this.setBoundingClientRect(); this.bindEvents(); const state = { original: { x: clientX, y: clientY, width: this.size.width, height: this.size.height, }, isResizing: true, backgroundStyle: { ...this.state.backgroundStyle, cursor: this.window.getComputedStyle(event.target as HTMLElement).cursor || 'auto', }, direction, flexBasis, }; this.setState(state); } onMouseMove(event: MouseEvent | TouchEvent) { if (!this.state.isResizing || !this.resizable || !this.window) { return; } if (this.window.TouchEvent && isTouchEvent(event)) { try { event.preventDefault(); event.stopPropagation(); } catch (e) { // Ignore on fail } } let { maxWidth, maxHeight, minWidth, minHeight } = this.props; const clientX = isTouchEvent(event) ? event.touches[0].clientX : event.clientX; const clientY = isTouchEvent(event) ? event.touches[0].clientY : event.clientY; const { direction, original, width, height } = this.state; const parentSize = this.getParentSize(); const max = calculateNewMax( parentSize, this.window.innerWidth, this.window.innerHeight, maxWidth, maxHeight, minWidth, minHeight, ); maxWidth = max.maxWidth; maxHeight = max.maxHeight; minWidth = max.minWidth; minHeight = max.minHeight; // Calculate new size let { newHeight, newWidth }: NewSize = this.calculateNewSizeFromDirection(clientX, clientY); // Calculate max size from boundary settings const boundaryMax = this.calculateNewMaxFromBoundary(maxWidth, maxHeight); // Calculate new size from aspect ratio const newSize = this.calculateNewSizeFromAspectRatio( newWidth, newHeight, { width: boundaryMax.maxWidth, height: boundaryMax.maxHeight }, { width: minWidth, height: minHeight }, ); newWidth = newSize.newWidth; newHeight = newSize.newHeight; if (this.props.grid) { const newGridWidth = snap(newWidth, this.props.grid[0]); const newGridHeight = snap(newHeight, this.props.grid[1]); const gap = this.props.snapGap || 0; newWidth = gap === 0 || Math.abs(newGridWidth - newWidth) <= gap ? newGridWidth : newWidth; newHeight = gap === 0 || Math.abs(newGridHeight - newHeight) <= gap ? newGridHeight : newHeight; } if (this.props.snap && this.props.snap.x) { newWidth = findClosestSnap(newWidth, this.props.snap.x, this.props.snapGap); } if (this.props.snap && this.props.snap.y) { newHeight = findClosestSnap(newHeight, this.props.snap.y, this.props.snapGap); } const delta = { width: newWidth - original.width, height: newHeight - original.height, }; if (width && typeof width === 'string') { if (endsWith(width, '%')) { const percent = (newWidth / parentSize.width) * 100; newWidth = `${percent}%`; } else if (endsWith(width, 'vw')) { const vw = (newWidth / this.window.innerWidth) * 100; newWidth = `${vw}vw`; } else if (endsWith(width, 'vh')) { const vh = (newWidth / this.window.innerHeight) * 100; newWidth = `${vh}vh`; } } if (height && typeof height === 'string') { if (endsWith(height, '%')) { const percent = (newHeight / parentSize.height) * 100; newHeight = `${percent}%`; } else if (endsWith(height, 'vw')) { const vw = (newHeight / this.window.innerWidth) * 100; newHeight = `${vw}vw`; } else if (endsWith(height, 'vh')) { const vh = (newHeight / this.window.innerHeight) * 100; newHeight = `${vh}vh`; } } const newState: { width: string | number; height: string | number; flexBasis?: string | number } = { width: this.createSizeForCssProperty(newWidth, 'width'), height: this.createSizeForCssProperty(newHeight, 'height'), }; if (this.flexDir === 'row') { newState.flexBasis = newState.width; } else if (this.flexDir === 'column') { newState.flexBasis = newState.height; } this.setState(newState); if (this.props.onResize) { this.props.onResize(event, direction, this.resizable, delta); } } onMouseUp(event: MouseEvent | TouchEvent) { const { isResizing, direction, original } = this.state; if (!isResizing || !this.resizable) { return; } const delta = { width: this.size.width - original.width, height: this.size.height - original.height, }; if (this.props.onResizeStop) { this.props.onResizeStop(event, direction, this.resizable, delta); } if (this.props.size) { this.setState(this.props.size); } this.unbindEvents(); this.setState({ isResizing: false, backgroundStyle: { ...this.state.backgroundStyle, cursor: 'auto' }, }); } updateSize(size: Size) { this.setState({ width: size.width, height: size.height }); } renderResizer() { const { enable, handleStyles, handleClasses, handleWrapperStyle, handleWrapperClass, handleComponent } = this.props; if (!enable) { return null; } const resizers = Object.keys(enable).map(dir => { if (enable[dir as Direction] !== false) { return ( <Resizer key={dir} direction={dir as Direction} onResizeStart={this.onResizeStart} replaceStyles={handleStyles && handleStyles[dir as Direction]} className={handleClasses && handleClasses[dir as Direction]} > {handleComponent && handleComponent[dir as Direction] ? handleComponent[dir as Direction] : null} </Resizer> ); } return null; }); // #93 Wrap the resize box in span (will not break 100% width/height) return ( <div className={handleWrapperClass} style={handleWrapperStyle}> {resizers} </div> ); } ref = (c: HTMLElement | null) => { if (c) { this.resizable = c; } }; render() { const extendsProps = Object.keys(this.props).reduce((acc, key) => { if (definedProps.indexOf(key) !== -1) { return acc; } acc[key] = this.props[key as keyof ResizableProps]; return acc; }, {} as { [key: string]: any }); const style: React.CSSProperties = { position: 'relative', userSelect: this.state.isResizing ? 'none' : 'auto', ...this.props.style, ...this.sizeStyle, maxWidth: this.props.maxWidth, maxHeight: this.props.maxHeight, minWidth: this.props.minWidth, minHeight: this.props.minHeight, boxSizing: 'border-box', flexShrink: 0, }; if (this.state.flexBasis) { style.flexBasis = this.state.flexBasis; } const Wrapper = this.props.as || 'div'; return ( <Wrapper ref={this.ref} style={style} className={this.props.className} {...extendsProps}> {this.state.isResizing && <div style={this.state.backgroundStyle} />} {this.props.children} {this.renderResizer()} </Wrapper> ); } }
mit
Gletschr/ephedrine
ephedrine/src/EphedrineMath.cpp
11980
//----------------------------------------------------------------------------- // // Ephedrine API // // File: src/EphedrineMath.cpp // // Author: Kostarev Georgy // E-Mail: kostarevgi@gmail.com // //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // // License: MIT (opensource.org/licenses/MIT) // // Copyright © 2017 Kostarev Georgy // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- #include "EphedrineMath.h" #include "EphedrineArray.h" //----------------------------------------------------------------------------- #include "internal/Log.h" #include "internal/Array.h" #include "internal/Context.h" //----------------------------------------------------------------------------- namespace Ephedrine { //------------------------------------------------------------------------- namespace Math { //--------------------------------------------------------------------- bool validate(Internal::Array *a, Internal::Array *b) { return a->getType() == b->getType() && a->getSize() == b->getSize() && a->getContext() == b->getContext(); } //--------------------------------------------------------------------- bool validate( Internal::Array *a, Internal::Array *b, Internal::Array *c) { return validate(a, b) && validate(b, c); } //--------------------------------------------------------------------- bool aa_uop_ext(unsigned offset, Array *a) { Internal::Array *i_a = (Internal::Array *)(a); Type type = i_a->getType(); size_t size = i_a->getSize(); Internal::Context *context = i_a->getContext(); cl_mem mem[1] = { i_a->getMemory(), }; Internal::Program program; switch(type) { case Type::EPH_Char: program = Internal::Program(offset); break; case Type::EPH_UChar: program = Internal::Program(offset + 1); break; case Type::EPH_Short: program = Internal::Program(offset + 2); break; case Type::EPH_UShort: program = Internal::Program(offset + 3); break; case Type::EPH_Int: program = Internal::Program(offset + 4); break; case Type::EPH_UInt: program = Internal::Program(offset + 5); break; case Type::EPH_Long: program = Internal::Program(offset + 6); break; case Type::EPH_ULong: program = Internal::Program(offset + 7); break; case Type::EPH_Float: program = Internal::Program(offset + 8); break; case Type::EPH_Double: program = Internal::Program(offset + 9); break; default: Internal::Log::error( "undefined array type %i.", type); return false; } return context->runProgram(program, size, 1, mem); } //--------------------------------------------------------------------- bool aa_bop_ext(unsigned offset, Array *a, Array *b, Array *result) { Internal::Array *i_a = (Internal::Array *)(a); Internal::Array *i_b = (Internal::Array *)(b); Internal::Array *i_result = (Internal::Array *)(result); if(!validate(i_a, i_b, i_result)) { Internal::Log::error( "invalid array type/size/context."); return false; } Type type = i_a->getType(); size_t size = i_a->getSize(); Internal::Context *context = i_a->getContext(); cl_mem mem[3] = { i_a->getMemory(), i_b->getMemory(), i_result->getMemory(), }; Internal::Program program; switch(type) { case Type::EPH_Char: program = Internal::Program(offset); break; case Type::EPH_UChar: program = Internal::Program(offset + 1); break; case Type::EPH_Short: program = Internal::Program(offset + 2); break; case Type::EPH_UShort: program = Internal::Program(offset + 3); break; case Type::EPH_Int: program = Internal::Program(offset + 4); break; case Type::EPH_UInt: program = Internal::Program(offset + 5); break; case Type::EPH_Long: program = Internal::Program(offset + 6); break; case Type::EPH_ULong: program = Internal::Program(offset + 7); break; case Type::EPH_Float: program = Internal::Program(offset + 8); break; case Type::EPH_Double: program = Internal::Program(offset + 9); break; default: Internal::Log::error( "undefined array type %i.", type); return false; } return context->runProgram(program, size, 3, mem); } //--------------------------------------------------------------------- bool a_fn1_ext(unsigned offset, Array *a, Array *result) { Internal::Array *i_a = (Internal::Array *)(a); Internal::Array *i_result = (Internal::Array *)(result); Type type = i_a->getType(); size_t size = i_a->getSize(); Internal::Context *context = i_a->getContext(); if( i_result->getType() != type || i_result->getSize() != size || i_result->getContext() != context) { Internal::Log::error( "invalid array type/size/context."); return false; } cl_mem mem[2] = { i_a->getMemory(), i_result->getMemory(), }; Internal::Program program; switch(type) { case Type::EPH_Float: program = Internal::Program(offset); break; case Type::EPH_Double: program = Internal::Program(offset + 1); break; default: Internal::Log::error( "undefined array type %i.", type); return false; } return context->runProgram(program, size, 2, mem); } //--------------------------------------------------------------------- bool inc(Array *a) { return aa_uop_ext( Internal::Program::EPH_A_Inc_Char, a); } //--------------------------------------------------------------------- bool dec(Array *a) { return aa_uop_ext( Internal::Program::EPH_A_Dec_Char, a); } //--------------------------------------------------------------------- bool add(Array *a, Array *b, Array *result) { return aa_bop_ext( Internal::Program::EPH_AA_Add_Char, a, b, result); } //--------------------------------------------------------------------- bool sub(Array *a, Array *b, Array *result) { return aa_bop_ext( Internal::Program::EPH_AA_Sub_Char, a, b, result); } //--------------------------------------------------------------------- bool mul(Array *a, Array *b, Array *result) { return aa_bop_ext( Internal::Program::EPH_AA_Mul_Char, a, b, result); } //--------------------------------------------------------------------- bool div(Array *a, Array *b, Array *result) { return aa_bop_ext( Internal::Program::EPH_AA_Div_Char, a, b, result); } //--------------------------------------------------------------------- bool cos(Array *a, Array *result) { return a_fn1_ext( Internal::Program::EPH_A_Cos_Float, a, result); } //--------------------------------------------------------------------- bool sin(Array *a, Array *result) { return a_fn1_ext( Internal::Program::EPH_A_Sin_Float, a, result); } //--------------------------------------------------------------------- bool tan(Array *a, Array *result) { return a_fn1_ext( Internal::Program::EPH_A_Tan_Float, a, result); } //--------------------------------------------------------------------- bool acos(Array *a, Array *result) { return a_fn1_ext( Internal::Program::EPH_A_Acos_Float, a, result); } //--------------------------------------------------------------------- bool asin(Array *a, Array *result) { return a_fn1_ext( Internal::Program::EPH_A_Asin_Float, a, result); } //--------------------------------------------------------------------- bool atan(Array *a, Array *result) { return a_fn1_ext( Internal::Program::EPH_A_Atan_Float, a, result); } //--------------------------------------------------------------------- bool cbrt(Array *a, Array *result) { return a_fn1_ext( Internal::Program::EPH_A_Cbrt_Float, a, result); } //--------------------------------------------------------------------- bool ceil(Array *a, Array *result) { return a_fn1_ext( Internal::Program::EPH_A_Ceil_Float, a, result); } //--------------------------------------------------------------------- bool erf(Array *a, Array *result) { return a_fn1_ext( Internal::Program::EPH_A_Erf_Float, a, result); } //--------------------------------------------------------------------- bool erfc(Array *a, Array *result) { return a_fn1_ext( Internal::Program::EPH_A_Erfc_Float, a, result); } //--------------------------------------------------------------------- bool exp(Array *a, Array *result) { return a_fn1_ext( Internal::Program::EPH_A_Exp_Float, a, result); } //--------------------------------------------------------------------- bool exp2(Array *a, Array *result) { return a_fn1_ext( Internal::Program::EPH_A_Exp2_Float, a, result); } //--------------------------------------------------------------------- bool exp10(Array *a, Array *result) { return a_fn1_ext( Internal::Program::EPH_A_Exp10_Float, a, result); } //--------------------------------------------------------------------- bool fabs(Array *a, Array *result) { return a_fn1_ext( Internal::Program::EPH_A_Fabs_Float, a, result); } //--------------------------------------------------------------------- bool floor(Array *a, Array *result) { return a_fn1_ext( Internal::Program::EPH_A_Floor_Float, a, result); } //--------------------------------------------------------------------- bool log(Array *a, Array *result) { return a_fn1_ext( Internal::Program::EPH_A_Log_Float, a, result); } //--------------------------------------------------------------------- bool log2(Array *a, Array *result) { return a_fn1_ext( Internal::Program::EPH_A_Log2_Float, a, result); } //--------------------------------------------------------------------- bool log10(Array *a, Array *result) { return a_fn1_ext( Internal::Program::EPH_A_Log10_Float, a, result); } //--------------------------------------------------------------------- bool trunc(Array *a, Array *result) { return a_fn1_ext( Internal::Program::EPH_A_Trunc_Float, a, result); } //--------------------------------------------------------------------- bool round(Array *a, Array *result) { return a_fn1_ext( Internal::Program::EPH_A_Round_Float, a, result); } //--------------------------------------------------------------------- } //------------------------------------------------------------------------- } //-----------------------------------------------------------------------------
mit
selvasingh/azure-sdk-for-java
sdk/datafactory/mgmt-v2018_06_01/src/main/java/com/microsoft/azure/management/datafactory/v2018_06_01/CreateLinkedIntegrationRuntimeRequest.java
3634
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.datafactory.v2018_06_01; import com.fasterxml.jackson.annotation.JsonProperty; /** * The linked integration runtime information. */ public class CreateLinkedIntegrationRuntimeRequest { /** * The name of the linked integration runtime. */ @JsonProperty(value = "name") private String name; /** * The ID of the subscription that the linked integration runtime belongs * to. */ @JsonProperty(value = "subscriptionId") private String subscriptionId; /** * The name of the data factory that the linked integration runtime belongs * to. */ @JsonProperty(value = "dataFactoryName") private String dataFactoryName; /** * The location of the data factory that the linked integration runtime * belongs to. */ @JsonProperty(value = "dataFactoryLocation") private String dataFactoryLocation; /** * Get the name of the linked integration runtime. * * @return the name value */ public String name() { return this.name; } /** * Set the name of the linked integration runtime. * * @param name the name value to set * @return the CreateLinkedIntegrationRuntimeRequest object itself. */ public CreateLinkedIntegrationRuntimeRequest withName(String name) { this.name = name; return this; } /** * Get the ID of the subscription that the linked integration runtime belongs to. * * @return the subscriptionId value */ public String subscriptionId() { return this.subscriptionId; } /** * Set the ID of the subscription that the linked integration runtime belongs to. * * @param subscriptionId the subscriptionId value to set * @return the CreateLinkedIntegrationRuntimeRequest object itself. */ public CreateLinkedIntegrationRuntimeRequest withSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; return this; } /** * Get the name of the data factory that the linked integration runtime belongs to. * * @return the dataFactoryName value */ public String dataFactoryName() { return this.dataFactoryName; } /** * Set the name of the data factory that the linked integration runtime belongs to. * * @param dataFactoryName the dataFactoryName value to set * @return the CreateLinkedIntegrationRuntimeRequest object itself. */ public CreateLinkedIntegrationRuntimeRequest withDataFactoryName(String dataFactoryName) { this.dataFactoryName = dataFactoryName; return this; } /** * Get the location of the data factory that the linked integration runtime belongs to. * * @return the dataFactoryLocation value */ public String dataFactoryLocation() { return this.dataFactoryLocation; } /** * Set the location of the data factory that the linked integration runtime belongs to. * * @param dataFactoryLocation the dataFactoryLocation value to set * @return the CreateLinkedIntegrationRuntimeRequest object itself. */ public CreateLinkedIntegrationRuntimeRequest withDataFactoryLocation(String dataFactoryLocation) { this.dataFactoryLocation = dataFactoryLocation; return this; } }
mit
Shtereva/Fundamentals-with-CSharp
Regex/03. Karate Strings/KarateStrings.cs
1109
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _03.Karate_Strings { class KarateStrings { static void Main() { var path = Console.ReadLine(); int power = 0; for (int i = 0; i < path.Length; i++) { if (path[i] == '>') { power = int.Parse(path[i + 1].ToString()) + power; i++; while (power > 0) { if (i < path.Length && path[i] == '>') { break; } try { path = path.Remove(i, 1); } catch (Exception e) { } power--; } i--; } } Console.WriteLine(path); } } }
mit
optimumweb/anode
js/vendor/jquery.ajaxForm.js
5872
/* * ajaxForm * * Validate and send a form asynchronously * @author Jonathan Roy <jroy@optimumweb.ca> * @version 2.1 * @package wpboilerplate */ $(function() { "use strict"; // jshint ;_; jQuery.fn.ajaxForm = function() { return this.each(function() { // define form elements var $form = $(this); var $formFields = $form.find('.fields'); var $formSuccess = $form.find('.success'); var $formError = $form.find('.error'); var $formWarning = $form.find('.warning'); var $formLoading = $form.find('.loading'); // define form properties var formId = $form.attr('id'); var formAction = $form.attr('action'); var formMethod = $form.attr('method'); var formEnctype = $form.attr('enctype'); // hide response messages and loading $formSuccess.hide(); $formWarning.hide(); $formError.hide(); $formLoading.hide(); // track form start var formStarted = false; $formFields.find('input, textarea').keypress(function() { if ( !formStarted ) { formStarted = true; $form.addClass('started'); // trigger google analytics if ( typeof _gaq != 'undefined' ) { _gaq.push(['_trackEvent', 'AjaxForms', 'Start', formId]); } } }); $form.submit(function(e) { // prevent default page load e.preventDefault(); $formSuccess.hide(); $formWarning.hide(); $formError.hide(); // show that we are working in the background $formLoading.show(); // assume no errors in submission var inputError = false; // validation settings var validClass = 'valid success'; var invalidClass = 'invalid error'; // validate all required fields $form.find('.required').each(function() { var $input = $(this); var $group = $input.parents('.control-group').first(); if ( $input.val() == '' ) { inputError = true; $input.removeClass( validClass ).addClass( invalidClass ); $group.removeClass( validClass ).addClass( invalidClass ); } else { $input.removeClass( invalidClass ).addClass( validClass ); $group.removeClass( invalidClass ).addClass( validClass ); } }); // validate emails $form.find('.valid.email, .valid[type="email"]').each(function() { var $input = $(this); var emailRegex = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; if ( !emailRegex.test( $input.val() ) ) { inputError = true; $input.removeClass( validClass ).addClass( invalidClass ).parents('.control-group').removeClass( validClass ).addClass( invalidClass ); } else { $input.removeClass( invalidClass ).addClass( validClass ).parents('.control-group').removeClass( invalidClass ).addClass( validClass ); } }); if ( !inputError ) { $form.trigger('valid'); $.ajax({ type: formMethod, url: formAction, data: $form.serialize(), contentType: formEnctype, statusCode: { 200: function() { $formSuccess.fadeIn(); $formFields.hide(); $form.trigger('success').addClass('sent'); // trigger google analytics if ( typeof _gaq != 'undefined' ) { _gaq.push(['_trackEvent', 'AjaxForms', 'Success', formId]); } }, 400: function() { $formWarning.fadeIn(); $form.trigger('warning'); // trigger google analytics if ( typeof _gaq != 'undefined' ) { _gaq.push(['_trackEvent', 'AjaxForms', 'Warning', formId]); } }, 500: function() { $form.trigger('error'); $formError.fadeIn(); // trigger google analytics if ( typeof _gaq != 'undefined' ) { _gaq.push(['_trackEvent', 'AjaxForms', 'Error', formId]); } } } }); } else { $form.trigger('invalid'); $formSuccess.hide(); $formWarning.fadeIn(); $formError.error(); } // hide the loading $formLoading.hide(); }); // show that the form is ajax-enabled $form.trigger('enabled').addClass('ajax-enabled'); }); }; });
mit
TracKer/epguides-api
lib/EpGuidesAPI/Episode.php
2299
<?php namespace EpGuidesAPI; class Episode { /** * @var Show */ private $show; private $title; private $is_special; private $season; private $episode; private $number; private $release_date; private $raw_data; public function __construct($show, $episode_data) { $this->raw_data = $episode_data; $this->show = $show; $this->title = $episode_data['title']; $this->is_special = (strtolower($episode_data['special']) == 'y') ? true : false; if ($this->is_special) { $this->season = null; $this->episode = null; $this->number = null; } else { $this->season = (is_numeric($episode_data['season'])) ? intval($episode_data['season']) : null; $this->episode = (is_numeric($episode_data['episode'])) ? intval($episode_data['episode']) : null; $this->number = (is_numeric($episode_data['number'])) ? intval($episode_data['number']) : null; } // CST timezone. $timezone = new \DateTimeZone('Canada/Saskatchewan'); $date = \DateTime::createFromFormat('d/M/y H:i:s', $episode_data['airdate'] . ' 12:00:00', $timezone); $this->release_date = $date->getTimestamp(); unset($date); unset($timezone); } public function getShow() { return $this->show; } public function getTitle() { return $this->title; } public function isSpecial() { return $this->is_special; } public function getSeason() { return $this->season; } public function getEpisode() { if ($this->is_special) { return false; } return $this->episode; } public function getNumber() { if ($this->is_special) { return false; } return $this->number; } public function getReleaseDate() { return $this->release_date; } public function getNextEpisode() { $episodes = $this->show->getEpisodes(); $next_episode = null; $found = false; foreach ($episodes as $episode) { if ($found) { $next_episode = $episode; break; } if ($episode === $this) { $found = true; continue; } } unset($found); unset($episodes); if ($next_episode !== null) { return $next_episode; } return false; } public function getRawData() { return $this->raw_data; } }
mit
sportngin/indefinite_article
lib/indefinite_article/version.rb
49
module IndefiniteArticle VERSION = "0.1.2" end
mit
prashanth-cpaul/ReactReduxSample
src/lib/dataStub.js
3854
let ucl = "UEFA Champions League", laliga = "La Liga", espCup = "Spanish Cup", euLeague = "Europa League", commS = "Community Shield", fac = "FA Cup", prem = "Premier League", cc = "Carling Cup", intl = "International Friendly", atlMad = "Atletico Madrid", manUtd = "Manchester United"; export default { "2009-2010": [ { team: atlMad, competition: ucl, appearances: 1, saves: 6 }, { team: atlMad, competition: laliga, appearances: 19, saves: 66 }, { team: atlMad, competition: espCup, appearances: 7, saves: 23 }, { team: atlMad, competition: euLeague, appearances: 8, saves: 42 } ], "2010-2011": [ { team: atlMad, competition: "Super Cup", appearances: 1, saves: 5 }, { team: atlMad, competition: laliga, appearances: 38, saves: 154 }, { team: atlMad, competition: espCup, appearances: 2, saves: 6 }, { team: atlMad, competition: euLeague, appearances: 5, saves: 26 } ], "2011-2012": [ { team: manUtd, competition: commS, appearances: 1, saves: 3 }, { team: manUtd, competition: ucl, appearances: 4, saves: 11 }, { team: manUtd, competition: fac, appearances: 1, saves: 11 }, { team: manUtd, competition: prem, appearances: 29, saves: 102 }, { team: "Spain Under-21", competition: "UEFA U21", appearances: 5, saves: 8 }, { team: manUtd, competition: euLeague, appearances: 4, saves: 22 } ], "2012-2013": [ { team: "Spain", competition: "Olympics", appearances: 3, saves: 7 }, { team: manUtd, competition: ucl, appearances: 7, saves: 25 }, { team: manUtd, competition: fac, appearances: 5, saves: 21 }, { team: manUtd, competition: prem, appearances: 28, saves: 84 }, { team: manUtd, competition: cc, appearances: 1, saves: 4 } ], "2013-2014": [ { team: manUtd, competition: commS, appearances: 1, saves: 0 }, { team: "Spain", competition: intl, appearances: 5, saves: 11 }, { team: manUtd, competition: ucl, appearances: 10, saves: 19 }, { team: manUtd, competition: prem, appearances: 37, saves: 99 }, { team: "Spain Under-21", competition: "UEFA U21", appearances: 5, saves: 11 }, { team: manUtd, competition: cc, appearances: 4, saves: 2 } ], "2014-2015": [ { team: manUtd, competition: "Champions Cup", appearances: 3, saves: 7 }, { team: "Spain", competition: intl, appearances: 3, saves: 7 }, { team: manUtd, competition: fac, appearances: 5, saves: 16 }, { team: manUtd, competition: ucl, appearances: 10, saves: 19 }, { team: manUtd, competition: prem, appearances: 37, saves: 93 }, { team: manUtd, competition: cc, appearances: 1, saves: 2 } ], "2015-2016": [ { team: manUtd, competition: "Champions Cup", appearances: 2, saves: 4 }, { team: "Spain", competition: "World Cup Qualifiers", appearances: 4, saves: 2 }, { team: manUtd, competition: fac, appearances: 6, saves: 25 }, { team: manUtd, competition: ucl, appearances: 6, saves: 16 }, { team: manUtd, competition: prem, appearances: 34, saves: 83 }, { team: manUtd, competition: cc, appearances: 1, saves: 3 }, { team: manUtd, competition: euLeague, appearances: 3, saves: 12 } ], "2016-2017": [ { team: manUtd, competition: commS, appearances: 1, saves: 1 }, { team: "Spain", competition: "Euro 2016", appearances: 4, saves: 10 }, { team: manUtd, competition: fac, appearances: 1, saves: 4 }, { team: manUtd, competition: prem, appearances: 27, saves: 55 }, { team: manUtd, competition: cc, appearances: 5, saves: 10 }, { team: "Spain", competition: intl, appearances: 3, saves: 8 }, { team: manUtd, competition: euLeague, appearances: 3, saves: 6 } ], "current season":{ "Appearances": 27, "Cleansheets": 10, "Saves": 55, "Goals Conceded": 23 } };
mit
laobubu/HyperMD
rollup.config.js
1467
import buble from 'rollup-plugin-buble' import typescript from 'rollup-plugin-typescript2' import { uglify } from 'rollup-plugin-uglify' const { banner, globalNames, externalNames, bundleFiles } = require(__dirname + '/dev/HyperMD.config') const plugins = { ts: typescript({ tsconfigOverride: { compilerOptions: { "target": "es6", "module": "es6", "declaration": false, } } }), uglify: uglify({ output: { comments: /^!/, }, }), buble: buble({ namedFunctionExpressions: false, transforms: { dangerousForOf: true, // simplify `for (let i=0;i...)` to `for (let it of arr)` } }), } var configs = [] function isExternal(mod) { if (/\.css$/.test(mod)) return true for (const modBase of externalNames) { if (mod.substr(0, modBase.length) === modBase) return true } return false } bundleFiles.forEach(item => { var item_plugins = [plugins.ts] // Essential: typescript if (item.uglify) item_plugins.push(plugins.uglify) // optional: uglify item_plugins.push(plugins.buble) // Essential: Buble var _banner = banner if (item.banner) _banner += "\n" + item.banner var out = { input: "./" + item.entry, external: isExternal, output: { file: './' + item.output, format: 'umd', name: item.name, globals: globalNames, banner: _banner, }, plugins: item_plugins } configs.push(out) }) export default configs
mit
mbdavid/LiteDB
LiteDB.Stress/Program.cs
605
using LiteDB; using LiteDB.Engine; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; namespace LiteDB.Stress { public class Program { static void Main(string[] args) { var filename = args.Length >= 1 ? args[0] : ""; var duration = TimeSpanEx.Parse(args.Length >= 2 ? args[1] : "60s"); var e = new TestExecution(filename, duration); e.Execute(); Console.ReadKey(); } } }
mit
testbars/testbars
src/bitcoinrpc.cpp
119457
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2012 The Litecoin Developers // Copyright (c) 2013 adam m. // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "wallet.h" #include "db.h" #include "walletdb.h" #include "net.h" #include "init.h" #include "ui_interface.h" #include "base58.h" #include "bitcoinrpc.h" #undef printf #include <boost/asio.hpp> #include <boost/asio/ip/v6_only.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <boost/asio/ssl.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/shared_ptr.hpp> #include <list> #define printf OutputDebugStringF using namespace std; using namespace boost; using namespace boost::asio; using namespace json_spirit; void ThreadRPCServer2(void* parg); static std::string strRPCUserColonPass; static int64 nWalletUnlockTime; static CCriticalSection cs_nWalletUnlockTime; extern Value getconnectioncount(const Array& params, bool fHelp); // in rpcnet.cpp extern Value getpeerinfo(const Array& params, bool fHelp); extern Value dumpprivkey(const Array& params, bool fHelp); // in rpcdump.cpp extern Value importprivkey(const Array& params, bool fHelp); extern Value getrawtransaction(const Array& params, bool fHelp); // in rcprawtransaction.cpp extern Value listunspent(const Array& params, bool fHelp); extern Value createrawtransaction(const Array& params, bool fHelp); extern Value decoderawtransaction(const Array& params, bool fHelp); extern Value signrawtransaction(const Array& params, bool fHelp); extern Value sendrawtransaction(const Array& params, bool fHelp); const Object emptyobj; void ThreadRPCServer3(void* parg); Object JSONRPCError(int code, const string& message) { Object error; error.push_back(Pair("code", code)); error.push_back(Pair("message", message)); return error; } void RPCTypeCheck(const Array& params, const list<Value_type>& typesExpected) { unsigned int i = 0; BOOST_FOREACH(Value_type t, typesExpected) { if (params.size() <= i) break; const Value& v = params[i]; if (v.type() != t) { string err = strprintf("Expected type %s, got %s", Value_type_name[t], Value_type_name[v.type()]); throw JSONRPCError(-3, err); } i++; } } void RPCTypeCheck(const Object& o, const map<string, Value_type>& typesExpected) { BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected) { const Value& v = find_value(o, t.first); if (v.type() == null_type) throw JSONRPCError(-3, strprintf("Missing %s", t.first.c_str())); if (v.type() != t.second) { string err = strprintf("Expected type %s for %s, got %s", Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]); throw JSONRPCError(-3, err); } } } double GetDifficulty(const CBlockIndex* blockindex = NULL) { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (blockindex == NULL) { if (pindexBest == NULL) return 1.0; else blockindex = pindexBest; } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } int64 AmountFromValue(const Value& value) { double dAmount = value.get_real(); if (dAmount <= 0.0 || dAmount > 84000000.0) throw JSONRPCError(-3, "Invalid amount"); int64 nAmount = roundint64(dAmount * COIN); if (!MoneyRange(nAmount)) throw JSONRPCError(-3, "Invalid amount"); return nAmount; } Value ValueFromAmount(int64 amount) { return (double)amount / (double)COIN; } std::string HexBits(unsigned int nBits) { union { int32_t nBits; char cBits[4]; } uBits; uBits.nBits = htonl((int32_t)nBits); return HexStr(BEGIN(uBits.cBits), END(uBits.cBits)); } std::string HelpRequiringPassphrase() { return pwalletMain->IsCrypted() ? "\nrequires wallet passphrase to be set with walletpassphrase first" : ""; } void EnsureWalletIsUnlocked() { if (pwalletMain->IsLocked()) throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first."); } void WalletTxToJSON(const CWalletTx& wtx, Object& entry) { int confirms = wtx.GetDepthInMainChain(); entry.push_back(Pair("confirmations", confirms)); if (confirms) { entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex())); entry.push_back(Pair("blockindex", wtx.nIndex)); } entry.push_back(Pair("txid", wtx.GetHash().GetHex())); entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime())); BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue) entry.push_back(Pair(item.first, item.second)); } string AccountFromValue(const Value& value) { string strAccount = value.get_str(); if (strAccount == "*") throw JSONRPCError(-11, "Invalid account name"); return strAccount; } Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex) { Object result; result.push_back(Pair("hash", block.GetHash().GetHex())); CMerkleTx txGen(block.vtx[0]); txGen.SetMerkleBranch(&block); result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain())); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION))); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); Array txs; BOOST_FOREACH(const CTransaction&tx, block.vtx) txs.push_back(tx.GetHash().GetHex()); result.push_back(Pair("tx", txs)); result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime())); result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce)); result.push_back(Pair("bits", HexBits(block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); if (blockindex->pnext) result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex())); return result; } /// Note: This interface may still be subject to change. string CRPCTable::help(string strCommand) const { string strRet; set<rpcfn_type> setDone; for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi) { const CRPCCommand *pcmd = mi->second; string strMethod = mi->first; // We already filter duplicates, but these deprecated screw up the sort order if (strMethod.find("label") != string::npos) continue; if (strCommand != "" && strMethod != strCommand) continue; try { Array params; rpcfn_type pfn = pcmd->actor; if (setDone.insert(pfn).second) (*pfn)(params, true); } catch (std::exception& e) { // Help text is returned in an exception string strHelp = string(e.what()); if (strCommand == "") if (strHelp.find('\n') != string::npos) strHelp = strHelp.substr(0, strHelp.find('\n')); strRet += strHelp + "\n"; } } if (strRet == "") strRet = strprintf("help: unknown command: %s\n", strCommand.c_str()); strRet = strRet.substr(0,strRet.size()-1); return strRet; } Value help(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "help [command]\n" "List commands, or get help for a command."); string strCommand; if (params.size() > 0) strCommand = params[0].get_str(); return tableRPC.help(strCommand); } Value stop(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "stop\n" "Stop TestBars server."); // Shutdown will take long enough that the response should get back StartShutdown(); return "TestBars server has now stopped running!"; } Value getblockcount(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getblockcount\n" "Returns the number of blocks in the longest block chain."); return nBestHeight; } Value getdifficulty(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getdifficulty\n" "Returns the proof-of-work difficulty as a multiple of the minimum difficulty."); return GetDifficulty(); } // Litecoin: Return average network hashes per second based on last number of blocks. Value GetNetworkHashPS(int lookup) { if (pindexBest == NULL) return 0; // If lookup is -1, then use blocks since last difficulty change. if (lookup <= 0) lookup = pindexBest->nHeight % 2016 + 1; // If lookup is larger than chain, then set it to chain length. if (lookup > pindexBest->nHeight) lookup = pindexBest->nHeight; CBlockIndex* pindexPrev = pindexBest; for (int i = 0; i < lookup; i++) pindexPrev = pindexPrev->pprev; double timeDiff = pindexBest->GetBlockTime() - pindexPrev->GetBlockTime(); double timePerBlock = timeDiff / lookup; return (boost::int64_t)(((double)GetDifficulty() * pow(2.0, 32)) / timePerBlock); } Value getnetworkhashps(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getnetworkhashps [blocks]\n" "Returns the estimated network hashes per second based on the last 120 blocks.\n" "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change."); return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120); } Value getgenerate(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getgenerate\n" "Returns true or false."); return GetBoolArg("-gen"); } Value setgenerate(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setgenerate <generate> [genproclimit]\n" "<generate> is true or false to turn generation on or off.\n" "Generation is limited to [genproclimit] processors, -1 is unlimited."); bool fGenerate = true; if (params.size() > 0) fGenerate = params[0].get_bool(); if (params.size() > 1) { int nGenProcLimit = params[1].get_int(); mapArgs["-genproclimit"] = itostr(nGenProcLimit); if (nGenProcLimit == 0) fGenerate = false; } mapArgs["-gen"] = (fGenerate ? "1" : "0"); GenerateBitcoins(fGenerate, pwalletMain); return Value::null; } Value gethashespersec(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "gethashespersec\n" "Returns a recent hashes per second performance measurement while generating."); if (GetTimeMillis() - nHPSTimerStart > 8000) return (boost::int64_t)0; return (boost::int64_t)dHashesPerSec; } Value getinfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getinfo\n" "Returns an object containing various state info."); CService addrProxy; GetProxy(NET_IPV4, addrProxy); Object obj; obj.push_back(Pair("version", (int)CLIENT_VERSION)); obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION)); obj.push_back(Pair("walletversion", pwalletMain->GetVersion())); obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance()))); obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("connections", (int)vNodes.size())); obj.push_back(Pair("proxy", (addrProxy.IsValid() ? addrProxy.ToStringIPPort() : string()))); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("testnet", fTestNet)); obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime())); obj.push_back(Pair("keypoolsize", pwalletMain->GetKeyPoolSize())); obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee))); obj.push_back(Pair("mininput", ValueFromAmount(nMinimumInputValue))); if (pwalletMain->IsCrypted()) obj.push_back(Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime / 1000)); obj.push_back(Pair("errors", GetWarnings("statusbar"))); return obj; } Value getmininginfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getmininginfo\n" "Returns an object containing mining-related information."); Object obj; obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize)); obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx)); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("errors", GetWarnings("statusbar"))); obj.push_back(Pair("generate", GetBoolArg("-gen"))); obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1))); obj.push_back(Pair("hashespersec", gethashespersec(params, false))); obj.push_back(Pair("networkhashps", getnetworkhashps(params, false))); obj.push_back(Pair("pooledtx", (uint64_t)mempool.size())); obj.push_back(Pair("testnet", fTestNet)); return obj; } Value getnewaddress(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getnewaddress [account]\n" "Returns a new TestBars address for receiving payments. " "If [account] is specified (recommended), it is added to the address book " "so payments received with the address will be credited to [account]."); // Parse the account first so we don't generate a key if there's an error string strAccount; if (params.size() > 0) strAccount = AccountFromValue(params[0]); if (!pwalletMain->IsLocked()) pwalletMain->TopUpKeyPool(); // Generate a new key that is added to wallet CPubKey newKey; if (!pwalletMain->GetKeyFromPool(newKey, false)) throw JSONRPCError(-12, "Error: Keypool ran out, please call keypoolrefill first"); CKeyID keyID = newKey.GetID(); pwalletMain->SetAddressBookName(keyID, strAccount); return CBitcoinAddress(keyID).ToString(); } CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false) { CWalletDB walletdb(pwalletMain->strWalletFile); CAccount account; walletdb.ReadAccount(strAccount, account); bool bKeyUsed = false; // Check if the current key has been used if (account.vchPubKey.IsValid()) { CScript scriptPubKey; scriptPubKey.SetDestination(account.vchPubKey.GetID()); for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid(); ++it) { const CWalletTx& wtx = (*it).second; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) bKeyUsed = true; } } // Generate a new key if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed) { if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false)) throw JSONRPCError(-12, "Error: Keypool ran out, please call keypoolrefill first"); pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount); walletdb.WriteAccount(strAccount, account); } return CBitcoinAddress(account.vchPubKey.GetID()); } Value getaccountaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaccountaddress <account>\n" "Returns the current TestBars address for receiving payments to this account."); // Parse the account first so we don't generate a key if there's an error string strAccount = AccountFromValue(params[0]); Value ret; ret = GetAccountAddress(strAccount).ToString(); return ret; } Value setaccount(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setaccount <testbars address> <account>\n" "Sets the account associated with the given address."); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(-5, "Invalid TestBars address"); string strAccount; if (params.size() > 1) strAccount = AccountFromValue(params[1]); // Detect when changing the account of an address that is the 'unused current key' of another account: if (pwalletMain->mapAddressBook.count(address.Get())) { string strOldAccount = pwalletMain->mapAddressBook[address.Get()]; if (address == GetAccountAddress(strOldAccount)) GetAccountAddress(strOldAccount, true); } pwalletMain->SetAddressBookName(address.Get(), strAccount); return Value::null; } Value getaccount(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaccount <testbars address>\n" "Returns the account associated with the given address."); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(-5, "Invalid TestBars address"); string strAccount; map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get()); if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty()) strAccount = (*mi).second; return strAccount; } Value getaddressesbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaddressesbyaccount <account>\n" "Returns the list of addresses for the given account."); string strAccount = AccountFromValue(params[0]); // Find all addresses that have the given account Array ret; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strName = item.second; if (strName == strAccount) ret.push_back(address.ToString()); } return ret; } Value settxfee(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1) throw runtime_error( "settxfee <amount>\n" "<amount> is a real and is rounded to the nearest 0.00000001"); // Amount int64 nAmount = 0; if (params[0].get_real() != 0.0) nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts nTransactionFee = nAmount; return true; } Value setmininput(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1) throw runtime_error( "setmininput <amount>\n" "<amount> is a real and is rounded to the nearest 0.00000001"); // Amount int64 nAmount = 0; if (params[0].get_real() != 0.0) nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts nMinimumInputValue = nAmount; return true; } Value sendtoaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) throw runtime_error( "sendtoaddress <testbars address> <amount> [comment] [comment-to]\n" "<amount> is a real and is rounded to the nearest 0.00000001" + HelpRequiringPassphrase()); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(-5, "Invalid TestBars address"); // Amount int64 nAmount = AmountFromValue(params[1]); // Wallet comments CWalletTx wtx; if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty()) wtx.mapValue["comment"] = params[2].get_str(); if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) wtx.mapValue["to"] = params[3].get_str(); if (pwalletMain->IsLocked()) throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first."); string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); if (strError != "") throw JSONRPCError(-4, strError); return wtx.GetHash().GetHex(); } Value signmessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "signmessage <testbars address> <message>\n" "Sign a message with the private key of an address"); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); string strMessage = params[1].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(-3, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(-3, "Address does not refer to key"); CKey key; if (!pwalletMain->GetKey(keyID, key)) throw JSONRPCError(-4, "Private key not available"); CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; vector<unsigned char> vchSig; if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig)) throw JSONRPCError(-5, "Sign failed"); return EncodeBase64(&vchSig[0], vchSig.size()); } Value verifymessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 3) throw runtime_error( "verifymessage <testbars address> <signature> <message>\n" "Verify a signed message"); string strAddress = params[0].get_str(); string strSign = params[1].get_str(); string strMessage = params[2].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(-3, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(-3, "Address does not refer to key"); bool fInvalid = false; vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid); if (fInvalid) throw JSONRPCError(-5, "Malformed base64 encoding"); CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; CKey key; if (!key.SetCompactSignature(Hash(ss.begin(), ss.end()), vchSig)) return false; return (key.GetPubKey().GetID() == keyID); } Value getreceivedbyaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getreceivedbyaddress <testbars address> [minconf=1]\n" "Returns the total amount received by <testbars address> in transactions with at least [minconf] confirmations."); // TestBars address CBitcoinAddress address = CBitcoinAddress(params[0].get_str()); CScript scriptPubKey; if (!address.IsValid()) throw JSONRPCError(-5, "Invalid TestBars address"); scriptPubKey.SetDestination(address.Get()); if (!IsMine(*pwalletMain,scriptPubKey)) return (double)0.0; // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Tally int64 nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !wtx.IsFinal()) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } return ValueFromAmount(nAmount); } void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook) { const CTxDestination& address = item.first; const string& strName = item.second; if (strName == strAccount) setAddress.insert(address); } } Value getreceivedbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getreceivedbyaccount <account> [minconf=1]\n" "Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations."); // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Get the set of pub keys assigned to account string strAccount = AccountFromValue(params[0]); set<CTxDestination> setAddress; GetAccountAddresses(strAccount, setAddress); // Tally int64 nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !wtx.IsFinal()) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address)) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } } return (double)nAmount / (double)COIN; } int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth) { int64 nBalance = 0; // Tally wallet transactions for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!wtx.IsFinal()) continue; int64 nGenerated, nReceived, nSent, nFee; wtx.GetAccountAmounts(strAccount, nGenerated, nReceived, nSent, nFee); if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth) nBalance += nReceived; nBalance += nGenerated - nSent - nFee; } // Tally internal accounting entries nBalance += walletdb.GetAccountCreditDebit(strAccount); return nBalance; } int64 GetAccountBalance(const string& strAccount, int nMinDepth) { CWalletDB walletdb(pwalletMain->strWalletFile); return GetAccountBalance(walletdb, strAccount, nMinDepth); } Value getbalance(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getbalance [account] [minconf=1]\n" "If [account] is not specified, returns the server's total available balance.\n" "If [account] is specified, returns the balance in the account."); if (params.size() == 0) return ValueFromAmount(pwalletMain->GetBalance()); int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); if (params[0].get_str() == "*") { // Calculate total balance a different way from GetBalance() // (GetBalance() sums up all unspent TxOuts) // getbalance and getbalance '*' should always return the same number. int64 nBalance = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!wtx.IsFinal()) continue; int64 allGeneratedImmature, allGeneratedMature, allFee; allGeneratedImmature = allGeneratedMature = allFee = 0; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount); if (wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived) nBalance += r.second; } BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listSent) nBalance -= r.second; nBalance -= allFee; nBalance += allGeneratedMature; } return ValueFromAmount(nBalance); } string strAccount = AccountFromValue(params[0]); int64 nBalance = GetAccountBalance(strAccount, nMinDepth); return ValueFromAmount(nBalance); } Value movecmd(const Array& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 5) throw runtime_error( "move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n" "Move from one account in your wallet to another."); string strFrom = AccountFromValue(params[0]); string strTo = AccountFromValue(params[1]); int64 nAmount = AmountFromValue(params[2]); if (params.size() > 3) // unused parameter, used to be nMinDepth, keep type-checking it though (void)params[3].get_int(); string strComment; if (params.size() > 4) strComment = params[4].get_str(); CWalletDB walletdb(pwalletMain->strWalletFile); if (!walletdb.TxnBegin()) throw JSONRPCError(-20, "database error"); int64 nNow = GetAdjustedTime(); // Debit CAccountingEntry debit; debit.strAccount = strFrom; debit.nCreditDebit = -nAmount; debit.nTime = nNow; debit.strOtherAccount = strTo; debit.strComment = strComment; walletdb.WriteAccountingEntry(debit); // Credit CAccountingEntry credit; credit.strAccount = strTo; credit.nCreditDebit = nAmount; credit.nTime = nNow; credit.strOtherAccount = strFrom; credit.strComment = strComment; walletdb.WriteAccountingEntry(credit); if (!walletdb.TxnCommit()) throw JSONRPCError(-20, "database error"); return true; } Value sendfrom(const Array& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 6) throw runtime_error( "sendfrom <fromaccount> <to testbars address> <amount> [minconf=1] [comment] [comment-to]\n" "<amount> is a real and is rounded to the nearest 0.00000001" + HelpRequiringPassphrase()); string strAccount = AccountFromValue(params[0]); CBitcoinAddress address(params[1].get_str()); if (!address.IsValid()) throw JSONRPCError(-5, "Invalid TestBars address"); int64 nAmount = AmountFromValue(params[2]); int nMinDepth = 1; if (params.size() > 3) nMinDepth = params[3].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty()) wtx.mapValue["comment"] = params[4].get_str(); if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty()) wtx.mapValue["to"] = params[5].get_str(); EnsureWalletIsUnlocked(); // Check funds int64 nBalance = GetAccountBalance(strAccount, nMinDepth); if (nAmount > nBalance) throw JSONRPCError(-6, "Account has insufficient funds"); // Send string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); if (strError != "") throw JSONRPCError(-4, strError); return wtx.GetHash().GetHex(); } Value sendmany(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) throw runtime_error( "sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n" "amounts are double-precision floating point numbers" + HelpRequiringPassphrase()); string strAccount = AccountFromValue(params[0]); Object sendTo = params[1].get_obj(); int nMinDepth = 1; if (params.size() > 2) nMinDepth = params[2].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) wtx.mapValue["comment"] = params[3].get_str(); set<CBitcoinAddress> setAddress; vector<pair<CScript, int64> > vecSend; int64 totalAmount = 0; BOOST_FOREACH(const Pair& s, sendTo) { CBitcoinAddress address(s.name_); if (!address.IsValid()) throw JSONRPCError(-5, string("Invalid TestBars address:")+s.name_); if (setAddress.count(address)) throw JSONRPCError(-8, string("Invalid parameter, duplicated address: ")+s.name_); setAddress.insert(address); CScript scriptPubKey; scriptPubKey.SetDestination(address.Get()); int64 nAmount = AmountFromValue(s.value_); totalAmount += nAmount; vecSend.push_back(make_pair(scriptPubKey, nAmount)); } EnsureWalletIsUnlocked(); // Check funds int64 nBalance = GetAccountBalance(strAccount, nMinDepth); if (totalAmount > nBalance) throw JSONRPCError(-6, "Account has insufficient funds"); // Send CReserveKey keyChange(pwalletMain); int64 nFeeRequired = 0; bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired); if (!fCreated) { if (totalAmount + nFeeRequired > pwalletMain->GetBalance()) throw JSONRPCError(-6, "Insufficient funds"); throw JSONRPCError(-4, "Transaction creation failed"); } if (!pwalletMain->CommitTransaction(wtx, keyChange)) throw JSONRPCError(-4, "Transaction commit failed"); return wtx.GetHash().GetHex(); } Value addmultisigaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) { string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n" "Add a nrequired-to-sign multisignature address to the wallet\"\n" "each key is a TestBars address or hex-encoded public key\n" "If [account] is specified, assign address to [account]."; throw runtime_error(msg); } int nRequired = params[0].get_int(); const Array& keys = params[1].get_array(); string strAccount; if (params.size() > 2) strAccount = AccountFromValue(params[2]); // Gather public keys if (nRequired < 1) throw runtime_error("a multisignature address must require at least one key to redeem"); if ((int)keys.size() < nRequired) throw runtime_error( strprintf("not enough keys supplied " "(got %d keys, but need at least %d to redeem)", keys.size(), nRequired)); std::vector<CKey> pubkeys; pubkeys.resize(keys.size()); for (unsigned int i = 0; i < keys.size(); i++) { const std::string& ks = keys[i].get_str(); // Case 1: TestBars address and we have full public key: CBitcoinAddress address(ks); if (address.IsValid()) { CKeyID keyID; if (!address.GetKeyID(keyID)) throw runtime_error( strprintf("%s does not refer to a key",ks.c_str())); CPubKey vchPubKey; if (!pwalletMain->GetPubKey(keyID, vchPubKey)) throw runtime_error( strprintf("no full public key for address %s",ks.c_str())); if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey)) throw runtime_error(" Invalid public key: "+ks); } // Case 2: hex public key else if (IsHex(ks)) { CPubKey vchPubKey(ParseHex(ks)); if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey)) throw runtime_error(" Invalid public key: "+ks); } else { throw runtime_error(" Invalid public key: "+ks); } } // Construct using pay-to-script-hash: CScript inner; inner.SetMultisig(nRequired, pubkeys); CScriptID innerID = inner.GetID(); pwalletMain->AddCScript(inner); pwalletMain->SetAddressBookName(innerID, strAccount); return CBitcoinAddress(innerID).ToString(); } struct tallyitem { int64 nAmount; int nConf; tallyitem() { nAmount = 0; nConf = std::numeric_limits<int>::max(); } }; Value ListReceived(const Array& params, bool fByAccounts) { // Minimum confirmations int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); // Whether to include empty accounts bool fIncludeEmpty = false; if (params.size() > 1) fIncludeEmpty = params[1].get_bool(); // Tally map<CBitcoinAddress, tallyitem> mapTally; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !wtx.IsFinal()) continue; int nDepth = wtx.GetDepthInMainChain(); if (nDepth < nMinDepth) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address)) continue; tallyitem& item = mapTally[address]; item.nAmount += txout.nValue; item.nConf = min(item.nConf, nDepth); } } // Reply Array ret; map<string, tallyitem> mapAccountTally; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strAccount = item.second; map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address); if (it == mapTally.end() && !fIncludeEmpty) continue; int64 nAmount = 0; int nConf = std::numeric_limits<int>::max(); if (it != mapTally.end()) { nAmount = (*it).second.nAmount; nConf = (*it).second.nConf; } if (fByAccounts) { tallyitem& item = mapAccountTally[strAccount]; item.nAmount += nAmount; item.nConf = min(item.nConf, nConf); } else { Object obj; obj.push_back(Pair("address", address.ToString())); obj.push_back(Pair("account", strAccount)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); ret.push_back(obj); } } if (fByAccounts) { for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it) { int64 nAmount = (*it).second.nAmount; int nConf = (*it).second.nConf; Object obj; obj.push_back(Pair("account", (*it).first)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); ret.push_back(obj); } } return ret; } Value listreceivedbyaddress(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "listreceivedbyaddress [minconf=1] [includeempty=false]\n" "[minconf] is the minimum number of confirmations before payments are included.\n" "[includeempty] whether to include addresses that haven't received any payments.\n" "Returns an array of objects containing:\n" " \"address\" : receiving address\n" " \"account\" : the account of the receiving address\n" " \"amount\" : total amount received by the address\n" " \"confirmations\" : number of confirmations of the most recent transaction included"); return ListReceived(params, false); } Value listreceivedbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "listreceivedbyaccount [minconf=1] [includeempty=false]\n" "[minconf] is the minimum number of confirmations before payments are included.\n" "[includeempty] whether to include accounts that haven't received any payments.\n" "Returns an array of objects containing:\n" " \"account\" : the account of the receiving addresses\n" " \"amount\" : total amount received by addresses with this account\n" " \"confirmations\" : number of confirmations of the most recent transaction included"); return ListReceived(params, true); } void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret) { int64 nGeneratedImmature, nGeneratedMature, nFee; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount); bool fAllAccounts = (strAccount == string("*")); // Generated blocks assigned to account "" if ((nGeneratedMature+nGeneratedImmature) != 0 && (fAllAccounts || strAccount == "")) { Object entry; entry.push_back(Pair("account", string(""))); if (nGeneratedImmature) { entry.push_back(Pair("category", wtx.GetDepthInMainChain() ? "immature" : "orphan")); entry.push_back(Pair("amount", ValueFromAmount(nGeneratedImmature))); } else { entry.push_back(Pair("category", "generate")); entry.push_back(Pair("amount", ValueFromAmount(nGeneratedMature))); } if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } // Sent if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount)) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent) { Object entry; entry.push_back(Pair("account", strSentAccount)); entry.push_back(Pair("address", CBitcoinAddress(s.first).ToString())); entry.push_back(Pair("category", "send")); entry.push_back(Pair("amount", ValueFromAmount(-s.second))); entry.push_back(Pair("fee", ValueFromAmount(-nFee))); if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } } // Received if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived) { string account; if (pwalletMain->mapAddressBook.count(r.first)) account = pwalletMain->mapAddressBook[r.first]; if (fAllAccounts || (account == strAccount)) { Object entry; entry.push_back(Pair("account", account)); entry.push_back(Pair("address", CBitcoinAddress(r.first).ToString())); entry.push_back(Pair("category", "receive")); entry.push_back(Pair("amount", ValueFromAmount(r.second))); if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } } } } void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret) { bool fAllAccounts = (strAccount == string("*")); if (fAllAccounts || acentry.strAccount == strAccount) { Object entry; entry.push_back(Pair("account", acentry.strAccount)); entry.push_back(Pair("category", "move")); entry.push_back(Pair("time", (boost::int64_t)acentry.nTime)); entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit))); entry.push_back(Pair("otheraccount", acentry.strOtherAccount)); entry.push_back(Pair("comment", acentry.strComment)); ret.push_back(entry); } } Value listtransactions(const Array& params, bool fHelp) { if (fHelp || params.size() > 3) throw runtime_error( "listtransactions [account] [count=10] [from=0]\n" "Returns up to [count] most recent transactions skipping the first [from] transactions for account [account]."); string strAccount = "*"; if (params.size() > 0) strAccount = params[0].get_str(); int nCount = 10; if (params.size() > 1) nCount = params[1].get_int(); int nFrom = 0; if (params.size() > 2) nFrom = params[2].get_int(); if (nCount < 0) throw JSONRPCError(-8, "Negative count"); if (nFrom < 0) throw JSONRPCError(-8, "Negative from"); Array ret; CWalletDB walletdb(pwalletMain->strWalletFile); // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap. typedef pair<CWalletTx*, CAccountingEntry*> TxPair; typedef multimap<int64, TxPair > TxItems; TxItems txByTime; // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry // would make this much faster for applications that do this a lot. for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { CWalletTx* wtx = &((*it).second); txByTime.insert(make_pair(wtx->GetTxTime(), TxPair(wtx, (CAccountingEntry*)0))); } list<CAccountingEntry> acentries; walletdb.ListAccountCreditDebit(strAccount, acentries); BOOST_FOREACH(CAccountingEntry& entry, acentries) { txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry))); } // iterate backwards until we have nCount items to return: for (TxItems::reverse_iterator it = txByTime.rbegin(); it != txByTime.rend(); ++it) { CWalletTx *const pwtx = (*it).second.first; if (pwtx != 0) ListTransactions(*pwtx, strAccount, 0, true, ret); CAccountingEntry *const pacentry = (*it).second.second; if (pacentry != 0) AcentryToJSON(*pacentry, strAccount, ret); if ((int)ret.size() >= (nCount+nFrom)) break; } // ret is newest to oldest if (nFrom > (int)ret.size()) nFrom = ret.size(); if ((nFrom + nCount) > (int)ret.size()) nCount = ret.size() - nFrom; Array::iterator first = ret.begin(); std::advance(first, nFrom); Array::iterator last = ret.begin(); std::advance(last, nFrom+nCount); if (last != ret.end()) ret.erase(last, ret.end()); if (first != ret.begin()) ret.erase(ret.begin(), first); std::reverse(ret.begin(), ret.end()); // Return oldest to newest return ret; } Value listaccounts(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "listaccounts [minconf=1]\n" "Returns Object that has account names as keys, account balances as values."); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); map<string, int64> mapAccountBalances; BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) { if (IsMine(*pwalletMain, entry.first)) // This address belongs to me mapAccountBalances[entry.second] = 0; } for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; int64 nGeneratedImmature, nGeneratedMature, nFee; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount); mapAccountBalances[strSentAccount] -= nFee; BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent) mapAccountBalances[strSentAccount] -= s.second; if (wtx.GetDepthInMainChain() >= nMinDepth) { mapAccountBalances[""] += nGeneratedMature; BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived) if (pwalletMain->mapAddressBook.count(r.first)) mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second; else mapAccountBalances[""] += r.second; } } list<CAccountingEntry> acentries; CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries); BOOST_FOREACH(const CAccountingEntry& entry, acentries) mapAccountBalances[entry.strAccount] += entry.nCreditDebit; Object ret; BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) { ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second))); } return ret; } Value listsinceblock(const Array& params, bool fHelp) { if (fHelp) throw runtime_error( "listsinceblock [blockhash] [target-confirmations]\n" "Get all transactions in blocks since block [blockhash], or all transactions if omitted"); CBlockIndex *pindex = NULL; int target_confirms = 1; if (params.size() > 0) { uint256 blockId = 0; blockId.SetHex(params[0].get_str()); pindex = CBlockLocator(blockId).GetBlockIndex(); } if (params.size() > 1) { target_confirms = params[1].get_int(); if (target_confirms < 1) throw JSONRPCError(-8, "Invalid parameter"); } int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1; Array transactions; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++) { CWalletTx tx = (*it).second; if (depth == -1 || tx.GetDepthInMainChain() < depth) ListTransactions(tx, "*", 0, true, transactions); } uint256 lastblock; if (target_confirms == 1) { lastblock = hashBestChain; } else { int target_height = pindexBest->nHeight + 1 - target_confirms; CBlockIndex *block; for (block = pindexBest; block && block->nHeight > target_height; block = block->pprev) { } lastblock = block ? block->GetBlockHash() : 0; } Object ret; ret.push_back(Pair("transactions", transactions)); ret.push_back(Pair("lastblock", lastblock.GetHex())); return ret; } Value gettransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "gettransaction <txid>\n" "Get detailed information about in-wallet transaction <txid>"); uint256 hash; hash.SetHex(params[0].get_str()); Object entry; if (!pwalletMain->mapWallet.count(hash)) throw JSONRPCError(-5, "Invalid or non-wallet transaction id"); const CWalletTx& wtx = pwalletMain->mapWallet[hash]; int64 nCredit = wtx.GetCredit(); int64 nDebit = wtx.GetDebit(); int64 nNet = nCredit - nDebit; int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0); entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee))); if (wtx.IsFromMe()) entry.push_back(Pair("fee", ValueFromAmount(nFee))); WalletTxToJSON(wtx, entry); Array details; ListTransactions(wtx, "*", 0, false, details); entry.push_back(Pair("details", details)); return entry; } Value backupwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "backupwallet <destination>\n" "Safely copies wallet.dat to destination, which can be a directory or a path with filename."); string strDest = params[0].get_str(); BackupWallet(*pwalletMain, strDest); return Value::null; } Value keypoolrefill(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "keypoolrefill\n" "Fills the keypool." + HelpRequiringPassphrase()); EnsureWalletIsUnlocked(); pwalletMain->TopUpKeyPool(); if (pwalletMain->GetKeyPoolSize() < GetArg("-keypool", 100)) throw JSONRPCError(-4, "Error refreshing keypool."); return Value::null; } void ThreadTopUpKeyPool(void* parg) { // Make this thread recognisable as the key-topping-up thread RenameThread("bitcoin-key-top"); pwalletMain->TopUpKeyPool(); } void ThreadCleanWalletPassphrase(void* parg) { // Make this thread recognisable as the wallet relocking thread RenameThread("bitcoin-lock-wa"); int64 nMyWakeTime = GetTimeMillis() + *((int64*)parg) * 1000; ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime); if (nWalletUnlockTime == 0) { nWalletUnlockTime = nMyWakeTime; do { if (nWalletUnlockTime==0) break; int64 nToSleep = nWalletUnlockTime - GetTimeMillis(); if (nToSleep <= 0) break; LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime); Sleep(nToSleep); ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime); } while(1); if (nWalletUnlockTime) { nWalletUnlockTime = 0; pwalletMain->Lock(); } } else { if (nWalletUnlockTime < nMyWakeTime) nWalletUnlockTime = nMyWakeTime; } LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime); delete (int64*)parg; } Value walletpassphrase(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2)) throw runtime_error( "walletpassphrase <passphrase> <timeout>\n" "Stores the wallet decryption key in memory for <timeout> seconds."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(-15, "Error: running with an unencrypted wallet, but walletpassphrase was called."); if (!pwalletMain->IsLocked()) throw JSONRPCError(-17, "Error: Wallet is already unlocked."); // Note that the walletpassphrase is stored in params[0] which is not mlock()ed SecureString strWalletPass; strWalletPass.reserve(100); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() > 0) { if (!pwalletMain->Unlock(strWalletPass)) throw JSONRPCError(-14, "Error: The wallet passphrase entered was incorrect."); } else throw runtime_error( "walletpassphrase <passphrase> <timeout>\n" "Stores the wallet decryption key in memory for <timeout> seconds."); CreateThread(ThreadTopUpKeyPool, NULL); int64* pnSleepTime = new int64(params[1].get_int64()); CreateThread(ThreadCleanWalletPassphrase, pnSleepTime); return Value::null; } Value walletpassphrasechange(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2)) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(-15, "Error: running with an unencrypted wallet, but walletpassphrasechange was called."); // TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strOldWalletPass; strOldWalletPass.reserve(100); strOldWalletPass = params[0].get_str().c_str(); SecureString strNewWalletPass; strNewWalletPass.reserve(100); strNewWalletPass = params[1].get_str().c_str(); if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass)) throw JSONRPCError(-14, "Error: The wallet passphrase entered was incorrect."); return Value::null; } Value walletlock(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0)) throw runtime_error( "walletlock\n" "Removes the wallet encryption key from memory, locking the wallet.\n" "After calling this method, you will need to call walletpassphrase again\n" "before being able to call any methods which require the wallet to be unlocked."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(-15, "Error: running with an unencrypted wallet, but walletlock was called."); { LOCK(cs_nWalletUnlockTime); pwalletMain->Lock(); nWalletUnlockTime = 0; } return Value::null; } Value encryptwallet(const Array& params, bool fHelp) { if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1)) throw runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (fHelp) return true; if (pwalletMain->IsCrypted()) throw JSONRPCError(-15, "Error: running with an encrypted wallet, but encryptwallet was called."); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strWalletPass; strWalletPass.reserve(100); strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() < 1) throw runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (!pwalletMain->EncryptWallet(strWalletPass)) throw JSONRPCError(-16, "Error: Failed to encrypt the wallet."); // BDB seems to have a bad habit of writing old data into // slack space in .dat files; that is bad if the old data is // unencrypted private keys. So: StartShutdown(); return "wallet encrypted; TestBars server stopping, restart to run with encrypted wallet"; } class DescribeAddressVisitor : public boost::static_visitor<Object> { public: Object operator()(const CNoDestination &dest) const { return Object(); } Object operator()(const CKeyID &keyID) const { Object obj; CPubKey vchPubKey; pwalletMain->GetPubKey(keyID, vchPubKey); obj.push_back(Pair("isscript", false)); obj.push_back(Pair("pubkey", HexStr(vchPubKey.Raw()))); obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed())); return obj; } Object operator()(const CScriptID &scriptID) const { Object obj; obj.push_back(Pair("isscript", true)); CScript subscript; pwalletMain->GetCScript(scriptID, subscript); std::vector<CTxDestination> addresses; txnouttype whichType; int nRequired; ExtractDestinations(subscript, whichType, addresses, nRequired); obj.push_back(Pair("script", GetTxnOutputType(whichType))); Array a; BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); obj.push_back(Pair("addresses", a)); if (whichType == TX_MULTISIG) obj.push_back(Pair("sigsrequired", nRequired)); return obj; } }; Value validateaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "validateaddress <testbars address>\n" "Return information about <testbars address>."); CBitcoinAddress address(params[0].get_str()); bool isValid = address.IsValid(); Object ret; ret.push_back(Pair("isvalid", isValid)); if (isValid) { CTxDestination dest = address.Get(); string currentAddress = address.ToString(); ret.push_back(Pair("address", currentAddress)); bool fMine = IsMine(*pwalletMain, dest); ret.push_back(Pair("ismine", fMine)); if (fMine) { Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest); ret.insert(ret.end(), detail.begin(), detail.end()); } if (pwalletMain->mapAddressBook.count(dest)) ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest])); } return ret; } Value getworkex(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getworkex [data, coinbase]\n" "If [data, coinbase] is not specified, returns extended work data.\n" ); if (vNodes.empty()) throw JSONRPCError(-9, "TestBars server is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(-10, "TestBars server is downloading blocks..."); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; static vector<CBlock*> vNewBlock; static CReserveKey reservekey(pwalletMain); if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlock* pblock; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlock* pblock, vNewBlock) delete pblock; vNewBlock.clear(); } nTransactionsUpdatedLast = nTransactionsUpdated; pindexPrev = pindexBest; nStart = GetTime(); // Create new block pblock = CreateNewBlock(reservekey); if (!pblock) throw JSONRPCError(-7, "Out of memory"); vNewBlock.push_back(pblock); } // Update nTime pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Prebuild hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); CTransaction coinbaseTx = pblock->vtx[0]; std::vector<uint256> merkle = pblock->GetMerkleBranch(0); Object result; result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << coinbaseTx; result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end()))); Array merkle_arr; printf("DEBUG: merkle size %i\n", merkle.size()); BOOST_FOREACH(uint256 merkleh, merkle) { printf("%s\n", merkleh.ToString().c_str()); merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh))); } result.push_back(Pair("merkle", merkle_arr)); return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); vector<unsigned char> coinbase; if(params.size() == 2) coinbase = ParseHex(params[1].get_str()); if (vchData.size() != 128) throw JSONRPCError(-8, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; if(coinbase.size() == 0) pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; else CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK! pblock->hashMerkleRoot = pblock->BuildMerkleTree(); return CheckWork(pblock, *pwalletMain, reservekey); } } Value getwork(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getwork [data]\n" "If [data] is not specified, returns formatted hash data to work on:\n" " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated " \"data\" : block data\n" " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated " \"target\" : little endian hash target\n" "If [data] is specified, tries to solve the block and returns true if it was successful."); if (vNodes.empty()) throw JSONRPCError(-9, "TestBars server is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(-10, "TestBars server is downloading blocks..."); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; // FIXME: thread safety static vector<CBlock*> vNewBlock; static CReserveKey reservekey(pwalletMain); if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlock* pblock; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlock* pblock, vNewBlock) delete pblock; vNewBlock.clear(); } nTransactionsUpdatedLast = nTransactionsUpdated; pindexPrev = pindexBest; nStart = GetTime(); // Create new block pblock = CreateNewBlock(reservekey); if (!pblock) throw JSONRPCError(-7, "Out of memory"); vNewBlock.push_back(pblock); } // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Prebuild hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); Object result; result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); result.push_back(Pair("algorithm", "scrypt:1024,1,1")); // specify that we should use the scrypt algorithm return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); if (vchData.size() != 128) throw JSONRPCError(-8, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; pblock->hashMerkleRoot = pblock->BuildMerkleTree(); return CheckWork(pblock, *pwalletMain, reservekey); } } Value getblocktemplate(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblocktemplate [params]\n" "If [params] does not contain a \"data\" key, returns data needed to construct a block to work on:\n" " \"version\" : block version\n" " \"previousblockhash\" : hash of current highest block\n" " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n" " \"coinbaseaux\" : data that should be included in coinbase\n" " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n" " \"target\" : hash target\n" " \"mintime\" : minimum timestamp appropriate for next block\n" " \"curtime\" : current timestamp\n" " \"mutable\" : list of ways the block template may be changed\n" " \"noncerange\" : range of valid nonces\n" " \"sigoplimit\" : limit of sigops in blocks\n" " \"sizelimit\" : limit of block size\n" " \"bits\" : compressed target of next block\n" " \"height\" : height of the next block\n" "If [params] does contain a \"data\" key, tries to solve the block and returns null if it was successful (and \"rejected\" if not)\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); const Object& oparam = params[0].get_obj(); std::string strMode; { const Value& modeval = find_value(oparam, "mode"); if (modeval.type() == str_type) strMode = modeval.get_str(); else if (find_value(oparam, "data").type() == null_type) strMode = "template"; else strMode = "submit"; } if (strMode == "template") { if (vNodes.empty()) throw JSONRPCError(-9, "TestBars server is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(-10, "TestBars server is downloading blocks..."); static CReserveKey reservekey(pwalletMain); // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlock* pblock; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5)) { nTransactionsUpdatedLast = nTransactionsUpdated; pindexPrev = pindexBest; nStart = GetTime(); // Create new block if(pblock) delete pblock; pblock = CreateNewBlock(reservekey); if (!pblock) throw JSONRPCError(-7, "Out of memory"); } // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; Array transactions; map<uint256, int64_t> setTxIndex; int i = 0; CTxDB txdb("r"); BOOST_FOREACH (CTransaction& tx, pblock->vtx) { uint256 txHash = tx.GetHash(); setTxIndex[txHash] = i++; if (tx.IsCoinBase()) continue; Object entry; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end()))); entry.push_back(Pair("hash", txHash.GetHex())); MapPrevTx mapInputs; map<uint256, CTxIndex> mapUnused; bool fInvalid = false; if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid)) { entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut()))); Array deps; BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs) { if (setTxIndex.count(inp.first)) deps.push_back(setTxIndex[inp.first]); } entry.push_back(Pair("depends", deps)); int64_t nSigOps = tx.GetLegacySigOpCount(); nSigOps += tx.GetP2SHSigOpCount(mapInputs); entry.push_back(Pair("sigops", nSigOps)); } transactions.push_back(entry); } Object aux; aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end()))); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); static Array aMutable; if (aMutable.empty()) { aMutable.push_back("time"); aMutable.push_back("transactions"); aMutable.push_back("prevblock"); } Object result; result.push_back(Pair("version", pblock->nVersion)); result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex())); result.push_back(Pair("transactions", transactions)); result.push_back(Pair("coinbaseaux", aux)); result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue)); result.push_back(Pair("target", hashTarget.GetHex())); result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1)); result.push_back(Pair("mutable", aMutable)); result.push_back(Pair("noncerange", "00000000ffffffff")); result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS)); result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE)); result.push_back(Pair("curtime", (int64_t)pblock->nTime)); result.push_back(Pair("bits", HexBits(pblock->nBits))); result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1))); return result; } else if (strMode == "submit") { // Parse parameters CDataStream ssBlock(ParseHex(find_value(oparam, "data").get_str()), SER_NETWORK, PROTOCOL_VERSION); CBlock pblock; ssBlock >> pblock; bool fAccepted = ProcessBlock(NULL, &pblock); return fAccepted ? Value::null : "rejected"; } throw JSONRPCError(-8, "Invalid mode"); } Value getrawmempool(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getrawmempool\n" "Returns all transaction ids in memory pool."); vector<uint256> vtxid; mempool.queryHashes(vtxid); Array a; BOOST_FOREACH(const uint256& hash, vtxid) a.push_back(hash.ToString()); return a; } Value getblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblockhash <index>\n" "Returns hash of block in best-block-chain at <index>."); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > nBestHeight) throw runtime_error("Block number out of range."); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hashBestChain]; while (pblockindex->nHeight > nHeight) pblockindex = pblockindex->pprev; return pblockindex->phashBlock->GetHex(); } Value getblock(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblock <hash>\n" "Returns details of a block with given block-hash."); std::string strHash = params[0].get_str(); uint256 hash(strHash); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(-5, "Block not found"); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; block.ReadFromDisk(pblockindex, true); return blockToJSON(block, pblockindex); } // // Call Table // static const CRPCCommand vRPCCommands[] = { // name function safe mode? // ------------------------ ----------------------- ---------- { "help", &help, true }, { "stop", &stop, true }, { "getblockcount", &getblockcount, true }, { "getconnectioncount", &getconnectioncount, true }, { "getpeerinfo", &getpeerinfo, true }, { "getdifficulty", &getdifficulty, true }, { "getnetworkhashps", &getnetworkhashps, true }, { "getgenerate", &getgenerate, true }, { "setgenerate", &setgenerate, true }, { "gethashespersec", &gethashespersec, true }, { "getinfo", &getinfo, true }, { "getmininginfo", &getmininginfo, true }, { "getnewaddress", &getnewaddress, true }, { "getaccountaddress", &getaccountaddress, true }, { "setaccount", &setaccount, true }, { "getaccount", &getaccount, false }, { "getaddressesbyaccount", &getaddressesbyaccount, true }, { "sendtoaddress", &sendtoaddress, false }, { "getreceivedbyaddress", &getreceivedbyaddress, false }, { "getreceivedbyaccount", &getreceivedbyaccount, false }, { "listreceivedbyaddress", &listreceivedbyaddress, false }, { "listreceivedbyaccount", &listreceivedbyaccount, false }, { "backupwallet", &backupwallet, true }, { "keypoolrefill", &keypoolrefill, true }, { "walletpassphrase", &walletpassphrase, true }, { "walletpassphrasechange", &walletpassphrasechange, false }, { "walletlock", &walletlock, true }, { "encryptwallet", &encryptwallet, false }, { "validateaddress", &validateaddress, true }, { "getbalance", &getbalance, false }, { "move", &movecmd, false }, { "sendfrom", &sendfrom, false }, { "sendmany", &sendmany, false }, { "addmultisigaddress", &addmultisigaddress, false }, { "getrawmempool", &getrawmempool, true }, { "getblock", &getblock, false }, { "getblockhash", &getblockhash, false }, { "gettransaction", &gettransaction, false }, { "listtransactions", &listtransactions, false }, { "signmessage", &signmessage, false }, { "verifymessage", &verifymessage, false }, { "getwork", &getwork, true }, { "getworkex", &getworkex, true }, { "listaccounts", &listaccounts, false }, { "settxfee", &settxfee, false }, { "setmininput", &setmininput, false }, { "getblocktemplate", &getblocktemplate, true }, { "listsinceblock", &listsinceblock, false }, { "dumpprivkey", &dumpprivkey, false }, { "importprivkey", &importprivkey, false }, { "listunspent", &listunspent, false }, { "getrawtransaction", &getrawtransaction, false }, { "createrawtransaction", &createrawtransaction, false }, { "decoderawtransaction", &decoderawtransaction, false }, { "signrawtransaction", &signrawtransaction, false }, { "sendrawtransaction", &sendrawtransaction, false }, }; CRPCTable::CRPCTable() { unsigned int vcidx; for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++) { const CRPCCommand *pcmd; pcmd = &vRPCCommands[vcidx]; mapCommands[pcmd->name] = pcmd; } } const CRPCCommand *CRPCTable::operator[](string name) const { map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name); if (it == mapCommands.end()) return NULL; return (*it).second; } // // HTTP protocol // // This ain't Apache. We're just using HTTP header for the length field // and to be compatible with other JSON-RPC implementations. // string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders) { ostringstream s; s << "POST / HTTP/1.1\r\n" << "User-Agent: testbars-json-rpc/" << FormatFullVersion() << "\r\n" << "Host: 127.0.0.1\r\n" << "Content-Type: application/json\r\n" << "Content-Length: " << strMsg.size() << "\r\n" << "Connection: close\r\n" << "Accept: application/json\r\n"; BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders) s << item.first << ": " << item.second << "\r\n"; s << "\r\n" << strMsg; return s.str(); } string rfc1123Time() { char buffer[64]; time_t now; time(&now); struct tm* now_gmt = gmtime(&now); string locale(setlocale(LC_TIME, NULL)); setlocale(LC_TIME, "C"); // we want posix (aka "C") weekday/month strings strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt); setlocale(LC_TIME, locale.c_str()); return string(buffer); } static string HTTPReply(int nStatus, const string& strMsg, bool keepalive) { if (nStatus == 401) return strprintf("HTTP/1.0 401 Authorization Required\r\n" "Date: %s\r\n" "Server: testbars-json-rpc/%s\r\n" "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n" "Content-Type: text/html\r\n" "Content-Length: 296\r\n" "\r\n" "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n" "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n" "<HTML>\r\n" "<HEAD>\r\n" "<TITLE>Error</TITLE>\r\n" "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n" "</HEAD>\r\n" "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n" "</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str()); const char *cStatus; if (nStatus == 200) cStatus = "OK"; else if (nStatus == 400) cStatus = "Bad Request"; else if (nStatus == 403) cStatus = "Forbidden"; else if (nStatus == 404) cStatus = "Not Found"; else if (nStatus == 500) cStatus = "Internal Server Error"; else cStatus = ""; return strprintf( "HTTP/1.1 %d %s\r\n" "Date: %s\r\n" "Connection: %s\r\n" "Content-Length: %d\r\n" "Content-Type: application/json\r\n" "Server: testbars-json-rpc/%s\r\n" "\r\n" "%s", nStatus, cStatus, rfc1123Time().c_str(), keepalive ? "keep-alive" : "close", strMsg.size(), FormatFullVersion().c_str(), strMsg.c_str()); } int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto) { string str; getline(stream, str); vector<string> vWords; boost::split(vWords, str, boost::is_any_of(" ")); if (vWords.size() < 2) return 500; proto = 0; const char *ver = strstr(str.c_str(), "HTTP/1."); if (ver != NULL) proto = atoi(ver+7); return atoi(vWords[1].c_str()); } int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet) { int nLen = 0; loop { string str; std::getline(stream, str); if (str.empty() || str == "\r") break; string::size_type nColon = str.find(":"); if (nColon != string::npos) { string strHeader = str.substr(0, nColon); boost::trim(strHeader); boost::to_lower(strHeader); string strValue = str.substr(nColon+1); boost::trim(strValue); mapHeadersRet[strHeader] = strValue; if (strHeader == "content-length") nLen = atoi(strValue.c_str()); } } return nLen; } int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet) { mapHeadersRet.clear(); strMessageRet = ""; // Read status int nProto = 0; int nStatus = ReadHTTPStatus(stream, nProto); // Read header int nLen = ReadHTTPHeader(stream, mapHeadersRet); if (nLen < 0 || nLen > (int)MAX_SIZE) return 500; // Read message if (nLen > 0) { vector<char> vch(nLen); stream.read(&vch[0], nLen); strMessageRet = string(vch.begin(), vch.end()); } string sConHdr = mapHeadersRet["connection"]; if ((sConHdr != "close") && (sConHdr != "keep-alive")) { if (nProto >= 1) mapHeadersRet["connection"] = "keep-alive"; else mapHeadersRet["connection"] = "close"; } return nStatus; } bool HTTPAuthorized(map<string, string>& mapHeaders) { string strAuth = mapHeaders["authorization"]; if (strAuth.substr(0,6) != "Basic ") return false; string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64); string strUserPass = DecodeBase64(strUserPass64); return strUserPass == strRPCUserColonPass; } // // JSON-RPC protocol. TestBars speaks version 1.0 for maximum compatibility, // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were // unspecified (HTTP errors and contents of 'error'). // // 1.0 spec: http://json-rpc.org/wiki/specification // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx // string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id) { Object request; request.push_back(Pair("method", strMethod)); request.push_back(Pair("params", params)); request.push_back(Pair("id", id)); return write_string(Value(request), false) + "\n"; } Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id) { Object reply; if (error.type() != null_type) reply.push_back(Pair("result", Value::null)); else reply.push_back(Pair("result", result)); reply.push_back(Pair("error", error)); reply.push_back(Pair("id", id)); return reply; } string JSONRPCReply(const Value& result, const Value& error, const Value& id) { Object reply = JSONRPCReplyObj(result, error, id); return write_string(Value(reply), false) + "\n"; } void ErrorReply(std::ostream& stream, const Object& objError, const Value& id) { // Send error reply from json-rpc error object int nStatus = 500; int code = find_value(objError, "code").get_int(); if (code == -32600) nStatus = 400; else if (code == -32601) nStatus = 404; string strReply = JSONRPCReply(Value::null, objError, id); stream << HTTPReply(nStatus, strReply, false) << std::flush; } bool ClientAllowed(const boost::asio::ip::address& address) { // Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses if (address.is_v6() && (address.to_v6().is_v4_compatible() || address.to_v6().is_v4_mapped())) return ClientAllowed(address.to_v6().to_v4()); if (address == asio::ip::address_v4::loopback() || address == asio::ip::address_v6::loopback() || (address.is_v4() // Chech whether IPv4 addresses match 127.0.0.0/8 (loopback subnet) && (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000)) return true; const string strAddress = address.to_string(); const vector<string>& vAllow = mapMultiArgs["-rpcallowip"]; BOOST_FOREACH(string strAllow, vAllow) if (WildcardMatch(strAddress, strAllow)) return true; return false; } // // IOStream device that speaks SSL but can also speak non-SSL // template <typename Protocol> class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> { public: SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn) { fUseSSL = fUseSSLIn; fNeedHandshake = fUseSSLIn; } void handshake(ssl::stream_base::handshake_type role) { if (!fNeedHandshake) return; fNeedHandshake = false; stream.handshake(role); } std::streamsize read(char* s, std::streamsize n) { handshake(ssl::stream_base::server); // HTTPS servers read first if (fUseSSL) return stream.read_some(asio::buffer(s, n)); return stream.next_layer().read_some(asio::buffer(s, n)); } std::streamsize write(const char* s, std::streamsize n) { handshake(ssl::stream_base::client); // HTTPS clients write first if (fUseSSL) return asio::write(stream, asio::buffer(s, n)); return asio::write(stream.next_layer(), asio::buffer(s, n)); } bool connect(const std::string& server, const std::string& port) { ip::tcp::resolver resolver(stream.get_io_service()); ip::tcp::resolver::query query(server.c_str(), port.c_str()); ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); ip::tcp::resolver::iterator end; boost::system::error_code error = asio::error::host_not_found; while (error && endpoint_iterator != end) { stream.lowest_layer().close(); stream.lowest_layer().connect(*endpoint_iterator++, error); } if (error) return false; return true; } private: bool fNeedHandshake; bool fUseSSL; asio::ssl::stream<typename Protocol::socket>& stream; }; class AcceptedConnection { public: virtual ~AcceptedConnection() {} virtual std::iostream& stream() = 0; virtual std::string peer_address_to_string() const = 0; virtual void close() = 0; }; template <typename Protocol> class AcceptedConnectionImpl : public AcceptedConnection { public: AcceptedConnectionImpl( asio::io_service& io_service, ssl::context &context, bool fUseSSL) : sslStream(io_service, context), _d(sslStream, fUseSSL), _stream(_d) { } virtual std::iostream& stream() { return _stream; } virtual std::string peer_address_to_string() const { return peer.address().to_string(); } virtual void close() { _stream.close(); } typename Protocol::endpoint peer; asio::ssl::stream<typename Protocol::socket> sslStream; private: SSLIOStreamDevice<Protocol> _d; iostreams::stream< SSLIOStreamDevice<Protocol> > _stream; }; void ThreadRPCServer(void* parg) { IMPLEMENT_RANDOMIZE_STACK(ThreadRPCServer(parg)); // Make this thread recognisable as the RPC listener RenameThread("bitcoin-rpclist"); try { vnThreadsRunning[THREAD_RPCLISTENER]++; ThreadRPCServer2(parg); vnThreadsRunning[THREAD_RPCLISTENER]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_RPCLISTENER]--; PrintException(&e, "ThreadRPCServer()"); } catch (...) { vnThreadsRunning[THREAD_RPCLISTENER]--; PrintException(NULL, "ThreadRPCServer()"); } printf("ThreadRPCServer exited\n"); } // Forward declaration required for RPCListen template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, bool fUseSSL, AcceptedConnection* conn, const boost::system::error_code& error); /** * Sets up I/O resources to accept and handle a new connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL) { // Accept connection AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL); acceptor->async_accept( conn->sslStream.lowest_layer(), conn->peer, boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>, acceptor, boost::ref(context), fUseSSL, conn, boost::asio::placeholders::error)); } /** * Accept and handle incoming connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL, AcceptedConnection* conn, const boost::system::error_code& error) { vnThreadsRunning[THREAD_RPCLISTENER]++; // Immediately start accepting new connections, except when we're canceled or our socket is closed. if (error != asio::error::operation_aborted && acceptor->is_open()) RPCListen(acceptor, context, fUseSSL); AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn); // TODO: Actually handle errors if (error) { delete conn; } // Restrict callers by IP. It is important to // do this before starting client thread, to filter out // certain DoS and misbehaving clients. else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address())) { // Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake. if (!fUseSSL) conn->stream() << HTTPReply(403, "", false) << std::flush; delete conn; } // start HTTP client thread else if (!CreateThread(ThreadRPCServer3, conn)) { printf("Failed to create RPC server client thread\n"); delete conn; } vnThreadsRunning[THREAD_RPCLISTENER]--; } void ThreadRPCServer2(void* parg) { printf("ThreadRPCServer started\n"); strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]; if (mapArgs["-rpcpassword"] == "") { unsigned char rand_pwd[32]; RAND_bytes(rand_pwd, 32); string strWhatAmI = "To use testbars"; if (mapArgs.count("-server")) strWhatAmI = strprintf(_("To use the %s option"), "\"-server\""); else if (mapArgs.count("-daemon")) strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\""); uiInterface.ThreadSafeMessageBox(strprintf( _("%s, you must set a rpcpassword in the configuration file:\n %s\n" "It is recommended you use the following random password:\n" "rpcuser=testbarsrpc\n" "rpcpassword=%s\n" "(you do not need to remember this password)\n" "If the file does not exist, create it with owner-readable-only file permissions.\n"), strWhatAmI.c_str(), GetConfigFile().string().c_str(), EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()), _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL); StartShutdown(); return; } const bool fUseSSL = GetBoolArg("-rpcssl"); asio::io_service io_service; ssl::context context(io_service, ssl::context::sslv23); if (fUseSSL) { context.set_options(ssl::context::no_sslv2); filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert")); if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile; if (filesystem::exists(pathCertFile)) context.use_certificate_chain_file(pathCertFile.string()); else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str()); filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem")); if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile; if (filesystem::exists(pathPKFile)) context.use_private_key_file(pathPKFile.string(), ssl::context::pem); else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str()); string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH"); SSL_CTX_set_cipher_list(context.impl(), strCiphers.c_str()); } // Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets const bool loopback = !mapArgs.count("-rpcallowip"); asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any(); ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", 55883)); boost::signals2::signal<void ()> StopRequests; try { boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(io_service)); acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); // Try making the socket dual IPv6/IPv4 (if listening on the "any" address) boost::system::error_code v6_only_error; acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, context, fUseSSL); // Cancel outstanding listen-requests for this acceptor when shutting down StopRequests.connect(signals2::slot<void ()>( static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get()) .track(acceptor)); // If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately if (loopback || v6_only_error) { bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any(); endpoint.address(bindAddress); acceptor.reset(new ip::tcp::acceptor(io_service)); acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, context, fUseSSL); // Cancel outstanding listen-requests for this acceptor when shutting down StopRequests.connect(signals2::slot<void ()>( static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get()) .track(acceptor)); } } catch(boost::system::system_error &e) { uiInterface.ThreadSafeMessageBox(strprintf(_("An error occured while setting up the RPC port %i for listening: %s"), endpoint.port(), e.what()), _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL); StartShutdown(); return; } vnThreadsRunning[THREAD_RPCLISTENER]--; while (!fShutdown) io_service.run_one(); vnThreadsRunning[THREAD_RPCLISTENER]++; StopRequests(); } class JSONRequest { public: Value id; string strMethod; Array params; JSONRequest() { id = Value::null; } void parse(const Value& valRequest); }; void JSONRequest::parse(const Value& valRequest) { // Parse request if (valRequest.type() != obj_type) throw JSONRPCError(-32600, "Invalid Request object"); const Object& request = valRequest.get_obj(); // Parse id now so errors from here on will have the id id = find_value(request, "id"); // Parse method Value valMethod = find_value(request, "method"); if (valMethod.type() == null_type) throw JSONRPCError(-32600, "Missing method"); if (valMethod.type() != str_type) throw JSONRPCError(-32600, "Method must be a string"); strMethod = valMethod.get_str(); if (strMethod != "getwork" && strMethod != "getblocktemplate") printf("ThreadRPCServer method=%s\n", strMethod.c_str()); // Parse params Value valParams = find_value(request, "params"); if (valParams.type() == array_type) params = valParams.get_array(); else if (valParams.type() == null_type) params = Array(); else throw JSONRPCError(-32600, "Params must be an array"); } static Object JSONRPCExecOne(const Value& req) { Object rpc_result; JSONRequest jreq; try { jreq.parse(req); Value result = tableRPC.execute(jreq.strMethod, jreq.params); rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id); } catch (Object& objError) { rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id); } catch (std::exception& e) { rpc_result = JSONRPCReplyObj(Value::null, JSONRPCError(-32700, e.what()), jreq.id); } return rpc_result; } static string JSONRPCExecBatch(const Array& vReq) { Array ret; for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++) ret.push_back(JSONRPCExecOne(vReq[reqIdx])); return write_string(Value(ret), false) + "\n"; } static CCriticalSection cs_THREAD_RPCHANDLER; void ThreadRPCServer3(void* parg) { IMPLEMENT_RANDOMIZE_STACK(ThreadRPCServer3(parg)); // Make this thread recognisable as the RPC handler RenameThread("bitcoin-rpchand"); { LOCK(cs_THREAD_RPCHANDLER); vnThreadsRunning[THREAD_RPCHANDLER]++; } AcceptedConnection *conn = (AcceptedConnection *) parg; bool fRun = true; loop { if (fShutdown || !fRun) { conn->close(); delete conn; { LOCK(cs_THREAD_RPCHANDLER); --vnThreadsRunning[THREAD_RPCHANDLER]; } return; } map<string, string> mapHeaders; string strRequest; ReadHTTP(conn->stream(), mapHeaders, strRequest); // Check authorization if (mapHeaders.count("authorization") == 0) { conn->stream() << HTTPReply(401, "", false) << std::flush; break; } if (!HTTPAuthorized(mapHeaders)) { printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str()); /* Deter brute-forcing short passwords. If this results in a DOS the user really shouldn't have their RPC port exposed.*/ if (mapArgs["-rpcpassword"].size() < 20) Sleep(250); conn->stream() << HTTPReply(401, "", false) << std::flush; break; } if (mapHeaders["connection"] == "close") fRun = false; JSONRequest jreq; try { // Parse request Value valRequest; if (!read_string(strRequest, valRequest)) throw JSONRPCError(-32700, "Parse error"); string strReply; // singleton request if (valRequest.type() == obj_type) { jreq.parse(valRequest); Value result = tableRPC.execute(jreq.strMethod, jreq.params); // Send reply strReply = JSONRPCReply(result, Value::null, jreq.id); // array of requests } else if (valRequest.type() == array_type) strReply = JSONRPCExecBatch(valRequest.get_array()); else throw JSONRPCError(-32700, "Top-level object parse error"); conn->stream() << HTTPReply(200, strReply, fRun) << std::flush; } catch (Object& objError) { ErrorReply(conn->stream(), objError, jreq.id); break; } catch (std::exception& e) { ErrorReply(conn->stream(), JSONRPCError(-32700, e.what()), jreq.id); break; } } delete conn; { LOCK(cs_THREAD_RPCHANDLER); vnThreadsRunning[THREAD_RPCHANDLER]--; } } json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array &params) const { // Find method const CRPCCommand *pcmd = tableRPC[strMethod]; if (!pcmd) throw JSONRPCError(-32601, "Method not found"); // Observe safe mode string strWarning = GetWarnings("rpc"); if (strWarning != "" && !GetBoolArg("-disablesafemode") && !pcmd->okSafeMode) throw JSONRPCError(-2, string("Safe mode: ") + strWarning); try { // Execute Value result; { LOCK2(cs_main, pwalletMain->cs_wallet); result = pcmd->actor(params, false); } return result; } catch (std::exception& e) { throw JSONRPCError(-1, e.what()); } } Object CallRPC(const string& strMethod, const Array& params) { if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "") throw runtime_error(strprintf( _("You must set rpcpassword=<password> in the configuration file:\n%s\n" "If the file does not exist, create it with owner-readable-only file permissions."), GetConfigFile().string().c_str())); // Connect to localhost bool fUseSSL = GetBoolArg("-rpcssl"); asio::io_service io_service; ssl::context context(io_service, ssl::context::sslv23); context.set_options(ssl::context::no_sslv2); asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context); SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL); iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d); if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "55883"))) throw runtime_error("couldn't connect to server"); // HTTP basic authentication string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]); map<string, string> mapRequestHeaders; mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64; // Send request string strRequest = JSONRPCRequest(strMethod, params, 1); string strPost = HTTPPost(strRequest, mapRequestHeaders); stream << strPost << std::flush; // Receive reply map<string, string> mapHeaders; string strReply; int nStatus = ReadHTTP(stream, mapHeaders, strReply); if (nStatus == 401) throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); else if (nStatus >= 400 && nStatus != 400 && nStatus != 404 && nStatus != 500) throw runtime_error(strprintf("server returned HTTP error %d", nStatus)); else if (strReply.empty()) throw runtime_error("no response from server"); // Parse reply Value valReply; if (!read_string(strReply, valReply)) throw runtime_error("couldn't parse reply from server"); const Object& reply = valReply.get_obj(); if (reply.empty()) throw runtime_error("expected reply to have result, error and id properties"); return reply; } template<typename T> void ConvertTo(Value& value) { if (value.type() == str_type) { // reinterpret string as unquoted json value Value value2; string strJSON = value.get_str(); if (!read_string(strJSON, value2)) throw runtime_error(string("Error parsing JSON:")+strJSON); value = value2.get_value<T>(); } else { value = value.get_value<T>(); } } // Convert strings to command-specific RPC representation Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { Array params; BOOST_FOREACH(const std::string &param, strParams) params.push_back(param); int n = params.size(); // // Special case non-string parameter types // if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]); if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]); if (strMethod == "setmininput" && n > 0) ConvertTo<double>(params[0]); if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]); if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]); if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]); if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]); if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]); if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]); if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2]); return params; } int CommandLineRPC(int argc, char *argv[]) { string strPrint; int nRet = 0; try { // Skip switches while (argc > 1 && IsSwitchChar(argv[1][0])) { argc--; argv++; } // Method if (argc < 2) throw runtime_error("too few parameters"); string strMethod = argv[1]; // Parameters default to strings std::vector<std::string> strParams(&argv[2], &argv[argc]); Array params = RPCConvertValues(strMethod, strParams); // Execute Object reply = CallRPC(strMethod, params); // Parse reply const Value& result = find_value(reply, "result"); const Value& error = find_value(reply, "error"); if (error.type() != null_type) { // Error strPrint = "error: " + write_string(error, false); int code = find_value(error.get_obj(), "code").get_int(); nRet = abs(code); } else { // Result if (result.type() == null_type) strPrint = ""; else if (result.type() == str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); } } catch (std::exception& e) { strPrint = string("error: ") + e.what(); nRet = 87; } catch (...) { PrintException(NULL, "CommandLineRPC()"); } if (strPrint != "") { fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str()); } return nRet; } #ifdef TEST int main(int argc, char *argv[]) { #ifdef _MSC_VER // Turn off microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); #endif setbuf(stdin, NULL); setbuf(stdout, NULL); setbuf(stderr, NULL); try { if (argc >= 2 && string(argv[1]) == "-server") { printf("server ready\n"); ThreadRPCServer(NULL); } else { return CommandLineRPC(argc, argv); } } catch (std::exception& e) { PrintException(&e, "main()"); } catch (...) { PrintException(NULL, "main()"); } return 0; } #endif const CRPCTable tableRPC;
mit
pact-foundation/pact-python
tests/test_broker.py
4974
import os from unittest import TestCase from mock import patch from pact.broker import Broker from pact.consumer import Consumer, Provider from pact.constants import BROKER_CLIENT_PATH from pact import broker as broker class BrokerTestCase(TestCase): def setUp(self): self.consumer = Consumer('TestConsumer') self.provider = Provider('TestProvider') self.addCleanup(patch.stopall) self.mock_Popen = patch.object(broker, 'Popen', autospec=True).start() self.mock_Popen.return_value.returncode = 0 self.mock_fnmatch = patch.object( broker.fnmatch, 'filter', autospec=True).start() self.mock_fnmatch.return_value = ['TestConsumer-TestProvider.json'] def test_publish_without_broker_url(self): broker = Broker() with self.assertRaises(RuntimeError): broker.publish("TestConsumer", "2.0.1") self.mock_Popen.assert_not_called() def test_publish_fails(self): self.mock_Popen.return_value.returncode = 1 broker = Broker(broker_base_url="http://localhost", broker_username="username", broker_password="password", broker_token="token") with self.assertRaises(RuntimeError): broker.publish("TestConsumer", "2.0.1", pact_dir='.') self.mock_Popen.assert_called_once_with([ BROKER_CLIENT_PATH, 'publish', '--consumer-app-version=2.0.1', '--broker-base-url=http://localhost', '--broker-username=username', '--broker-password=password', '--broker-token=token', './TestConsumer-TestProvider.json']) def test_publish_with_broker_url_environment_variable(self): BROKER_URL_ENV = 'http://broker.url' os.environ["PACT_BROKER_BASE_URL"] = BROKER_URL_ENV broker = Broker(broker_username="username", broker_password="password") broker.publish("TestConsumer", "2.0.1", pact_dir='.') self.mock_Popen.assert_called_once_with([ BROKER_CLIENT_PATH, 'publish', '--consumer-app-version=2.0.1', f"--broker-base-url={BROKER_URL_ENV}", '--broker-username=username', '--broker-password=password', './TestConsumer-TestProvider.json']) del os.environ["PACT_BROKER_BASE_URL"] def test_basic_authenticated_publish(self): broker = Broker(broker_base_url="http://localhost", broker_username="username", broker_password="password") broker.publish("TestConsumer", "2.0.1", pact_dir='.') self.mock_Popen.assert_called_once_with([ BROKER_CLIENT_PATH, 'publish', '--consumer-app-version=2.0.1', '--broker-base-url=http://localhost', '--broker-username=username', '--broker-password=password', './TestConsumer-TestProvider.json']) def test_token_authenticated_publish(self): broker = Broker(broker_base_url="http://localhost", broker_username="username", broker_password="password", broker_token="token") broker.publish("TestConsumer", "2.0.1", pact_dir='.') self.mock_Popen.assert_called_once_with([ BROKER_CLIENT_PATH, 'publish', '--consumer-app-version=2.0.1', '--broker-base-url=http://localhost', '--broker-username=username', '--broker-password=password', '--broker-token=token', './TestConsumer-TestProvider.json']) def test_git_tagged_publish(self): broker = Broker(broker_base_url="http://localhost") broker.publish("TestConsumer", "2.0.1", tag_with_git_branch=True, pact_dir='.') self.mock_Popen.assert_called_once_with([ BROKER_CLIENT_PATH, 'publish', '--consumer-app-version=2.0.1', '--broker-base-url=http://localhost', './TestConsumer-TestProvider.json', '--tag-with-git-branch']) def test_manual_tagged_publish(self): broker = Broker(broker_base_url="http://localhost") broker.publish("TestConsumer", "2.0.1", consumer_tags=['tag1', 'tag2'], pact_dir='.') self.mock_Popen.assert_called_once_with([ BROKER_CLIENT_PATH, 'publish', '--consumer-app-version=2.0.1', '--broker-base-url=http://localhost', './TestConsumer-TestProvider.json', '-t', 'tag1', '-t', 'tag2'])
mit
DirectMyFile/JPower
modules/Core/src/main/java/jpower/core/Task.java
737
package jpower.core; import jpower.core.internal.CancelStateTracker; @FunctionalInterface public interface Task extends Runnable { /** * Used to run in Threads */ @Override default void run() { execute(); } /** * Executes this Task */ void execute(); /** * Checks if this task is canceled * * @return Task is Canceled */ default boolean isCanceled() { return CancelStateTracker.isCanceled(this); } /** * Cancels the Task */ default void cancel() { CancelStateTracker.setCanceled(this, true); } /** * Actives the Task if it is canceled */ default void activate() { CancelStateTracker.setCanceled(this, false); } }
mit
csteinmetz1/pyloudnorm
pyloudnorm/util.py
925
import numpy as np def valid_audio(data, rate, block_size): """ Validate input audio data. Ensure input is numpy array of floating point data bewteen -1 and 1 Params ------- data : ndarray Input audio data rate : int Sampling rate of the input audio in Hz block_size : int Analysis block size in seconds Returns ------- valid : bool True if valid audio """ if not isinstance(data, np.ndarray): raise ValueError("Data must be of type numpy.ndarray.") if not np.issubdtype(data.dtype, np.floating): raise ValueError("Data must be floating point.") if data.ndim == 2 and data.shape[1] > 5: raise ValueError("Audio must have five channels or less.") if data.shape[0] < block_size * rate: raise ValueError("Audio must have length greater than the block size.") return True
mit
Jozain/three.js
examples/js/shaders/GlossyMirrorShader.js
7218
THREE.GlossyMirrorShader = { defines: { "SPECULAR_MAP": 0, "ROUGHNESS_MAP": 0, "GLOSSY_REFLECTIONS": 1, "REFLECTION_LOD_LEVELS": 4, "PERSPECTIVE_CAMERA": 1 }, uniforms: { "metalness": { type: "f", value: 0.0 }, "specularColor": { type: "c", value: new THREE.Color( 0xffffff ) }, "tSpecular": { type: "t", value: null }, "tReflection": { type: "t", value: null }, "tReflection1": { type: "t", value: null }, "tReflection2": { type: "t", value: null }, "tReflection3": { type: "t", value: null }, "tReflection4": { type: "t", value: null }, "tReflectionDepth": { type: "t", value: null }, "roughness": { type: "f", value: 0.0 }, "distanceFade": { type: "f", value: 0.01 }, "fresnelStrength": { type: "f", value: 1.0 }, "reflectionTextureMatrix" : { type: "m4", value: new THREE.Matrix4() }, "mirrorCameraWorldMatrix": { type: "m4", value: new THREE.Matrix4() }, "mirrorCameraProjectionMatrix": { type: "m4", value: new THREE.Matrix4() }, "mirrorCameraInverseProjectionMatrix": { type: "m4", value: new THREE.Matrix4() }, "mirrorCameraNear": { type: "f", value: 0 }, "mirrorCameraFar": { type: "f", value: 0 }, "screenSize": { type: "v2", value: new THREE.Vector2() }, "mirrorNormal": { type: "v3", value: new THREE.Vector3() }, "mirrorWorldPosition": { type: "v3", value: new THREE.Vector3() } }, vertexShader: [ "uniform mat4 reflectionTextureMatrix;", "varying vec4 mirrorCoord;", "varying vec3 vecPosition;", "varying vec3 worldNormal;", "varying vec2 vUv;", "void main() {", "vUv = uv;", "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );", "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );", "vecPosition = cameraPosition - worldPosition.xyz;", "worldNormal = (modelMatrix * vec4(normal,0.0)).xyz;", "mirrorCoord = reflectionTextureMatrix * worldPosition;", "gl_Position = projectionMatrix * mvPosition;", "}" ].join( "\n" ), blending: THREE.NormalBlending, transparent: true, fragmentShader: [ "#include <common>", "#include <packing>", "#include <bsdfs>", "uniform float roughness;", "#if ROUGHNESS_MAP == 1", "uniform sampler2D tRoughness;", "#endif", "uniform float metalness;", "uniform float distanceFade;", "uniform float fresnelStrength;", "uniform vec3 specularColor;", "#if SPECULAR_MAP == 1", "uniform sampler2D tSpecular;", "#endif", "uniform sampler2D tReflection;", "#if GLOSSY_REFLECTIONS == 1", "uniform sampler2D tReflection1;", "uniform sampler2D tReflection2;", "uniform sampler2D tReflection3;", "uniform sampler2D tReflection4;", "uniform sampler2D tReflectionDepth;", "#endif", "varying vec3 vecPosition;", "varying vec3 worldNormal;", "varying vec2 vUv;", "varying vec4 mirrorCoord;", "uniform mat4 mirrorCameraProjectionMatrix;", "uniform mat4 mirrorCameraInverseProjectionMatrix;", "uniform mat4 mirrorCameraWorldMatrix;", "uniform float mirrorCameraNear;", "uniform float mirrorCameraFar;", "uniform vec2 screenSize;", "uniform vec3 mirrorNormal;", "uniform vec3 mirrorWorldPosition;", "#if GLOSSY_REFLECTIONS == 1", "float getReflectionDepth() {", "return unpackRGBAToDepth( texture2DProj( tReflectionDepth, mirrorCoord ) );", "}", "float getReflectionViewZ( const in float reflectionDepth ) {", "#if PERSPECTIVE_CAMERA == 1", "return perspectiveDepthToViewZ( reflectionDepth, mirrorCameraNear, mirrorCameraFar );", "#else", "return orthographicDepthToViewZ( reflectionDepth, mirrorCameraNear, mirrorCameraFar );", "#endif", "}", "vec3 getReflectionViewPosition( const in vec2 screenPosition, const in float reflectionDepth, const in float reflectionViewZ ) {", "float clipW = mirrorCameraProjectionMatrix[2][3] * reflectionViewZ + mirrorCameraProjectionMatrix[3][3];", "vec4 clipPosition = vec4( ( vec3( screenPosition, reflectionDepth ) - 0.5 ) * 2.0, 1.0 );", "clipPosition *= clipW;", // unprojection. "return ( mirrorCameraInverseProjectionMatrix * clipPosition ).xyz;", "}", "#endif", "vec4 getReflection( const in vec4 mirrorCoord, const in float lodLevel ) {", "#if GLOSSY_REFLECTIONS == 0", "return texture2DProj( tReflection, mirrorCoord );", "#else", "vec4 color0, color1;", "float alpha;", "if( lodLevel < 1.0 ) {", "color0 = texture2DProj( tReflection, mirrorCoord );", "color1 = texture2DProj( tReflection1, mirrorCoord );", "alpha = lodLevel;", "}", "else if( lodLevel < 2.0) {", "color0 = texture2DProj( tReflection1, mirrorCoord );", "color1 = texture2DProj( tReflection2, mirrorCoord );", "alpha = lodLevel - 1.0;", "}", "else if( lodLevel < 3.0 ) {", "color0 = texture2DProj( tReflection2, mirrorCoord );", "color1 = texture2DProj( tReflection3, mirrorCoord );", "alpha = lodLevel - 2.0;", "}", "else {", "color0 = texture2DProj( tReflection3, mirrorCoord );", "color1 = color0;", "alpha = 0.0;", "}", "return mix( color0, color1, alpha );", "#endif", "}", "void main() {", "vec3 specular = specularColor;", "#if SPECULAR_MAP == 1", "specular *= texture2D( tSpecular, vUv );", "#endif", "float fade = 1.0;", "#if GLOSSY_REFLECTIONS == 1", "float localRoughness = roughness;", "#if ROUGHNESS_MAP == 1", "localRoughness *= texture2D( tRoughness, vUv ).r;", "#endif", "vec2 screenPosition = gl_FragCoord.xy / screenSize;", "float reflectionDepth = getReflectionDepth();", "float reflectionViewZ = getReflectionViewZ( reflectionDepth );", "vec3 reflectionViewPosition = getReflectionViewPosition( screenPosition, reflectionDepth, reflectionViewZ );", "vec3 reflectionWorldPosition = ( mirrorCameraWorldMatrix * vec4( reflectionViewPosition, 1.0 ) ).xyz;", "vec3 closestPointOnMirror = projectOnPlane( reflectionWorldPosition, mirrorWorldPosition, mirrorNormal );", "vec3 pointOnMirror = linePlaneIntersect( cameraPosition, normalize( reflectionWorldPosition - cameraPosition ), mirrorWorldPosition, mirrorNormal );", "float distance = length( closestPointOnMirror - reflectionWorldPosition );", "localRoughness = localRoughness * distance * 0.2;", "float lodLevel = localRoughness;", "fade = 1.0 - ( distanceFade * distance );", "#else", "float lodLevel = 0.0;", "#endif", "vec4 reflection = getReflection( mirrorCoord, lodLevel );", // apply dieletric-conductor model parameterized by metalness parameter. "float dotNV = clamp( dot( normalize( worldNormal ), normalize( vecPosition ) ), EPSILON, 1.0 );", "specular = mix( vec3( 0.05 ), specular, metalness );", // TODO: Invert fresnel. "vec3 fresnel;", "if( fresnelStrength < 0.0 ) {", "fresnel = mix( specular, specular * pow( dotNV, 2.0 ), -fresnelStrength ) * pow( 1.0 - roughness, 2.0 );", "} else {", "fresnel = mix( specular, F_Schlick( specular, dotNV ), fresnelStrength ) * pow( 1.0 - roughness, 2.0 );", "}", "gl_FragColor = vec4( reflection.rgb, fresnel * fade * reflection.a );", // fresnel controls alpha "}" ].join( "\n" ) };
mit
duboviy/misc
map_it.py
498
#!/usr/bin/env python # Launches a map in the browser using an address from the command line or clipboard. import webbrowser import sys import pyperclip # pip install pyperclip def map_it(): if len(sys.argv) > 1: # get address from command line address = ' '.join(sys.argv[1:]) else: # get address from clipboard address = pyperclip.paste() webbrowser.open('https://www.google.com/maps/place/' + address) if __name__ == '__main__': map_it()
mit
cheminfo-js/chromatography
src/util/__tests__/getClosestData.test.js
287
import { simple4 as chromatogram } from '../../../testFiles/examples'; test('Get closest data', () => { // time : [1, 2, 3, 4] expect(chromatogram.getClosestData(1.9)).toStrictEqual({ rt: 2, index: 1, data: [ [102, 202, 302], [12, 22, 32], ], }); });
mit
cuckata23/wurfl-data
data/alcatel_ot903_ver1.php
1344
<?php return array ( 'id' => 'alcatel_ot903_ver1', 'fallback' => 'generic_android_ver2_3', 'capabilities' => array ( 'uaprof' => 'http://www-ccpp.tcl-ta.com/files/ALCATEL_ONE_TOUCH_903.xml', 'model_name' => 'OT-903', 'brand_name' => 'Alcatel', 'marketing_name' => 'One Touch 903', 'release_date' => '2012_july', 'table_support' => 'true', 'physical_screen_height' => '96', 'columns' => '10', 'physical_screen_width' => '54', 'rows' => '36', 'max_image_width' => '320', 'resolution_width' => '540', 'resolution_height' => '960', 'jpg' => 'true', 'gif' => 'true', 'bmp' => 'true', 'png' => 'true', 'colors' => '262144', 'wap_push_support' => 'true', 'mms_png' => 'true', 'mms_3gpp' => 'true', 'mms_max_size' => '300000', 'mms_max_width' => '1024', 'sender' => 'true', 'mms_max_height' => '768', 'mms_gif_static' => 'true', 'mms_video' => 'true', 'mms_midi_monophonic' => 'true', 'receiver' => 'true', 'mms_wbmp' => 'true', 'mms_mp3' => 'true', 'mms_amr' => 'true', 'mms_mp4' => 'true', 'mms_jpeg_baseline' => 'true', 'mms_gif_animated' => 'true', 'wav' => 'true', 'aac' => 'true', 'mp3' => 'true', 'amr' => 'true', 'midi_monophonic' => 'true', 'imelody' => 'true', ), );
mit
jmervine/omnistruct
omnistruct.rb
844
Dir.glob(File.join(File.dirname(__FILE__), 'ext', '*.rb')).each do |lib| require lib end require 'json' # Top level class, mainly for correct requiring, but wraps Hash extensions as # well. module OmniStruct # Wraps Hash.to_struct # # Examples: # # s = OmniStruct.new({:foo => :bar}) # s.class # #=> ClassyHashStruct # s.foo # #=> :bar # # s = OmniStruct.new({:foo => :bar}) # s.class # #=> ClassyHashStruct # s.foo # #=> :bar def self.new hash=Hash.new, type=Hash.struct_type return hash.to_struct(type) end # Wraps Hash.struct_type def self.struct_type Hash.struct_type end # Wraps Hash.struct_type= def self.struct_type= type Hash.struct_type = type end protected # Wraps Hash.struct_types def self.struct_types Hash.send(:struct_types) end end
mit
itconsultis/weixin-payment
src/ITC/Weixin/Payment/Contracts/MessageFactory.php
275
<?php namespace ITC\Weixin\Payment\Contracts; interface MessageFactory { /** * @param mixed $data * @param array $required * * @return ITC\Weixin\Payment\Contracts\Message */ public function createMessage($data = null, $required = null); }
mit
charlessweet/amandadb
Amanda.IO/IAmandaFile.cs
368
using System.IO; namespace Amanda.IO { public interface IAmandaFile { bool Exists { get; } string GetNameWithoutExtension(); string GetRelativeFileName(); bool IsLargerThan(double fileSizeInGb); Stream OpenRead(); Stream OpenWrite(); void Truncate(); long Size { get; } } }
mit
caninojories/farmer
front-end/resources/js/routes/client/signup/farmer.js
1430
(function() { 'use strict'; angular .module('app.signup') .controller('Farmer', Farmer); Farmer.$inject = ['$q', '$rootScope', '$state', 'commonsDataService', 'signupServiceApi']; /* @ngInject */ function Farmer($q, $rootScope, $state, commonsDataService, signupServiceApi) { var vm = this; /*literals*/ /*functions*/ vm.register_farmer=register_farmer; function register_farmer(){ console.log('farmer'); $q.all([register_farmerCallback()]) .then(function(response) { console.log(response); }); } function register_farmerCallback() { return commonsDataService .httpPOSTQueryParams('signup/farmer', { first_name : vm.ffirst_name, last_name: vm.flast_name, email:vm.femail , password:vm.fpassword , company_name:vm.fcompany_name, address:vm.faddress , city:vm.fcity , state:vm.fstate , zip:vm.fzip , phone:vm.fphone , description:vm.fdescription , farm_size:vm.ffarm_size }, signupServiceApi) .then(function(response) { $rootScope.signup_success = true; $state.go('signup'); }).catch(function(error) { /*error*/ console.log('error'); }); } } }());
mit
umurkaragoz/laravel-std-admin
src/ManagesEditing.php
1034
<?php namespace Umurkaragoz\StdAdmin; use Illuminate\Database\Eloquent\Builder; /** * Trait ManagesEdit * Supplies common data to both `create` and `edit` operations. * * @package Umurkaragoz\StdAdmin */ trait ManagesEditing { /* ----------------------------------------------------------------------------------------------------------------------- supply Edit Data -+- */ /** * Parses edit data and supplies it to view. * * @return mixed */ private function supplyEditData() { $variables = $this->editData(); foreach ($variables as $variable => $data) { app('view')->share($variable, $data); } } /* ------------------------------------------------------------------------------------------------------------------------------ edit Data -+- */ /** * Override this method and supply common data for both 'create' and 'edit' operations. * * @return array */ public function editData() { return []; } }
mit
Innodite/laravel5-scaffold
src/Innodite/Generator/Generators/Common/MigrationGenerator.php
1743
<?php namespace Innodite\Generator\Generators\Common; use Config; use Innodite\Generator\CommandData; use Innodite\Generator\Generators\GeneratorProvider; use Innodite\Generator\SchemaCreator; class MigrationGenerator implements GeneratorProvider { /** @var CommandData */ private $commandData; private $path; function __construct($commandData) { $this->commandData = $commandData; $this->path = Config::get('generator.path_migration', base_path('database/migrations/')); } public function generate() { $templateData = $this->commandData->templatesHelper->getTemplate("Migration", "Common"); $templateData = $this->fillTemplate($templateData); $fileName = date('Y_m_d_His') . "_" . "create_" . $this->commandData->tableName . "_table.php"; $path = $this->path . $fileName; $this->commandData->fileHelper->writeFile($path, $templateData); $this->commandData->commandObj->comment("\nMigration created: "); $this->commandData->commandObj->info($fileName); } private function fillTemplate($templateData) { $templateData = str_replace('$MODEL_NAME_PLURAL$', $this->commandData->modelNamePlural, $templateData); $templateData = str_replace('$TABLE_NAME$', $this->commandData->tableName, $templateData); $templateData = str_replace('$FIELDS$', $this->generateFieldsStr(), $templateData); return $templateData; } private function generateFieldsStr() { $fieldsStr = "\$table->increments('id');\n"; foreach($this->commandData->inputFields as $field) { $fieldsStr .= SchemaCreator::createField($field['fieldInput']); } $fieldsStr .= "\t\t\t\$table->timestamps();"; if($this->commandData->useSoftDelete) $fieldsStr .= "\n\t\t\t\$table->softDeletes();"; return $fieldsStr; } }
mit
kaoDev/waterchat-app
src/components/profile-picture.tsx
423
import glamorous from 'glamorous' export const ProfilePicture = glamorous.div< { url?: string, diameter?: number } >( { borderRadius: '50%', backgroundPosition: 'center', backgroundColor: 'black', backgroundRepeat: 'no-repeat', backgroundSize: 'contain', }, ({ url = '', diameter = 50 }) => ({ backgroundImage: `url(${url})`, height: `${diameter}px`, width: `${diameter}px`, }) )
mit
i-square/LeetCode
451-sort-characters-by-frequency/sort-characters-by-frequency_[AC4_29ms].cpp
1106
// Given a string, sort it in decreasing order based on the frequency of characters. // // Example 1: // // Input: // "tree" // // Output: // "eert" // // Explanation: // 'e' appears twice while 'r' and 't' both appear once. // So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. // // // // Example 2: // // Input: // "cccaaa" // // Output: // "cccaaa" // // Explanation: // Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. // Note that "cacaca" is incorrect, as the same characters must be together. // // // // Example 3: // // Input: // "Aabb" // // Output: // "bbAa" // // Explanation: // "bbaA" is also a valid answer, but "Aabb" is incorrect. // Note that 'A' and 'a' are treated as two different characters. class Solution { public: string frequencySort(string s) { int freq[256] = { 0 }; for (const auto &c : s) ++freq[c]; sort(s.begin(), s.end(), [&](char &a, char &b) { return freq[a] > freq[b] || (freq[a] == freq[b] && a > b); }); return s; } };
mit
Xeltor/ovale
src/simulationcraft/text-tools.ts
2938
import { LuaArray, tonumber, setmetatable, rawset, type, tostring, pairs } from "@wowts/lua"; import { format, gsub, upper, lower, match } from "@wowts/string"; import { Annotation } from "./definitions"; import { OvalePool } from "../Pool"; export let INDENT: LuaArray<string> = {} { INDENT[0] = ""; let metatable = { __index: function (tbl: LuaArray<string>, key: string) { const _key = tonumber(key); if (_key > 0) { let s = `${tbl[_key - 1]}\t`; rawset(tbl, key, s); return s; } return INDENT[0]; } } setmetatable(INDENT, metatable); } export function print_r( data: any ) { let buffer: string = "" let padder: string = " " let max: number = 10 function _repeat(str: string, num: number) { let output: string = "" for (let i = 0; i < num; i += 1) { output = output + str; } return output; } function _dumpvar(d: any, depth: number) { if (depth > max) return let t = type(d) let str = d !== undefined && tostring(d) || "" if (t == "table") { buffer = buffer + format(" (%s) {\n", str) for (const [k, v] of pairs(d)) { buffer = buffer + format(" %s [%s] =>", _repeat(padder, depth+1), k) _dumpvar(v, depth+1) } buffer = buffer + format(" %s }\n", _repeat(padder, depth)) } else if (t == "number") { buffer = buffer + format(" (%s) %d\n", t, str) } else { buffer = buffer + format(" (%s) %s\n", t, str) } } _dumpvar(data, 0) return buffer } export const self_outputPool = new OvalePool<LuaArray<string>>("OvaleSimulationCraft_outputPool"); function CamelCaseHelper(first: string, rest: string) { return `${upper(first)}${lower(rest)}`; } export function CamelCase(s: string) { let tc = gsub(s, "(%a)(%w*)", CamelCaseHelper); return gsub(tc, "[%s_]", ""); } export function LowerSpecialization(annotation: Annotation) { return lower(annotation.specialization); } export function OvaleFunctionName(name: string, annotation: Annotation) { let functionName = lower(`${name}actions`); if (annotation.specialization) { functionName = `${LowerSpecialization(annotation)}${functionName}`; } return functionName; } export function OvaleTaggedFunctionName(name: string, tag: string): [string?, string?] { let bodyName, conditionName; let [prefix, suffix] = match(name, "([a-z]%w+)(actions)$"); if (prefix && suffix) { bodyName = lower(`${prefix}${tag}${suffix}`); conditionName = lower(`${prefix}${tag}postconditions`); } return [bodyName, conditionName]; }
mit
igraal/stats-table
tests/Tests/DynamicColumn/RelativeColumnBuilderTest.php
1088
<?php namespace Tests\DynamicColumn; use IgraalOSL\StatsTable\DynamicColumn\RelativeColumnBuilder; use IgraalOSL\StatsTable\StatsTableBuilder; class RelativeColumnBuilderTest extends \PHPUnit_Framework_TestCase { public function testWithData() { $statsTable = new StatsTableBuilder( [ 'first' => ['a' => 1, 'b' => 2, 'c' => 0], 'second' => ['a' => 4, 'b' => 5, 'd' => 0] ] ); $aColumnBuilder = new RelativeColumnBuilder('a'); $this->assertEquals( ['first' => .2, 'second' => .8], $aColumnBuilder->buildColumnValues($statsTable) ); $abColumnBuilder = new RelativeColumnBuilder(['a', 'b']); $this->assertEquals( ['first' => .25, 'second' => .75], $abColumnBuilder->buildColumnValues($statsTable) ); $cColumnBuilder = new RelativeColumnBuilder('c'); $this->assertEquals( ['first' => 0, 'second' => 0], $cColumnBuilder->buildColumnValues($statsTable) ); } }
mit
vir-mir/test_kudago
test_kudago_import/models.py
2959
# -*- coding: utf-8 -*- from django.db import models class Gallery(models.Model): image_url = models.URLField(max_length=255, verbose_name='Ссылка на изображение', unique=True) class Tag(models.Model): name = models.CharField(max_length=255, unique=True) class City(models.Model): name = models.CharField(max_length=255, unique=True) class Metro(models.Model): name = models.CharField(max_length=255, unique=True) class Person(models.Model): role = models.CharField(max_length=255) name = models.CharField(max_length=255) class Meta: unique_together = ( ('name', 'role',) ) class Phone(models.Model): type = models.CharField(max_length=255) number = models.BigIntegerField() class Meta: unique_together = ( ('number', 'type') ) class WorkTime(models.Model): type = models.CharField(max_length=255) time = models.CharField(max_length=255) class Meta: unique_together = ( ('time', 'type') ) class Event(models.Model): event_id = models.IntegerField(default=0) title = models.CharField(verbose_name='Название', max_length=255) type = models.CharField(max_length=255) runtime = models.IntegerField(null=True, blank=True) age_restricted = models.IntegerField(default=0) tags = models.ManyToManyField(Tag, blank=True, related_name='events') gallery = models.ManyToManyField(Gallery, blank=True, related_name='events') persons = models.ManyToManyField(Person, blank=True, related_name='events') text = models.TextField(null=True, blank=True) description = models.TextField(null=True, blank=True) class Place(models.Model): place_id = models.IntegerField(default=0) title = models.CharField(verbose_name='Название', max_length=255) type = models.CharField(max_length=255) address = models.CharField(null=True, blank=True, max_length=255) coordinates_lt = models.FloatField(null=True, blank=True) coordinates_lg = models.FloatField(null=True, blank=True) url = models.URLField(max_length=255, null=True, blank=True) city = models.ForeignKey(City, related_name='places', null=True, blank=True) tags = models.ManyToManyField(Tag, blank=True, related_name='places') metros = models.ManyToManyField(Metro, blank=True, related_name='places') work_times = models.ManyToManyField(WorkTime, blank=True, related_name='places') gallery = models.ManyToManyField(Gallery, blank=True, related_name='places') phones = models.ManyToManyField(Phone, blank=True, related_name='places') text = models.TextField(null=True, blank=True) class Schedule(models.Model): date = models.DateField() time = models.DateTimeField() event = models.ManyToManyField(Event, blank=True) place = models.ManyToManyField(Place, blank=True) time_till = models.DateTimeField(null=True, blank=True)
mit
theWaR13/ivk
app/reducers/long-poll.js
736
import * as con from 'app/constants/long-poll'; const initialState = { lpKey: '', lpServer: '', lpTs: '', updates: [], requestNumber: '', isFetching: false }; export default function longPoll(state=initialState, action) { switch (action.type) { case con.SAVE_LP_DATA: return { ...state, lpKey: action.payload.lpKey, lpServer: action.payload.lpServer, lpTs: action.payload.lpTs, isFetching: false }; case con.UPDATE_LP_TS: return { ...state, lpTs: action.payload.lpTs, updates: action.payload.updates, requestNumber: action.payload.requestNumber, isFetching: false }; default: return state; } }
mit
EmberSands/esi_client
spec/models/get_characters_character_id_not_found_spec.rb
1036
=begin #EVE Swagger Interface #An OpenAPI for EVE Online OpenAPI spec version: 0.4.6.dev11 Generated by: https://github.com/swagger-api/swagger-codegen.git =end require 'spec_helper' require 'json' require 'date' # Unit tests for ESIClient::GetCharactersCharacterIdNotFound # Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) # Please update as you see appropriate describe 'GetCharactersCharacterIdNotFound' do before do # run before each test @instance = ESIClient::GetCharactersCharacterIdNotFound.new end after do # run after each test end describe 'test an instance of GetCharactersCharacterIdNotFound' do it 'should create an instact of GetCharactersCharacterIdNotFound' do expect(@instance).to be_instance_of(ESIClient::GetCharactersCharacterIdNotFound) end end describe 'test attribute "error"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end
mit
ribeiro-ucl/UCLGoProject
UCLGo/management/commands/fix_permissions.py
1110
import sys from django.contrib.auth.management import _get_all_permissions from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType from django.core.management.base import BaseCommand from django.apps import apps class Command(BaseCommand): help = "Fix permissions for proxy models." def handle(self, *args, **options): for model in apps.get_models(): opts = model._meta sys.stdout.write('{}-{}\n'.format(opts.app_label, opts.object_name.lower())) ctype, created = ContentType.objects.get_or_create( app_label=opts.app_label, model=opts.object_name.lower()) for codename, name in _get_all_permissions(opts): sys.stdout.write(' --{}\n'.format(codename)) p, created = Permission.objects.get_or_create( codename=codename, content_type=ctype, defaults={'name': name}) if created: sys.stdout.write('Adding permission {}\n'.format(p))
mit
SamaPanda/symfony
vendor/symfony/symfony/src/Symfony/Component/Config/Loader/DelegatingLoader.php
1351
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Config\Loader; use Symfony\Component\Config\Exception\FileLoaderLoadException; /** * DelegatingLoader delegates loading to other loaders using a loader resolver. * * This loader acts as an array of LoaderInterface objects - each having * a chance to load a given resource (handled by the resolver) * * @author Fabien Potencier <fabien@symfony.com> */ class DelegatingLoader extends Loader { /** * @param LoaderResolverInterface $resolver A LoaderResolverInterface instance */ public function __construct(LoaderResolverInterface $resolver) { $this->resolver = $resolver; } /** * {@inheritdoc} */ public function load($resource, $type = null) { if (false === $loader = $this->resolver->resolve($resource, $type)) { throw new FileLoaderLoadException($resource); } return $loader->load($resource, $type); } /** * {@inheritdoc} */ public function supports($resource, $type = null) { return false !== $this->resolver->resolve($resource, $type); } }
mit
VidaID/bcoin
bench/script.js
932
'use strict'; var assert = require('assert'); var crypto = require('../lib/crypto/crypto'); var Script = require('../lib/script/script'); var bench = require('./bench'); var opcodes = Script.opcodes; var i, hashes, end; Script.prototype.fromPubkeyhashOld = function fromScripthash(hash) { assert(Buffer.isBuffer(hash) && hash.length === 20); this.push(opcodes.OP_DUP); this.push(opcodes.OP_HASH160); this.push(hash); this.push(opcodes.OP_EQUALVERIFY); this.push(opcodes.OP_CHECKSIG); this.compile(); return this; }; Script.fromPubkeyhashOld = function fromScripthash(hash) { return new Script().fromPubkeyhashOld(hash); }; hashes = []; for (i = 0; i < 100000; i++) hashes.push(crypto.randomBytes(20)); end = bench('old'); for (i = 0; i < hashes.length; i++) Script.fromPubkeyhashOld(hashes[i]); end(i); end = bench('hash'); for (i = 0; i < hashes.length; i++) Script.fromPubkeyhash(hashes[i]); end(i);
mit
alexanderpa/angular-number-converter
karma.conf.js
1604
// Karma configuration module.exports = function(config) { config.set({ // base path, that will be used to resolve files and exclude basePath: '', frameworks: ["jasmine"], // list of files / patterns to load in the browser files: [ 'bower_components/angular/angular.min.js', 'bower_components/angular-mocks/angular-mocks.js', 'bower_components/underscore/underscore-min.js', 'dist/angular-number-converter.min.js', 'test/*.js' ], // list of files to exclude exclude: [ ], // test results reporter to use // possible values: 'dots', 'progress', 'junit' reporters: ['progress'], // web server port port: 9876, // cli runner port runnerPort: 9100, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: ['PhantomJS'], // If browser does not capture in given timeout [ms], kill it captureTimeout: 60000, // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false }); };
mit
ernestas-poskus/codeschool
Rails 4 Zombie Outlaws/routes_test_html_patch.rb
206
class WeaponsControllerTest < ActionController::TestCase test "updates weapon" do patch :update, zombie_id: @zombie, weapons: { name: 'Scythe' } assert_redirected_to zombie_url(@zombie) end end
mit
htfy96/htscheme
types/float.hpp
161
#ifndef __SCHEME_TYPES_FLOAT #define __SCHEME_TYPES_FLOAT #include "arch.hpp" #include <string> PARSER_DECLARATION(FloatParser, Float, long double) #endif
mit
hetcollectief/express-upload
example/app/router.js
700
var _ = require('underscore') , upload = require('express-upload'); module.exports = function(app) { app.get('/', function(req, res) { res.redirect('/upload'); }); // ROUTE: GET /upload app.get('/upload', function(req, res) { res.render('upload', _.extend({ title: 'Server Upload', uploadpath: '/upload' }, res.locals)); }); // ROUTE: GET /s3upload app.get('/s3upload', function(req, res) { res.render('upload', _.extend({ title: 'S3 Upload', uploadpath: '/s3upload' }, res.locals)); }); // ROUTE: ALL /upload app.use('/upload', upload.handler({})); // ROUTE: ALL /upload app.use('/s3upload', upload.s3handler( require('./../credentials.json') )); };
mit
mipengine/mip-extensions-platform
mip-jia-house-style/mip-jia-house-style.js
6597
/** * @file mip-jia-house-style 组件 * @author */ define(function (require) { var $ = require('zepto'); var customElement = require('customElement').create(); // 根据传入面积获取室厅卫的数量 function fenFn(obj, area) { if (area <= 60) { obj.find('input[name="shi1"]').val(1); obj.find('input[name="ting1"]').val(1); obj.find('input[name="chu1"]').val(1); obj.find('input[name="wei1"]').val(1); } else if (area > 60 && area <= 90) { obj.find('input[name="shi1"]').val(2); obj.find('input[name="ting1"]').val(1); obj.find('input[name="chu1"]').val(1); obj.find('input[name="wei1"]').val(1); } else if (area > 90 && area <= 110) { obj.find('input[name="shi1"]').val(3); obj.find('input[name="ting1"]').val(1); obj.find('input[name="chu1"]').val(1); obj.find('input[name="wei1"]').val(1); } else if (area > 110 && area <= 130) { obj.find('input[name="shi1"]').val(3); obj.find('input[name="ting1"]').val(2); obj.find('input[name="chu1"]').val(1); obj.find('input[name="wei1"]').val(1); } else if (area > 130 && area <= 150) { obj.find('input[name="shi1"]').val(3); obj.find('input[name="ting1"]').val(2); obj.find('input[name="chu1"]').val(1); obj.find('input[name="wei1"]').val(2); } else if (area > 150 && area <= 180) { obj.find('input[name="shi1"]').val(4); obj.find('input[name="ting1"]').val(2); obj.find('input[name="chu1"]').val(1); obj.find('input[name="wei1"]').val(2); } else if (area > 180) { obj.find('input[name="shi1"]').val(4); obj.find('input[name="ting1"]').val(2); obj.find('input[name="chu1"]').val(1); obj.find('input[name="wei1"]').val(2); } } var urlHrefObject = (function () { var hrefUrlArr = []; var obj = {}; if (window.location.search.substr(1) && window.location.search.substr(1).length > 2) { hrefUrlArr = window.location.search.substr(1).split('&'); for (var i = 0; i < hrefUrlArr.length; i++) { var arr = hrefUrlArr[i].split('='); obj[arr[0]] = arr[1]; } } return obj; })(); function validateArea(obj) { obj.find('#pm_area').change(function () { var pmArea = parseInt(obj.find('#pm_area').val(), 10); fenFn(obj, pmArea); }); // 改变select的值 obj.find('.zx-select').change(function () { var curObj = this; var index = curObj.selectedIndex; var text = curObj.options[index].text; obj.find('.fg-title').text(text); }); // 点击加号按钮 obj.find('.add-btn').click(function () { var i = parseInt($(this).prev().prev().val(), 10); var maxNum = 2; if ($(this).prev().text() === '室') { maxNum = 6; } else if ($(this).prev().text() === '厅') { maxNum = 5; } else if ($(this).prev().text() === '厨') { maxNum = 2; } else if ($(this).prev().text() === '卫') { maxNum = 4; } if (i < maxNum) { i++; $(this).prev().prev().val(i); } }); // 点击减号按钮 obj.find('.minus-btn').click(function () { var i = parseInt($(this).next().val(), 10); if (i > 1) { i--; $(this).next().val(i); } }); // 判断链接带的id号给面积、风格、室赋值 if (urlHrefObject.sid === 'sid1') { if (urlHrefObject.picid) { $.ajax({ url: '//m.jia.com/new_zhuangxiu/get_aladdin_dantu', type: 'get', data: {'pic_id': urlHrefObject.picid}, success: function (data) { if (data.status === 200) { if (data.squre !== undefined && data.squre !== '' && data.squre !== '0') { obj.find('#pm_area').val(parseInt(data.squre, 10)); } if (data.bedroomNum !== undefined && data.bedroomNum !== '' && data.bedroomNum !== '0') { obj.find('#shi').val(parseInt(data.bedroomNum, 10)); } if (data.genre !== undefined && data.genre !== '') { obj.find('.fg-title').text(data.genre + '风格'); obj.find('.zx-select').val(data.genre + '风格'); } } }, error: function () { } }); } if (urlHrefObject.picids) { $.ajax({ url: '//m.jia.com/new_zhuangxiu/get_aladdin_tuji', type: 'get', data: {'pic_ids': urlHrefObject.picids}, success: function (data) { if (data.status === 200) { if (data.squre !== undefined && data.squre !== '' && data.squre !== '0') { obj.find('#pm_area').val(parseInt(data.squre, 10)); } if (data.bedroomNum !== undefined && data.bedroomNum !== '' && data.bedroomNum !== '0') { obj.find('#shi').val(parseInt(data.bedroomNum, 10)); } if (data.genre !== undefined && data.genre !== '') { obj.find('.fg-title').text(data.genre + '风格'); obj.find('.zx-select').val(data.genre + '风格'); } } }, error: function () { } }); } } } customElement.prototype.firstInviewCallback = function () { var thisObj = this.element; validateArea($(thisObj)); }; return customElement; });
mit
SilkStack/Silk.Data.SQL.ORM
Silk.Data.SQL.ORM/Silk.Data/IDeferred.cs
942
using System.Threading.Tasks; namespace Silk.Data { /// <summary> /// A deferred task waiting to be executed. /// </summary> public interface IDeferred { /// <summary> /// Create a new instance of the preferred transaction controller implemenation. /// Note: this might not be the transaction controller the task will end up using. /// </summary> /// <returns></returns> ITransactionController GetTransactionControllerImplementation(); /// <summary> /// Set the transaction controller to use when executing. /// </summary> /// <param name="transactionController"></param> void SetSharedTransactionController(ITransactionController transactionController); /// <summary> /// Execute the deferred task. /// </summary> void Execute(); /// <summary> /// Execute the deferred task asynchronously. /// </summary> /// <returns></returns> Task ExecuteAsync(); } }
mit
DeclanCarter/CDDLabs
Lab 3 Rendezvous/html/search/searchdata.js
301
var indexSectionsWithContent = { 0: "mrstw", 1: "s", 2: "ms", 3: "mstw", 4: "r" }; var indexSectionNames = { 0: "all", 1: "classes", 2: "files", 3: "functions", 4: "pages" }; var indexSectionLabels = { 0: "All", 1: "Classes", 2: "Files", 3: "Functions", 4: "Pages" };
mit
WildflowerSchools/sensei
frontend/src/visualizations/components/entityTypeSection.js
987
import * as d3 from "d3"; import _ from 'lodash'; const defaultOpts = { rowHeight: 30, className: 'sections', labels: true } export default function entityTypeSection(selection, opts = {}) { opts = _.merge({}, defaultOpts, opts); selection.exit().remove(); // selects group tag that corresponds to the current entity type selection .attr("id", (d) => { return d[0]; }) // sets the y displacement for the current entity type group .attr("transform", (d) => { return `translate(0,${d[1].y * opts.rowHeight})` }) selection .enter() .append("g") .attr("class", opts.className) .merge(selection) if (!opts.labels) return; let text = selection.selectAll('text') .data((d, x, y) => { return [d[0]]; }) text.enter() .append("text") .attr("x", 0) .attr("y", 0) .attr("style", `font-weight: bold; opacity: ${opts.hideLabels ? 0 : 1}`) .text((d) => { return d; }); }
mit
heilc/TableTop
TableTop.Domain.CMS/Services/NuPickersService.cs
1543
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TableTop.Domain.CMS.Interfaces; using TableTop.Models.CMS.Models; using TableTop.Repository.CMS.Interfaces; using TableTop.Repository.CMS.Services; using Umbraco.Core.Models; using Umbraco.Web; namespace TableTop.Domain.CMS.Services { public class NuPickersService : INuPickersService { private IDittoService _dittoService; private UmbracoHelper _umbHelper; public NuPickersService(IDittoService ditto) { _umbHelper = new UmbracoHelper(UmbracoContext.Current); _dittoService = ditto; } public IEnumerable<KeyValuePair<string,string>> GetNPCDropdown(string campaignName, string ddType) { var root = _umbHelper.TypedContentAtRoot(); var campaign = root.DescendantsOrSelf("campaign").Where(m => m.Name == campaignName).FirstOrDefault(); if (campaign != null) { var npcs = campaign.DescendantsOrSelf(ddType); if (npcs != null) { return npcs.Select(m => GetKeyValuePairFromItem(m)); } } return null; } private KeyValuePair<string, string> GetKeyValuePairFromItem(IPublishedContent m) { var npc = _dittoService.ContentAs<NPCModel>(m); return new KeyValuePair<string, string>(m.Id.ToString(), npc.CharacterName); } } }
mit
valdisiljuconoks/ImageResizer.Plugins.EPiServerBlobReader
samples/SampleAlloy/Models/Media/ImageFile.cs
579
using EPiServer.Core; using EPiServer.DataAnnotations; using EPiServer.Framework.DataAnnotations; using System.ComponentModel.DataAnnotations; namespace SampleAlloy.Models.Media { [ContentType(GUID = "0A89E464-56D4-449F-AEA8-2BF774AB8730")] [MediaDescriptor(ExtensionString = "jpg,jpeg,jpe,ico,gif,bmp,png")] public class ImageFile : ImageData { /// <summary> /// Gets or sets the copyright. /// </summary> /// <value> /// The copyright. /// </value> public virtual string Copyright { get; set; } } }
mit
graphaware/GithubNeo4j
src/GraphAware/Neo4jBundle/GraphAwareNeo4jBundle.php
779
<?php namespace GraphAware\Neo4jBundle; use Symfony\Component\HttpKernel\Bundle\Bundle, Symfony\Component\DependencyInjection\ContainerBuilder; use Neoxygen\NeoClient\DependencyInjection\Compiler\ConnectionRegistryCompilerPass, Neoxygen\NeoClient\DependencyInjection\Compiler\NeoClientExtensionsCompilerPass; use GraphAware\Neo4jBundle\DependencyInjection\Compiler\EventSubscribersCompilerPass; class GraphAwareNeo4jBundle extends Bundle { public function build(ContainerBuilder $container) { parent::build($container); $container->addCompilerPass(new ConnectionRegistryCompilerPass()); $container->addCompilerPass(new NeoClientExtensionsCompilerPass()); $container->addCompilerPass(new EventSubscribersCompilerPass()); } }
mit
SoubhagyaDash/ApplicationInsights-Home
Samples/Heartbeat/AspNetCore/ASPNetCoreSample/Models/ErrorViewModel.cs
224
using System; namespace ASPNetCoreSample.Models { public class ErrorViewModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); } }
mit
abhineet97/webrtc-chess
app/lib/peer.js
1971
'use strict'; import SimplePeer from 'simple-peer'; /** Class representing a library-independent WebRTC peer */ class Peer { /** * Create a peer. * @param {string} id */ constructor(id) { this._isInitiator = id === ''; this._id = id || this._genID(); this._offer = null; this._answer = null; this._p = null; this.onWSOpen = null; this.onConnect = null; this.onData = null; this.onClose = null; } /** * Returns a random string. * @return {string} */ _genID() { return Math.random() .toString(16) .substr(2, 10); } /** * Sends data to remote peer. * @param {object} data */ send(data) { this._p.send(data); } /** * Performs signalling. */ signal() { this._p = new SimplePeer({initiator: this._isInitiator, trickle: false}); const isSecure = location.protocol === 'https:'; const ws = new WebSocket( (isSecure ? 'wss://' : 'ws://') + location.host + '/ws?id=' + this._id, ); ws.onmessage = (e) => { const msg = JSON.parse(e.data); if (msg.type === 'offer_request' && this._isInitiator) { ws.send(JSON.stringify(this._offer)); } else if ( (msg.type === 'offer' && !this._isInitiator) || (msg.type === 'answer' && this._isInitiator) ) { this._p.signal(msg); } }; ws.onopen = () => { if (this._isInitiator) { this.onWSOpen(this._id); } else { ws.send(JSON.stringify({type: 'offer_request'})); } }; this._p.on('signal', (signal) => { this['_' + signal.type] = signal; if (signal.type === 'answer') { ws.send(JSON.stringify(signal)); } }); this._p.on('connect', () => { ws.close(); this.onConnect(); }); this._p.on('data', (data) => { this.onData(data); }); this._p.on('close', () => { this.onClose(); }); } } export default Peer;
mit
omniscopeio/flight-plans
app/models/user.rb
430
class User < ActiveRecord::Base enum role: [:user, :vip, :admin] after_initialize :set_default_role, :if => :new_record? def set_default_role self.role ||= :user end # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :confirmable, :recoverable, :rememberable, :trackable, :validatable end
mit
d-fischer/twitch
packages/chat/src/commands/TwitchPrivateMessage.ts
2672
import type { BaseCheermoteList, CheermoteFormat, ParsedMessageCheerPart, ParsedMessagePart } from '@twurple/common'; import { fillTextPositions, rtfm } from '@twurple/common'; import { MessageTypes } from 'ircv3'; import { ChatUser } from '../ChatUser'; import { parseEmoteOffsets, parseEmotePositions } from '../utils/emoteUtil'; /** * An IRC PRIVMSG, with easy accessors for commonly used data from its tags. */ @rtfm<TwitchPrivateMessage>('chat', 'TwitchPrivateMessage', 'id') export class TwitchPrivateMessage extends MessageTypes.Commands.PrivateMessage { /** * The ID of the message. */ get id(): string { return this._tags.get('id')!; } /** * Info about the user that send the message, like their user ID and their status in the current channel. */ get userInfo(): ChatUser { return new ChatUser(this._prefix!.nick, this._tags); } /** * The ID of the channel the message is in. */ get channelId(): string | null { return this._tags.get('room-id') ?? null; } /** * Whether the message is a cheer. */ get isCheer(): boolean { return this._tags.has('bits'); } /** * The number of bits cheered with the message. */ get bits(): number { return Number(this._tags.get('bits') ?? 0); } /** * The offsets of emote usages in the message. */ get emoteOffsets(): Map<string, string[]> { return parseEmoteOffsets(this._tags.get('emotes')); } /** * Parses the message, separating text from emote usages. */ parseEmotes(): ParsedMessagePart[] { const messageText = this.params.content; const foundEmotes: ParsedMessagePart[] = parseEmotePositions(messageText, this.emoteOffsets); return fillTextPositions(messageText, foundEmotes); } /** * Parses the message, separating text from emote usages and cheers. * * @param cheermotes A list of cheermotes. * @param cheermoteFormat The format to show the cheermotes in. */ parseEmotesAndBits(cheermotes: BaseCheermoteList<unknown>, cheermoteFormat: CheermoteFormat): ParsedMessagePart[] { const messageText = this.params.content; const foundCheermotes = cheermotes.parseMessage(messageText, cheermoteFormat); const foundEmotesAndCheermotes: ParsedMessagePart[] = [ ...parseEmotePositions(messageText, this.emoteOffsets), ...foundCheermotes.map( (cheermote): ParsedMessageCheerPart => ({ type: 'cheer', position: cheermote.position, length: cheermote.length, name: cheermote.name, amount: cheermote.amount, displayInfo: cheermote.displayInfo }) ) ]; foundEmotesAndCheermotes.sort((a, b) => a.position - b.position); return fillTextPositions(messageText, foundEmotesAndCheermotes); } }
mit
cs383-4/sQuire
src/main/java/squire/Users/ProjectFile.java
902
package squire.Users; /** * Implements files to be used by the project database */ import squire.BaseModel; import javax.persistence.Entity; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity //some databases have user as a reserved word, so following ebean examples, prefix tables with "o_" @Table(name = "o_project_file") public class ProjectFile extends BaseModel { public static final ProjectFileFinder find = new ProjectFileFinder(); @ManyToOne() private Project project; private String name; public ProjectFile(String name) { this.name = name; } public Project getProject() { return project; } public void setProject(Project project) { this.project = project; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
mit
gfviegas/anboil
template/components/socket/socket.service.js
2085
/* global io */ 'use strict'; angular.module('applicationApp') .factory('socket', function(socketFactory) { // socket.io now auto-configures its connection when we ommit a connection url var ioSocket = io('', { // Send auth token on connection, you will need to DI the Auth service above // 'query': 'token=' + Auth.getToken() path: '/socket.io-client' }); var socket = socketFactory({ ioSocket: ioSocket }); return { socket: socket, /** * Register listeners to sync an array with updates on a model * * Takes the array we want to sync, the model name that socket updates are sent from, * and an optional callback function after new items are updated. * * @param {String} modelName * @param {Array} array * @param {Function} cb */ syncUpdates: function (modelName, array, cb) { cb = cb || angular.noop; /** * Syncs item creation/updates on 'model:save' */ socket.on(modelName + ':save', function (item) { var oldItem = _.find(array, {_id: item._id}); var index = array.indexOf(oldItem); var event = 'created'; // replace oldItem if it exists // otherwise just add item to the collection if (oldItem) { array.splice(index, 1, item); event = 'updated'; } else { array.push(item); } cb(event, item, array); }); /** * Syncs removed items on 'model:remove' */ socket.on(modelName + ':remove', function (item) { var event = 'deleted'; _.remove(array, {_id: item._id}); cb(event, item, array); }); }, /** * Removes listeners for a models updates on the socket * * @param modelName */ unsyncUpdates: function (modelName) { socket.removeAllListeners(modelName + ':save'); socket.removeAllListeners(modelName + ':remove'); } }; });
mit
ahonn/ahonn.github.io
store/post.ts
649
import * as next from 'next'; import Api from '../lib/api'; interface IGetReducerPayload { id: number; post: IGithubIssue; } export default { state: { posts: {}, }, reducers: { get(state: any, payload: IGetReducerPayload) { const { id, post } = payload; return { ...state, posts: { ...state.posts, [id]: post, }, }; }, }, effects: { async getAsync(payload: { ctx?: next.NextPageContext; id: number }) { const { ctx, id } = payload; const post: IGithubIssue = await Api.create(ctx).post(id); return this.get({ id, post }); }, }, };
mit
Tetcoin/tetcoin
src/qt/locale/bitcoin_ro_RO.ts
109726
<?xml version="1.0" ?><!DOCTYPE TS><TS language="ro_RO" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Tetcoin</source> <translation>Despre Tetcoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;Tetcoin&lt;/b&gt; version</source> <translation>&lt;b&gt;Tetcoin&lt;/b&gt; versiunea</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The Litecoin Developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Listă de adrese</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Dublu-click pentru a edita adresa sau eticheta</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Creaţi o adresă nouă</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Copiați adresa selectată în clipboard</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Adresă nouă</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your Tetcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Acestea sunt adresele dumneavoastră Tetcoin pentru a primi plăţi. Dacă doriţi, puteți da o adresa diferită fiecărui expeditor, pentru a putea ţine evidenţa plăţilor.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Copiază adresa</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Arata codul QR</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Tetcoin address</source> <translation>Semneaza mesajul pentru a dovedi ca detii aceasta adresa Bitocin</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Semneaza mesajul</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Sterge adresele curent selectate din lista</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified Tetcoin address</source> <translation>Verifica mesajul pentru a te asigura ca a fost insemnat cu o adresa tetcoin specifica</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation> Verifica mesajele</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Șterge</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your Tetcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Copiază &amp;eticheta</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Editează</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Exportă Lista de adrese</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Fisier csv: valori separate prin virgulă (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Eroare la exportare.</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Eroare la scrierea în fişerul %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Etichetă</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresă</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(fără etichetă)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Introduceți fraza de acces.</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Frază de acces nouă </translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Repetaţi noua frază de acces</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Introduceţi noua parolă a portofelului electronic.&lt;br/&gt;Vă rugăm să folosiţi &lt;b&gt;minimum 10 caractere aleatoare&lt;/b&gt;, sau &lt;b&gt;minimum 8 cuvinte&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Criptează portofelul</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Aceasta operație are nevoie de un portofel deblocat.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Deblochează portofelul</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Această operaţiune necesită parola pentru decriptarea portofelului electronic.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Decriptează portofelul.</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Schimbă fraza de acces</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Introduceţi vechea parola a portofelului eletronic şi apoi pe cea nouă.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Confirmă criptarea portofelului.</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR LITECOINS&lt;/b&gt;!</source> <translation>Atenție: Dacă pierdeţi parola portofelului electronic dupa criptare, &lt;b&gt;VEŢI PIERDE ÎNTREAGA SUMĂ DE LITECOIN ACUMULATĂ&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Sunteţi sigur că doriţi să criptaţi portofelul electronic?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Atentie! Caps Lock este pornit</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Portofel criptat </translation> </message> <message> <location line="-56"/> <source>Tetcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your tetcoins from being stolen by malware infecting your computer.</source> <translation>Tetcoin se va închide acum pentru a termina procesul de criptare. Amintiți-vă că criptarea portofelului dumneavoastră nu poate proteja în totalitate tetcoins dvs. de a fi furate de intentii rele.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Criptarea portofelului a eșuat.</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Criptarea portofelului a eșuat din cauza unei erori interne. Portofelul tău nu a fost criptat.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Fraza de acces introdusă nu se potrivește.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Deblocarea portofelului electronic a eşuat.</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Parola introdusă pentru decriptarea portofelului electronic a fost incorectă.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Decriptarea portofelului electronic a eşuat.</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Parola portofelului electronic a fost schimbată.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>Semneaza &amp;mesaj...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Se sincronizează cu reţeaua...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Detalii</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Afişează detalii despre portofelul electronic</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Tranzacţii</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Istoricul tranzacţiilor</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Editaţi lista de adrese şi etichete.</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Lista de adrese pentru recepţionarea plăţilor</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>Ieșire</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Părăsiţi aplicaţia</translation> </message> <message> <location line="+4"/> <source>Show information about Tetcoin</source> <translation>Informaţii despre Tetcoin</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Despre &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Informaţii despre Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Setări...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>Criptează portofelul electronic...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup portofelul electronic...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Schimbă parola...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Importare blocks de pe disk...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-347"/> <source>Send coins to a Tetcoin address</source> <translation>&amp;Trimiteţi Tetcoin către o anumită adresă</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for Tetcoin</source> <translation>Modifică setările pentru Tetcoin</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Creaza copie de rezerva a portofelului intr-o locatie diferita</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>&amp;Schimbă parola folosită pentru criptarea portofelului electronic</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>&amp; Fereastra debug</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Deschide consola de debug si diagnosticare</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>Verifica mesajul</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>Tetcoin</source> <translation>Tetcoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Portofelul</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About Tetcoin</source> <translation>&amp;Despre Tetcoin</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>Arata/Ascunde</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your Tetcoin addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Tetcoin addresses</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Fişier</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Setări</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Ajutor</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Bara de ferestre de lucru</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+47"/> <source>Tetcoin client</source> <translation>Client Tetcoin</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to Tetcoin network</source> <translation><numerusform>%n active connections to Tetcoin network</numerusform><numerusform>%n active connections to Tetcoin network</numerusform><numerusform>%n active connections to Tetcoin network</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Actualizat</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Se actualizează...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Confirma taxa tranzactiei</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Tranzacţie expediată</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Tranzacţie recepţionată</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Data: %1⏎ Suma: %2⏎ Tipul: %3⏎ Addresa: %4⏎</translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid Tetcoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Portofelul electronic este &lt;b&gt;criptat&lt;/b&gt; iar in momentul de faţă este &lt;b&gt;deblocat&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Portofelul electronic este &lt;b&gt;criptat&lt;/b&gt; iar in momentul de faţă este &lt;b&gt;blocat&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. Tetcoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Alerta retea</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Editează adresa</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Eticheta</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Eticheta asociată cu această înregistrare în Lista de adrese</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Adresă</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Adresa asociată cu această înregistrare în Lista de adrese. Aceasta poate fi modificată doar pentru expediere.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Noua adresă de primire</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Noua adresă de trimitere</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Editează adresa de primire</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Editează adresa de trimitere</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Adresa introdusă &quot;%1&quot; se află deja în Lista de adrese.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Tetcoin address.</source> <translation>Adresa introdusă &quot;%1&quot; nu este o adresă tetcoin valabilă.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Portofelul electronic nu a putut fi deblocat .</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>New key generation failed.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>Tetcoin-Qt</source> <translation>Tetcoin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>versiunea</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Uz:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>command-line setări</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>UI setări</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Seteaza limba, de exemplu: &quot;de_DE&quot; (initialt: system locale)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Incepe miniaturizare</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Afișează pe ecran splash la pornire (implicit: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Setări</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Principal</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Plăteşte comision pentru tranzacţie &amp;f</translation> </message> <message> <location line="+31"/> <source>Automatically start Tetcoin after logging in to the system.</source> <translation>Porneşte automat programul Tetcoin la pornirea computerului.</translation> </message> <message> <location line="+3"/> <source>&amp;Start Tetcoin on system login</source> <translation>&amp;S Porneşte Tetcoin la pornirea sistemului</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>&amp;Retea</translation> </message> <message> <location line="+6"/> <source>Automatically open the Tetcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Deschide automat în router portul aferent clientului Tetcoin. Funcţionează doar în cazul în care routerul e compatibil UPnP şi opţiunea e activată.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Mapeaza portul folosind &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the Tetcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Conectare la reţeaua Tetcoin folosind un proxy SOCKS (de exemplu, când conexiunea se stabileşte prin reţeaua Tor)</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Conectează prin proxy SOCKS:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>Proxy &amp;IP:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>Adresa de IP a proxy serverului (de exemplu: 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Port:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Portul pe care se concetează proxy serverul (de exemplu: 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS &amp;Versiune:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Versiunea SOCKS a proxiului (ex. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Fereastra</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Afişează doar un icon in tray la ascunderea ferestrei</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;M Ascunde în tray în loc de taskbar</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Ascunde fereastra în locul părăsirii programului în momentul închiderii ferestrei. Când acestă opţiune e activă, aplicaţia se va opri doar în momentul selectării comenzii Quit din menu.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>&amp;i Ascunde fereastra în locul închiderii programului</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Afişare</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>Interfata &amp; limba userului</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Tetcoin.</source> <translation>Limba interfeței utilizatorului poate fi setat aici. Această setare va avea efect după repornirea Tetcoin.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Unitatea de măsură pentru afişarea sumelor:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Alege subdiviziunea folosită la afişarea interfeţei şi la trimiterea de tetcoin.</translation> </message> <message> <location line="+9"/> <source>Whether to show Tetcoin addresses in the transaction list or not.</source> <translation>Vezi dacă adresele Tetcoin sunt în lista de tranzacție sau nu</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Afişează adresele în lista de tranzacţii</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp; OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp; Renunta</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>Aplica</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>Initial</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Atentie!</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Tetcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Adresa tetcoin pe care a-ti specificat-o este invalida</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Form</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Tetcoin network after a connection is established, but this process has not completed yet.</source> <translation>Informațiile afișate pot fi expirate. Portofelul tău se sincronizează automat cu rețeaua Tetcoin după ce o conexiune este stabilita, dar acest proces nu a fost finalizat încă.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Balanţă:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Neconfirmat:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Portofelul</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation>Nematurizat:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Balanta minata care nu s-a maturizat inca</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Ultimele tranzacţii&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Soldul contul</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Totalul tranzacţiilor care aşteaptă să fie confirmate şi care nu sunt încă luate în calcul la afişarea soldului contului.</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>Nu este sincronizat</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start tetcoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>Dialogul codului QR</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Cerere de plata</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Sumă:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Etichetă:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Mesaj:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>Salvare ca...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Eroare la incercarea codarii URl-ului in cod QR</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>Suma introdusa nu este valida, verifica suma.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Salveaza codul QR</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>Imagini de tip PNG (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Numaele clientului</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>N/A</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Versiunea clientului</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp; Informatie</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Foloseste versiunea OpenSSL</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Data pornirii</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Retea</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Numarul de conexiuni</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>Pe testnet</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Lant bloc</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Numarul curent de blockuri</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Estimarea totala a blocks</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Ultimul block a fost gasit la:</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Deschide</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Command-line setări</translation> </message> <message> <location line="+7"/> <source>Show the Tetcoin-Qt help message to get a list with possible Tetcoin command-line options.</source> <translation>Arata mesajul de ajutor Tetcoin-QT pentru a obtine o lista cu posibilele optiuni ale comenzilor Tetcoin</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>&amp; Arata</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Consola</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Construit la data:</translation> </message> <message> <location line="-104"/> <source>Tetcoin - Debug window</source> <translation>Tetcoin-Fereastra pentru debug</translation> </message> <message> <location line="+25"/> <source>Tetcoin Core</source> <translation>Tetcoin Core</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Loguri debug</translation> </message> <message> <location line="+7"/> <source>Open the Tetcoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Deschide logurile debug din directorul curent. Aceasta poate dura cateva secunde pentru fisierele mai mari</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Curata consola</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Tetcoin RPC console.</source> <translation>Bun venit la consola tetcoin RPC</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Foloseste sagetile sus si jos pentru a naviga in istoric si &lt;b&gt;Ctrl-L&lt;/b&gt; pentru a curata.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Scrie &lt;b&gt;help&lt;/b&gt; pentru a vedea comenzile disponibile</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Trimite Tetcoin</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Trimite simultan către mai mulţi destinatari</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>&amp;Adaugă destinatar</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Sterge toate spatiile de tranzactie</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Şterge &amp;tot</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Balanţă:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Confirmă operaţiunea de trimitere</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;S Trimite</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; la %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Confirmaţi trimiterea de tetcoin</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Sunteţi sigur că doriţi să trimiteţi %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> şi </translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>Adresa destinatarului nu este validă, vă rugăm să o verificaţi.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Suma de plată trebuie să fie mai mare decât 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Suma depăşeşte soldul contului.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Total depăşeşte soldul contului in cazul plăţii comisionului de %1.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>S-a descoperit o adresă care figurează de două ori. Expedierea se poate realiza către fiecare adresă doar o singură dată pe operaţiune.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Eroare: Tranyacţia a fost respinsă. Acesta poate fi rezultatul cheltuirii prealabile a unei sume de tetcoin din portofelul electronic, ca în cazul folosirii unei copii a fisierului wallet.dat, în care s-au efectuat tranzacţii neînregistrate în fisierul curent.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Form</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>Su&amp;mă :</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Plăteşte Că&amp;tre:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Adaugă o etichetă acestei adrese pentru a o trece în Lista de adrese</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;L Etichetă:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Alegeţi adresa din Listă</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Lipiţi adresa copiată in clipboard.</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Şterge destinatarul</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Tetcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Introduceţi o adresă Tetcoin (de exemplu: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Semnatura- Semneaza/verifica un mesaj</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>Semneaza Mesajul</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Introduceţi o adresă Tetcoin (de exemplu: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Alegeţi adresa din Listă</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Lipiţi adresa copiată in clipboard.</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Introduce mesajul pe care vrei sa il semnezi, aici.</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Copiaza semnatura curenta in clipboard-ul sistemului</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Tetcoin address</source> <translation>Semneaza mesajul pentru a dovedi ca detii acesta adresa Tetcoin</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Reseteaza toate spatiile mesajelor semnate.</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Şterge &amp;tot</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>Verifica mesajul</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Introduceţi o adresă Tetcoin (de exemplu: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Tetcoin address</source> <translation>Verifica mesajul pentru a fi sigur ca a fost semnat cu adresa Tetcoin specifica</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Reseteaza toate spatiile mesajelor semnate.</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Tetcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Introduceţi o adresă Tetcoin (de exemplu: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Click &quot;Semneaza msajul&quot; pentru a genera semnatura</translation> </message> <message> <location line="+3"/> <source>Enter Tetcoin signature</source> <translation>Introduce semnatura bitocin</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Adresa introdusa nu este valida</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Te rugam verifica adresa si introduce-o din nou</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>Adresa introdusa nu se refera la o cheie.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Blocarea portofelului a fost intrerupta</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>Cheia privata pentru adresa introdusa nu este valida.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Semnarea mesajului a esuat</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Mesaj Semnat!</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Aceasta semnatura nu a putut fi decodata</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Verifica semnatura si incearca din nou</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>Semnatura nu seamana!</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Verificarea mesajului a esuat</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Mesaj verificat</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The Litecoin Developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Deschis până la %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/neconfirmat</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 confirmări</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Stare</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Sursa</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Generat</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>De la</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Către</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>Adresa posedata</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>etichetă</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Credit</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>nu este acceptat</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Debit</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Comisionul tranzacţiei</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Suma netă</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Mesaj</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Comentarii</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID-ul tranzactiei</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Monedele tetcoin generate se pot cheltui dupa parcurgerea a 120 de blocuri. După ce a fost generat, s-a propagat în reţea, urmând să fie adăugat lanţului de blocuri. Dacă nu poate fi inclus in lanţ, starea sa va deveni &quot;neacceptat&quot; si nu va putea fi folosit la tranzacţii. Acest fenomen se întâmplă atunci cand un alt nod a generat un bloc la o diferenţa de câteva secunde.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Informatii pentru debug</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Tranzacţie</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>Intrari</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Sumă</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>Adevarat!</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>Fals!</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, nu s-a propagat încă</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>necunoscut</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Detaliile tranzacţiei</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Afişează detalii despre tranzacţie</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tipul</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Cantitate</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Deschis până la %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Neconectat (%1 confirmări)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Neconfirmat (%1 din %2 confirmări)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Confirmat (%1 confirmări)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Blocul nu a fost recepţionat de niciun alt nod şi e probabil că nu va fi acceptat.</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generat, dar neacceptat</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Recepţionat cu</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Primit de la:</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Trimis către</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Plată către un cont propriu</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Produs</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n/a)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Starea tranzacţiei. Treceţi cu mouse-ul peste acest câmp pentru afişarea numărului de confirmări.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Data şi ora la care a fost recepţionată tranzacţia.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Tipul tranzacţiei.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Adresa de destinaţie a tranzacţiei.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Suma extrasă sau adăugată la sold.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Toate</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Astăzi</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Săptămâna aceasta</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Luna aceasta</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Luna trecută</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Anul acesta</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Între...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Recepţionat cu...</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Trimis către</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Către propriul cont</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Produs</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Altele</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Introduceţi adresa sau eticheta pentru căutare</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Cantitatea produsă</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Copiază adresa</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copiază eticheta</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copiază sumă</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Editează eticheta</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Arata detaliile tranzactiei</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Exportă tranzacţiile</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Fişier text cu valori separate prin virgulă (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Confirmat</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tipul</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Etichetă</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Adresă</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Sumă</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Eroare în timpul exportului</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Fisierul %1 nu a putut fi accesat pentru scriere.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Interval:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>către</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Trimite Tetcoin</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>Date portofel (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Copia de rezerva a esuat</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>A apărut o eroare la încercarea de a salva datele din portofel intr-o noua locație.</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>Tetcoin version</source> <translation>versiunea Tetcoin</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Uz:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or tetcoind</source> <translation>Trimite comanda la -server sau tetcoind</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Listă de comenzi</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Ajutor pentru o comandă</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Setări:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: tetcoin.conf)</source> <translation>Specifica-ți configurația fisierului (in mod normal: tetcoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: tetcoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Specifica datele directorului</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Seteaza marimea cache a bazei de date in MB (initial: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 8877 or testnet: 18877)</source> <translation>Lista a conectiunile in &lt;port&gt; (initial: 8877 sau testnet: 18877)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Se menține la cele mai multe conexiuni &lt;n&gt; cu colegii (implicit: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Conecteaza-te la nod pentru a optine adresa peer, si deconecteaza-te</translation> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation>Specifica adresa ta publica</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Prag pentru deconectarea colegii funcționează corect (implicit: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Numărul de secunde pentru a păstra colegii funcționează corect la reconectare (implicit: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8899 or testnet: 18899)</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Se accepta command line si comenzi JSON-RPC</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Ruleaza în background ca un demon și accepta comenzi.</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Utilizeaza test de retea</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Accepta conexiuni de la straini (initial: 1 if no -proxy or -connect) </translation> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=tetcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Tetcoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Tetcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Seteaza marimea maxima a tranzactie mare/mica in bytes (initial:27000)</translation> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Tetcoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>Optiuni creare block</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Conecteaza-te doar la nod(urile) specifice</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Descopera propria ta adresa IP (intial: 1)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Copie de ieșire de depanare cu timestamp</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the Tetcoin Wiki for SSL setup instructions)</source> <translation>Optiuni SSl (vezi Tetcoin wiki pentru intructiunile de instalare)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Selecteaza versiunea socks-ului pe care vrei sa il folosesti (4-5, initial: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Trimite urmări / debug info la consola loc de debug.log fișier</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Trimite urmări / debug info la depanatorul</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Foloseste UPnP pentru a vedea porturile (initial: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Foloseste UPnP pentru a vedea porturile (initial: 1 cand listezi)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Username pentru conectiunile JSON-RPC</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Parola pentru conectiunile JSON-RPC</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Permiteti conectiunile JSON-RPC de la o adresa IP specifica.</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Trimite comenzi la nod, ruland pe ip-ul (initial: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Executa comanda cand cel mai bun block se schimba (%s in cmd se inlocuieste cu block hash)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Actualizeaza portofelul la ultimul format</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Setarea marimii cheii bezinului la &lt;n&gt;(initial 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Rescanare lanțul de bloc pentru tranzacțiile portofel lipsă</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Foloseste Open SSL(https) pentru coneciunile JSON-RPC</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Certificatul serverulu (initial: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Cheia privata a serverului ( initial: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Accepta cifruri (initial: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Acest mesaj de ajutor.</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Nu se poate lega %s cu acest calculator (retunare eroare legatura %d, %s) </translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Conectează prin proxy SOCKS</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Permite DNS-ului sa se uite dupa -addnode, -seednode si -connect</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Încarc adrese...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Eroare incarcand wallet.dat: Portofel corupt</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Tetcoin</source> <translation>Eroare incarcare wallet.dat: Portofelul are nevoie de o versiune Tetcoin mai noua</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart Tetcoin to complete</source> <translation>Portofelul trebuie rescris: restarteaza aplicatia tetcoin pentru a face asta.</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Eroare incarcand wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Adresa proxy invalida: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Retea specificata necunoscuta -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Necunoscut -socks proxy version requested: %i</translation> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Nu se poate rezolca -bind address: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Nu se poate rezolva -externalip address: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Suma invalida pentru -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Suma invalida</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Fonduri insuficiente</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Încarc indice bloc...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Add a node to connect to and attempt to keep the connection open details suggestions history </translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. Tetcoin is probably already running.</source> <translation>Imposibilitatea de a lega la% s pe acest computer. Tetcoin este, probabil, deja în execuție.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Taxa pe kb pentru a adauga tranzactii trimise</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Încarc portofel...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>Nu se poate face downgrade la portofel</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Nu se poate scrie adresa initiala</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Rescanez...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Încărcare terminată</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation>Pentru a folosii optiunea %s</translation> </message> <message> <location line="-74"/> <source>Error</source> <translation>Eroare</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
mit
hongjianqiang/Reading-Notes
精通JavaScript开发/第一章/1-34.js
297
(function() { 'use strict'; // ECMAScript 5 中的属性定义 var personalDetails = { name: 'Den Odell', email: 'den.odell@me.com' }; Object.defineProperty(personalDetails, 'age', { value: 25, writable: false, enumerable: true, configurable: true }); })();
mit
crestonbunch/botbox
common/game/synchronized.go
2890
package game import ( "errors" "golang.org/x/net/websocket" "log" "sync" "time" ) type SynchronizedGameClient struct { id string conn *websocket.Conn watchdog *Watchdog send chan ServerMessage receive chan ClientMessage err chan ClientError } func (c *SynchronizedGameClient) Id() string { return c.id } func (c *SynchronizedGameClient) Conn() *websocket.Conn { return c.conn } func (c *SynchronizedGameClient) Watchdog() *Watchdog { return c.watchdog } func (c *SynchronizedGameClient) Send() chan ServerMessage { return c.send } func (c *SynchronizedGameClient) Receive() chan ClientMessage { return c.receive } func (c *SynchronizedGameClient) Error() chan ClientError { return c.err } type SynchronizedStateManager struct { state GameState timeout time.Duration } func NewSynchronizedStateManager( game GameState, timeout time.Duration, ) *SynchronizedStateManager { return &SynchronizedStateManager{game, timeout} } func (m *SynchronizedStateManager) NewClient( id string, conn *websocket.Conn, ) GameClient { return &SynchronizedGameClient{ id, conn, NewWatchdog(m.timeout), make(chan ServerMessage), make(chan ClientMessage), make(chan ClientError), } } // Synchronizes gameplay so both players make moves at the same time. If a // player does not make a move in the allotted timeframe, then it its turn // is skipped and a timeout error is sent along the error channel. Game states // may punish a client by doing something if the action received is the empty // string. func (m *SynchronizedStateManager) Play( clients []GameClient, stateChan chan GameState, errChan chan error, ) *sync.WaitGroup { var wg sync.WaitGroup wg.Add(1) go func() { for !m.state.Finished() { // wait for actions from every player to commit them simultaneously actions := make([]string, len(clients)) // block for all players and queue up their actions for i, c := range clients { watchCh := c.Watchdog().Watch() log.Println("Sending message to client " + c.Id()) // note that if an error is returned, then the action will be the empty // string, so a state can kill a player if the empty string is received // to punish bad players select { case c.Send() <- ServerMessage{i, m.state.Actions(i), m.state.View(i)}: case <-watchCh: errChan <- errors.New("Client send timeout") } select { case msg := <-c.Receive(): actions[i] = msg.Action case err := <-c.Error(): errChan <- err case <-watchCh: errChan <- errors.New("Client receive timeout") } c.Watchdog().Stop() log.Println("Got action '" + actions[i] + "' from client " + c.Id()) } // commit actions simultaneously for i, a := range actions { m.state.Do(i, a) } stateChan <- m.state log.Println("Committed actions.") } wg.Done() }() return &wg }
mit
CaliburnFx/Caliburn
src/Caliburn/PresentationFramework/Actions/ActionAttribute.cs
1358
namespace Caliburn.PresentationFramework.Actions { using System; /// <summary> /// Designates an <see cref="IAction"/>. /// </summary> public class ActionAttribute : Attribute, IActionFactory { /// <summary> /// Gets or sets a value indicating whether to block interaction with the trigger during asynchronous execution. /// </summary> /// <value><c>true</c> if should block; otherwise, <c>false</c>.</value> public bool BlockInteraction { get; set; } /// <summary> /// Creates an <see cref="IAction"/> using the specified context. /// </summary> /// <param name="context">The context.</param> /// <returns>The <see cref="IAction"/>.</returns> public IAction Create(ActionCreationContext context) { var method = context.MethodFactory .CreateFrom(context.Method); var action = new SynchronousAction( context.ServiceLocator, method, context.MessageBinder, context.CreateFilterManager(method), BlockInteraction ); context.ConventionManager .ApplyActionCreationConventions(action, method); return action; } } }
mit
Centural/Centural.github.io
assets/js/mapsAPI.js
2311
--- --- function initialize() { $.getJSON( 'https://githubschool.github.io/open-enrollment-classes-introduction-to-github/createMap.topojson', function (data) { var mapSize = new google.maps.Size(256, 256), // original size, fallback for space invador images scaledSize = new google.maps.Size(20, 20), // size on map, fallback for space invador images anchor = new google.maps.Point(0, 32), // start point map = new google.maps.Map(document.getElementById('map'), { zoom: 2, minZoom: 2, center: new google.maps.LatLng(10, 15), mapTypeId: 'terrain', //disableDefaultUI: true, mapTypeControl: false, panControl: false, //scaleControl: false, scrollwheel: false, streetViewControl: false, //zoomControl: false, //draggable: false, styles: [ { featureType: 'administrative', elementType: 'geometry', stylers: [{visibility: 'off'}] }, { featureType: 'administrative.country', stylers: [{visibility: 'off'}] }, { featureType: 'water', elementType: 'labels', stylers: [{visibility: 'off'}] }, { featureType: 'administrative', elementType: 'labels', stylers: [{visibility: 'off'}] } ] }), markers = data.features.map(function (coords) { var coordinates = coords.geometry.coordinates, username = coords.properties.username; return new google.maps.Marker({ position: new google.maps.LatLng( coordinates[1], coordinates[0] ), map: map, title: username, icon: { url: 'https://github.com/' + username + '.png?size=20', size: mapSize, scaledSize: scaledSize, anchor: anchor } }); }); new MarkerClusterer(map, markers, { imagePath: '{{site.baseurl}}/images/cluster/m', averageCenter: true, minimumClusterSize: 42 }); } ); }
mit
tranquvis/SimpleSmsRemote
app/src/main/java/tranquvis/simplesmsremote/Adapters/ManageControlModulesListAdapter.java
2335
package tranquvis.simplesmsremote.Adapters; import android.content.Context; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.List; import tranquvis.simplesmsremote.CommandManagement.Modules.Module; import tranquvis.simplesmsremote.Data.AppDataManager; import tranquvis.simplesmsremote.R; /** * Created by Andi on 28.08.2016. */ public class ManageControlModulesListAdapter extends ArrayAdapter<Module> { private static final int LAYOUT_RES = R.layout.listview_item_manage_control_modules; public ManageControlModulesListAdapter(Context context, List<Module> data) { super(context, LAYOUT_RES, data); } @NonNull @Override public View getView(int position, View convertView, @NonNull ViewGroup parent) { if (convertView == null) { LayoutInflater inflater = (LayoutInflater) getContext(). getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(LAYOUT_RES, parent, false); } Module module = getItem(position); TextView titleTextView = (TextView) convertView.findViewById(R.id.textView_title); ImageView stateImageView = (ImageView) convertView. findViewById(R.id.imageView_state); ImageView moduleIconImageView = (ImageView) convertView.findViewById(R.id.imageView_type); if (module.getIconRes() != -1) { moduleIconImageView.setImageResource(module.getIconRes()); } if (module.getTitleRes() != -1) titleTextView.setText(module.getTitleRes()); else titleTextView.setText(module.getId()); //changeStateButton.setImageDrawable(); if (!module.isCompatible(getContext())) { stateImageView.setImageResource(R.drawable.ic_remove_circle_red_400_24dp); } else if (!AppDataManager.getDefault().isModuleEnabled(module)) { stateImageView.setImageResource(R.drawable.ic_add_circle_indigo_400_24dp); } else { stateImageView.setImageResource(R.drawable.ic_check_circle_green_400_24dp); } return convertView; } }
mit
IrmantasLiepis/logo-design
public/js/vendor/angular2-notifications/lib/notification.component.js
9640
"use strict"; const core_1 = require('@angular/core'); const platform_browser_1 = require('@angular/platform-browser'); const notifications_service_1 = require('./notifications.service'); class NotificationComponent { constructor(notificationService, domSanitizer) { this.notificationService = notificationService; this.domSanitizer = domSanitizer; this.progressWidth = 0; this.stopTime = false; this.count = 0; this.instance = () => { this.diff = (new Date().getTime() - this.start) - (this.count * this.speed); if (this.count++ === this.steps) { this.remove(); } else if (!this.stopTime) { if (this.showProgressBar) this.progressWidth += 100 / this.steps; this.timer = setTimeout(this.instance, (this.speed - this.diff)); } }; } ngOnInit() { if (this.animate) { this.item.state = this.animate; } if (this.item.override) { this.attachOverrides(); } if (this.timeOut !== 0) { this.startTimeOut(); } this.safeSvg = this.domSanitizer.bypassSecurityTrustHtml(this.item.icon); } startTimeOut() { this.steps = this.timeOut / 10; this.speed = this.timeOut / this.steps; this.start = new Date().getTime(); this.timer = setTimeout(this.instance, this.speed); } onEnter() { if (this.pauseOnHover) { this.stopTime = true; } } onLeave() { if (this.pauseOnHover) { this.stopTime = false; setTimeout(this.instance, (this.speed - this.diff)); } } setPosition() { return this.position !== 0 ? this.position * 90 : 0; } onClick($e) { this.item.click.emit($e); if (this.clickToClose) { this.remove(); } } attachOverrides() { Object.keys(this.item.override).forEach(a => { if (this.hasOwnProperty(a)) { this[a] = this.item.override[a]; } }); } ngOnDestroy() { clearTimeout(this.timer); } remove() { if (this.animate) { this.item.state = this.animate + 'Out'; setTimeout(() => this.notificationService.set(this.item, false), 310); } else { this.notificationService.set(this.item, false); } } } NotificationComponent.decorators = [ { type: core_1.Component, args: [{ selector: 'simple-notification', encapsulation: core_1.ViewEncapsulation.None, animations: [ core_1.trigger('enterLeave', [ core_1.state('fromRight', core_1.style({ opacity: 1, transform: 'translateX(0)' })), core_1.transition('* => fromRight', [ core_1.style({ opacity: 0, transform: 'translateX(5%)' }), core_1.animate('400ms ease-in-out') ]), core_1.state('fromRightOut', core_1.style({ opacity: 0, transform: 'translateX(-5%)' })), core_1.transition('fromRight => fromRightOut', [ core_1.style({ opacity: 1, transform: 'translateX(0)' }), core_1.animate('300ms ease-in-out') ]), core_1.state('fromLeft', core_1.style({ opacity: 1, transform: 'translateX(0)' })), core_1.transition('* => fromLeft', [ core_1.style({ opacity: 0, transform: 'translateX(-5%)' }), core_1.animate('400ms ease-in-out') ]), core_1.state('fromLeftOut', core_1.style({ opacity: 0, transform: 'translateX(5%)' })), core_1.transition('fromLeft => fromLeftOut', [ core_1.style({ opacity: 1, transform: 'translateX(0)' }), core_1.animate('300ms ease-in-out') ]), core_1.state('scale', core_1.style({ opacity: 1, transform: 'scale(1)' })), core_1.transition('* => scale', [ core_1.style({ opacity: 0, transform: 'scale(0)' }), core_1.animate('400ms ease-in-out') ]), core_1.state('scaleOut', core_1.style({ opacity: 0, transform: 'scale(0)' })), core_1.transition('scale => scaleOut', [ core_1.style({ opacity: 1, transform: 'scale(1)' }), core_1.animate('400ms ease-in-out') ]), core_1.state('rotate', core_1.style({ opacity: 1, transform: 'rotate(0deg)' })), core_1.transition('* => rotate', [ core_1.style({ opacity: 0, transform: 'rotate(5deg)' }), core_1.animate('400ms ease-in-out') ]), core_1.state('rotateOut', core_1.style({ opacity: 0, transform: 'rotate(-5deg)' })), core_1.transition('rotate => rotateOut', [ core_1.style({ opacity: 1, transform: 'rotate(0deg)' }), core_1.animate('400ms ease-in-out') ]) ]) ], template: ` <div class="simple-notification" [@enterLeave]="item.state" (click)="onClick($e)" [class]="theClass" [ngClass]="{ 'alert': item.type === 'alert', 'error': item.type === 'error', 'success': item.type === 'success', 'info': item.type === 'info', 'bare': item.type === 'bare', 'rtl-mode': rtl }" (mouseenter)="onEnter()" (mouseleave)="onLeave()"> <div *ngIf="!item.html"> <div class="sn-title">{{item.title}}</div> <div class="sn-content">{{item.content | max:maxLength}}</div> <div *ngIf="item.type !== 'bare'" [innerHTML]="safeSvg"></div> </div> <div *ngIf="item.html" [innerHTML]="item.html"></div> <div class="sn-progress-loader" *ngIf="showProgressBar"> <span [ngStyle]="{'width': progressWidth + '%'}"></span> </div> </div> `, styles: [` .simple-notification { width: 100%; padding: 10px 20px; box-sizing: border-box; position: relative; float: left; margin-bottom: 10px; color: #fff; cursor: pointer; transition: all 0.5s; } .simple-notification .sn-title { margin: 0; padding: 0 50px 0 0; line-height: 30px; font-size: 20px; } .simple-notification .sn-content { margin: 0; font-size: 16px; padding: 0 50px 0 0; line-height: 20px; } .simple-notification svg { position: absolute; box-sizing: border-box; top: 0; right: 0; width: 70px; height: 70px; padding: 10px; fill: #fff; } .simple-notification.rtl-mode { direction: rtl; } .simple-notification.rtl-mode .sn-content { padding: 0 0 0 50px; } .simple-notification.rtl-mode svg { left: 0; right: auto; } .simple-notification.error { background: #F44336; } .simple-notification.success { background: #8BC34A; } .simple-notification.alert { background: #ffdb5b; } .simple-notification.info { background: #03A9F4; } .simple-notification .sn-progress-loader { position: absolute; top: 0; left: 0; width: 100%; height: 5px; } .simple-notification .sn-progress-loader span { float: left; height: 100%; } .simple-notification.success .sn-progress-loader span { background: #689F38; } .simple-notification.error .sn-progress-loader span { background: #D32F2F; } .simple-notification.alert .sn-progress-loader span { background: #edc242; } .simple-notification.info .sn-progress-loader span { background: #0288D1; } .simple-notification.bare .sn-progress-loader span { background: #ccc; } `] },] }, ]; NotificationComponent.ctorParameters = [ { type: notifications_service_1.NotificationsService, }, { type: platform_browser_1.DomSanitizer, }, ]; NotificationComponent.propDecorators = { 'timeOut': [{ type: core_1.Input },], 'showProgressBar': [{ type: core_1.Input },], 'pauseOnHover': [{ type: core_1.Input },], 'clickToClose': [{ type: core_1.Input },], 'maxLength': [{ type: core_1.Input },], 'theClass': [{ type: core_1.Input },], 'rtl': [{ type: core_1.Input },], 'animate': [{ type: core_1.Input },], 'position': [{ type: core_1.Input },], 'item': [{ type: core_1.Input },], }; exports.NotificationComponent = NotificationComponent; //# sourceMappingURL=notification.component.js.map
mit
danielsan80/danilosanchi-net
src/Dan/UserBundle/DataFixtures/ORM/LoadGroupData.php
859
<?php namespace Dan\UserBundle\DataFixtures\ORM; use Doctrine\ORM\EntityManager; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use Dan\UserBundle\Entity\Group; class LoadGroupData extends AbstractFixture implements OrderedFixtureInterface { public function load(ObjectManager $manager) { $group = new Group('SuperAdmin'); $group->addRole('ROLE_SUPER_ADMIN'); $manager->persist($group); $this->addReference('superadmin', $group); $group = new Group('Admin'); $group->addRole('ROLE_ADMIN'); $manager->persist($group); $this->addReference('admin', $group); $manager->flush(); } public function getOrder() { return 1; } }
mit
jjcollinge/DroneSimulation
src/DroneSim/WebApp/wwwroot/lib/babylonjs/src/Culling/babylon.boundingSphere.ts
2228
module BABYLON { export class BoundingSphere { public center: Vector3; public radius: number; public centerWorld: Vector3; public radiusWorld: number; private _tempRadiusVector = Vector3.Zero(); constructor(public minimum: Vector3, public maximum: Vector3) { var distance = Vector3.Distance(minimum, maximum); this.center = Vector3.Lerp(minimum, maximum, 0.5); this.radius = distance * 0.5; this.centerWorld = Vector3.Zero(); this._update(Matrix.Identity()); } // Methods public _update(world: Matrix): void { Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld); Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector); this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius; } public isInFrustum(frustumPlanes: Plane[]): boolean { for (var i = 0; i < 6; i++) { if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld) return false; } return true; } public intersectsPoint(point: Vector3): boolean { var x = this.centerWorld.x - point.x; var y = this.centerWorld.y - point.y; var z = this.centerWorld.z - point.z; var distance = Math.sqrt((x * x) + (y * y) + (z * z)); if (Math.abs(this.radiusWorld - distance) < Epsilon) return false; return true; } // Statics public static Intersects(sphere0: BoundingSphere, sphere1: BoundingSphere): boolean { var x = sphere0.centerWorld.x - sphere1.centerWorld.x; var y = sphere0.centerWorld.y - sphere1.centerWorld.y; var z = sphere0.centerWorld.z - sphere1.centerWorld.z; var distance = Math.sqrt((x * x) + (y * y) + (z * z)); if (sphere0.radiusWorld + sphere1.radiusWorld < distance) return false; return true; } } }
mit
carlosedusousa/curso-java-fonts
trabalho4/src/oo/edu/empregado/TralhadorHora.java
1823
// (c)2014|carlosedusousa. package oo.edu.empregado; // TralhadorHora: empregado que é pago por hora e que recebe um adicional // por hora extra trabalhada. O retorno do método ganho desta classe é o // resultado da operação sobre os valores atribuídos aos atributos // desta classe da seguinte forma: salarioHora * horas. public class TralhadorHora extends Empregado { // Atributo da classe. public double salarioHora; public int horas; public int horasExtras; // Construtor da classe. public TralhadorHora(String primeiroNome, String ultimoNome, String cargo, double salarioHora, int horas, int horasExtras) { super(primeiroNome, ultimoNome, cargo); setHoras(horas); setSalarioHora(salarioHora); setHorasExtras(horasExtras); } public double getSalarioHora() { return salarioHora; } // Define o valor do salário. public void setSalarioHora(double salarioHora) { this.salarioHora = salarioHora; } // Retorna as horas trabalhadas. public int getHoras() { return horas; } // Atribui a quantidade de horas trabalhadas. public void setHoras(int horas) { this.horas = horas; } // Retorna as horas extras trabalhadas. public int getHorasExtras() { return horasExtras; } // Atribui a quantidade de horas trabalhadas. public void setHorasExtras(int horasExtras) { this.horasExtras = horasExtras; } // Método da classe para salário de Horista mais horas extras // (para exemplo será fixado em 50% do valor da hora normal trabalhada). public double calcularGanho() { return getSalarioHora() * getHoras() + getSalarioHora() * getHorasExtras() / 2; } // Método de impressão. public String toString() { return "Empregado: " + getPrimeiroNome() + " " + getUltimoNome() + "\nSalario: " + calcularGanho() + "\nCargo: " + super.getCargo(); } }
mit