answer
stringlengths 15
1.25M
|
|---|
#-- encoding: UTF-8
# OpenProject is a project management system.
# This program is free software; you can redistribute it and/or
# This program is free software; you can redistribute it and/or
# as published by the Free Software Foundation; either version 2
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
require File.expand_path('../../test_helper', __FILE__)
class EnabledModuleTest < ActiveSupport::TestCase
def <API key>
CustomField.delete_all
FactoryGirl.create(:type_standard)
project = Project.create!(:name => 'Project with wiki', :identifier => 'wikiproject')
assert_nil project.wiki
project.<API key> = ['wiki']
wiki = FactoryGirl.create :wiki, :project => project
project.reload
assert_not_nil project.wiki
assert_equal 'Wiki', project.wiki.start_page
end
def <API key>
project = FactoryGirl.create :project
wiki = FactoryGirl.create :wiki, :project => project
project.reload
assert_not_nil project.wiki
project.<API key> = []
project.reload
<API key> 'Wiki.count' do
project.<API key> = ['wiki']
end
assert_not_nil project.wiki
end
end
|
var expect = require('chai').expect,
sinon = require('sinon'),
EventEmitter = require('../src/EventEmitter');
describe('EventEmitter tests', function() {
var emitter,
foo,
bar;
beforeEach(function() {
emitter = new EventEmitter();
foo = sinon.spy();
bar = sinon.spy();
});
describe('.on', function() {
it('should throw error if foo is not a function', function() {
var fn = emitter.on.bind(null, 'abc', 'abc');
expect(fn).to.throw(TypeError);
});
it('should register event with emitter._events', function() {
emitter.on('data', foo);
expect(emitter._events.data[0]).to.equal(foo);
});
it('should be able to register multiple foos', function() {
emitter.on('data', foo);
emitter.on('data', bar);
expect(emitter._events.data[0]).to.equal(foo);
expect(emitter._events.data[1]).to.equal(bar);
});
it('should return itself', function() {
expect(emitter.on('data', foo)).to.equal(emitter);
});
it('emits newListener event with event name and listener args', function() {
var emitSpy = sinon.spy(emitter, 'emit');
emitter.on('foo', foo);
sinon.assert.calledOnce(emitSpy);
sinon.assert.calledWith(emitSpy, 'newListener', 'foo', foo);
});
});
describe('.emit', function() {
beforeEach(function() {
emitter.on('data', foo);
emitter.on('data', bar);
});
it('should trigger listeners bound to event', function() {
emitter.emit('data');
expect(foo.calledOnce).to.be.true;
expect(bar.calledOnce).to.be.true;
});
it('should trigger listeners in order', function() {
emitter.emit('data');
expect(foo.calledBefore(bar)).to.be.true;
});
it('should apply arguments to each listener', function() {
var arg1 = 1,
arg2 = '2',
arg3 = {};
emitter.emit('data', arg1, arg2, arg3);
sinon.assert.calledWithExactly(foo, arg1, arg2, arg3);
});
it('should bind "this" to the emitter in listener', function(done) {
var fn = function() {
expect(this).to.equal(emitter);
done();
};
emitter.on('data', fn);
emitter.emit('data');
});
it('should return true if listeners were fired', function() {
expect(emitter.emit('data')).to.be.true;
});
it('should return false if no listeners fired', function() {
expect(emitter.emit('adf')).to.be.false;
});
});
describe('.removeAllListeners', function() {
beforeEach(function() {
emitter.on('foo', foo);
emitter.on('foo', function() {});
emitter.on('bar', bar);
});
it('should remove all listeners if no parameter', function() {
emitter.removeAllListeners();
expect(emitter._events).to.be.empty;
});
it('should only remove listeners to specified event', function() {
emitter.removeAllListeners('foo');
expect(emitter._events.foo).to.be.undefined;
expect(emitter._events.bar).to.not.be.undefined;
});
it('should return the emitter', function() {
expect(emitter.removeAllListeners()).to.equal(emitter);
});
});
describe('.removeListener', function() {
var baz;
beforeEach(function() {
baz = sinon.spy();
emitter.on('foo', foo);
emitter.on('foo', baz);
emitter.on('bar', bar);
});
it('should remove only one listener for event', function() {
emitter.removeListener('foo', baz);
expect(emitter._events.foo.length).to.equal(1);
expect(emitter._events.foo[0]).to.equal(foo);
});
it('should throw error if listener is not a function', function() {
var fn = emitter.removeListener.bind(emitter, 'foo', 'foo');
expect(fn).to.throw(TypeError);
});
it('should return the emitter', function() {
expect(emitter.removeListener('foo', foo)).to.equal(emitter);
});
it('should be able to remove listener added by .once', function() {
var qux = sinon.spy();
emitter.once('bar', qux);
emitter.removeListener('bar', qux);
expect(emitter._events.bar.length).to.equal(1);
expect(emitter._events.bar[0]).to.equal(bar);
});
it('should emit removeListener event with event name and listener args', function() {
var emitSpy = sinon.spy(emitter, 'emit');
emitter.removeListener('foo', foo);
sinon.assert.calledOnce(emitSpy);
sinon.assert.calledWith(emitSpy, 'removeListener', 'foo', foo);
});
});
describe('.once', function() {
it('should throw error if listener is not a function', function() {
var fn = emitter.once.bind(null, 'abc', 'abc');
expect(fn).to.throw(TypeError);
});
it('should register a listener', function() {
emitter.once('foo', foo);
expect(emitter._events.foo.length).to.equal(1);
});
it('should run registered function', function() {
emitter.once('foo', foo);
emitter.emit('foo');
expect(foo.calledOnce).to.be.true;
});
it('should remove listener after .emit', function() {
emitter.once('foo', foo);
emitter.emit('foo');
expect(emitter._events.foo).to.be.empty;
});
it('should pass all parameters from listener', function() {
var arg1 = 1,
arg2 = '2',
arg3 = {};
emitter.once('foo', foo);
emitter.emit('foo', arg1, arg2, arg3);
sinon.assert.calledWithExactly(foo, arg1, arg2, arg3);
});
it('should return the emitter', function() {
expect(emitter.once('foo', foo)).to.equal(emitter);
});
it('emits newListener event with event name and listener args', function() {
var emitSpy = sinon.spy(emitter, 'emit');
emitter.once('foo', foo);
sinon.assert.calledOnce(emitSpy);
sinon.assert.calledWith(emitSpy, 'newListener', 'foo', foo);
});
});
describe('.listeners', function() {
beforeEach(function() {
emitter.on('foo', foo);
emitter.on('bar', bar);
});
it('should return an array of listeners for an event', function() {
expect(emitter.listeners('foo')).to.deep.equal([foo]);
});
it('should return an empty array for unregistered events', function() {
expect(emitter.listeners('abcd')).to.deep.equal([]);
});
});
describe('.addListener', function() {
it('should be alias to .on', function() {
expect(emitter.addListener).to.equal(emitter.on);
});
});
describe('.off', function() {
it('should alias to .removeListener', function() {
expect(emitter.off).to.equal(emitter.removeListener);
});
});
describe('EventEmitter.listenerCount', function() {
beforeEach(function() {
emitter.on('foo', foo);
emitter.on('foo', function() {});
emitter.on('bar', bar);
});
it('should return 0 for non emitters', function() {
expect(EventEmitter.listenerCount(1)).to.equal(0);
});
it('should return 0 for no listeners', function() {
expect(EventEmitter.listenerCount(emitter, 'baz')).to.equal(0);
});
it('should return number of listeners', function() {
expect(EventEmitter.listenerCount(emitter, 'foo')).to.equal(2);
});
});
});
|
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.<API key> = true
config.action_controller.perform_caching = false
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
# Don't care if the mailer can't send.
config.action_mailer.<API key> = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.<API key> = true
# Raises error for missing translations
# config.action_view.<API key> = true
config.logger = Logger.new(STDOUT)
end
|
#!/bin/bash
. 'functions.sh'
print "Building site............"
GIT=`which git`
# Clone repo and add symblink
if [ ! -d $ROOTFS/app/project/docroot ]
then
print "Downloading latest Drupal Core ..."
exec 'wget -O - http://ftp.drupal.org/files/projects/drupal-7.39.tar.gz | tar zxf -'
exec 'mv drupal-7.39 app/project/docroot'
exec 'ln -s project/docroot app/docroot'
print "Cloning git repo ..."
exec "$GIT clone git@bitbucket.org:kurobits/condo-profile.git app/project/docroot/profiles/condo"
DEFAULT_DIR="$ROOTFS/app/project/docroot/sites/default"
print "Adding config and files directory ..."
exec "mkdir -p $DEFAULT_DIR/files"
exec "chmod a+rw $DEFAULT_DIR/files"
exec "cp $DEFAULT_DIR/default.settings.php $DEFAULT_DIR/settings.php"
echo '' >> $DEFAULT_DIR/settings.php
echo '// read local settings' >> $DEFAULT_DIR/settings.php
echo 'if (file_exists(__DIR__ . "/local.settings.php")) {' >> $DEFAULT_DIR/settings.php
echo ' require(__DIR__ . "/local.settings.php");' >> $DEFAULT_DIR/settings.php
echo '}' >> $DEFAULT_DIR/settings.php
print "Copying local settings for site ..."
exec "cp $ROOTFS/local.settings.php $DEFAULT_DIR"
print ''
print '
print 'Levantar contenedores con ./d4d up y luego entrar a:'
print 'http://localhost:8000/install.php'
fi
# Add local settings and files directory
|
/**
* @constructor
* @extends {WebInspector.Object}
* @param {string} id
* @param {string} name
*/
WebInspector.ProfileType = function(id, name)
{
WebInspector.Object.call(this);
this._id = id;
this._name = name;
/** @type {!Array.<!WebInspector.ProfileHeader>} */
this._profiles = [];
/** @type {?WebInspector.ProfileHeader} */
this.<API key> = null;
this._nextProfileUid = 1;
window.addEventListener("unload", this._clearTempStorage.bind(this), false);
}
/**
* @enum {string}
*/
WebInspector.ProfileType.Events = {
AddProfileHeader: "add-profile-header",
ProfileComplete: "profile-complete",
RemoveProfileHeader: "<API key>",
ViewUpdated: "view-updated"
}
WebInspector.ProfileType.prototype = {
/**
* @return {boolean}
*/
hasTemporaryView: function()
{
return false;
},
/**
* @return {?string}
*/
fileExtension: function()
{
return null;
},
get statusBarItems()
{
return [];
},
get buttonTooltip()
{
return "";
},
get id()
{
return this._id;
},
get treeItemTitle()
{
return this._name;
},
get name()
{
return this._name;
},
/**
* @return {boolean}
*/
buttonClicked: function()
{
return false;
},
get description()
{
return "";
},
/**
* @return {boolean}
*/
isInstantProfile: function()
{
return false;
},
/**
* @return {boolean}
*/
isEnabled: function()
{
return true;
},
/**
* @return {!Array.<!WebInspector.ProfileHeader>}
*/
getProfiles: function()
{
/**
* @param {!WebInspector.ProfileHeader} profile
* @return {boolean}
* @this {WebInspector.ProfileType}
*/
function isFinished(profile)
{
return this.<API key> !== profile;
}
return this._profiles.filter(isFinished.bind(this));
},
/**
* @return {?Element}
*/
decorationElement: function()
{
return null;
},
/**
* @nosideeffects
* @param {number} uid
* @return {?WebInspector.ProfileHeader}
*/
getProfile: function(uid)
{
for (var i = 0; i < this._profiles.length; ++i) {
if (this._profiles[i].uid === uid)
return this._profiles[i];
}
return null;
},
/**
* @param {!File} file
*/
loadFromFile: function(file)
{
var name = file.name;
if (name.endsWith(this.fileExtension()))
name = name.substr(0, name.length - this.fileExtension().length);
var profile = this.<API key>(name);
profile.setFromFile();
this.<API key>(profile);
this.addProfile(profile);
profile.loadFromFile(file);
},
/**
* @param {string} title
* @return {!WebInspector.ProfileHeader}
*/
<API key>: function(title)
{
throw new Error("Needs implemented.");
},
/**
* @param {!WebInspector.ProfileHeader} profile
*/
addProfile: function(profile)
{
this._profiles.push(profile);
this.<API key>(WebInspector.ProfileType.Events.AddProfileHeader, profile);
},
/**
* @param {!WebInspector.ProfileHeader} profile
*/
removeProfile: function(profile)
{
var index = this._profiles.indexOf(profile);
if (index === -1)
return;
this._profiles.splice(index, 1);
this._disposeProfile(profile);
},
_clearTempStorage: function()
{
for (var i = 0; i < this._profiles.length; ++i)
this._profiles[i].removeTempFile();
},
/**
* @nosideeffects
* @return {?WebInspector.ProfileHeader}
*/
<API key>: function()
{
return this.<API key>;
},
/**
* @param {?WebInspector.ProfileHeader} profile
*/
<API key>: function(profile)
{
if (this.<API key>)
this.<API key>.target().profilingLock.release();
if (profile)
profile.target().profilingLock.acquire();
this.<API key> = profile;
},
<API key>: function()
{
},
_reset: function()
{
var profiles = this._profiles.slice(0);
for (var i = 0; i < profiles.length; ++i)
this._disposeProfile(profiles[i]);
this._profiles = [];
this._nextProfileUid = 1;
},
/**
* @param {!WebInspector.ProfileHeader} profile
*/
_disposeProfile: function(profile)
{
this.<API key>(WebInspector.ProfileType.Events.RemoveProfileHeader, profile);
profile.dispose();
if (this.<API key> === profile) {
this.<API key>();
this.<API key>(null);
}
},
__proto__: WebInspector.Object.prototype
}
/**
* @interface
*/
WebInspector.ProfileType.DataDisplayDelegate = function()
{
}
WebInspector.ProfileType.DataDisplayDelegate.prototype = {
/**
* @param {?WebInspector.ProfileHeader} profile
* @return {?WebInspector.View}
*/
showProfile: function(profile) { },
/**
* @param {!HeapProfilerAgent.<API key>} snapshotObjectId
* @param {string} perspectiveName
*/
showObject: function(snapshotObjectId, perspectiveName) { }
}
/**
* @constructor
* @extends {WebInspector.TargetAwareObject}
* @param {!WebInspector.Target} target
* @param {!WebInspector.ProfileType} profileType
* @param {string} title
*/
WebInspector.ProfileHeader = function(target, profileType, title)
{
WebInspector.TargetAwareObject.call(this, target);
this._profileType = profileType;
this.title = title;
this.uid = profileType._nextProfileUid++;
this._fromFile = false;
}
/**
* @constructor
* @param {?string} subtitle
* @param {boolean|undefined} wait
*/
WebInspector.ProfileHeader.StatusUpdate = function(subtitle, wait)
{
/** @type {?string} */
this.subtitle = subtitle;
/** @type {boolean|undefined} */
this.wait = wait;
}
WebInspector.ProfileHeader.Events = {
UpdateStatus: "UpdateStatus",
ProfileReceived: "ProfileReceived"
}
WebInspector.ProfileHeader.prototype = {
/**
* @return {!WebInspector.ProfileType}
*/
profileType: function()
{
return this._profileType;
},
/**
* @param {?string} subtitle
* @param {boolean=} wait
*/
updateStatus: function(subtitle, wait)
{
this.<API key>(WebInspector.ProfileHeader.Events.UpdateStatus, new WebInspector.ProfileHeader.StatusUpdate(subtitle, wait));
},
/**
* Must be implemented by subclasses.
* @param {!WebInspector.ProfileType.DataDisplayDelegate} dataDisplayDelegate
* @return {!WebInspector.<API key>}
*/
<API key>: function(dataDisplayDelegate)
{
throw new Error("Needs implemented.");
},
/**
* @param {!WebInspector.ProfileType.DataDisplayDelegate} dataDisplayDelegate
* @return {!WebInspector.View}
*/
createView: function(dataDisplayDelegate)
{
throw new Error("Not implemented.");
},
removeTempFile: function()
{
if (this._tempFile)
this._tempFile.remove();
},
dispose: function()
{
},
/**
* @param {!Function} callback
*/
load: function(callback)
{
},
/**
* @return {boolean}
*/
canSaveToFile: function()
{
return false;
},
saveToFile: function()
{
throw new Error("Needs implemented");
},
/**
* @param {!File} file
*/
loadFromFile: function(file)
{
throw new Error("Needs implemented");
},
/**
* @return {boolean}
*/
fromFile: function()
{
return this._fromFile;
},
setFromFile: function()
{
this._fromFile = true;
},
__proto__: WebInspector.TargetAwareObject.prototype
}
/**
* @constructor
* @implements {WebInspector.Searchable}
* @implements {WebInspector.ProfileType.DataDisplayDelegate}
* @extends {WebInspector.<API key>}
*/
WebInspector.ProfilesPanel = function()
{
WebInspector.<API key>.call(this, "profiles");
this.registerRequiredCSS("panelEnablerView.css");
this.registerRequiredCSS("heapProfiler.css");
this.registerRequiredCSS("profilesPanel.css");
this._target = /** @type {!WebInspector.Target} */ (WebInspector.targetManager.activeTarget());
this._target.profilingLock.addEventListener(WebInspector.Lock.Events.StateChanged, this.<API key>, this);
this._searchableView = new WebInspector.SearchableView(this);
var mainView = new WebInspector.VBox();
this._searchableView.show(mainView.element);
mainView.show(this.mainElement());
this.<API key> = new WebInspector.<API key>(this);
this.sidebarTree.appendChild(this.<API key>);
this.profileViews = document.createElement("div");
this.profileViews.id = "profile-views";
this.profileViews.classList.add("vbox");
this._searchableView.element.appendChild(this.profileViews);
var statusBarContainer = document.<API key>("div", "profiles-status-bar");
mainView.element.insertBefore(statusBarContainer, mainView.element.firstChild);
this._statusBarElement = statusBarContainer.createChild("div", "status-bar");
this.sidebarElement().classList.add("<API key>");
var <API key> = document.<API key>("div", "profiles-status-bar");
this.sidebarElement().insertBefore(<API key>, this.sidebarElement().firstChild);
this._statusBarButtons = <API key>.createChild("div", "status-bar");
this.recordButton = new WebInspector.StatusBarButton("", "<API key>");
this.recordButton.addEventListener("click", this.toggleRecordButton, this);
this._statusBarButtons.appendChild(this.recordButton.element);
this.clearResultsButton = new WebInspector.StatusBarButton(WebInspector.UIString("Clear all profiles."), "<API key>");
this.clearResultsButton.addEventListener("click", this._reset, this);
this._statusBarButtons.appendChild(this.clearResultsButton.element);
this.<API key> = this._statusBarElement.createChild("div");
this.<API key> = this._statusBarElement.createChild("div");
this._profileGroups = {};
this._launcherView = new WebInspector.<API key>(this);
this._launcherView.addEventListener(WebInspector.<API key>.EventTypes.ProfileTypeSelected, this.<API key>, this);
this._profileToView = [];
this.<API key> = {};
var types = WebInspector.ProfileTypeRegistry.instance.profileTypes();
for (var i = 0; i < types.length; i++)
this.<API key>(types[i]);
this._launcherView.<API key>();
this.<API key>.select();
this._showLauncherView();
this.<API key>();
this.element.addEventListener("contextmenu", this.<API key>.bind(this), true);
this._registerShortcuts();
this.<API key>();
WebInspector.settings.<API key>.addChangeListener(this.<API key>, this);
}
/**
* @constructor
*/
WebInspector.ProfileTypeRegistry = function() {
this._profileTypes = [];
this.cpuProfileType = new WebInspector.CPUProfileType();
this._addProfileType(this.cpuProfileType);
this.<API key> = new WebInspector.<API key>();
this._addProfileType(this.<API key>);
this.<API key> = new WebInspector.<API key>();
this._addProfileType(this.<API key>);
HeapProfilerAgent.enable();
if (Capabilities.isMainFrontend && WebInspector.experimentsSettings.canvasInspection.isEnabled()) {
this.canvasProfileType = new WebInspector.CanvasProfileType();
this._addProfileType(this.canvasProfileType);
}
}
WebInspector.ProfileTypeRegistry.prototype = {
/**
* @param {!WebInspector.ProfileType} profileType
*/
_addProfileType: function(profileType)
{
this._profileTypes.push(profileType);
},
/**
* @return {!Array.<!WebInspector.ProfileType>}
*/
profileTypes: function()
{
return this._profileTypes;
}
}
WebInspector.ProfilesPanel.prototype = {
/**
* @return {!WebInspector.SearchableView}
*/
searchableView: function()
{
return this._searchableView;
},
<API key>: function()
{
if (this.<API key>)
this.element.removeChild(this.<API key>);
this.<API key> = WebInspector.<API key>(this._loadFromFile.bind(this));
this.element.appendChild(this.<API key>);
},
<API key>: function(fileName)
{
var types = WebInspector.ProfileTypeRegistry.instance.profileTypes();
for (var i = 0; i < types.length; i++) {
var type = types[i];
var extension = type.fileExtension();
if (!extension)
continue;
if (fileName.endsWith(type.fileExtension()))
return type;
}
return null;
},
_registerShortcuts: function()
{
this.registerShortcuts(WebInspector.ShortcutsScreen.<API key>.StartStopRecording, this.toggleRecordButton.bind(this));
},
<API key>: function()
{
var intervalUs = WebInspector.settings.<API key>.get() ? 100 : 1000;
ProfilerAgent.setSamplingInterval(intervalUs, didChangeInterval);
function didChangeInterval(error)
{
if (error)
WebInspector.messageSink.addErrorMessage(error, true);
}
},
/**
* @param {!File} file
*/
_loadFromFile: function(file)
{
this.<API key>();
var profileType = this.<API key>(file.name);
if (!profileType) {
var extensions = [];
var types = WebInspector.ProfileTypeRegistry.instance.profileTypes();
for (var i = 0; i < types.length; i++) {
var extension = types[i].fileExtension();
if (!extension || extensions.indexOf(extension) !== -1)
continue;
extensions.push(extension);
}
WebInspector.messageSink.addMessage(WebInspector.UIString("Can't load file. Only files with extensions '%s' can be loaded.", extensions.join("', '")));
return;
}
if (!!profileType.<API key>()) {
WebInspector.messageSink.addMessage(WebInspector.UIString("Can't load profile while another profile is recording."));
return;
}
profileType.loadFromFile(file);
},
/**
* @return {boolean}
*/
toggleRecordButton: function()
{
if (!this.recordButton.enabled())
return true;
var type = this.<API key>;
var isProfiling = type.buttonClicked();
this._updateRecordButton(isProfiling);
if (isProfiling) {
this._launcherView.profileStarted();
if (type.hasTemporaryView())
this.showProfile(type.<API key>());
} else {
this._launcherView.profileFinished();
}
return true;
},
<API key>: function()
{
this._updateRecordButton(this.recordButton.toggled);
},
/**
* @param {boolean} toggled
*/
_updateRecordButton: function(toggled)
{
var enable = toggled || !this._target.profilingLock.isAcquired();
this.recordButton.setEnabled(enable);
this.recordButton.toggled = toggled;
if (enable)
this.recordButton.title = this.<API key> ? this.<API key>.buttonTooltip : "";
else
this.recordButton.title = WebInspector.UIString("Another profiler is already active");
if (this.<API key>)
this._launcherView.updateProfileType(this.<API key>, enable);
},
<API key>: function()
{
this._updateRecordButton(false);
this._launcherView.profileFinished();
},
/**
* @param {!WebInspector.Event} event
*/
<API key>: function(event)
{
this.<API key> = /** @type {!WebInspector.ProfileType} */ (event.data);
this.<API key>();
},
<API key>: function()
{
this._updateRecordButton(this.recordButton.toggled);
this.<API key>.removeChildren();
var statusBarItems = this.<API key>.statusBarItems;
if (statusBarItems) {
for (var i = 0; i < statusBarItems.length; ++i)
this.<API key>.appendChild(statusBarItems[i]);
}
},
_reset: function()
{
WebInspector.Panel.prototype.reset.call(this);
var types = WebInspector.ProfileTypeRegistry.instance.profileTypes();
for (var i = 0; i < types.length; i++)
types[i]._reset();
delete this.visibleView;
delete this.currentQuery;
this.searchCanceled();
this._profileGroups = {};
this._updateRecordButton(false);
this._launcherView.profileFinished();
this.sidebarTree.element.classList.remove("some-expandable");
this._launcherView.detach();
this.profileViews.removeChildren();
this.<API key>.removeChildren();
this.removeAllListeners();
this.recordButton.visible = true;
this.<API key>.classList.remove("hidden");
this.clearResultsButton.element.classList.remove("hidden");
this.<API key>.select();
this._showLauncherView();
},
_showLauncherView: function()
{
this.closeVisibleView();
this.<API key>.removeChildren();
this._launcherView.show(this.profileViews);
this.visibleView = this._launcherView;
},
<API key>: function()
{
HeapProfilerAgent.collectGarbage();
},
/**
* @param {!WebInspector.ProfileType} profileType
*/
<API key>: function(profileType)
{
this._launcherView.addProfileType(profileType);
var profileTypeSection = new WebInspector.<API key>(this, profileType);
this.<API key>[profileType.id] = profileTypeSection
this.sidebarTree.appendChild(profileTypeSection);
profileTypeSection.childrenListElement.addEventListener("contextmenu", this.<API key>.bind(this), true);
/**
* @param {!WebInspector.Event} event
* @this {WebInspector.ProfilesPanel}
*/
function onAddProfileHeader(event)
{
this._addProfileHeader(/** @type {!WebInspector.ProfileHeader} */ (event.data));
}
/**
* @param {!WebInspector.Event} event
* @this {WebInspector.ProfilesPanel}
*/
function <API key>(event)
{
this.<API key>(/** @type {!WebInspector.ProfileHeader} */ (event.data));
}
/**
* @param {!WebInspector.Event} event
* @this {WebInspector.ProfilesPanel}
*/
function profileComplete(event)
{
this.showProfile(/** @type {!WebInspector.ProfileHeader} */ (event.data));
}
profileType.addEventListener(WebInspector.ProfileType.Events.ViewUpdated, this.<API key>, this);
profileType.addEventListener(WebInspector.ProfileType.Events.AddProfileHeader, onAddProfileHeader, this);
profileType.addEventListener(WebInspector.ProfileType.Events.RemoveProfileHeader, <API key>, this);
profileType.addEventListener(WebInspector.ProfileType.Events.ProfileComplete, profileComplete, this);
var profiles = profileType.getProfiles();
for (var i = 0; i < profiles.length; i++)
this._addProfileHeader(profiles[i]);
},
/**
* @param {?Event} event
*/
<API key>: function(event)
{
var element = event.srcElement;
while (element && !element.treeElement && element !== this.element)
element = element.parentElement;
if (!element)
return;
if (element.treeElement && element.treeElement.<API key>) {
element.treeElement.<API key>(event, this);
return;
}
var contextMenu = new WebInspector.ContextMenu(event);
if (this.visibleView instanceof WebInspector.HeapSnapshotView) {
this.visibleView.populateContextMenu(contextMenu, event);
}
if (element !== this.element || event.srcElement === this.sidebarElement()) {
contextMenu.appendItem(WebInspector.UIString("Load\u2026"), this.<API key>.click.bind(this.<API key>));
}
contextMenu.show();
},
<API key>: function()
{
this.<API key>.click();
},
/**
* @param {!WebInspector.ProfileHeader} profile
*/
_addProfileHeader: function(profile)
{
var profileType = profile.profileType();
var typeId = profileType.id;
this.<API key>[typeId].addProfileHeader(profile);
if (!this.visibleView || this.visibleView === this._launcherView)
this.showProfile(profile);
},
/**
* @param {!WebInspector.ProfileHeader} profile
*/
<API key>: function(profile)
{
if (profile.profileType().<API key> === profile)
this.<API key>();
var i = this.<API key>(profile);
if (i !== -1)
this._profileToView.splice(i, 1);
var profileType = profile.profileType();
var typeId = profileType.id;
var sectionIsEmpty = this.<API key>[typeId].removeProfileHeader(profile);
// No other item will be selected if there aren't any other profiles, so
// make sure that view gets cleared when the last profile is removed.
if (sectionIsEmpty) {
this.<API key>.select();
this._showLauncherView();
}
},
/**
* @param {?WebInspector.ProfileHeader} profile
* @return {?WebInspector.View}
*/
showProfile: function(profile)
{
if (!profile || (profile.profileType().<API key>() === profile) && !profile.profileType().hasTemporaryView())
return null;
var view = this._viewForProfile(profile);
if (view === this.visibleView)
return view;
this.closeVisibleView();
view.show(this.profileViews);
this.visibleView = view;
var profileTypeSection = this.<API key>[profile.profileType().id];
var sidebarElement = profileTypeSection.<API key>(profile);
sidebarElement.revealAndSelect();
this.<API key>.removeChildren();
var statusBarItems = view.statusBarItems;
if (statusBarItems)
for (var i = 0; i < statusBarItems.length; ++i)
this.<API key>.appendChild(statusBarItems[i]);
return view;
},
/**
* @param {!HeapProfilerAgent.<API key>} snapshotObjectId
* @param {string} perspectiveName
*/
showObject: function(snapshotObjectId, perspectiveName)
{
var heapProfiles = WebInspector.ProfileTypeRegistry.instance.<API key>.getProfiles();
for (var i = 0; i < heapProfiles.length; i++) {
var profile = heapProfiles[i];
// FIXME: allow to choose snapshot if there are several options.
if (profile.maxJSObjectId >= snapshotObjectId) {
this.showProfile(profile);
var view = this._viewForProfile(profile);
view.highlightLiveObject(perspectiveName, snapshotObjectId);
break;
}
}
},
/**
* @param {!WebInspector.ProfileHeader} profile
* @return {!WebInspector.View}
*/
_viewForProfile: function(profile)
{
var index = this.<API key>(profile);
if (index !== -1)
return this._profileToView[index].view;
var view = profile.createView(this);
view.element.classList.add("profile-view");
this._profileToView.push({ profile: profile, view: view});
return view;
},
/**
* @param {!WebInspector.ProfileHeader} profile
* @return {number}
*/
<API key>: function(profile)
{
for (var i = 0; i < this._profileToView.length; i++) {
if (this._profileToView[i].profile === profile)
return i;
}
return -1;
},
closeVisibleView: function()
{
if (this.visibleView)
this.visibleView.detach();
delete this.visibleView;
},
/**
* @param {string} query
* @param {boolean} shouldJump
* @param {boolean=} jumpBackwards
*/
performSearch: function(query, shouldJump, jumpBackwards)
{
this.searchCanceled();
var visibleView = this.visibleView;
if (!visibleView)
return;
/**
* @this {WebInspector.ProfilesPanel}
*/
function finishedCallback(view, searchMatches)
{
if (!searchMatches)
return;
this._searchableView.<API key>(searchMatches);
this._searchResultsView = view;
if (shouldJump) {
if (jumpBackwards)
view.<API key>();
else
view.<API key>();
this._searchableView.<API key>(view.<API key>());
}
}
visibleView.currentQuery = query;
visibleView.performSearch(query, finishedCallback.bind(this));
},
<API key>: function()
{
if (!this._searchResultsView)
return;
if (this._searchResultsView !== this.visibleView)
return;
this._searchResultsView.<API key>();
this._searchableView.<API key>(this._searchResultsView.<API key>());
},
<API key>: function()
{
if (!this._searchResultsView)
return;
if (this._searchResultsView !== this.visibleView)
return;
this._searchResultsView.<API key>();
this._searchableView.<API key>(this._searchResultsView.<API key>());
},
searchCanceled: function()
{
if (this._searchResultsView) {
if (this._searchResultsView.searchCanceled)
this._searchResultsView.searchCanceled();
this._searchResultsView.currentQuery = null;
this._searchResultsView = null;
}
this._searchableView.<API key>(0);
},
/**
* @param {!Event} event
* @param {!WebInspector.ContextMenu} contextMenu
* @param {!Object} target
*/
<API key>: function(event, contextMenu, target)
{
if (!(target instanceof WebInspector.RemoteObject))
return;
if (WebInspector.inspectorView.currentPanel() !== this)
return;
var object = /** @type {!WebInspector.RemoteObject} */ (target);
var objectId = object.objectId;
if (!objectId)
return;
var heapProfiles = WebInspector.ProfileTypeRegistry.instance.<API key>.getProfiles();
if (!heapProfiles.length)
return;
/**
* @this {WebInspector.ProfilesPanel}
*/
function revealInView(viewName)
{
HeapProfilerAgent.getHeapObjectId(objectId, <API key>.bind(this, viewName));
}
/**
* @this {WebInspector.ProfilesPanel}
*/
function <API key>(viewName, error, result)
{
if (WebInspector.inspectorView.currentPanel() !== this)
return;
if (!error)
this.showObject(result, viewName);
}
if (WebInspector.settings.<API key>.get())
contextMenu.appendItem(WebInspector.UIString(WebInspector.<API key>() ? "Reveal in Dominators view" : "Reveal in Dominators View"), revealInView.bind(this, "Dominators"));
contextMenu.appendItem(WebInspector.UIString(WebInspector.<API key>() ? "Reveal in Summary view" : "Reveal in Summary View"), revealInView.bind(this, "Summary"));
},
__proto__: WebInspector.<API key>.prototype
}
/**
* @constructor
* @extends {WebInspector.<API key>}
* @param {!WebInspector.ProfileType.DataDisplayDelegate} dataDisplayDelegate
* @param {!WebInspector.ProfileType} profileType
*/
WebInspector.<API key> = function(dataDisplayDelegate, profileType)
{
WebInspector.<API key>.call(this, profileType.treeItemTitle, null, true);
this.<API key> = dataDisplayDelegate;
this.<API key> = [];
this._profileGroups = {};
this.hidden = true;
}
/**
* @constructor
*/
WebInspector.<API key>.ProfileGroup = function()
{
this.<API key> = [];
this.sidebarTreeElement = null;
}
WebInspector.<API key>.prototype = {
/**
* @param {!WebInspector.ProfileHeader} profile
*/
addProfileHeader: function(profile)
{
this.hidden = false;
var profileType = profile.profileType();
var sidebarParent = this;
var profileTreeElement = profile.<API key>(this.<API key>);
this.<API key>.push(profileTreeElement);
if (!profile.fromFile() && profileType.<API key>() !== profile) {
var profileTitle = profile.title;
var group = this._profileGroups[profileTitle];
if (!group) {
group = new WebInspector.<API key>.ProfileGroup();
this._profileGroups[profileTitle] = group;
}
group.<API key>.push(profileTreeElement);
var groupSize = group.<API key>.length;
if (groupSize === 2) {
// Make a group TreeElement now that there are 2 profiles.
group.sidebarTreeElement = new WebInspector.<API key>(this.<API key>, profile.title);
var <API key> = group.<API key>[0];
// Insert at the same index for the first profile of the group.
var index = this.children.indexOf(<API key>);
this.insertChild(group.sidebarTreeElement, index);
// Move the first profile to the group.
var selected = <API key>.selected;
this.removeChild(<API key>);
group.sidebarTreeElement.appendChild(<API key>);
if (selected)
<API key>.revealAndSelect();
<API key>.small = true;
<API key>.mainTitle = WebInspector.UIString("Run %d", 1);
this.treeOutline.element.classList.add("some-expandable");
}
if (groupSize >= 2) {
sidebarParent = group.sidebarTreeElement;
profileTreeElement.small = true;
profileTreeElement.mainTitle = WebInspector.UIString("Run %d", groupSize);
}
}
sidebarParent.appendChild(profileTreeElement);
},
/**
* @param {!WebInspector.ProfileHeader} profile
* @return {boolean}
*/
removeProfileHeader: function(profile)
{
var index = this.<API key>(profile);
if (index === -1)
return false;
var profileTreeElement = this.<API key>[index];
this.<API key>.splice(index, 1);
var sidebarParent = this;
var group = this._profileGroups[profile.title];
if (group) {
var groupElements = group.<API key>;
groupElements.splice(groupElements.indexOf(profileTreeElement), 1);
if (groupElements.length === 1) {
// Move the last profile out of its group and remove the group.
var pos = sidebarParent.children.indexOf(group.sidebarTreeElement);
this.insertChild(groupElements[0], pos);
groupElements[0].small = false;
groupElements[0].mainTitle = group.sidebarTreeElement.title;
this.removeChild(group.sidebarTreeElement);
}
if (groupElements.length !== 0)
sidebarParent = group.sidebarTreeElement;
}
sidebarParent.removeChild(profileTreeElement);
profileTreeElement.dispose();
if (this.children.length)
return false;
this.hidden = true;
return true;
},
/**
* @param {!WebInspector.ProfileHeader} profile
* @return {?WebInspector.<API key>}
*/
<API key>: function(profile)
{
var index = this.<API key>(profile);
return index === -1 ? null : this.<API key>[index];
},
/**
* @param {!WebInspector.ProfileHeader} profile
* @return {number}
*/
<API key>: function(profile)
{
var elements = this.<API key>;
for (var i = 0; i < elements.length; i++) {
if (elements[i].profile === profile)
return i;
}
return -1;
},
__proto__: WebInspector.<API key>.prototype
}
/**
* @constructor
* @implements {WebInspector.ContextMenu.Provider}
*/
WebInspector.ProfilesPanel.ContextMenuProvider = function()
{
}
WebInspector.ProfilesPanel.ContextMenuProvider.prototype = {
/**
* @param {!Event} event
* @param {!WebInspector.ContextMenu} contextMenu
* @param {!Object} target
*/
<API key>: function(event, contextMenu, target)
{
WebInspector.inspectorView.panel("profiles").<API key>(event, contextMenu, target);
}
}
/**
* @constructor
* @extends {WebInspector.SidebarTreeElement}
* @param {!WebInspector.ProfileType.DataDisplayDelegate} dataDisplayDelegate
* @param {!WebInspector.ProfileHeader} profile
* @param {string} className
*/
WebInspector.<API key> = function(dataDisplayDelegate, profile, className)
{
this.<API key> = dataDisplayDelegate;
this.profile = profile;
WebInspector.SidebarTreeElement.call(this, className, profile.title, "", profile, false);
this.refreshTitles();
profile.addEventListener(WebInspector.ProfileHeader.Events.UpdateStatus, this._updateStatus, this);
if (profile.canSaveToFile())
this._createSaveLink();
else
profile.addEventListener(WebInspector.ProfileHeader.Events.ProfileReceived, this._onProfileReceived, this);
}
WebInspector.<API key>.prototype = {
_createSaveLink: function()
{
this._saveLinkElement = this.titleContainer.createChild("span", "save-link");
this._saveLinkElement.textContent = WebInspector.UIString("Save");
this._saveLinkElement.addEventListener("click", this._saveProfile.bind(this), false);
},
_onProfileReceived: function(event)
{
this._createSaveLink();
},
/**
* @param {!WebInspector.Event} event
*/
_updateStatus: function(event)
{
var statusUpdate = event.data;
if (statusUpdate.subtitle !== null)
this.subtitle = statusUpdate.subtitle;
if (typeof statusUpdate.wait === "boolean")
this.wait = statusUpdate.wait;
this.refreshTitles();
},
dispose: function()
{
this.profile.removeEventListener(WebInspector.ProfileHeader.Events.UpdateStatus, this._updateStatus, this);
this.profile.removeEventListener(WebInspector.ProfileHeader.Events.ProfileReceived, this._onProfileReceived, this);
},
onselect: function()
{
this.<API key>.showProfile(this.profile);
},
/**
* @return {boolean}
*/
ondelete: function()
{
this.profile.profileType().removeProfile(this.profile);
return true;
},
/**
* @param {!Event} event
* @param {!WebInspector.ProfilesPanel} panel
*/
<API key>: function(event, panel)
{
var profile = this.profile;
var contextMenu = new WebInspector.ContextMenu(event);
// FIXME: use context menu provider
contextMenu.appendItem(WebInspector.UIString("Load\u2026"), panel.<API key>.click.bind(panel.<API key>));
if (profile.canSaveToFile())
contextMenu.appendItem(WebInspector.UIString("Save\u2026"), profile.saveToFile.bind(profile));
contextMenu.appendItem(WebInspector.UIString("Delete"), this.ondelete.bind(this));
contextMenu.show();
},
_saveProfile: function(event)
{
this.profile.saveToFile();
},
__proto__: WebInspector.SidebarTreeElement.prototype
}
/**
* @constructor
* @extends {WebInspector.SidebarTreeElement}
* @param {!WebInspector.ProfileType.DataDisplayDelegate} dataDisplayDelegate
* @param {string} title
* @param {string=} subtitle
*/
WebInspector.<API key> = function(dataDisplayDelegate, title, subtitle)
{
WebInspector.SidebarTreeElement.call(this, "<API key>", title, subtitle, null, true);
this.<API key> = dataDisplayDelegate;
}
WebInspector.<API key>.prototype = {
onselect: function()
{
if (this.children.length > 0)
this.<API key>.showProfile(this.children[this.children.length - 1].profile);
},
__proto__: WebInspector.SidebarTreeElement.prototype
}
/**
* @constructor
* @extends {WebInspector.SidebarTreeElement}
* @param {!WebInspector.ProfilesPanel} panel
*/
WebInspector.<API key> = function(panel)
{
this._panel = panel;
this.small = false;
WebInspector.SidebarTreeElement.call(this, "<API key>", WebInspector.UIString("Profiles"), "", null, false);
}
WebInspector.<API key>.prototype = {
onselect: function()
{
this._panel._showLauncherView();
},
get selectable()
{
return true;
},
__proto__: WebInspector.SidebarTreeElement.prototype
}
importScript("../sdk/CPUProfileModel.js");
importScript("CPUProfileDataGrid.js");
importScript("<API key>.js");
importScript("<API key>.js");
importScript("<API key>.js");
importScript("CPUProfileView.js");
importScript("HeapSnapshotCommon.js");
importScript("HeapSnapshotProxy.js");
importScript("<API key>.js");
importScript("<API key>.js");
importScript("HeapSnapshotView.js");
importScript("ProfileLauncherView.js");
importScript("CanvasProfileView.js");
importScript("<API key>.js");
WebInspector.ProfileTypeRegistry.instance = new WebInspector.ProfileTypeRegistry();
|
// Darken Region
// LAX_DarkenRegion.js
// v0.02
/*:
* @plugindesc v0.02 Use regions to black out areas.
* @author LuciusAxelrod
*
*
* @help
* Place regions on the map in the editor, then either add them to the default
* list or add them to the dark region list using the add command listed below.
* Note: Tiles without a region are in region 0. Adding region 0 to the dark
* region list will black out every tile
*
* Plugin Commands:
* DarkenRegion add [region list] # Adds the listed regions to the dark
* region list. The list is space
* separated. For example:
* DarkenRegion add 1 3 5 78
* DarkenRegion remove [region list] # Removes the listed regions from the
* dark region list. The list is space
* separated. For example:
* DarkenRegion remove 4 7 200 2
* DarkenRegion toggle [region list] # Toggle on/off each of the listed
* regions. For example:
* DarkenRegion toggle 1 5 7 112 250
* DarkenRegion clear # Clears the dark region list.
*/
// Parameter Variables
(function() {
var <API key> = Game_Interpreter.prototype.pluginCommand;
Game_Interpreter.prototype.pluginCommand = function(command, args) {
<API key>.call(this, command, args);
if (command === 'DarkenRegion') {
if(args[0] === 'add') {
for(var i = 1; i < args.length; i++) {
$gameSystem.addToDarkList(args[i]);
}
} else if(args[0] === 'remove') {
for(var i = 1; i < args.length; i++) {
$gameSystem.removeFromDarkList(args[i]);
}
} else if(args[0] === 'toggle') {
for(var i = 1; i < args.length; i++) {
if($gameSystem.isDarkRegion(args[i])) {
$gameSystem.removeFromDarkList(args[i]);
} else {
$gameSystem.addToDarkList(args[i]);
}
}
} else if(args[0] === 'clear') {
$gameSystem.clearDarkList();
}
}
};
Game_System.prototype.isDarkRegion = function(regionId) {
if(this._darkList) {
return !!this._darkList[regionId];
}
}
Game_System.prototype.addToDarkList = function(regionId) {
if(!this._darkList) {
this.clearDarkList();
}
this._darkList[Number(regionId)] = true;
}
Game_System.prototype.removeFromDarkList = function(regionId) {
if(this._darkList) {
this._darkList[Number(regionId)] = false;
}
}
Game_System.prototype.clearDarkList = function() {
this._darkList = [];
}
Tilemap.prototype._paintTiles = function(startX, startY, x, y) {
var tableEdgeVirtualId = 10000;
var darkRegionVirtualId = 10000;
var mx = startX + x;
var my = startY + y;
var dx = (mx * this._tileWidth).mod(this._layerWidth);
var dy = (my * this._tileHeight).mod(this._layerHeight);
var lx = dx / this._tileWidth;
var ly = dy / this._tileHeight;
var tileId0 = this._readMapData(mx, my, 0);
var tileId1 = this._readMapData(mx, my, 1);
var tileId2 = this._readMapData(mx, my, 2);
var tileId3 = this._readMapData(mx, my, 3);
var tileId5 = this._readMapData(mx, my, 5);
var shadowBits = this._readMapData(mx, my, 4);
var upperTileId1 = this._readMapData(mx, my - 1, 1);
var lowerTiles = [];
var upperTiles = [];
if (this._isHigherTile(tileId0)) {
upperTiles.push(tileId0);
} else {
lowerTiles.push(tileId0);
}
if (this._isHigherTile(tileId1)) {
upperTiles.push(tileId1);
} else {
lowerTiles.push(tileId1);
}
lowerTiles.push(-shadowBits);
if (this._isTableTile(upperTileId1) && !this._isTableTile(tileId1)) {
if (!Tilemap.isShadowingTile(tileId0)) {
lowerTiles.push(tableEdgeVirtualId + upperTileId1);
}
}
if (this._isOverpassPosition(mx, my)) {
upperTiles.push(tileId2);
upperTiles.push(tileId3);
} else {
if (this._isHigherTile(tileId2)) {
upperTiles.push(tileId2);
} else {
lowerTiles.push(tileId2);
}
if (this._isHigherTile(tileId3)) {
upperTiles.push(tileId3);
} else {
lowerTiles.push(tileId3);
}
if($gameSystem.isDarkRegion(tileId5)){
upperTiles.push(darkRegionVirtualId + tileId5);
}
}
var lastLowerTiles = this._readLastTiles(0, lx, ly);
if (!lowerTiles.equals(lastLowerTiles) ||
(Tilemap.isTileA1(tileId0) && this._frameUpdated)) {
this._lowerBitmap.clearRect(dx, dy, this._tileWidth, this._tileHeight);
for (var i = 0; i < lowerTiles.length; i++) {
var lowerTileId = lowerTiles[i];
if (lowerTileId < 0) {
this._drawShadow(this._lowerBitmap, shadowBits, dx, dy);
} else if (lowerTileId >= tableEdgeVirtualId) {
this._drawTableEdge(this._lowerBitmap, upperTileId1, dx, dy);
} else {
this._drawTile(this._lowerBitmap, lowerTileId, dx, dy);
}
}
this._writeLastTiles(0, lx, ly, lowerTiles);
}
var lastUpperTiles = this._readLastTiles(1, lx, ly);
if (!upperTiles.equals(lastUpperTiles)) {
this._upperBitmap.clearRect(dx, dy, this._tileWidth, this._tileHeight);
for (var j = 0; j < upperTiles.length; j++) {
if(upperTiles[j] >= darkRegionVirtualId) {
this._drawDarkness(this._upperBitmap, dx, dy);
} else {
this._drawTile(this._upperBitmap, upperTiles[j], dx, dy);
}
}
this._writeLastTiles(1, lx, ly, upperTiles);
}
};
Tilemap.prototype._drawDarkness = function(bitmap, dx, dy) {
var w = this._tileWidth;
var h = this._tileHeight;
var color = 'rgba(0,0,0,1)';
bitmap.fillRect(dx, dy, w, h, color);
};
})();
|
#include "minunit.h"
#include <lcthw/darray_algos.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>
static inline int intcmp(int **a, int **b) {
return **a - **b;
}
static inline int sintcmp(int *a, int *b) {
return *a - *b;
}
int make_random(DArray *array, size_t n) {
srand(time(NULL));
size_t i = 0;
for(i = 0; i < n; i++) {
int *random = DArray_new(array);
*random = rand();
check(DArray_push(array, random) == 0, "Inserting random values failed.");
}
return 0;
error:
return -1;
}
int is_sorted(DArray *array, DArray_compare cmp) {
int i = 0;
for(i = 0; i < DArray_count(array) - 1; i++) {
if(cmp(DArray_get(array, i), DArray_get(array, i+1)) > 0) {
return 0;
}
}
return 1;
}
char *run_sort_test(int (*func)(DArray *, DArray_compare), const char *name) {
DArray *nums = DArray_create(sizeof(int *), 20);
int rc = make_random(nums, 20);
mu_assert(rc == 0, "Randomization failed.");
mu_assert(!is_sorted(nums, (DArray_compare)sintcmp), "Numbers should start not sorted.");
debug("--- Testing %s sorting algorithm", name);
rc = func(nums, (DArray_compare)intcmp);
mu_assert(rc == 0, "Sort failed.");
mu_assert(is_sorted(nums, (DArray_compare)sintcmp), "Sort didn't sort properly.");
<API key>(nums);
return NULL;
}
char *test_qsort() {
return run_sort_test(DArray_qsort, "qsort");
}
char *test_heapsort() {
return run_sort_test(DArray_heapsort, "heapsort");
}
char *test_mergesort() {
return run_sort_test(DArray_mergesort, "mergesort");
}
char *speed_sort_test(int (*func)(DArray *, DArray_compare), const char *name) {
size_t N = 10000;
debug("--- Testing the speed of %s", name);
DArray *source = DArray_create(sizeof(void *), N+1);
clock_t fastest = LONG_MAX;
int rc = make_random(source, N);
mu_assert(rc == 0, "Randomizing the source DArray failed.");
int i = 0;
for(i = 0; i < 25; i++) {
DArray *test = DArray_create(sizeof(int *), N+1);
rc = DArray_copy(source, test);
mu_assert(rc == 0, "Copy failed.");
clock_t elapsed = -clock();
rc = func(test, (DArray_compare)intcmp);
elapsed += clock();
mu_assert(rc == 0, "Sort failed.");
mu_assert(is_sorted(test, (DArray_compare)sintcmp), "Sort didn't sort properly.");
if(elapsed < fastest) fastest = elapsed;
DArray_destroy(test);
}
debug("Fastest time for sort: %s, size %zu: %f", name, N, ((float)fastest)/CLOCKS_PER_SEC);
<API key>(source);
return NULL;
}
char *test_speed_qsort() {
return speed_sort_test(DArray_qsort, "quicksort");
}
char *<API key>() {
return speed_sort_test(DArray_mergesort, "mergesort");
}
char *test_speed_heapsort() {
return speed_sort_test(DArray_heapsort, "heapsort");
}
char *test_cmp() {
DArray *fake = DArray_create(sizeof(int), 10);
int *num1 = DArray_new(fake);
int *num2 = DArray_new(fake);
*num1 = 100;
*num2 = 20;
mu_assert(sintcmp(num1, num2) > 0, "Comparison fails on 100, 20.");
*num1 = 50;
*num2 = 50;
mu_assert(sintcmp(num1, num2) == 0, "Comparison fails on 50, 50.");
*num1 = 30;
*num2 = 60;
mu_assert(sintcmp(num1, num2) < 0, "Comparison fails on 30, 60.");
<API key>(fake);
return NULL;
}
char *all_tests() {
mu_suite_start();
mu_run_test(test_cmp);
mu_run_test(test_qsort);
mu_run_test(test_heapsort);
mu_run_test(test_mergesort);
mu_run_test(test_speed_qsort);
mu_run_test(<API key>);
mu_run_test(test_speed_heapsort);
return NULL;
}
RUN_TESTS(all_tests);
|
<!DOCTYPE html>
<html>
<h1>Sensor Data</h1>
</center>
<table>
<tr>
<td>Temperature</td>
<td>
<input id="temperature" type="text" value="">
</td>
</tr>
<tr>
<td>Precipitation</td>
<td>
<input id="precipitation" type="text" value="">
</td>
</tr>
<tr>
<td>Humidity</td>
<td>
<input id="humidity" type="text" value="">
</td>
</tr>
<tr>
<td>Wind</td>
<td>
<input id="wind" type="text" value="">
</td>
</tr>
<tr>
<td></td>
<td>
<button id="save" onclick="saveWeather()">Save</button>
<button id="clear" onclick="clearForm()">Clear</button>
<button id="read" onclick="readWeather()">Read</button>
</td>
</tr>
</table>
</center>
<script>
var saveWeather = function(){
};
var readWeather = function(){
};
var clearForm = function(){
};
</script>
</html>
|
"use strict";
(function() {
function get_promise(endpoint) {
return function($http) {
return $http.get(endpoint);
};
}
angular.module('pagerbot-admin', ['ngRoute', 'ngTable', 'angular-loading-bar'])
.config(function ($routeProvider) {
$routeProvider
.when('/intro', {
templateUrl: 'views/intro.html',
controller: 'PagerdutyCtrl',
resolve: {
pd: function(pagerduty_promise) {
return pagerduty_promise;
}
}
})
.when('/chatbot-settings', {
templateUrl: 'views/bot.html',
controller: 'BotSetupCtrl',
resolve: {
bot_info: get_promise('/api/bot')
}
})
.when('/plugin-setup', {
templateUrl: 'views/plugins.html',
controller: 'PluginSetupCtrl',
resolve: {
plugin_info: get_promise('/api/plugins')
}
})
.when('/user-aliases', {
templateUrl: 'views/users.html',
controller: 'UserAliasCtrl',
resolve: {
users: get_promise('/api/users')
}
})
.when('/schedule-aliases', {
templateUrl: 'views/schedules.html',
controller: 'ScheduleAliasCtrl',
resolve: {
schedules: get_promise('/api/schedules')
}
})
.when('/deploy', {
templateUrl: 'views/deploy.html',
controller: 'DeployCtrl'
})
.otherwise({
redirectTo: '/intro'
});
});
})();
|
<?php
/**
* AAddress filter form.
*
* @package alumni
* @subpackage filter
* @author E.R. Nurwijayadi
* @version 1.0
*/
class AAddressFormFilter extends <API key>
{
/**
* @see AddressFormFilter
*/
static protected $order_by_choices = array(
null => '',
6 => 'ID',
21 => 'Name (Alumna/us)',
'' => '
60 => 'Address',
61 => 'Region',
63 => 'Code: Country',
64 => 'Code: Province',
65 => 'Code: District',
66 => 'Postal Code',
67 => 'Street',
68 => 'Area',
69 => 'Building'
);
public function configure()
{
$this->widgetSchema-><API key>('list');
$this-><API key>();
$this-><API key>($this);
$this->widgetSchema['order_by'] = new sfWidgetFormChoice(array(
'choices' => self::$order_by_choices));
$this->validatorSchema['order_by'] = new sfValidatorPass();
$this->widgetSchema['department_id'] = new sfWidgetFormChoice(array(
'choices' => array(null => '')
));
$this->useFields(array(
'department_id', 'faculty_id', 'program_id',
'class_year', 'decade', 'order_by'
));
$query = Doctrine_Core::getTable('AAddress')
->createQuery('r')
->leftJoin('r.Country n')
->leftJoin('r.Province p')
->leftJoin('r.District w')
->leftJoin('r.Alumni a')
->leftJoin('a.ACommunities ac');
$this->setQuery($query);
}
public function <API key>(Doctrine_Query $query, $field, $values)
{
$order_by_choices = array(
6 => 'r.lid',
21 => 'a.name',
60 => 'r.address',
61 => 'r.region',
63 => 'r.country_id',
64 => 'r.province_id',
65 => 'r.district_id',
66 => 'r.postal_code',
67 => 'r.street',
68 => 'r.area',
69 => 'r.building'
);
if ( array_key_exists($values, $order_by_choices) )
$query->orderBy( $order_by_choices[$values] );
}
/* This parts needs Trait in PHP 5.4 */
public function <API key>(Doctrine_Query $query, $field, $values)
{ if (!empty($values) ) $query->andWhere('ac.department_id = ?', $values); }
public function <API key>(Doctrine_Query $query, $field, $values)
{ if (!empty($values) ) $query->andWhere('ac.faculty_id = ?', $values); }
public function <API key>(Doctrine_Query $query, $field, $values)
{ if (!empty($values) ) $query->andWhere('ac.program_id = ?', $values); }
public function <API key>(Doctrine_Query $query, $field, $values)
{ if (!empty($values['text']) ) $query->andWhere('ac.class_year = ?', $values['text']); }
public function <API key>(Doctrine_Query $query, $field, $values)
{
$decades = array(1960, 1970, 1980, 1990, 2000, 2010);
if ( in_array( $values, $decades ) )
{
$query->andWhere('ac.class_year >= ?', $values);
$query->andWhere('ac.class_year <= ?', $values+9);
}
}
}
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class DailySeedAndCleanup extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('featured_games', function (Blueprint $table) {
$table->increments('id');
$table->date('day')->unique();
$table->integer('seed_id');
$table->string('description')->default('');
$table->timestamps();
});
Schema::table('seeds', function (Blueprint $table) {
$table->dropColumn(['patch']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('seeds', function (Blueprint $table) {
$table->json('patch');
});
Schema::dropIfExists('featured_games');
}
}
|
@import url(https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic);
@font-face {
font-family: 'League Gothic';
src: url("../../lib/font/<API key>.eot");
src: url("../../lib/font/<API key>.eot?#iefix") format("embedded-opentype"), url("../../lib/font/<API key>.woff") format("woff"), url("../../lib/font/<API key>.ttf") format("truetype"), url("../../lib/font/<API key>.svg#LeagueGothicRegular") format("svg");
font-weight: normal;
font-style: normal; }
body {
background: #1c1e20;
background: -moz-radial-gradient(center, circle cover, #555a5f 0%, #1c1e20 100%);
background: -webkit-gradient(radial, center center, 0px, center center, 100%, color-stop(0%, #555a5f), color-stop(100%, #1c1e20));
background: -<API key>(center, circle cover, #555a5f 0%, #1c1e20 100%);
background: -o-radial-gradient(center, circle cover, #555a5f 0%, #1c1e20 100%);
background: -ms-radial-gradient(center, circle cover, #555a5f 0%, #1c1e20 100%);
background: radial-gradient(center, circle cover, #555a5f 0%, #1c1e20 100%);
background-color: #2b2b2b; }
.reveal {
font-family: "Lato", sans-serif;
font-size: 36px;
font-weight: normal;
letter-spacing: -0.02em;
color: #eeeeee; }
::selection {
color: white;
background: #ff5e99;
text-shadow: none; }
.reveal h1,
.reveal h2,
.reveal h3,
.reveal h4,
.reveal h5,
.reveal h6 {
margin: 0 0 20px 0;
color: #eeeeee;
font-family: "Lato", Helvetica, sans-serif;
line-height: 0.9em;
letter-spacing: 0.02em;
font-weight: 700;
text-shadow: 0px 0px 6px rgba(0, 0, 0, 0.2); }
.reveal h1 {
text-shadow: 0 1px 0 #cccccc, 0 2px 0 #c9c9c9, 0 3px 0 #bbbbbb, 0 4px 0 #b9b9b9, 0 5px 0 #aaaaaa, 0 6px 1px rgba(0, 0, 0, 0.1), 0 0 5px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.3), 0 3px 5px rgba(0, 0, 0, 0.2), 0 5px 10px rgba(0, 0, 0, 0.25), 0 20px 20px rgba(0, 0, 0, 0.15); }
.reveal a:not(.image) {
color: #13daec;
text-decoration: none;
-webkit-transition: color .15s ease;
-moz-transition: color .15s ease;
-ms-transition: color .15s ease;
-o-transition: color .15s ease;
transition: color .15s ease; }
.reveal a:not(.image):hover {
color: #71e9f4;
text-shadow: none;
border: none; }
.reveal .roll span:after {
color: #fff;
background: #0d99a5; }
.reveal section img {
margin: 15px 0px;
background: rgba(255, 255, 255, 0.12);
border: 4px solid #eeeeee;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.15);
-webkit-transition: all .2s linear;
-moz-transition: all .2s linear;
-ms-transition: all .2s linear;
-o-transition: all .2s linear;
transition: all .2s linear; }
.reveal a:hover img {
background: rgba(255, 255, 255, 0.2);
border-color: #13daec;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.55); }
.reveal .controls div.navigate-left,
.reveal .controls div.navigate-left.enabled {
border-right-color: #13daec; }
.reveal .controls div.navigate-right,
.reveal .controls div.navigate-right.enabled {
border-left-color: #13daec; }
.reveal .controls div.navigate-up,
.reveal .controls div.navigate-up.enabled {
border-bottom-color: #13daec; }
.reveal .controls div.navigate-down,
.reveal .controls div.navigate-down.enabled {
border-top-color: #13daec; }
.reveal .controls div.navigate-left.enabled:hover {
border-right-color: #71e9f4; }
.reveal .controls div.navigate-right.enabled:hover {
border-left-color: #71e9f4; }
.reveal .controls div.navigate-up.enabled:hover {
border-bottom-color: #71e9f4; }
.reveal .controls div.navigate-down.enabled:hover {
border-top-color: #71e9f4; }
.reveal .progress {
background: rgba(0, 0, 0, 0.2); }
.reveal .progress span {
background: #13daec;
-webkit-transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985);
-moz-transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985);
-ms-transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985);
-o-transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985);
transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985); }
.reveal .slide-number {
color: #13daec; }
|
<?php
namespace GEPedag\EntidadesBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\<API key>\Configuration\Method;
use Sensio\Bundle\<API key>\Configuration\Template;
use GEPedag\EntidadesBundle\Entity\Asignatura;
use GEPedag\EntidadesBundle\Form\AsignaturaType;
class <API key> extends Controller {
/**
* @Method("GET")
* @Template()
*/
public function indexAction() {
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('<API key>:Asignatura')->findAll();
return [
'entities' => $entities
];
}
/**
* @Method("POST")
*/
public function createAction(Request $request) {
$asignatura = new Asignatura();
$form = $this->createForm(new AsignaturaType(), $asignatura);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($asignatura);
$em->flush();
$this->get('session')->getFlashBag()->add(
'success', 'La asignatura <i>' . $asignatura . '</i> se ha creado con éxito!');
return $this->redirect($this->generateUrl('ge_asign_homepage'));
}
// print_r($form->getErrors());die;
// foreach ($form->getErrors() as $error) {
$this->get('session')->getFlashBag()->add('error', 'Error al registrar la asignatura.');
return $this->redirect($this->generateUrl('ge_asign_homepage'));
}
/**
* @Method("GET")
* @Template("<API key>:Asignatura:new_edit.html.twig")
*/
public function newAction() {
$asignatura = new Asignatura();
$titulo = 'Crear';
$form = $this->createForm(new AsignaturaType(), $asignatura);
$form->add('submit', 'submit', array('label' => $titulo));
return [
'action' => $this->generateUrl('ge_asign_create'),
'entity' => $asignatura,
'form' => $form->createView(),
'titulo' => $titulo,
];
}
/**
* @Method("GET")
*/
public function editAction($id) {
$titulo = 'Actualizar';
$em = $this->getDoctrine()->getManager();
$asignatura = $em->getRepository('<API key>:Asignatura')->find($id);
if (!$asignatura) {
throw $this-><API key>('No existe la Asignatura con id: ' . $id);
}
$editForm = $this->createForm(new AsignaturaType(), $asignatura);
$editForm->add('submit', 'submit', array('label' => $titulo));
return $this->render('<API key>:Asignatura:new_edit.html.twig', [
'action' => $this->generateUrl('ge_asign_update', array('id' => $asignatura->getId())),
'entity' => $asignatura,
'titulo' => $titulo,
'form' => $editForm->createView()
]);
}
/**
* @Method("POST")
*/
public function updateAction(Request $request, $id) {
$em = $this->getDoctrine()->getManager();
$asignatura = $em->getRepository('<API key>:Asignatura')->find($id);
if (!$asignatura) {
$this->get('session')->getFlashBag()->add(
'error', 'No existe la asignatura con id: ' . $id);
return $this->redirect($this->generateUrl('ge_asign_homepage'));
}
$editForm = $this->createForm(new AsignaturaType(), $asignatura);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->persist($asignatura);
$em->flush();
$this->get('session')->getFlashBag()->add(
'success', 'Muy Bien! La asignatura <i>' . $asignatura . '</i> se ha actualizado con éxito!');
return $this->redirect($this->generateUrl('ge_asign_homepage'));
}
$this->get('session')->getFlashBag()->add(
'success', 'Error al crear la asignatura.');
return $this->redirect($this->generateUrl('ge_asign_homepage'));
}
/**
* @Method("GET")
*/
public function deleteAction(Request $request, $id) {
$em = $this->getDoctrine()->getManager();
$asignatura = $em->getRepository('<API key>:Asignatura')->find($id);
if (!$asignatura) {
$this->get('session')->getFlashBag()->add(
'error', 'No existe la asignatura con id: ' . $id);
return $this->redirect($this->generateUrl('ge_asign_homepage'));
}
$em->remove($asignatura);
$em->flush();
$this->get('session')->getFlashBag()->add(
'success', 'La asignatura <i>' . $asignatura . '</i> se ha eliminado.');
return $this->redirect($this->generateUrl('ge_asign_homepage'));
}
}
|
QMathematics
=========
Dependence:
1. QT (QTSQL QTSVG QTSCRIPT QTPLUGIN)
2. MySql (qsqlmysql4.dll libmysql.dll)
3. QWT
4. GSL
|
""" Tests for Dynamo3 """
import sys
import unittest
from decimal import Decimal
from pickle import dumps, loads
from urllib.parse import urlparse
from botocore.exceptions import ClientError
from mock import ANY, MagicMock, patch
from dynamo3 import (
Binary,
Dynamizer,
DynamoDBConnection,
DynamoDBError,
DynamoKey,
GlobalIndex,
Limit,
Table,
ThroughputException,
)
from dynamo3.constants import STRING
from dynamo3.result import Capacity, ConsumedCapacity, Count, ResultSet, add_dicts
class BaseSystemTest(unittest.TestCase):
"""Base class for system tests"""
dynamo: DynamoDBConnection = None # type: ignore
def setUp(self):
super(BaseSystemTest, self).setUp()
# Clear out any pre-existing tables
for tablename in self.dynamo.list_tables():
self.dynamo.delete_table(tablename)
def tearDown(self):
super(BaseSystemTest, self).tearDown()
for tablename in self.dynamo.list_tables():
self.dynamo.delete_table(tablename)
self.dynamo.clear_hooks()
class TestMisc(BaseSystemTest):
"""Tests that don't fit anywhere else"""
def tearDown(self):
super(TestMisc, self).tearDown()
self.dynamo.<API key> = False
def <API key>(self):
"""Connection can access host of endpoint"""
urlparse(self.dynamo.host)
def <API key>(self):
"""Connection can access name of connected region"""
self.assertTrue(isinstance(self.dynamo.region, str))
def <API key>(self):
"""Can connect to a dynamo region"""
conn = DynamoDBConnection.connect("us-west-1")
self.assertIsNotNone(conn.host)
def <API key>(self):
"""Can connect to a dynamo region with credentials"""
conn = DynamoDBConnection.connect(
"us-west-1", access_key="abc", secret_key="12345"
)
self.assertIsNotNone(conn.host)
def <API key>(self):
"""Can connect to a dynamo host without passing in a session"""
conn = DynamoDBConnection.connect("us-west-1", host="localhost")
self.assertIsNotNone(conn.host)
@patch("dynamo3.connection.time")
def <API key>(self, time):
"""Throughput exceptions trigger a retry of the request"""
def call(*_, **__):
"""Dummy service call"""
response = {
"ResponseMetadata": {
"HTTPStatusCode": 400,
},
"Error": {
"Code": "<API key>",
"Message": "Does not matter",
},
}
raise ClientError(response, "list_tables")
with patch.object(self.dynamo, "client") as client:
client.list_tables.side_effect = call
with self.assertRaises(ThroughputException):
self.dynamo.call("list_tables")
self.assertEqual(len(time.sleep.mock_calls), self.dynamo.request_retries - 1)
self.assertTrue(time.sleep.called)
def <API key>(self):
"""Describing a missing table returns None"""
ret = self.dynamo.describe_table("foobar")
self.assertIsNone(ret)
def <API key>(self):
"""Table can look up properties on response object"""
hash_key = DynamoKey("id")
self.dynamo.create_table("foobar", hash_key=hash_key)
ret = self.dynamo.describe_table("foobar")
assert ret is not None
self.assertEqual(ret.item_count, ret["ItemCount"])
with self.assertRaises(KeyError):
self.assertIsNotNone(ret["Missing"])
def <API key>(self):
"""Index can look up properties on response object"""
index = GlobalIndex.all("idx-name", DynamoKey("id"))
index.response = {"FooBar": 2}
self.assertEqual(index["FooBar"], 2)
with self.assertRaises(KeyError):
self.assertIsNotNone(index["Missing"])
def <API key>(self):
"""Describing a table during a delete operation should not crash"""
response = {
"ItemCount": 0,
"<API key>": {
"<API key>": 0,
"ReadCapacityUnits": 5,
"WriteCapacityUnits": 5,
},
"TableName": "myTableName",
"TableSizeBytes": 0,
"TableStatus": "DELETING",
}
table = Table.from_response(response)
self.assertEqual(table.status, "DELETING")
def test_delete_missing(self):
"""Deleting a missing table returns False"""
ret = self.dynamo.delete_table("foobar")
self.assertTrue(not ret)
def <API key>(self):
"""DynamoDBError can re-raise itself if missing original exception"""
err = DynamoDBError(400, Code="ErrCode", Message="Ouch", args={})
caught = False
try:
err.re_raise()
except DynamoDBError as e:
caught = True
self.assertEqual(err, e)
self.assertTrue(caught)
def test_re_raise(self):
"""DynamoDBError can re-raise itself with stacktrace of original exc"""
caught = False
try:
try:
raise Exception("Hello")
except Exception as e1:
err = DynamoDBError(
400,
Code="ErrCode",
Message="Ouch",
args={},
exc_info=sys.exc_info(),
)
err.re_raise()
except DynamoDBError as e:
caught = True
import traceback
tb = traceback.format_tb(e.__traceback__)
self.assertIn("Hello", tb[-1])
self.assertEqual(e.status_code, 400)
self.assertTrue(caught)
def <API key>(self):
"""When <API key>=True, always return capacity"""
self.dynamo.<API key> = True
with patch.object(self.dynamo, "call") as call:
call().get.return_value = None
rs = self.dynamo.scan("foobar")
list(rs)
call.assert_called_with(
"scan",
TableName="foobar",
<API key>="INDEXES",
ConsistentRead=False,
)
def <API key>(self):
"""Call to ListTables should page results"""
hash_key = DynamoKey("id")
for i in range(120):
self.dynamo.create_table("table%d" % i, hash_key=hash_key)
tables = list(self.dynamo.list_tables(110))
self.assertEqual(len(tables), 110)
def test_limit_complete(self):
"""A limit with item_capacity = 0 is 'complete'"""
limit = Limit(item_limit=0)
self.assertTrue(limit.complete)
def <API key>(self):
"""Create table shall wait for the table to come online."""
tablename = "foobar_wait"
hash_key = DynamoKey("id")
self.dynamo.create_table(tablename, hash_key=hash_key, wait=True)
self.assertIsNotNone(self.dynamo.describe_table(tablename))
def <API key>(self):
"""Delete table shall wait for the table to go offline."""
tablename = "foobar_wait"
hash_key = DynamoKey("id")
self.dynamo.create_table(tablename, hash_key=hash_key, wait=True)
result = self.dynamo.delete_table(tablename, wait=True)
self.assertTrue(result)
class TestDataTypes(BaseSystemTest):
"""Tests for Dynamo data types"""
def make_table(self):
"""Convenience method for making a table"""
hash_key = DynamoKey("id")
self.dynamo.create_table("foobar", hash_key=hash_key)
def test_string(self):
"""Store and retrieve a string"""
self.make_table()
self.dynamo.put_item("foobar", {"id": "abc"})
item = list(self.dynamo.scan("foobar"))[0]
self.assertEqual(item["id"], "abc")
self.assertTrue(isinstance(item["id"], str))
def test_int(self):
"""Store and retrieve an int"""
self.make_table()
self.dynamo.put_item("foobar", {"id": "a", "num": 1})
item = list(self.dynamo.scan("foobar"))[0]
self.assertEqual(item["num"], 1)
def test_float(self):
"""Store and retrieve a float"""
self.make_table()
self.dynamo.put_item("foobar", {"id": "a", "num": 1.1})
item = list(self.dynamo.scan("foobar"))[0]
self.assertAlmostEqual(float(item["num"]), 1.1)
def test_decimal(self):
"""Store and retrieve a Decimal"""
self.make_table()
self.dynamo.put_item("foobar", {"id": "a", "num": Decimal("1.1")})
item = list(self.dynamo.scan("foobar"))[0]
self.assertEqual(item["num"], Decimal("1.1"))
def test_binary(self):
"""Store and retrieve a binary"""
self.make_table()
self.dynamo.put_item("foobar", {"id": "a", "data": Binary("abc")})
item = list(self.dynamo.scan("foobar"))[0]
self.assertEqual(item["data"].value, b"abc")
def test_binary_bytes(self):
"""Store and retrieve bytes as a binary"""
self.make_table()
data = {"a": 1, "b": 2}
self.dynamo.put_item("foobar", {"id": "a", "data": Binary(dumps(data))})
item = list(self.dynamo.scan("foobar"))[0]
self.assertEqual(loads(item["data"].value), data)
def test_string_set(self):
"""Store and retrieve a string set"""
self.make_table()
item = {
"id": "a",
"datas": set(["a", "b"]),
}
self.dynamo.put_item("foobar", item)
ret = list(self.dynamo.scan("foobar"))[0]
self.assertEqual(ret, item)
def test_number_set(self):
"""Store and retrieve a number set"""
self.make_table()
item = {
"id": "a",
"datas": set([1, 2, 3]),
}
self.dynamo.put_item("foobar", item)
ret = list(self.dynamo.scan("foobar"))[0]
self.assertEqual(ret, item)
def test_binary_set(self):
"""Store and retrieve a binary set"""
self.make_table()
item = {
"id": "a",
"datas": set([Binary("a"), Binary("b")]),
}
self.dynamo.put_item("foobar", item)
ret = list(self.dynamo.scan("foobar"))[0]
self.assertEqual(ret, item)
def test_binary_equal(self):
"""Binary should eq other Binaries and also raw bytestrings"""
self.assertEqual(Binary("a"), Binary("a"))
self.assertEqual(Binary("a"), b"a")
self.assertFalse(Binary("a") != Binary("a"))
def test_binary_repr(self):
"""Binary repr should wrap the contained value"""
self.assertEqual(repr(Binary("a")), "Binary(%r)" % b"a")
def <API key>(self):
"""Binary will convert unicode to bytes"""
b = Binary("a")
self.assertTrue(isinstance(b.value, bytes))
def <API key>(self):
"""Binary must wrap a string type"""
with self.assertRaises(TypeError):
Binary(2) # type: ignore
def test_bool(self):
"""Store and retrieve a boolean"""
self.make_table()
self.dynamo.put_item("foobar", {"id": "abc", "b": True})
item = list(self.dynamo.scan("foobar"))[0]
self.assertEqual(item["b"], True)
self.assertTrue(isinstance(item["b"], bool))
def test_list(self):
"""Store and retrieve a list"""
self.make_table()
self.dynamo.put_item("foobar", {"id": "abc", "l": ["a", 1, False]})
item = list(self.dynamo.scan("foobar"))[0]
self.assertEqual(item["l"], ["a", 1, False])
def test_dict(self):
"""Store and retrieve a dict"""
self.make_table()
data = {
"i": 1,
"s": "abc",
"n": None,
"l": ["a", 1, True],
"b": False,
}
self.dynamo.put_item("foobar", {"id": "abc", "d": data})
item = list(self.dynamo.scan("foobar"))[0]
self.assertEqual(item["d"], data)
def test_nested_dict(self):
"""Store and retrieve a nested dict"""
self.make_table()
data = {
"s": "abc",
"d": {
"i": 42,
},
}
self.dynamo.put_item("foobar", {"id": "abc", "d": data})
item = list(self.dynamo.scan("foobar"))[0]
self.assertEqual(item["d"], data)
def test_nested_list(self):
"""Store and retrieve a nested list"""
self.make_table()
data = [
1,
[
True,
None,
"abc",
],
]
self.dynamo.put_item("foobar", {"id": "abc", "l": data})
item = list(self.dynamo.scan("foobar"))[0]
self.assertEqual(item["l"], data)
def <API key>(self):
"""Dynamizer throws error on unrecognized type"""
value = {
"ASDF": "abc",
}
with self.assertRaises(TypeError):
self.dynamo.dynamizer.decode(value)
class TestDynamizer(unittest.TestCase):
"""Tests for the Dynamizer"""
def <API key>(self):
"""Can register a custom encoder"""
from datetime import datetime
dynamizer = Dynamizer()
dynamizer.register_encoder(datetime, lambda d, v: (STRING, v.isoformat()))
now = datetime.utcnow()
self.assertEqual(dynamizer.raw_encode(now), (STRING, now.isoformat()))
def <API key>(self):
"""If no encoder is found, raise ValueError"""
from datetime import datetime
dynamizer = Dynamizer()
with self.assertRaises(ValueError):
dynamizer.encode(datetime.utcnow())
class TestResultModels(unittest.TestCase):
"""Tests for the model classes in results.py"""
def <API key>(self):
"""add_dict where one argument is None returns the other"""
f = object()
self.assertEqual(add_dicts(f, None), f)
self.assertEqual(add_dicts(None, f), f)
def test_add_dicts(self):
"""Merge two dicts of values together"""
a = {
"a": 1,
"b": 2,
}
b = {
"a": 3,
"c": 4,
}
ret = add_dicts(a, b)
self.assertEqual(
ret,
{
"a": 4,
"b": 2,
"c": 4,
},
)
def test_count_repr(self):
"""Count repr"""
count = Count(0, 0)
self.assertEqual(repr(count), "Count(0)")
def test_count_addition(self):
"""Count addition"""
count = Count(4, 2)
self.assertEqual(count + 5, 9)
def <API key>(self):
"""Count subtraction"""
count = Count(4, 2)
self.assertEqual(count - 2, 2)
def <API key>(self):
"""Count multiplication"""
count = Count(4, 2)
self.assertEqual(2 * count, 8)
def test_count_division(self):
"""Count division"""
count = Count(4, 2)
self.assertEqual(count / 2, 2)
def <API key>(self):
"""Count addition with one None consumed_capacity"""
cap = Capacity(3, 0)
count = Count(4, 2)
count2 = Count(5, 3, cap)
ret = count + count2
self.assertEqual(ret, 9)
self.assertEqual(ret.scanned_count, 5)
self.assertEqual(ret.consumed_capacity, cap)
def <API key>(self):
"""Count addition with consumed_capacity"""
count = Count(4, 2, Capacity(3, 0))
count2 = Count(5, 3, Capacity(2, 0))
ret = count + count2
self.assertEqual(ret, 9)
self.assertEqual(ret.scanned_count, 5)
self.assertEqual(ret.consumed_capacity.read, 5)
def test_capacity_math(self):
"""Capacity addition and equality"""
cap = Capacity(2, 4)
s = set([cap])
self.assertIn(Capacity(2, 4), s)
self.assertNotEqual(Capacity(1, 4), cap)
self.assertEqual(Capacity(1, 1) + Capacity(2, 2), Capacity(3, 3))
def <API key>(self):
"""String formatting for Capacity"""
c = Capacity(1, 3)
self.assertEqual(str(c), "R:1.0 W:3.0")
c = Capacity(0, 0)
self.assertEqual(str(c), "0")
def <API key>(self):
"""ConsumedCapacity can parse results with only Total"""
response = {
"TableName": "foobar",
"ReadCapacityUnits": 4,
"WriteCapacityUnits": 5,
}
cap = ConsumedCapacity.from_response(response)
self.assertEqual(cap.total, (4, 5))
self.assertIsNone(cap.table_capacity)
def <API key>(self):
"""ConsumedCapacity addition and equality"""
cap = ConsumedCapacity(
"foobar",
Capacity(0, 10),
Capacity(0, 2),
{
"l-index": Capacity(0, 4),
},
{
"g-index": Capacity(0, 3),
},
)
c2 = ConsumedCapacity(
"foobar",
Capacity(0, 10),
Capacity(0, 2),
{
"l-index": Capacity(0, 4),
"l-index2": Capacity(0, 7),
},
)
self.assertNotEqual(cap, c2)
c3 = ConsumedCapacity(
"foobar",
Capacity(0, 10),
Capacity(0, 2),
{
"l-index": Capacity(0, 4),
},
{
"g-index": Capacity(0, 3),
},
)
self.assertIn(cap, set([c3]))
combined = cap + c2
self.assertEqual(
cap + c2,
ConsumedCapacity(
"foobar",
Capacity(0, 20),
Capacity(0, 4),
{
"l-index": Capacity(0, 8),
"l-index2": Capacity(0, 7),
},
{
"g-index": Capacity(0, 3),
},
),
)
self.assertIn(str(Capacity(0, 3)), str(combined))
def <API key>(self):
"""Cannot add ConsumedCapacity of two different tables"""
c1 = ConsumedCapacity("foobar", Capacity(1, 28))
c2 = ConsumedCapacity("boofar", Capacity(3, 0))
with self.assertRaises(TypeError):
c1 += c2
def <API key>(self):
"""Regression test.
If result has no items but does have LastEvaluatedKey, keep querying.
"""
conn = MagicMock()
conn.dynamizer.decode_keys.side_effect = lambda x: x
items = ["a", "b"]
results = [
{"Items": [], "LastEvaluatedKey": {"foo": 1, "bar": 2}},
{"Items": [], "LastEvaluatedKey": {"foo": 1, "bar": 2}},
{"Items": items},
]
conn.call.side_effect = lambda *_, **__: results.pop(0)
rs = ResultSet(conn, Limit())
results = list(rs)
self.assertEqual(results, items)
class TestHooks(BaseSystemTest):
"""Tests for connection callback hooks"""
def tearDown(self):
super(TestHooks, self).tearDown()
for hooks in self.dynamo._hooks.values():
while hooks:
hooks.pop()
def test_precall(self):
"""precall hooks are called before an API call"""
hook = MagicMock()
self.dynamo.subscribe("precall", hook)
def throw(**_):
"""Throw an exception to terminate the request"""
raise Exception()
with patch.object(self.dynamo, "client") as client:
client.describe_table.side_effect = throw
with self.assertRaises(Exception):
self.dynamo.describe_table("foobar")
hook.assert_called_with(self.dynamo, "describe_table", {"TableName": "foobar"})
def test_postcall(self):
"""postcall hooks are called after API call"""
hash_key = DynamoKey("id")
self.dynamo.create_table("foobar", hash_key=hash_key)
calls = []
def hook(*args):
"""Log the call into a list"""
calls.append(args)
self.dynamo.subscribe("postcall", hook)
self.dynamo.describe_table("foobar")
self.assertEqual(len(calls), 1)
args = calls[0]
self.assertEqual(len(args), 4)
conn, command, kwargs, response = args
self.assertEqual(conn, self.dynamo)
self.assertEqual(command, "describe_table")
self.assertEqual(kwargs["TableName"], "foobar")
self.assertEqual(response["Table"]["TableName"], "foobar")
def test_capacity(self):
"""capacity hooks are called whenever response has ConsumedCapacity"""
hash_key = DynamoKey("id")
self.dynamo.create_table("foobar", hash_key=hash_key)
hook = MagicMock()
self.dynamo.subscribe("capacity", hook)
with patch.object(self.dynamo, "client") as client:
client.scan.return_value = {
"Items": [],
"ConsumedCapacity": {
"TableName": "foobar",
"ReadCapacityUnits": 4,
},
}
rs = self.dynamo.scan("foobar")
list(rs)
cap = ConsumedCapacity("foobar", Capacity(4, 0))
hook.assert_called_with(self.dynamo, "scan", ANY, ANY, cap)
def test_subscribe(self):
"""Can subscribe and unsubscribe from hooks"""
hook = lambda: None
self.dynamo.subscribe("precall", hook)
self.assertEqual(len(self.dynamo._hooks["precall"]), 1)
self.dynamo.unsubscribe("precall", hook)
self.assertEqual(len(self.dynamo._hooks["precall"]), 0)
|
{% include header.html %}
{% include about.html %}
{% include work.html %}
{% include contact.html %}
{% include footer.html %}
|
@import url('https://fonts.googleapis.com/css?family=Inconsolata|Jim+Nightshade');
body {
overflow: hidden;
font-family: 'Inconsolata', monospace;
color: #333333;
}
#start, .main, #gameTime, #endBoard {
margin: 0 auto;
padding: 30px;
text-align: center;
width: 100%;
height: auto;
}
#gameTime, #endBoard {
display: none;
}
h1, h2 {
display: inline-block;
}
.choose {
font-family: 'Jim Nightshade', cursive;
cursor: pointer;
}
.active {
color: #7ACA99;
}
.board {
width: 300px;
height: 300px;
margin: 0 auto;
}
.table {
font-family: 'Jim Nightshade', cursive;
width: 100px;
height: 100px;
border: 2px solid #7ACA99;
text-align: center;
float: left;
box-sizing: border-box;
cursor: pointer;
font-size: 50px;
font-weight: bold;
line-height: 100px;
}
.disabled {
pointer-events: none;
opacity: 0.7;
background-color: #f4f4f4;
}
#gameStart, #resetGame {
color: #333333;
border: 2px solid #7ACA99;
border-radius: 10px;
font-size: 16px;
text-decoration: none;
padding: 15px 32px;
cursor: pointer;
background-color: white;
-webkit-transition: all .3s; /* Safari */
transition: all .3s;
}
#gameStart:hover, #resetGame:hover {
background-color: #7ACA99;
color: white;
font-weight: bolder;
}
#gameStart:visited, #gameStart:active, #gameStart:focus,
#resetGame:visited, #resetGame:active, #resetGame:focus {
outline: none;
}
footer {
position: absolute;
bottom: 10px;
left: 0;
width: 100%;
background-color: #7ACA99;
font-size: 0.7em;
text-align: center;
}
footer > p {
margin: 0;
}
a {
text-decoration: none;
}
a:hover {
color: white;
}
|
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "CREATE EXTENSION pg_prttn_tools" to load this file. \quit
-- Function: prttn_tools.create_child_table(
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- BOOLEAN)
CREATE OR REPLACE FUNCTION prttn_tools.create_child_table(
p_schema CHARACTER VARYING,
p_table CHARACTER VARYING,
p_child_schema CHARACTER VARYING,
p_child_table CHARACTER VARYING,
p_check_condition CHARACTER VARYING,
p_with_rule BOOLEAN)
RETURNS TEXT AS
$body$
DECLARE
v_ddl_text CHARACTER VARYING;
BEGIN
v_ddl_text := 'CREATE TABLE ' || p_child_schema || '.' || p_child_table ||
' ( LIKE ' || p_schema || '.' || p_table || ' INCLUDING ALL )';
EXECUTE v_ddl_text;
v_ddl_text := 'ALTER TABLE ' || p_child_schema || '.' || p_child_table ||
' INHERIT ' || p_schema || '.' || p_table;
EXECUTE v_ddl_text;
IF p_check_condition IS NOT NULL THEN
v_ddl_text := 'ALTER TABLE ' ||
p_child_schema || '.' || p_child_table ||
' ADD CONSTRAINT ' || p_child_table || '_check CHECK ' ||
p_check_condition;
EXECUTE v_ddl_text;
IF p_with_rule THEN
v_ddl_text := 'CREATE RULE route_' ||
p_child_schema || '_' || p_child_table || ' AS ' ||
' ON INSERT TO ' || p_schema ||'.'|| p_table ||
' WHERE ' || p_check_condition || ' DO INSTEAD INSERT INTO ' ||
p_child_schema || '.' || p_child_table || ' VALUES (new.*)';
EXECUTE v_ddl_text;
END IF;
END IF;
RETURN 'created';
END;
$body$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION prttn_tools.create_child_table(CHARACTER VARYING,
CHARACTER VARYING, CHARACTER VARYING, CHARACTER VARYING, CHARACTER VARYING,
BOOLEAN) OWNER TO postgres;
-- Function: prttn_tools.drop_ins_trigger(
-- CHARACTER VARYING,
-- CHARACTER VARYING)
CREATE OR REPLACE FUNCTION prttn_tools.drop_ins_trigger(
p_schema CHARACTER VARYING,
p_table CHARACTER VARYING)
RETURNS TEXT AS
$body$
DECLARE
v_ddl_text CHARACTER VARYING;
BEGIN
v_ddl_text := 'DROP TRIGGER ' || p_table || '_part_ins_tr ON ' ||
p_schema || '.' || p_table;
EXECUTE v_ddl_text;
v_ddl_text := 'DROP FUNCTION IF EXISTS ' || p_schema || '.' || p_table ||
'_part_ins_tr()';
EXECUTE v_ddl_text;
v_ddl_text := 'DROP FUNCTION IF EXISTS ' || p_schema || '.' || p_table ||
'_part_ins_tr_ac()';
EXECUTE v_ddl_text;
RETURN 'ok';
END;
$body$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION prttn_tools.drop_ins_trigger(CHARACTER VARYING,
CHARACTER VARYING) OWNER TO postgres;
-- Function: prttn_tools.part_list_check(
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING)
CREATE OR REPLACE FUNCTION prttn_tools.part_list_check(
p_schema CHARACTER VARYING,
p_table CHARACTER VARYING,
p_list_column CHARACTER VARYING,
p_list_value CHARACTER VARYING)
RETURNS table(
child_table CHARACTER VARYING,
child_table_status CHARACTER VARYING,
child_list CHARACTER VARYING
) AS
$body$
DECLARE
v_count INTEGER;
BEGIN
child_table := p_table || '_' || p_list_value;
child_list := p_list_value;
SELECT count(*) INTO v_count
FROM pg_catalog.pg_tables
WHERE schemaname = p_schema AND tablename = child_table;
IF v_count != 0 THEN
child_table_status := 'exist';
ELSE
child_table_status := 'noexist';
END IF;
-- Returns:
-- child_table <API key>
-- child_table_status exist/noexist
-- child_list p_list_value
RETURN NEXT;
RETURN;
END;
$body$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION prttn_tools.part_list_check(CHARACTER VARYING, CHARACTER VARYING,
CHARACTER VARYING, CHARACTER VARYING) OWNER TO postgres;
-- Function: prttn_tools.part_list_add(
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- BOOLEAN)
CREATE OR REPLACE FUNCTION prttn_tools.part_list_add(
p_schema CHARACTER VARYING,
p_table CHARACTER VARYING,
p_list_column CHARACTER VARYING,
p_list_value CHARACTER VARYING,
p_with_rule BOOLEAN)
RETURNS table(
child_table CHARACTER VARYING,
child_table_status CHARACTER VARYING,
child_list CHARACTER VARYING
) AS
$body$
DECLARE
v_count INTEGER;
v_check_condition CHARACTER VARYING;
v_ddl_text CHARACTER VARYING;
BEGIN
SELECT count(*) INTO v_count
FROM information_schema.tables t
JOIN information_schema.columns c
ON t.table_catalog = c.table_catalog
AND t.table_schema = c.table_schema
AND t.table_name = c.table_name
WHERE t.table_catalog::name = current_database() AND
t.table_type = 'BASE TABLE' AND
t.table_schema = p_schema AND
t.table_name = p_table AND
c.column_name = p_list_column;
IF v_count != 1 THEN
raise 'incorrect master table %', p_schema || '.' || p_table;
END IF;
SELECT r.child_table, r.child_table_status, r.child_list
INTO child_table, child_table_status, child_list
FROM prttn_tools.part_list_check(p_schema, p_table, p_list_column,
p_list_value) r;
v_check_condition := '(' ||
p_list_column || ' = ' || quote_literal(p_list_value) || ')';
IF child_table_status = 'noexist' THEN
SELECT prttn_tools.create_child_table(p_schema, p_table,
p_schema, child_table, v_check_condition, p_with_rule)
INTO child_table_status;
END IF;
-- Returns:
-- child_table <API key>
-- child_table_status exist/created
-- child_list p_list_value
RETURN NEXT;
RETURN;
END;
$body$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION prttn_tools.part_list_add(CHARACTER VARYING, CHARACTER VARYING,
CHARACTER VARYING, CHARACTER VARYING, BOOLEAN) OWNER TO postgres;
-- Function: prttn_tools.<API key>(
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- BOOLEAN)
CREATE OR REPLACE FUNCTION prttn_tools.<API key>(
p_schema CHARACTER VARYING,
p_table CHARACTER VARYING,
p_list_column CHARACTER VARYING,
p_autocreate BOOLEAN)
RETURNS TABLE(
trigger_function CHARACTER VARYING,
trigger_status CHARACTER VARYING
) AS
$body$
DECLARE
v_sql TEXT;
BEGIN
trigger_function := p_schema || '.' || p_table || '_part_ins_tr';
IF p_autocreate THEN
trigger_function := trigger_function || '_ac';
END IF;
v_sql := 'CREATE OR REPLACE FUNCTION ' || trigger_function || '()
RETURNS TRIGGER AS
$trigger$
DECLARE
-- this function is automatically created
-- from prttn_tools.<API key>
-- ' || now() || '
v_child_table CHARACTER VARYING;
<API key> CHARACTER VARYING;
BEGIN
SELECT child_table, child_table_status
INTO v_child_table, <API key>
FROM prttn_tools.part_list_check(
' || quote_literal(p_schema) || ',
' || quote_literal(p_table) || ',
' || quote_literal(p_list_column) || ',
new.' || p_list_column || '::CHARACTER VARYING);';
IF p_autocreate THEN
v_sql := v_sql || '
IF <API key> = ''noexist'' THEN
SELECT child_table, child_table_status
INTO v_child_table, <API key>
FROM prttn_tools.part_list_add(
' || quote_literal(p_schema) || ',
' || quote_literal(p_table) || ',
' || quote_literal(p_list_column) || ',
new.' || p_list_column || '::CHARACTER VARYING,
FALSE);
END IF;';
END IF;
v_sql := v_sql || '
IF <API key> = ''exist'' OR <API key> = ''created''
THEN
EXECUTE ''INSERT INTO ' || p_schema || '.'' || v_child_table ||
'' SELECT ( ('' || quote_literal(new) ||
'')::' || p_schema || '.' || p_table || ' ).*'';
ELSE
RAISE ''child table % not exist'', v_child_table;
END IF;
RETURN NULL;
END;
$trigger$
LANGUAGE plpgsql VOLATILE
COST 100;
CREATE TRIGGER ' || p_table || '_part_ins_tr
BEFORE INSERT
ON ' || p_schema || '.' || p_table || '
FOR EACH ROW
EXECUTE PROCEDURE ' || trigger_function || '();';
EXECUTE v_sql;
trigger_status := 'created';
RETURN NEXT;
RETURN;
END;
$body$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION prttn_tools.<API key>(CHARACTER VARYING,
CHARACTER VARYING, CHARACTER VARYING, BOOLEAN) OWNER TO postgres;
-- Function: prttn_tools.part_time_check(
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- TIMESTAMP WITHOUT TIME ZONE)
CREATE OR REPLACE FUNCTION prttn_tools.part_time_check(
p_schema CHARACTER VARYING,
p_table CHARACTER VARYING,
p_time_column CHARACTER VARYING,
p_time_range CHARACTER VARYING,
p_time_value TIMESTAMP WITHOUT TIME ZONE)
RETURNS TABLE(
child_table CHARACTER VARYING,
child_table_status CHARACTER VARYING,
child_time_from TIMESTAMP WITHOUT TIME ZONE,
child_time_to TIMESTAMP WITHOUT TIME ZONE
) AS
$body$
DECLARE
v_count INTEGER;
BEGIN
child_table := p_table || '_';
CASE lower(p_time_range)
WHEN 'year' THEN
child_table := child_table || to_char(p_time_value, 'yyyy');
child_time_from := date_trunc('year', p_time_value);
child_time_to := date_trunc('year',
p_time_value + interval '1 year');
WHEN 'month' THEN
child_table := child_table || to_char(p_time_value, 'yyyymm');
child_time_from := date_trunc('month', p_time_value);
child_time_to := date_trunc('month',
p_time_value + interval '1 month');
WHEN 'day' THEN
child_table := child_table || to_char(p_time_value, 'yyyymmdd');
child_time_from := date_trunc('day', p_time_value);
child_time_to := date_trunc('day',
p_time_value + interval '1 day');
WHEN 'hour' THEN
child_table := child_table ||
to_char(p_time_value, 'yyyymmdd_hh24');
child_time_from := date_trunc('hour', p_time_value);
child_time_to := date_trunc('hour',
p_time_value + interval '1 hour');
WHEN 'minute' THEN
child_table := child_table ||
to_char(p_time_value, 'yyyymmdd_hh24mi');
child_time_from := date_trunc('minute', p_time_value);
child_time_to := date_trunc('minute',
p_time_value + interval '1 minute');
ELSE
RAISE 'incorrect variable p_time_range %s', p_time_range;
END CASE;
SELECT count(*) INTO v_count
FROM pg_catalog.pg_tables
WHERE schemaname = p_schema AND tablename = child_table;
IF v_count != 0 THEN
child_table_status := 'exist';
ELSE
child_table_status := 'noexist';
END IF;
-- Returns:
-- child_table | <API key>
-- child_table_status | exist/noexist
RETURN NEXT;
RETURN;
END;
$body$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION prttn_tools.part_time_check(CHARACTER VARYING, CHARACTER VARYING,
CHARACTER VARYING, CHARACTER VARYING, TIMESTAMP WITHOUT TIME ZONE)
OWNER TO postgres;
-- Function: prttn_tools.part_time_add(
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- TIMESTAMP WITHOUT TIME ZONE,
-- BOOLEAN)
CREATE OR REPLACE FUNCTION prttn_tools.part_time_add(
p_schema CHARACTER VARYING,
p_table CHARACTER VARYING,
p_time_column CHARACTER VARYING,
p_time_range CHARACTER VARYING,
p_time_value TIMESTAMP WITHOUT TIME ZONE,
p_with_rule BOOLEAN)
RETURNS TABLE(
child_table CHARACTER VARYING,
child_table_status CHARACTER VARYING,
child_time_from TIMESTAMP WITHOUT TIME ZONE,
child_time_to TIMESTAMP WITHOUT TIME ZONE
) AS
$body$
DECLARE
v_count INTEGER;
v_check_condition CHARACTER VARYING;
v_ddl_text CHARACTER VARYING;
BEGIN
-- p_schemaname.p_tablename.p_time_column(timestamp without time zone)
SELECT count(*) INTO v_count
FROM information_schema.tables t
JOIN information_schema.columns c
ON t.table_catalog = c.table_catalog
AND t.table_schema = c.table_schema
AND t.table_name = c.table_name
WHERE t.table_catalog::name = current_database() AND
t.table_type = 'BASE TABLE' AND
t.table_schema = p_schema AND
t.table_name = p_table AND
c.column_name = p_time_column AND
c.data_type = 'timestamp without time zone';
IF v_count != 1 THEN
RAISE 'incorrect master table %', p_schema || '.' || p_table;
END IF;
SELECT r.child_table, r.child_table_status, r.child_time_from,
r.child_time_to
INTO child_table, child_table_status, child_time_from, child_time_to
FROM prttn_tools.part_time_check(p_schema, p_table, p_time_column,
p_time_range, p_time_value) r;
v_check_condition := '(' ||
p_time_column || ' >= ' || quote_literal(child_time_from) || ' AND ' ||
p_time_column || ' < ' || quote_literal(child_time_to) || ')';
IF child_table_status = 'noexist' THEN
SELECT prttn_tools.create_child_table(p_schema, p_table,
p_schema, child_table, v_check_condition, p_with_rule)
INTO child_table_status;
END IF;
-- Returns:
-- child_table <API key>
-- child_table_status exist/created
RETURN NEXT;
RETURN;
END;
$body$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION prttn_tools.part_time_add(CHARACTER VARYING, CHARACTER VARYING,
CHARACTER VARYING, CHARACTER VARYING, TIMESTAMP WITHOUT TIME ZONE, BOOLEAN)
OWNER TO postgres;
-- Function: prttn_tools.<API key>(
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- BOOLEAN)
CREATE OR REPLACE FUNCTION prttn_tools.<API key>(
p_schema CHARACTER VARYING,
p_table CHARACTER VARYING,
p_time_column CHARACTER VARYING,
p_time_range CHARACTER VARYING,
p_autocreate BOOLEAN)
RETURNS TABLE(
trigger_function CHARACTER VARYING,
trigger_status CHARACTER VARYING
) AS
$body$
DECLARE
v_sql TEXT;
BEGIN
trigger_function := p_schema || '.' || p_table || '_part_ins_tr';
IF p_autocreate THEN
trigger_function := trigger_function || '_ac';
END IF;
v_sql := 'CREATE OR REPLACE FUNCTION ' || trigger_function || '()
RETURNS TRIGGER AS
$trigger$
DECLARE
-- this function is automatically created
-- from prttn_tools.<API key>
-- ' || now() || '
v_child_table CHARACTER VARYING;
<API key> CHARACTER VARYING;
BEGIN
SELECT child_table, child_table_status
INTO v_child_table, <API key>
FROM prttn_tools.part_time_check(
' || quote_literal(p_schema) || ',
' || quote_literal(p_table) || ',
' || quote_literal(p_time_column) || ',
' || quote_literal(p_time_range) || ',
new.' || p_time_column || '::TIMESTAMP WITHOUT TIME ZONE);';
IF p_autocreate THEN
v_sql := v_sql || '
IF <API key> = ''noexist'' THEN
SELECT child_table, child_table_status
INTO v_child_table, <API key>
FROM prttn_tools.part_time_add(
' || quote_literal(p_schema) || ',
' || quote_literal(p_table) || ',
' || quote_literal(p_time_column) || ',
' || quote_literal(p_time_range) || ',
new.' || p_time_column || '::TIMESTAMP WITHOUT TIME ZONE,
FALSE);
END IF;';
END IF;
v_sql := v_sql || '
IF <API key> = ''exist'' OR <API key> = ''created''
THEN
EXECUTE ''INSERT INTO ' || p_schema || '.'' || v_child_table ||
'' SELECT ( ('' || quote_literal(new) ||
'')::' || p_schema || '.' || p_table || ' ).*'';
ELSE
RAISE ''child table % not exist'', v_child_table;
END IF;
RETURN NULL;
END;
$trigger$
LANGUAGE plpgsql VOLATILE
COST 100;
CREATE TRIGGER ' || p_table || '_part_ins_tr
BEFORE INSERT
ON ' || p_schema || '.' || p_table || '
FOR EACH ROW
EXECUTE PROCEDURE ' || trigger_function || '();';
EXECUTE v_sql;
trigger_status := 'created';
RETURN NEXT;
RETURN;
END;
$body$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION prttn_tools.<API key>(CHARACTER VARYING,
CHARACTER VARYING, CHARACTER VARYING, CHARACTER VARYING, BOOLEAN)
OWNER TO postgres;
-- Function: prttn_tools.<API key>(
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- TIMESTAMP WITHOUT TIME ZONE)
CREATE OR REPLACE FUNCTION prttn_tools.<API key>(
p_schema CHARACTER VARYING,
p_table CHARACTER VARYING,
p_list_column CHARACTER VARYING,
p_list_value CHARACTER VARYING,
p_time_column CHARACTER VARYING,
p_time_range CHARACTER VARYING,
p_time_value TIMESTAMP WITHOUT TIME ZONE)
RETURNS TABLE(
child_table CHARACTER VARYING,
child_table_status CHARACTER VARYING,
child_list CHARACTER VARYING,
child_time_from TIMESTAMP WITHOUT TIME ZONE,
child_time_to TIMESTAMP WITHOUT TIME ZONE
) AS
$body$
DECLARE
v_count INTEGER;
BEGIN
child_table := p_table || '_' || p_list_value || '_';
child_list := p_list_value;
CASE lower(p_time_range)
WHEN 'year' THEN
child_table := child_table || to_char(p_time_value, 'yyyy');
child_time_from := date_trunc('year', p_time_value);
child_time_to := date_trunc('year',
p_time_value + interval '1 year');
WHEN 'month' THEN
child_table := child_table || to_char(p_time_value, 'yyyymm');
child_time_from := date_trunc('month', p_time_value);
child_time_to := date_trunc('month',
p_time_value + interval '1 month');
WHEN 'day' THEN
child_table := child_table || to_char(p_time_value, 'yyyymmdd');
child_time_from := date_trunc('day', p_time_value);
child_time_to := date_trunc('day',
p_time_value + interval '1 day');
WHEN 'hour' THEN
child_table := child_table ||
to_char(p_time_value, 'yyyymmdd_hh24');
child_time_from := date_trunc('hour', p_time_value);
child_time_to := date_trunc('hour',
p_time_value + interval '1 hour');
WHEN 'minute' THEN
child_table := child_table ||
to_char(p_time_value, 'yyyymmdd_hh24mi');
child_time_from := date_trunc('minute', p_time_value);
child_time_to := date_trunc('minute',
p_time_value + interval '1 minute');
ELSE
RAISE 'incorrect variable p_time_range %s', p_time_range;
END CASE;
SELECT count(*) INTO v_count
FROM pg_catalog.pg_tables
WHERE schemaname = p_schema AND tablename = child_table;
IF v_count != 0 THEN
child_table_status := 'exist';
ELSE
child_table_status := 'noexist';
END IF;
-- Returns:
-- child_table <API key>
-- child_table_status exist/noexist
-- child_list p_list_value
RETURN NEXT;
RETURN;
END;
$body$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION prttn_tools.<API key>(CHARACTER VARYING,
CHARACTER VARYING, CHARACTER VARYING, CHARACTER VARYING, CHARACTER VARYING,
CHARACTER VARYING, TIMESTAMP WITHOUT TIME ZONE) OWNER TO postgres;
-- Function: prttn_tools.part_list_time_add(
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- TIMESTAMP WITHOUT TIME ZONE,
-- BOOLEAN)
CREATE OR REPLACE FUNCTION prttn_tools.part_list_time_add(
p_schema CHARACTER VARYING,
p_table CHARACTER VARYING,
p_list_column CHARACTER VARYING,
p_list_value CHARACTER VARYING,
p_time_column CHARACTER VARYING,
p_time_range CHARACTER VARYING,
p_time_value TIMESTAMP WITHOUT TIME ZONE,
p_with_rule BOOLEAN)
RETURNS TABLE(
child_table CHARACTER VARYING,
child_table_status CHARACTER VARYING,
child_list CHARACTER VARYING,
child_time_from TIMESTAMP WITHOUT TIME ZONE,
child_time_to TIMESTAMP WITHOUT TIME ZONE
) AS
$body$
DECLARE
v_count INTEGER;
v_check_condition CHARACTER VARYING;
v_ddl_text CHARACTER VARYING;
BEGIN
-- p_schemaname.p_tablename.p_list_column
-- p_schemaname.p_tablename.p_time_column(timestamp without time zone)
SELECT count(*) INTO v_count
FROM information_schema.tables t
JOIN information_schema.columns c
ON t.table_catalog = c.table_catalog
AND t.table_schema = c.table_schema
AND t.table_name = c.table_name
WHERE t.table_catalog::name = current_database() AND
t.table_type = 'BASE TABLE' AND
t.table_schema = p_schema AND
t.table_name = p_table AND
(c.column_name = p_list_column OR
(c.column_name = p_time_column AND
c.data_type = 'timestamp without time zone'
)
);
IF v_count != 2 THEN
RAISE 'incorrect master table %', p_schema || '.' || p_table;
END IF;
SELECT r.child_table, r.child_table_status, r.child_list, r.child_time_from,
r.child_time_to INTO child_table, child_table_status, child_list,
child_time_from, child_time_to
FROM prttn_tools.<API key>(p_schema, p_table, p_list_column,
p_list_value, p_time_column, p_time_range, p_time_value) r;
v_check_condition := '(' ||
p_list_column || ' = ' || quote_literal(p_list_value) || ' AND ' ||
p_time_column || ' >= ' || quote_literal(child_time_from) || ' AND ' ||
p_time_column || ' < ' || quote_literal(child_time_to) || ')';
IF child_table_status = 'noexist' THEN
SELECT prttn_tools.create_child_table(p_schema, p_table,
p_schema, child_table, v_check_condition, p_with_rule)
INTO child_table_status;
END IF;
-- Returns:
-- child_table <API key>
-- child_table_status exist/created
-- child_list p_list_value
RETURN NEXT;
RETURN;
END;
$body$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION prttn_tools.part_list_time_add(CHARACTER VARYING,
CHARACTER VARYING, CHARACTER VARYING, CHARACTER VARYING, CHARACTER VARYING,
CHARACTER VARYING, TIMESTAMP WITHOUT TIME ZONE, BOOLEAN) OWNER TO postgres;
-- Function: prttn_tools.<API key>(
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- BOOLEAN)
CREATE OR REPLACE FUNCTION prttn_tools.<API key>(
p_schema CHARACTER VARYING,
p_table CHARACTER VARYING,
p_list_column CHARACTER VARYING,
p_time_column CHARACTER VARYING,
p_time_range CHARACTER VARYING,
p_autocreate BOOLEAN)
RETURNS TABLE(
trigger_function CHARACTER VARYING,
trigger_status CHARACTER VARYING
) AS
$body$
DECLARE
v_sql TEXT;
BEGIN
trigger_function := p_schema || '.' || p_table || '_part_ins_tr';
v_sql := 'CREATE OR REPLACE FUNCTION ' || trigger_function || '()
RETURNS TRIGGER AS
$trigger$
DECLARE
-- this function is automatically created
-- from prttn_tools.<API key>
-- ' || now() || '
v_child_table CHARACTER VARYING;
<API key> CHARACTER VARYING;
BEGIN
SELECT child_table, child_table_status
INTO v_child_table, <API key>
FROM prttn_tools.<API key>(
' || quote_literal(p_schema) || ',
' || quote_literal(p_table) || ',
' || quote_literal(p_list_column) || ',
new.' || p_list_column || '::CHARACTER VARYING,
' || quote_literal(p_time_column) || ',
' || quote_literal(p_time_range) || ',
new.' || p_time_column || '::TIMESTAMP WITHOUT TIME ZONE);';
IF p_autocreate THEN
v_sql := v_sql || '
IF <API key> = ''noexist'' THEN
SELECT child_table, child_table_status
INTO v_child_table, <API key>
FROM prttn_tools.part_list_time_add(
' || quote_literal(p_schema) || ',
' || quote_literal(p_table) || ',
' || quote_literal(p_list_column) || ',
new.' || p_list_column || '::CHARACTER VARYING,
' || quote_literal(p_time_column) || ',
' || quote_literal(p_time_range) || ',
new.' || p_time_column || '::TIMESTAMP WITHOUT TIME ZONE,
FALSE);
END IF;';
END IF;
v_sql := v_sql || '
IF <API key> = ''exist'' OR <API key> = ''created''
THEN
EXECUTE ''INSERT INTO ' || p_schema || '.'' || v_child_table ||
'' SELECT ( ('' || quote_literal(new) ||
'')::' || p_schema || '.' || p_table || ' ).*'';
ELSE
RAISE ''child table % not exist'', v_child_table;
END IF;
RETURN NULL;
END;
$trigger$
LANGUAGE plpgsql VOLATILE
COST 100;
CREATE TRIGGER ' || p_table || '_part_ins_tr
BEFORE INSERT
ON ' || p_schema || '.' || p_table || '
FOR EACH ROW
EXECUTE PROCEDURE ' || trigger_function || '();';
EXECUTE v_sql;
trigger_status := 'created';
RETURN NEXT;
RETURN;
END;
$body$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION prttn_tools.<API key>(CHARACTER VARYING,
CHARACTER VARYING, CHARACTER VARYING, CHARACTER VARYING, CHARACTER VARYING,
BOOLEAN) OWNER TO postgres;
-- Function: prttn_tools.part_merge(
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING,
-- CHARACTER VARYING)
CREATE OR REPLACE FUNCTION prttn_tools.part_merge(
p_parent_schema CHARACTER VARYING,
p_parent_table CHARACTER VARYING,
p_child_schema CHARACTER VARYING,
p_child_table CHARACTER VARYING)
RETURNS TEXT AS
$body$
DECLARE
v_count BIGINT;
v_sql_text CHARACTER VARYING;
BEGIN
SELECT count(*) INTO v_count
FROM information_schema.tables t1
WHERE t1.table_catalog::name = current_database()
AND t1.table_type = 'BASE TABLE'
AND t1.table_schema = p_parent_schema
AND t1.table_name = p_parent_table;
IF v_count != 1 THEN
RAISE 'parent table not found: %', p_parent_schema || '.' ||
p_parent_table;
END IF;
SELECT count(*) INTO v_count
FROM information_schema.tables t1
WHERE t1.table_catalog::name = current_database()
AND t1.table_type = 'BASE TABLE'
AND t1.table_schema = p_child_schema
AND t1.table_name = p_child_table;
IF v_count != 1 THEN
RAISE 'child table not found: %', p_child_schema || '.' ||
p_child_table;
END IF;
SELECT count(*) INTO v_count FROM (
SELECT c1.column_name, c1.data_type
FROM information_schema.tables t1
JOIN information_schema.columns c1
ON t1.table_catalog = c1.table_catalog
AND t1.table_schema = c1.table_schema
AND t1.table_name = c1.table_name
WHERE t1.table_catalog::name = current_database()
AND t1.table_type = 'BASE TABLE'
AND t1.table_schema = p_parent_schema
AND t1.table_name = p_parent_table
EXCEPT
SELECT c2.column_name, c2.data_type
FROM information_schema.tables t2
JOIN information_schema.columns c2
ON t2.table_catalog = c2.table_catalog
AND t2.table_schema = c2.table_schema
AND t2.table_name = c2.table_name
WHERE t2.table_catalog::name = current_database()
AND t2.table_type = 'BASE TABLE'
AND t2.table_schema = p_child_schema
AND t2.table_name = p_child_table
) tt;
IF v_count != 0 THEN
RAISE 'tables are not compatible: %', p_parent_schema || '.' ||
p_parent_table || ', ' || p_child_schema || '.' || p_child_table;
END IF;
v_sql_text := 'INSERT INTO ' || p_parent_schema || '.' || p_parent_table ||
' SELECT * FROM ' || p_child_schema || '.' || p_child_table;
EXECUTE v_sql_text;
v_sql_text := 'DROP TABLE ' || p_child_schema || '.' || p_child_table;
EXECUTE v_sql_text;
RETURN 'ok';
END;
$body$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION prttn_tools.part_merge(CHARACTER VARYING, CHARACTER VARYING,
CHARACTER VARYING, CHARACTER VARYING) OWNER TO postgres;
|
layout: post
status: publish
published: true
title: WCF Metadata Publication and Others
author:
display_name: Tomas Restrepo
login: tomasr
email: tomas@winterdom.com
url: http://winterdom.com/
author_login: tomasr
author_email: tomas@winterdom.com
author_url: http://winterdom.com/
wordpress_id: 68
wordpress_url: http://winterdom.com/2006/10/<API key>
date: '2006-10-19 18:11:32 +0000'
date_gmt: '2006-10-19 18:11:32 +0000'
categories:
- WCF
- WinFX
- Web Services
tags: []
comments: []
<p><!--start_raw
<p><a href="http://blogs.msdn.com/ralph.squillace/">Ralph Squillace</a> posted an <a href="http://blogs.msdn.com/ralph.squillace/archive/2006/10/19/<API key>.aspx">walkthrough entry</a> of how metadata publication (MEX + WSDL) is enabled in Windows Communication Foundation. Besides discussing the configuration aspects, he also briefly touches on how those aspects affect the runtime behavior. </p>
<p>This came at a perfect time for me because I spent a few hours yesterday going over the System.ServiceModel assemblies with reflector trying to understand how it was that the metadata endpoints get hooked up to a service, so this helps a bit. I still need to look closely at a few issues before I understand what's going on well enough to try at something similar I've been wanting to play with...</p>
<p>Ralph has also been writing some samples about Sessionless Duplex Services <a href="http://blogs.msdn.com/ralph.squillace/archive/2006/10/10/<API key>.-<API key>.aspx">here</a> and <a href="http://blogs.msdn.com/ralph.squillace/archive/2006/10/19/<API key>.aspx">here</a> which are quite interesting as well.</p>
<div class="<API key>" id="<API key>:<API key>" contenteditable="false" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<p><span class="TagSite">Technorati:</span> <a href="http://technorati.com/tag/Windows+Communication+Foundation" rel="tag" class="tag">Windows Communication Foundation</a>, <a href="http://technorati.com/tag/WCF" rel="tag" class="tag">WCF</a><br /><!-- StartInsertedTags: Windows Communication Foundation, WCF :EndInsertedTags --></p></div><!--end_raw--></p>
|
layout: angular
title: "Angularjs $scope"
date: 2016-01-01
author: Hao
category: blog
description: Angularjs $scope angularjs github wiki stackflow...
JavaScript Prototypal Inheritance
javascriptangularjs scope
`parentScope`aString, aNumber, anArray, anObject, aFunction 5 `childScope``parentScope``childScope``parentScope`JavaScriptchild scope`parentScope`
JavaScript Prototypal Inheritance
<iframe src="http://jsfiddle.net/hchen1202/e9257kt1/embedded/" style="width: 100%; height: 300px;"></iframe>
String & Num
childScope.aString = 'child string'
The prototype chain is not consulted, and a new aString property is added to the childScope. This new property hides/shadows the parentScope property with the same name.
Array & Object & Funciton
childScope.anArray[1] = 22
childScope.anObject.property1 = 'child prop1'
The prototype chain is consulted because the objects (anArray and anObject) are not found in the childScope. The objects are found in the parentScope, and the property values are updated on the original objects. No new properties are added to the childScope; no new objects are created.
Angular Scope Inheritance
Angularjs
* `Scope``inherit prototypically`: ng-repeat, ng-include, ng-swith, ng-view, ng-controller, directive with scope: true, directive with transclude: true.
* `isolate scope`directive with scope: {...}
* `default directive` `new scope`, `directive` scope: false
# ng-include
ng-include`child scope`, prototypically inherit from `parent scope`.
<iframe style="width: 100%; height: 300px;" src="http://jsfiddle.net/hchen1202/z5q33kg6/embedded/" ></iframe>
inputhide/shaddow parent scope. template
<input ng-model="$parent.myPrimitive">
`child property`, `prototypal inheritance`
# ng-switch
ng-swithng-include `two-way binding`, use $parent, or change the model to be an object and then bind to a property of that object.
# ng-repeat
ng-repeatitem`ng-repeat`scope`parent scope` prototypically inherit, item`child scope`
<iframe style="width: 100%; height: 300px;" src="http://jsfiddle.net/hchen1202/5ye3amjd/1/embedded/" ></iframe>
# ng-controller
ng-controllercontrollershare data`service`
|
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Video Player</title>
<link rel="stylesheet" type="text/css" href="css/styles.css" />
</head>
<body>
<div class="srt"></div>
<div style="float:right; padding: 10px;">Events: <ol class="events" style="height: 390px; overflow: scroll;"></ol></div>
<div id="video-container"></div>
<div id="<API key>"></div>
<hr />
<div>Current time/ Duration: <span class="time"></span>/<span class="duration"></span></div>
<div>Speed: <span class="speed"></span></div>
<div>Muted: <span class="mute"></span></div>
<div>Volume level: <span class="volume"></span></div>
<div>Quality: <span class="quality"></span></div>
<!--script type="text/javascript" src="../build/VideoPlayer.min.js"></script
<script>
var requirejs = {
baseUrl: 'js/',
paths: {
'jquery': '../../lib/1.7.2.jquery.min'
}
}
</script>
<script src="../lib/require.js"></script>
<script type="text/javascript">
// new s2js.Video('HTML5', $('#video-container'), {
// sources: [
// volume: 0.5,
// playbackRate: 2.0,
// autoplay: false,
// controls: true,
// loop: true,
// muted: true,
</script>
<script type="text/javascript">
require([
'utils', 'player', 'controls/vcr', 'controls/play_button',
'controls/mute_button', 'controls/progress_slider', 'controls/transcripts', 'components/menu'
], function (Utils, Video, VCR, PlayButton, MuteButton, ProgressSlider, Transcripts, Menu) {
p = new Video('Youtube', $('#<API key>'), {
videoId: 'M7lc1UVf-VE',
volume: 0.75,
playbackRate: 1.0,
autoplay: 0,
controls: 1,
loop: 1,
muted: true,
plugins: [
VCR,
PlayButton,
MuteButton,
ProgressSlider,
Transcripts,
Menu
]
});
var d = document.getElementById('s2js-player-0');
var updateEvent = function (event) {
$('.events').append('<li>' + event + '</li>')
};
d.addEventListener('timeupdate', function () {
$('.time').html(Utils.Utils.secondsToTimecode(p.currentTime));
});
d.addEventListener('durationchange', function () {
$('.duration').html(Utils.Utils.secondsToTimecode(p.duration));
});
d.addEventListener('volumechange', function () {
$('.volume').html(p.volume);
$('.mute').html(p.muted.toString());
});
d.addEventListener('ratechange', function () {
$('.speed').html(p.playbackRate);
});
d.addEventListener('qualitychange', function () {
$('.quality').html(p.playbackQuality);
});
['canplay', 'ratechange', 'loadedmetadata', 'loadeddata', 'durationchange',
'ended', 'play', 'playing', 'pause', 'progress', 'qualitychange', 'error',
'volumechange'
].forEach(function (eventName) {
d.addEventListener(eventName, function () {
updateEvent(eventName);
}, false);
});
});
</script>
</body>
</html>
|
#ifndef GAME_H
#define GAME_H
#include <array>
class Game
{
public:
//Standard Con/Destructors
Game(); //Initialize the board.
~Game(); //Not sure if I need this, but it's here in case
//Are we playing the game?
bool isRunning = true;
//The easiest way I could implement stalemate
//detection with my limited knowledge.
//Is the board completely full, thereby causing a stalemate?
bool isStalemate = false;
//Board specific variables.
static const int MAX_ROWS = 3; //Bounds for our board array
static const int MAX_COLS = 3;
//Return the bounds of our board.
//Useful for, say, only allowing the player
//to make a move within board boundaries
//when player data is in a different class.
int get_max_rows() { return MAX_ROWS; }
int get_max_cols() { return MAX_COLS; }
//Return our private piece variables for public use.
char get_piece_x() { return pieceX; }
char get_piece_o() { return pieceO; }
//Print the board in its current state
void print_board();
//Print our help board. This board does not change.
void print_help_board();
//Check for an overlap, IE placing an X on top of an O.
//Returns false if there is an overlap. The space is invalid.
//Does NOT check for input sanity or bounds!!! This is done
//in some other class, likely going to be the player class.
bool is_valid_space(int xPosition, int yPosition);
//Check for every possible win using piece as the winning piece.
//For example, check if O is the winning piece.
//Returns true on a win, false otherwise.
bool is_victory(char piece);
//Allow a different function/class/file/whatever to acces the board.
//This is done to allow placement of pieces to the board without
//the risk of accidently trashing it. is_valid_space() should always
//be called first, and it likely will be called in this function.
//Returns false if it cannot place the piece.
bool add_new_piece(int xPosition, int yPosition, char piece);
//Removes all pieces from the board, re-sets the score (if I chose to
//implement scoring) to zero. This is used in preperation for a new game.
void reset();
//Simple random number generator, with bounds.
int get_random_num(int bound = 0);
//Place a piece on the board based on user input.
int make_move(int input, char piece);
private:
//Three win calcualtion functions to make my job easier.
//Check for vertical, horizontal, or diagonal wins independently.
//Used by is_victory() to simplify win checking even more.
bool is_win_vertical(char piece);
bool is_win_horizontal(char piece);
bool is_win_diagonal(char piece);
//char board[MAX_ROWS][MAX_COLS]; //The board itself
std::array<std::array<char, MAX_ROWS>, MAX_COLS> board; //The board itself
//These make setting up the board/player(s)/etc MUCH easier.
char pieceX = 'X'; //The player class assigns these variables to a local var.
char pieceO = 'O'; //for example, something like: player.set_piece(game.pieceX);
char pieceNeutral = '-'; //The blank or empty piece.
//Settings for making a help board. Shows the player which number corresponds
//to the tile he/she wants. Below are variables for that.
int helpBoard[MAX_ROWS][MAX_COLS];
};
#endif
|
// <API key>.h
// HNBKitDemo
#import "<API key>.h"
@interface <API key> : <API key>
@end
|
<!
~ Copyright (c) 2017. MIT-license for Jari Van Melckebeke
~ Note that there was a lot of educational work in this project,
~ this project was (or is) used for an assignment from Realdolmen in Belgium.
~ Please just don't abuse my work
<html>
<head>
<meta charset="utf-8">
<script src="esl.js"></script>
<script src="config.js"></script>
</head>
<body>
<style>
html, body, #main {
width: 100%;
height: 100%;
}
</style>
<div id="main"></div>
<script>
require([
'echarts',
'echarts/chart/scatter',
'echarts/component/legend',
'echarts/component/polar'
], function (echarts) {
var chart = echarts.init(document.getElementById('main'), null, {
renderer: 'canvas'
});
var data1 = [];
var data2 = [];
var data3 = [];
for (var i = 0; i < 100; i++) {
data1.push([Math.random() * 5, Math.random() * 360]);
data2.push([Math.random() * 5, Math.random() * 360]);
data3.push([Math.random() * 10, Math.random() * 360]);
}
chart.setOption({
legend: {
data: ['scatter', 'scatter2', 'scatter3']
},
polar: {
},
angleAxis: {
type: 'value'
},
radiusAxis: {
axisAngle: 0
},
series: [{
coordinateSystem: 'polar',
name: 'scatter',
type: 'scatter',
symbolSize: 10,
data: data1
}, {
coordinateSystem: 'polar',
name: 'scatter2',
type: 'scatter',
symbolSize: 10,
data: data2
}, {
coordinateSystem: 'polar',
name: 'scatter3',
type: 'scatter',
symbolSize: 10,
data: data3
}]
});
})
</script>
</body>
</html>
|
# Contributing
I explicitly welcome contributions from people who have never contributed to open-source before: we were all beginners once!
I can help build on a partially working pull request with the aim of getting it merged.
I am also actively seeking to diversify our contributors and especially welcome contributions from women from all backgrounds and people of color. <sup>[1](#References)</sup>
If you're interested in contributing, fork this repo and create a pull request.
Please include a short descriptive link to your code in the readme, and order the link alphpabetically by file name.
Include a description of each data structure or algorithm at the top of the file, and if you feel that your code needs further explanation,
you can include a more detailed summary in the Data Structures or Algorithms subfolder's readme.
Please follow the [Ruby](https:
Tests are recommended, but optional.
If you're looking for inspiration, I'd love to have a:
+ [Priority Queue](https://en.wikipedia.org/wiki/Priority_queue)
+ [Valid Sudoku Board](https://en.wikipedia.org/wiki/<API key>)
+ [Sorting Algorithms](https://en.wikipedia.org/wiki/Sorting_algorithm#<API key>)
+ [A* Search Algorithm](https://en.wikipedia.org/wiki/A*_search_algorithm)
+ [Knuth-Morris-Pratt Algorithm](https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm)
+ [Heap](https://en.wikipedia.org/wiki/Heap_\(data_structure\))
+ [Bloom Filter](https://en.wikipedia.org/wiki/Bloom_filter)
+ [Or refactor one of these files!](/REFACTOR.md)
## Attribution
1. I used and modified [Homebrew's](https://github.com/Homebrew/brew#contributing) welcoming contributing section.
|
Alchemy sentiment analysis: <SHA1-like>
Africa Is Talking: <SHA256-like>
|
module.exports = {
project: {
server: {
basePath: '',
ip: '0.0.0.0',
request: {
sesskey: 'sid',
limit: 5000,
parameters: 60
},
render: 'swig',
path: {
routes: 'app/routes',
views: 'app/views',
public: 'public/',
docs: false
},
views: {
extension: 'swig',
errors: 'errors/'
}
}
},
environment: {
server: {
debug: true,
host: 'localhost',
port: 3000,
request: {
secret: new Date().getTime() + '' + Math.random(),
cors: true,
geolocation: false
},
views: {
cache: false
}
}
}
};
|
<?php
namespace RedMedica\ConsultasBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use RedMedica\ConsultasBundle\Entity\Article;
use FOS\ElasticaBundle\Configuration\Search;
/**
* Category
*
* @ORM\Table(name="category")
* @ORM\Entity()
* @Search(repositoryClass="RedMedica\ConsultasBundle\Entity\SearchRepository\CategoryRepository")
*/
class Category
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* @var string
*
* @ORM\Column(name="label", type="string", length=250, nullable=false)
*/
protected $label;
/**
* @var Doctrine\Common\Collections\ArrayCollection
*
* @ORM\OneToMany(targetEntity="RedMedica\ConsultasBundle\Entity\Article", mappedBy="category")
*/
protected $articles;
public function __construct()
{
$this->articles = new ArrayCollection();
}
public function __toString()
{
return $this->label;
}
public function getId()
{
return $this->id;
}
public function setLabel($label)
{
$this->label = $label;
return $this;
}
public function getLabel()
{
return $this->label;
}
public function addArticle(Article $article)
{
$this->articles->add($article);
return $this;
}
public function setArticles($articles)
{
$this->articles = $articles;
return $this;
}
public function getArticles()
{
return $this->articles;
}
}
|
import React from "react";
import styled from 'styled-components'
import Link from './link';
const nextArrow = "/icons/next-arrow.png";
const prevArrow = "/icons/prev-arrow.png";
const PatternLink = styled.span`
width: 100%;
display: flex;
flex-direction: column;
padding: 1em;
float: ${props => props.previous ? 'left' : 'right'}
@media(min-width: $width-tablet) {
width: auto;
}
`;
const ImageContainer = styled.span`
height: 50px;
`;
const Image = styled.img`
height: 100%;
background-color: white;
float: ${props => props.previous ? 'right' : 'left'}
`;
const ArrowContainer = styled.div`
display: flex;
flex-direction: ${props => props.previous ? 'row-reverse' : 'row'};
align-items: center;
`;
const Name = styled.p`
padding: 10px 0;
`;
const Arrow = styled.img`
height: 10px;
flex-direction: row-reverse;
padding: ${props => props.previous ? '0 10px 0 0' : '0 0 0 10px'};
`;
const NextPrevPattern = ({pattern, direction}) => {
const previous = direction === "previous"
return (
<Link href={pattern.url}>
<PatternLink previous={previous}>
<ImageContainer>
<Image previous={previous} src={pattern.painted || pattern.lineDrawing} />
</ImageContainer>
<ArrowContainer previous={previous}>
<Name>{pattern.name}</Name>
{
(direction === "next") &&
<Arrow src={nextArrow}/>
}
{
(direction === "previous") &&
<Arrow previous src={prevArrow} />
}
</ArrowContainer>
</PatternLink>
</Link>
)
};
export default NextPrevPattern;
|
#ifndef <API key>
#define <API key>
#include "net.h"
#include "validationinterface.h"
/** Default for -maxorphantx, maximum number of orphan transactions kept in memory */
static const unsigned int <API key> = 100;
/** Expiration time for orphan transactions in seconds */
static const int64_t <API key> = 20 * 60;
/** Minimum time between orphan transactions expire time checks in seconds */
static const int64_t <API key> = 5 * 60;
/** Default number of orphan+recently-replaced txn to keep around for block reconstruction */
static const unsigned int <API key> = 100;
/** Register with a network node to receive its signals */
void RegisterNodeSignals(CNodeSignals& nodeSignals);
/** Unregister a network node */
void <API key>(CNodeSignals& nodeSignals);
class PeerLogicValidation : public <API key> {
private:
CConnman* connman;
public:
PeerLogicValidation(CConnman* connmanIn);
virtual void SyncTransaction(const CTransaction& tx, const CBlockIndex* pindex, int nPosInBlock);
virtual void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload);
virtual void BlockChecked(const CBlock& block, const CValidationState& state);
virtual void NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock);
};
struct CNodeStateStats {
int nMisbehavior;
int nSyncHeight;
int nCommonHeight;
std::vector<int> vHeightInFlight;
};
/** Get statistics from node state */
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats);
/** Increase a node's misbehavior score. */
void Misbehaving(NodeId nodeid, int howmuch);
/** Process protocol messages received from a given node */
bool ProcessMessages(CNode* pfrom, CConnman& connman, std::atomic<bool>& interrupt);
/**
* Send queued protocol messages to be sent to a give node.
*
* @param[in] pto The node which we are sending messages to.
* @param[in] connman The connection manager for that node.
* @param[in] interrupt Interrupt condition for processing threads
* @return True if there is more work to be done
*/
bool SendMessages(CNode* pto, CConnman& connman, std::atomic<bool>& interrupt);
#endif // <API key>
|
# $Header: svn://svn/SWM/trunk/web/Reports/<API key>.pm 8251 2013-04-08 09:00:53Z rlee $
package Reports::<API key>;
use strict;
use lib ".";
use <API key>;
use Reports::ReportAdvanced;
our @ISA =qw(Reports::ReportAdvanced);
use strict;
sub _getConfiguration {
my $self = shift;
my $currentLevel = $self->{'EntityTypeID'} || 0;
my $Data = $self->{'Data'};
my $SystemConfig = $self->{'SystemConfig'};
my $clientValues = $Data->{'clientValues'};
my $CommonVals = getCommonValues(
$Data,
{
MYOB => 1,
},
);
my $txt_Clr = $Data->{'SystemConfig'}{'txtCLR'} || 'Clearance';
my %config = (
Name => 'Transactions Sold Report',
StatsReport => 0,
MemberTeam => 0,
ReportEntity => 3,
ReportLevel => 0,
Template => 'default_adv',
TemplateEmail => 'default_adv_CSV',
DistinctValues => 1,
SQLBuilder => \&SQLBuilder,
DefaultPermType => 'NONE',
Fields => {
intPaymentType=> [
'Payment Type',
{
active=>1,
displaytype=>'lookup',
fieldtype=>'dropdown',
dropdownoptions => \%Defs::paymentTypes,
allowsort=>1,
dbfield=>'TL.intPaymentType'
}
],
strTXN=> [
'PayPal Reference Number',
{
displaytype=>'text',
fieldtype=>'text',
dbfield=>'TL.strTXN',
active=>1
}
],
intLogID=> [
'Payment Log ID',
{
displaytype=>'text',
fieldtype=>'text',
dbfield=>'TL.intLogID',
allowgrouping=>1,
active=>1
}
],
dtSettlement=> [
'Settlement Date',
{
active=>1,
displaytype=>'date',
fieldtype=>'datetime',
allowsort=>1,
dbformat=>' DATE_FORMAT(dtSettlement,"%d/%m/%Y %H:%i")'
}
],
intAmount => [
'Total Amount Paid',
{
displaytype=>'currency',
fieldtype=>'text',
allowsort=>1,
dbfield=>'TL.intAmount',
active=>1
}
],
SplitAmount=> [
'Split Amount',
{
displaytype=>'currency',
fieldtype=>'text',
allowsort=>1,
total=>1,
active=>1
}
],
SplitLevel=> [
'Split Level',
{
displaytype=>'text',
fieldtype=>'text',
allowsort=>1,
active=>1
}
],
PaymentFor=> [
'Payment For',
{
active=>1,
displaytype=>'text',
fieldtype=>'text',
allowsort => 1
}
],
intExportBankFileID=> [
'PayPal Distribution ID',
{
displaytype=>'text',
fieldtype=>'text',
dbfield=>'<API key>'
}
],
intMyobExportID=> [
'SP Invoice Run',
{
displaytype=>'lookup',
fieldtype=>'dropdown',
dropdownoptions => $CommonVals->{'MYOB'}{'Values'},
active=>1,
dbfield=>'intMyobExportID'
}
],
dtRun=> [
'Date Funds Received',
{
displaytype=>'date',
fieldtype=>'date',
allowsort=>1,
dbformat=>' DATE_FORMAT(dtRun,"%d/%m/%Y")',
allowgrouping=>1,
sortfield=>'TL.dtSettlement'
}
],
},
Order => [qw(
intLogID
intPaymentType
strTXN
intAmount
dtSettlement
PaymentFor
SplitLevel
SplitAmount
intMyobExportID
)],
OptionGroups => {
default => ['Details',{}],
},
Config => {
FormFieldPrefix => 'c',
FormName => 'txnform_',
EmailExport => 1,
limitView => 5000,
EmailSenderAddress => $Defs::admin_email,
SecondarySort => 1,
RunButtonLabel => 'Run Report',
},
);
$self->{'Config'} = \%config;
}
sub SQLBuilder {
my($self, $OptVals, $ActiveFields) =@_ ;
my $currentLevel = $self->{'EntityTypeID'} || 0;
my $intID = $self->{'EntityID'} || 0;
my $Data = $self->{'Data'};
my $clientValues = $Data->{'clientValues'};
my $SystemConfig = $Data->{'SystemConfig'};
my $from_levels = $OptVals->{'FROM_LEVELS'};
my $from_list = $OptVals->{'FROM_LIST'};
my $where_levels = $OptVals->{'WHERE_LEVELS'};
my $where_list = $OptVals->{'WHERE_LIST'};
my $current_from = $OptVals->{'CURRENT_FROM'};
my $current_where = $OptVals->{'CURRENT_WHERE'};
my $select_levels = $OptVals->{'SELECT_LEVELS'};
my $sql = '';
{ #Work out SQL
my $clubWHERE = $currentLevel == $Defs::LEVEL_CLUB
? qq[ AND ML.intClubID = $intID ]
: '';
$sql = qq[
SELECT DISTINCT
TL.intLogID,
TL.intAmount,
TL.strTXN,
TL.intPaymentType,
ML.intLogType,
ML.intEntityType,
ML.intMyobExportID,
dtSettlement,
IF(T.intTableType=$Defs::LEVEL_PERSON, CONCAT(M.strLocalSurname, ", ", M.strLocalFirstname), Entity.strLocalName) as PaymentFor,
SUM(ML.curMoney) as SplitAmount,
IF(ML.intEntityType = $Defs::LEVEL_NATIONAL, 'National Split',
IF(ML.intEntityType = $Defs::LEVEL_STATE, 'State Split',
IF(ML.intEntityType = $Defs::LEVEL_REGION, 'Region Split',
IF(ML.intEntityType = $Defs::LEVEL_ZONE, 'Zone Split',
IF(ML.intEntityType = $Defs::LEVEL_CLUB, 'Club Split',
IF((ML.intEntityType = 0 AND intLogType IN (2,3)), 'Fees', '')
)
)
)
)
) as SplitLevel
FROM
tblTransLog as TL
INNER JOIN tblMoneyLog as ML ON (
ML.intTransLogID = TL.intLogID
AND ML.intLogType IN ($Defs::ML_TYPE_SPMAX, $Defs::ML_TYPE_LPF, $Defs::ML_TYPE_SPLIT)
)
LEFT JOIN tblTransactions as T ON (
T.intTransactionID = ML.intTransactionID
)
LEFT JOIN tblPerson as M ON (
M.intPersonID = T.intID
AND T.intTableType = $Defs::LEVEL_PERSON
)
LEFT JOIN tblEntity as Entity ON (
Entity.intEntityID = T.intID
AND T.intTableType = $Defs::LEVEL_PERSON
)
LEFT JOIN tblRegoForm as RF ON (
RF.intRegoFormID= TL.intRegoFormID
)
WHERE TL.intRealmID = $Data->{'Realm'}
$clubWHERE
$where_list
GROUP BY TL.intLogID
];
return ($sql,'');
}
}
1;
|
#!/usr/bin/node --harmony
'use strict'
const noble = require('noble'),
program = require('commander')
program
.version('0.0.1')
.option('-p, --prefix <integer>', 'Manufacturer identifier prefixed to all fan commands', parseInt)
.option('-t, --target [mac]', 'MAC address of devices to target', function(val){ return val.toLowerCase() })
.option('-s, --service <uuid>', 'UUID of fan controller BLE service')
.option('-w, --write <uuid>', 'UUID of fan controller BLE write characteristic')
.option('-n, --notify <uuid>', 'UUID of fan controller BLE notify characteristic')
class FanRequest {
writeInto(buffer) {
throw new TypeError('Must override method')
}
toBuffer() {
var buffer
if (program.prefix > 0) {
buffer = new Buffer(13)
buffer.writeUInt8(program.prefix)
this.writeInto(buffer.slice(1))
} else {
buffer = new Buffer(12)
this.writeInto(buffer)
}
const checksum = buffer.slice(0, buffer.length - 1).reduce(function(a, b){
return a + b
}, 0) & 255
buffer.writeUInt8(checksum, buffer.length - 1)
return buffer
}
}
class FanGetStateRequest extends FanRequest {
writeInto(buffer) {
buffer.fill(0)
buffer.writeUInt8(160)
}
}
Math.clamp = function(number, min, max) {
return Math.max(min, Math.min(number, max))
}
class <API key> extends FanRequest {
constructor(isOn, level) {
super()
this.on = isOn ? 1 : 0
this.level = Math.clamp(level, 0, 100)
}
writeInto(buffer) {
buffer.fill(0)
buffer.writeUInt8(161)
buffer.writeUInt8(255, 4)
buffer.writeUInt8(100, 5)
buffer.writeUInt8((this.on << 7) | this.level, 6)
buffer.fill(255, 7, 10)
}
}
class <API key> extends FanRequest {
constructor(level) {
super()
this.level = Math.clamp(level, 0, 3)
}
writeInto(buffer) {
buffer.fill(0)
buffer.writeUInt8(161)
buffer.writeUInt8(this.level, 4)
buffer.fill(255, 5, 10)
}
}
class FanResponse {
static fromBuffer(buffer) {
if (program.prefix > 0) {
buffer = buffer.slice(1)
}
if (buffer.readUInt8(0) != 176) { return null }
const response = new FanResponse()
const windVelocity = buffer.readUInt8(2)
response.supportsFanReversal = (windVelocity & 0b00100000) != 0
response.maximumFanLevel = windVelocity & 0b00011111
const currentWindVelocity = buffer.readUInt8(4)
response.isFanReversed = (currentWindVelocity & 0b10000000) != 0
response.fanLevel = currentWindVelocity & 0b00011111
const currentBrightness = buffer.readUInt8(6)
response.lightIsOn = (currentBrightness & 0b10000000) != 0
response.lightBrightness = (currentBrightness & 0b01111111)
return response
}
}
// MARK: -
var command
program
.command('current')
.description('print current state')
.action(function(env, options) {
command = new FanGetStateRequest()
})
program
.command('fan')
.description('adjusts the fan')
.option('-l --level <size>', 'Fan speed', /^(off|low|medium|high)$/i, 'high')
.action(function(env, options) {
var level
switch (env.level) {
case 'low':
level = 1
break
case 'medium':
level = 2
break
case 'high':
level = 3
break
default:
level = 0
break
}
command = new <API key>(level)
})
program
.command('light <on|off>')
.description('adjusts the light')
.option('-l, --level <percent>', 'Light brightness', parseInt, 100)
.action(function(env, options) {
command = new <API key>(env !== 'off', options.level)
})
program.parse(process.argv);
if (!command) {
program.help();
}
if (!program.target) {
throw new Error('MAC address required')
}
const serviceUUID = program.service || '<API key>'
const writeUUID = program.write || '<API key>'
const notifyUUID = program.notify || '<API key>'
noble.on('stateChange', function(state) {
if (state === 'poweredOn') {
console.log('scanning.')
noble.startScanning([ serviceUUID ], false)
} else {
noble.stopScanning()
}
})
noble.on('discover', function(peripheral) {
console.log('found ' + peripheral.address)
if (peripheral.address !== program.target) { return }
noble.stopScanning()
explore(peripheral)
});
function bail(error) {
console.log('failed: ' + error);
process.exit(1)
}
function explore(peripheral) {
console.log('connecting.')
peripheral.once('disconnect', function() {
peripheral.removeAllListeners()
explore(peripheral)
})
peripheral.connect(function(error) {
if (error) { bail(error); }
peripheral.<API key>([ serviceUUID ], [ writeUUID, notifyUUID ], function(error, services, characteristics) {
if (error) { bail(error); }
var service = services[0]
var write = characteristics[0], notify = characteristics[1]
notify.on('data', function(data, isNotification) {
const response = FanResponse.fromBuffer(data)
if (response) {
console.log(response)
} else {
console.log('sent')
}
process.exit()
})
notify.subscribe(function(error) {
if (error) { bail(error); }
console.log('sending')
const buffer = command.toBuffer()
write.write(buffer, false, function(error){
if (error) { bail(error); }
})
})
})
})
}
|
layout: post
category: ""
tags: [zsh,fish,linux]
[TOC]
zsh yosemite bug?
Mac Yosemite ,,php,macport
zsh,,`zsh`100%cpu,macbook
,. ,,.
fish,shell,,..
fish.

> zsh,
>reply: Any chance that it's this issue with zsh-autosuggestions?
[](https://github.com/tarruda/zsh-autosuggestions/issues/24 )
zsh-autosuggestions .
fish
- Autosuggestions history,
- completions man
- `zsh`fish `autojump` [oh-my-fish](https://github.com/bpinto/oh-my-fishURL )
- `fish-config` fish
`zsh`,`fish`,`zsh`
`fish` ,,`zsh`.
[oh-my-zsh](https:
,fish.
[oh-my-fish](https://github.com/bpinto/oh-my-fishURL )
brew install fish
sudo vi /etc/shells /usr/local/bin/fish,
chsh -s /usr/local/bin/fish
git clone git://github.com/bpinto/oh-my-fish.git ~/.oh-my-fish
copy
cp ~/.oh-my-fish/templates/config.fish ~/.config/fish/config.fish
fish
- ~/config/fish/config.fish
set fish_plugins autojump bundler brew
set -xu PATH /usr/local/bin:$PATH
export `set -x`:
`set -x PATH /usr/local/bin $PATH`
-x : -export
-u : fish session
fish
fish ,
ruby
function rg
rails generate $argv
end
|
const HEX_SHORT = /^#([a-fA-F0-9]{3})$/;
const HEX = /^#([a-fA-F0-9]{6})$/;
function roundColors(obj, round) {
if (!round) return obj;
const o = {};
for (let k in obj) {
o[k] = Math.round(obj[k]);
}
return o;
}
function hasProp(obj, key) {
return obj.hasOwnProperty(key);
}
function isRgb(obj) {
return hasProp(obj, "r") && hasProp(obj, "g") && hasProp(obj, "b");
}
export default class Color {
static normalizeHex(hex) {
if (HEX.test(hex)) {
return hex;
} else if (HEX_SHORT.test(hex)) {
const r = hex.slice(1, 2);
const g = hex.slice(2, 3);
const b = hex.slice(3, 4);
return `#${r + r}${g + g}${b + b}`;
}
return null;
}
static hexToRgb(hex) {
const normalizedHex = this.normalizeHex(hex);
if (normalizedHex == null) {
return null;
}
const m = normalizedHex.match(HEX);
const i = parseInt(m[1], 16);
const r = (i >> 16) & 0xFF;
const g = (i >> 8) & 0xFF;
const b = i & 0xFF;
return { r, g, b };
}
static rgbToHex(rgb) {
const { r, g, b} = rgb;
const i = ((Math.round(r) & 0xFF) << 16) + ((Math.round(g) & 0xFF) << 8) + (Math.round(b) & 0xFF);
const s = i.toString(16).toLowerCase();
return `#${"000000".substring(s.length) + s}`;
}
static rgbToHsv(rgb, round = true) {
const { r, g, b } = rgb;
const min = Math.min(r, g, b);
const max = Math.max(r, g, b);
const delta = max - min;
const hsv = {};
if (max === 0) {
hsv.s = 0;
} else {
hsv.s = (delta / max * 1000) / 10;
}
if (max === min) {
hsv.h = 0;
} else if (r === max) {
hsv.h = (g - b) / delta;
} else if (g === max) {
hsv.h = 2 + (b - r) / delta;
} else {
hsv.h = 4 + (r - g) / delta;
}
hsv.h = Math.min(hsv.h * 60, 360);
hsv.h = hsv.h < 0 ? hsv.h + 360 : hsv.h;
hsv.v = ((max / 255) * 1000) / 10;
return roundColors(hsv, round);
}
static rgbToXyz(rgb, round = true) {
const r = rgb.r / 255;
const g = rgb.g / 255;
const b = rgb.b / 255;
const rr = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : r / 12.92;
const gg = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : g / 12.92;
const bb = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : b / 12.92;
const x = (rr * 0.4124 + gg * 0.3576 + bb * 0.1805) * 100;
const y = (rr * 0.2126 + gg * 0.7152 + bb * 0.0722) * 100;
const z = (rr * 0.0193 + gg * 0.1192 + bb * 0.9505) * 100;
return roundColors({ x, y, z }, round);
}
static rgbToLab(rgb, round = true) {
const xyz = Color.rgbToXyz(rgb, false);
let { x, y, z } = xyz;
x /= 95.047;
y /= 100;
z /= 108.883;
x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
const l = (116 * y) - 16;
const a = 500 * (x - y);
const b = 200 * (y - z);
return roundColors({ l, a, b }, round);
}
constructor(value) {
this.original = value;
if (isRgb(value)) {
this.rgb = value;
this.hex = Color.rgbToHex(value);
} else {
this.hex = Color.normalizeHex(value);
this.rgb = Color.hexToRgb(this.hex);
}
this.hsv = Color.rgbToHsv(this.rgb);
}
}
|
export { default } from 'ember-validation/components/<API key>';
|
.WeatherStations {
margin: 30px 30px 30px 30px;
}
.clear{
clear: both;
}
|
/*global window */
/*jshint bitwise:false */
/**
* @public
* @type {Object|null}
*/
var module;
/**
* API entry
* @public
* @param {function(Object)|Date|number} start the starting date
* @param {function(Object)|Date|number} end the ending date
* @param {number} units the units to populate
* @return {Object|number}
*/
var countdown = (
/**
* @param {Object} module CommonJS Module
*/
function(module) {
/*jshint smarttabs:true */
'use strict';
/**
* @private
* @const
* @type {number}
*/
var MILLISECONDS = 0x001;
/**
* @private
* @const
* @type {number}
*/
var SECONDS = 0x002;
/**
* @private
* @const
* @type {number}
*/
var MINUTES = 0x004;
/**
* @private
* @const
* @type {number}
*/
var HOURS = 0x008;
/**
* @private
* @const
* @type {number}
*/
var DAYS = 0x010;
/**
* @private
* @const
* @type {number}
*/
var WEEKS = 0x020;
/**
* @private
* @const
* @type {number}
*/
var MONTHS = 0x040;
/**
* @private
* @const
* @type {number}
*/
var YEARS = 0x080;
/**
* @private
* @const
* @type {number}
*/
var DECADES = 0x100;
/**
* @private
* @const
* @type {number}
*/
var CENTURIES = 0x200;
/**
* @private
* @const
* @type {number}
*/
var MILLENNIA = 0x400;
/**
* @private
* @const
* @type {number}
*/
var DEFAULTS = YEARS|MONTHS|DAYS|HOURS|MINUTES|SECONDS;
/**
* @private
* @const
* @type {number}
*/
var <API key> = 1000;
/**
* @private
* @const
* @type {number}
*/
var SECONDS_PER_MINUTE = 60;
/**
* @private
* @const
* @type {number}
*/
var MINUTES_PER_HOUR = 60;
/**
* @private
* @const
* @type {number}
*/
var HOURS_PER_DAY = 24;
/**
* @private
* @const
* @type {number}
*/
var <API key> = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * <API key>;
/**
* @private
* @const
* @type {number}
*/
var DAYS_PER_WEEK = 7;
/**
* @private
* @const
* @type {number}
*/
var MONTHS_PER_YEAR = 12;
/**
* @private
* @const
* @type {number}
*/
var YEARS_PER_DECADE = 10;
/**
* @private
* @const
* @type {number}
*/
var DECADES_PER_CENTURY = 10;
/**
* @private
* @const
* @type {number}
*/
var <API key> = 10;
/**
* @private
* @param {number} x number
* @return {number}
*/
var ceil = Math.ceil;
/**
* @private
* @param {number} x number
* @return {number}
*/
var floor = Math.floor;
/**
* @private
* @param {Date} ref reference date
* @param {number} shift number of months to shift
* @return {number} number of days shifted
*/
function borrowMonths(ref, shift) {
var prevTime = ref.getTime();
// increment month by shift
ref.setMonth( ref.getMonth() + shift );
// this is the trickiest since months vary in length
return Math.round( (ref.getTime() - prevTime) / <API key> );
}
/**
* @private
* @param {Date} ref reference date
* @return {number} number of days
*/
function daysPerMonth(ref) {
var a = ref.getTime();
// increment month by 1
var b = new Date(a);
b.setMonth( ref.getMonth() + 1 );
// this is the trickiest since months vary in length
return Math.round( (b.getTime() - a) / <API key> );
}
/**
* @private
* @param {Date} ref reference date
* @return {number} number of days
*/
function daysPerYear(ref) {
var a = ref.getTime();
// increment year by 1
var b = new Date(a);
b.setFullYear( ref.getFullYear() + 1 );
// this is the trickiest since years (periodically) vary in length
return Math.round( (b.getTime() - a) / <API key> );
}
/**
* Applies the Timespan to the given date.
*
* @private
* @param {Timespan} ts
* @param {Date=} date
* @return {Date}
*/
function addToDate(ts, date) {
date = (date instanceof Date) || ((date !== null) && isFinite(date)) ? new Date(+date) : new Date();
if (!ts) {
return date;
}
// if there is a value field, use it directly
var value = +ts.value || 0;
if (value) {
date.setTime(date.getTime() + value);
return date;
}
value = +ts.milliseconds || 0;
if (value) {
date.setMilliseconds(date.getMilliseconds() + value);
}
value = +ts.seconds || 0;
// if (value) {
date.setSeconds(date.getSeconds() + value);
value = +ts.minutes || 0;
if (value) {
date.setMinutes(date.getMinutes() + value);
}
value = +ts.hours || 0;
if (value) {
date.setHours(date.getHours() + value);
}
value = +ts.weeks || 0;
if (value) {
value *= DAYS_PER_WEEK;
}
value += +ts.days || 0;
if (value) {
date.setDate(date.getDate() + value);
}
value = +ts.months || 0;
if (value) {
date.setMonth(date.getMonth() + value);
}
value = +ts.millennia || 0;
if (value) {
value *= <API key>;
}
value += +ts.centuries || 0;
if (value) {
value *= DECADES_PER_CENTURY;
}
value += +ts.decades || 0;
if (value) {
value *= YEARS_PER_DECADE;
}
value += +ts.years || 0;
if (value) {
date.setFullYear(date.getFullYear() + value);
}
return date;
}
/**
* @private
* @const
* @type {number}
*/
var LABEL_MILLISECONDS = 0;
/**
* @private
* @const
* @type {number}
*/
var LABEL_SECONDS = 1;
/**
* @private
* @const
* @type {number}
*/
var LABEL_MINUTES = 2;
/**
* @private
* @const
* @type {number}
*/
var LABEL_HOURS = 3;
/**
* @private
* @const
* @type {number}
*/
var LABEL_DAYS = 4;
/**
* @private
* @const
* @type {number}
*/
var LABEL_WEEKS = 5;
/**
* @private
* @const
* @type {number}
*/
var LABEL_MONTHS = 6;
/**
* @private
* @const
* @type {number}
*/
var LABEL_YEARS = 7;
/**
* @private
* @const
* @type {number}
*/
var LABEL_DECADES = 8;
/**
* @private
* @const
* @type {number}
*/
var LABEL_CENTURIES = 9;
/**
* @private
* @const
* @type {number}
*/
var LABEL_MILLENNIA = 10;
/**
* @private
* @type {Array}
*/
var LABELS_SINGLUAR;
/**
* @private
* @type {Array}
*/
var LABELS_PLURAL;
/**
* @private
* @type {string}
*/
var LABEL_LAST;
/**
* @private
* @type {string}
*/
var LABEL_DELIM;
/**
* @private
* @type {string}
*/
var LABEL_NOW;
/**
* Formats a number as a string
*
* @private
* @param {number} value
* @return {string}
*/
var formatNumber;
/**
* @private
* @param {number} value
* @param {number} unit unit index into label list
* @return {string}
*/
function plurality(value, unit) {
return formatNumber(value)+((value === 1) ? LABELS_SINGLUAR[unit] : LABELS_PLURAL[unit]);
}
/**
* Formats the entries with singular or plural labels
*
* @private
* @param {Timespan} ts
* @return {Array}
*/
var formatList;
/**
* Timespan representation of a duration of time
*
* @private
* @this {Timespan}
* @constructor
*/
function Timespan() {}
/**
* Formats the Timespan as a sentence
*
* @param {string=} emptyLabel the string to use when no values returned
* @return {string}
*/
Timespan.prototype.toString = function(emptyLabel) {
var label = formatList(this);
var count = label.length;
if (!count) {
return emptyLabel ? ''+emptyLabel : LABEL_NOW;
}
if (count === 1) {
return label[0];
}
var last = LABEL_LAST+label.pop();
return label.join(LABEL_DELIM)+last;
};
/**
* Formats the Timespan as a sentence in HTML
*
* @param {string=} tag HTML tag name to wrap each value
* @param {string=} emptyLabel the string to use when no values returned
* @return {string}
*/
Timespan.prototype.toHTML = function(tag, emptyLabel) {
tag = tag || 'span';
var label = formatList(this);
var count = label.length;
if (!count) {
emptyLabel = emptyLabel || LABEL_NOW;
return emptyLabel ? '<'+tag+'>'+emptyLabel+'</'+tag+'>' : emptyLabel;
}
for (var i=0; i<count; i++) {
// wrap each unit in tag
label[i] = '<'+tag+'>'+label[i]+'</'+tag+'>';
}
if (count === 1) {
return label[0];
}
var last = LABEL_LAST+label.pop();
return label.join(LABEL_DELIM)+last;
};
/**
* Applies the Timespan to the given date
*
* @param {Date=} date the date to which the timespan is added.
* @return {Date}
*/
Timespan.prototype.addTo = function(date) {
return addToDate(this, date);
};
/**
* Formats the entries as English labels
*
* @private
* @param {Timespan} ts
* @return {Array}
*/
formatList = function(ts) {
var list = [];
var value = ts.millennia;
if (value) {
list.push(plurality(value, LABEL_MILLENNIA));
}
value = ts.centuries;
if (value) {
list.push(plurality(value, LABEL_CENTURIES));
}
value = ts.decades;
if (value) {
list.push(plurality(value, LABEL_DECADES));
}
value = ts.years;
if (value) {
list.push(plurality(value, LABEL_YEARS));
}
value = ts.months;
if (value) {
list.push(plurality(value, LABEL_MONTHS));
}
value = ts.weeks;
if (value) {
list.push(plurality(value, LABEL_WEEKS));
}
value = ts.days;
if (value) {
list.push(plurality(value, LABEL_DAYS));
}
value = ts.hours;
if (value) {
list.push(plurality(value, LABEL_HOURS));
}
value = ts.minutes;
if (value) {
list.push(plurality(value, LABEL_MINUTES));
}
value = ts.seconds;
// if (value) {
list.push(plurality(value, LABEL_SECONDS));
value = ts.milliseconds;
if (value) {
list.push(plurality(value, LABEL_MILLISECONDS));
}
return list;
};
/**
* Borrow any underflow units, carry any overflow units
*
* @private
* @param {Timespan} ts
* @param {string} toUnit
*/
function rippleRounded(ts, toUnit) {
switch (toUnit) {
case 'seconds':
if (ts.seconds !== SECONDS_PER_MINUTE || isNaN(ts.minutes)) {
return;
}
// ripple seconds up to minutes
ts.minutes++;
ts.seconds = 0;
/* falls through */
case 'minutes':
if (ts.minutes !== MINUTES_PER_HOUR || isNaN(ts.hours)) {
return;
}
// ripple minutes up to hours
ts.hours++;
ts.minutes = 0;
/* falls through */
case 'hours':
if (ts.hours !== HOURS_PER_DAY || isNaN(ts.days)) {
return;
}
// ripple hours up to days
ts.days++;
ts.hours = 0;
/* falls through */
case 'days':
if (ts.days !== DAYS_PER_WEEK || isNaN(ts.weeks)) {
return;
}
// ripple days up to weeks
ts.weeks++;
ts.days = 0;
/* falls through */
case 'weeks':
if (ts.weeks !== daysPerMonth(ts.refMonth)/DAYS_PER_WEEK || isNaN(ts.months)) {
return;
}
// ripple weeks up to months
ts.months++;
ts.weeks = 0;
/* falls through */
case 'months':
if (ts.months !== MONTHS_PER_YEAR || isNaN(ts.years)) {
return;
}
// ripple months up to years
ts.years++;
ts.months = 0;
/* falls through */
case 'years':
if (ts.years !== YEARS_PER_DECADE || isNaN(ts.decades)) {
return;
}
// ripple years up to decades
ts.decades++;
ts.years = 0;
/* falls through */
case 'decades':
if (ts.decades !== DECADES_PER_CENTURY || isNaN(ts.centuries)) {
return;
}
// ripple decades up to centuries
ts.centuries++;
ts.decades = 0;
/* falls through */
case 'centuries':
if (ts.centuries !== <API key> || isNaN(ts.millennia)) {
return;
}
// ripple centuries up to millennia
ts.millennia++;
ts.centuries = 0;
/* falls through */
}
}
/**
* Ripple up partial units one place
*
* @private
* @param {Timespan} ts timespan
* @param {number} frac accumulated fractional value
* @param {string} fromUnit source unit name
* @param {string} toUnit target unit name
* @param {number} conversion multiplier between units
* @param {number} digits max number of decimal digits to output
* @return {number} new fractional value
*/
function fraction(ts, frac, fromUnit, toUnit, conversion, digits) {
if (ts[fromUnit] >= 0) {
frac += ts[fromUnit];
delete ts[fromUnit];
}
frac /= conversion;
if (frac + 1 <= 1) {
// drop if below machine epsilon
return 0;
}
if (ts[toUnit] >= 0) {
// ensure does not have more than specified number of digits
ts[toUnit] = +(ts[toUnit] + frac).toFixed(digits);
rippleRounded(ts, toUnit);
return 0;
}
return frac;
}
/**
* Ripple up partial units to next existing
*
* @private
* @param {Timespan} ts
* @param {number} digits max number of decimal digits to output
*/
function fractional(ts, digits) {
var frac = fraction(ts, 0, 'milliseconds', 'seconds', <API key>, digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'seconds', 'minutes', SECONDS_PER_MINUTE, digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'minutes', 'hours', MINUTES_PER_HOUR, digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'hours', 'days', HOURS_PER_DAY, digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'days', 'weeks', DAYS_PER_WEEK, digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'weeks', 'months', daysPerMonth(ts.refMonth)/DAYS_PER_WEEK, digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'months', 'years', daysPerYear(ts.refMonth)/daysPerMonth(ts.refMonth), digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'years', 'decades', YEARS_PER_DECADE, digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'decades', 'centuries', DECADES_PER_CENTURY, digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'centuries', 'millennia', <API key>, digits);
// should never reach this with remaining fractional value
if (frac) { throw new Error('Fractional unit overflow'); }
}
/**
* Borrow any underflow units, carry any overflow units
*
* @private
* @param {Timespan} ts
*/
function ripple(ts) {
var x;
if (ts.milliseconds < 0) {
// ripple seconds down to milliseconds
x = ceil(-ts.milliseconds / <API key>);
ts.seconds -= x;
ts.milliseconds += x * <API key>;
} else if (ts.milliseconds >= <API key>) {
// ripple milliseconds up to seconds
ts.seconds += floor(ts.milliseconds / <API key>);
ts.milliseconds %= <API key>;
}
if (ts.seconds < 0) {
// ripple minutes down to seconds
x = ceil(-ts.seconds / SECONDS_PER_MINUTE);
ts.minutes -= x;
ts.seconds += x * SECONDS_PER_MINUTE;
} else if (ts.seconds >= SECONDS_PER_MINUTE) {
// ripple seconds up to minutes
ts.minutes += floor(ts.seconds / SECONDS_PER_MINUTE);
ts.seconds %= SECONDS_PER_MINUTE;
}
if (ts.minutes < 0) {
// ripple hours down to minutes
x = ceil(-ts.minutes / MINUTES_PER_HOUR);
ts.hours -= x;
ts.minutes += x * MINUTES_PER_HOUR;
} else if (ts.minutes >= MINUTES_PER_HOUR) {
// ripple minutes up to hours
ts.hours += floor(ts.minutes / MINUTES_PER_HOUR);
ts.minutes %= MINUTES_PER_HOUR;
}
if (ts.hours < 0) {
// ripple days down to hours
x = ceil(-ts.hours / HOURS_PER_DAY);
ts.days -= x;
ts.hours += x * HOURS_PER_DAY;
} else if (ts.hours >= HOURS_PER_DAY) {
// ripple hours up to days
ts.days += floor(ts.hours / HOURS_PER_DAY);
ts.hours %= HOURS_PER_DAY;
}
while (ts.days < 0) {
// NOTE: never actually seen this loop more than once
// ripple months down to days
ts.months
ts.days += borrowMonths(ts.refMonth, 1);
}
// weeks is always zero here
if (ts.days >= DAYS_PER_WEEK) {
// ripple days up to weeks
ts.weeks += floor(ts.days / DAYS_PER_WEEK);
ts.days %= DAYS_PER_WEEK;
}
if (ts.months < 0) {
// ripple years down to months
x = ceil(-ts.months / MONTHS_PER_YEAR);
ts.years -= x;
ts.months += x * MONTHS_PER_YEAR;
} else if (ts.months >= MONTHS_PER_YEAR) {
// ripple months up to years
ts.years += floor(ts.months / MONTHS_PER_YEAR);
ts.months %= MONTHS_PER_YEAR;
}
// years is always non-negative here
// decades, centuries and millennia are always zero here
if (ts.years >= YEARS_PER_DECADE) {
// ripple years up to decades
ts.decades += floor(ts.years / YEARS_PER_DECADE);
ts.years %= YEARS_PER_DECADE;
if (ts.decades >= DECADES_PER_CENTURY) {
// ripple decades up to centuries
ts.centuries += floor(ts.decades / DECADES_PER_CENTURY);
ts.decades %= DECADES_PER_CENTURY;
if (ts.centuries >= <API key>) {
// ripple centuries up to millennia
ts.millennia += floor(ts.centuries / <API key>);
ts.centuries %= <API key>;
}
}
}
}
/**
* Remove any units not requested
*
* @private
* @param {Timespan} ts
* @param {number} units the units to populate
* @param {number} max number of labels to output
* @param {number} digits max number of decimal digits to output
*/
function pruneUnits(ts, units, max, digits) {
var count = 0;
// Calc from largest unit to smallest to prevent underflow
if (!(units & MILLENNIA) || (count >= max)) {
// ripple millennia down to centuries
ts.centuries += ts.millennia * <API key>;
delete ts.millennia;
} else if (ts.millennia) {
count++;
}
if (!(units & CENTURIES) || (count >= max)) {
// ripple centuries down to decades
ts.decades += ts.centuries * DECADES_PER_CENTURY;
delete ts.centuries;
} else if (ts.centuries) {
count++;
}
if (!(units & DECADES) || (count >= max)) {
// ripple decades down to years
ts.years += ts.decades * YEARS_PER_DECADE;
delete ts.decades;
} else if (ts.decades) {
count++;
}
if (!(units & YEARS) || (count >= max)) {
// ripple years down to months
ts.months += ts.years * MONTHS_PER_YEAR;
delete ts.years;
} else if (ts.years) {
count++;
}
if (!(units & MONTHS) || (count >= max)) {
// ripple months down to days
if (ts.months) {
ts.days += borrowMonths(ts.refMonth, ts.months);
}
delete ts.months;
if (ts.days >= DAYS_PER_WEEK) {
// ripple day overflow back up to weeks
ts.weeks += floor(ts.days / DAYS_PER_WEEK);
ts.days %= DAYS_PER_WEEK;
}
} else if (ts.months) {
count++;
}
if (!(units & WEEKS) || (count >= max)) {
// ripple weeks down to days
ts.days += ts.weeks * DAYS_PER_WEEK;
delete ts.weeks;
} else if (ts.weeks) {
count++;
}
if (!(units & DAYS) || (count >= max)) {
//ripple days down to hours
ts.hours += ts.days * HOURS_PER_DAY;
delete ts.days;
} else if (ts.days) {
count++;
}
if (!(units & HOURS) || (count >= max)) {
// ripple hours down to minutes
ts.minutes += ts.hours * MINUTES_PER_HOUR;
delete ts.hours;
} else if (ts.hours) {
count++;
}
if (!(units & MINUTES) || (count >= max)) {
// ripple minutes down to seconds
ts.seconds += ts.minutes * SECONDS_PER_MINUTE;
delete ts.minutes;
} else if (ts.minutes) {
count++;
}
if (!(units & SECONDS) || (count >= max)) {
// ripple seconds down to milliseconds
ts.milliseconds += ts.seconds * <API key>;
delete ts.seconds;
} else if (ts.seconds) {
count++;
}
// nothing to ripple milliseconds down to
// so ripple back up to smallest existing unit as a fractional value
if (!(units & MILLISECONDS) || (count >= max)) {
fractional(ts, digits);
}
}
/**
* Populates the Timespan object
*
* @private
* @param {Timespan} ts
* @param {?Date} start the starting date
* @param {?Date} end the ending date
* @param {number} units the units to populate
* @param {number} max number of labels to output
* @param {number} digits max number of decimal digits to output
*/
function populate(ts, start, end, units, max, digits) {
var now = new Date();
ts.start = start = start || now;
ts.end = end = end || now;
ts.units = units;
ts.value = end.getTime() - start.getTime();
if (ts.value < 0) {
// swap if reversed
var tmp = end;
end = start;
start = tmp;
}
// reference month for determining days in month
ts.refMonth = new Date(start.getFullYear(), start.getMonth(), 15, 12, 0, 0);
try {
// reset to initial deltas
ts.millennia = 0;
ts.centuries = 0;
ts.decades = 0;
ts.years = end.getFullYear() - start.getFullYear();
ts.months = end.getMonth() - start.getMonth();
ts.weeks = 0;
ts.days = end.getDate() - start.getDate();
ts.hours = end.getHours() - start.getHours();
ts.minutes = end.getMinutes() - start.getMinutes();
ts.seconds = end.getSeconds() - start.getSeconds();
ts.milliseconds = end.getMilliseconds() - start.getMilliseconds();
ripple(ts);
pruneUnits(ts, units, max, digits);
} finally {
delete ts.refMonth;
}
return ts;
}
/**
* Determine an appropriate refresh rate based upon units
*
* @private
* @param {number} units the units to populate
* @return {number} milliseconds to delay
*/
function getDelay(units) {
if (units & MILLISECONDS) {
// refresh very quickly
return <API key> / 30; //30Hz
}
if (units & SECONDS) {
// refresh every second
return <API key>; //1Hz
}
if (units & MINUTES) {
// refresh every minute
return <API key> * SECONDS_PER_MINUTE;
}
if (units & HOURS) {
// refresh hourly
return <API key> * SECONDS_PER_MINUTE * MINUTES_PER_HOUR;
}
if (units & DAYS) {
// refresh daily
return <API key> * SECONDS_PER_MINUTE * MINUTES_PER_HOUR * HOURS_PER_DAY;
}
// refresh the rest weekly
return <API key> * SECONDS_PER_MINUTE * MINUTES_PER_HOUR * HOURS_PER_DAY * DAYS_PER_WEEK;
}
/**
* API entry point
*
* @public
* @param {Date|number|Timespan|null|function(Timespan,number)} start the starting date
* @param {Date|number|Timespan|null|function(Timespan,number)} end the ending date
* @param {number=} units the units to populate
* @param {number=} max number of labels to output
* @param {number=} digits max number of decimal digits to output
* @return {Timespan|number}
*/
function countdown(start, end, units, max, digits) {
var callback;
// ensure some units or use defaults
units = +units || DEFAULTS;
// max must be positive
max = (max > 0) ? max : NaN;
// clamp digits to an integer between [0, 20]
digits = (digits > 0) ? (digits < 20) ? Math.round(digits) : 20 : 0;
// ensure start date
var startTS = null;
if ('function' === typeof start) {
callback = start;
start = null;
} else if (!(start instanceof Date)) {
if ((start !== null) && isFinite(start)) {
start = new Date(+start);
} else {
if ('object' === typeof startTS) {
startTS = /** @type{Timespan} */(start);
}
start = null;
}
}
// ensure end date
var endTS = null;
if ('function' === typeof end) {
callback = end;
end = null;
} else if (!(end instanceof Date)) {
if ((end !== null) && isFinite(end)) {
end = new Date(+end);
} else {
if ('object' === typeof end) {
endTS = /** @type{Timespan} */(end);
}
end = null;
}
}
// must wait to interpret timespans until after resolving dates
if (startTS) {
start = addToDate(startTS, end);
}
if (endTS) {
end = addToDate(endTS, start);
}
if (!start && !end) {
// used for unit testing
return new Timespan();
}
if (!callback) {
return populate(new Timespan(), /** @type{Date} */(start), /** @type{Date} */(end), /** @type{number} */(units), /** @type{number} */(max), /** @type{number} */(digits));
}
// base delay off units
var delay = getDelay(units),
timerId,
fn = function() {
callback(
populate(new Timespan(), /** @type{Date} */(start), /** @type{Date} */(end), /** @type{number} */(units), /** @type{number} */(max), /** @type{number} */(digits)),
timerId
);
};
fn();
return (timerId = setInterval(fn, delay));
}
/**
* @public
* @const
* @type {number}
*/
countdown.MILLISECONDS = MILLISECONDS;
/**
* @public
* @const
* @type {number}
*/
countdown.SECONDS = SECONDS;
/**
* @public
* @const
* @type {number}
*/
countdown.MINUTES = MINUTES;
/**
* @public
* @const
* @type {number}
*/
countdown.HOURS = HOURS;
/**
* @public
* @const
* @type {number}
*/
countdown.DAYS = DAYS;
/**
* @public
* @const
* @type {number}
*/
countdown.WEEKS = WEEKS;
/**
* @public
* @const
* @type {number}
*/
countdown.MONTHS = MONTHS;
/**
* @public
* @const
* @type {number}
*/
countdown.YEARS = YEARS;
/**
* @public
* @const
* @type {number}
*/
countdown.DECADES = DECADES;
/**
* @public
* @const
* @type {number}
*/
countdown.CENTURIES = CENTURIES;
/**
* @public
* @const
* @type {number}
*/
countdown.MILLENNIA = MILLENNIA;
/**
* @public
* @const
* @type {number}
*/
countdown.DEFAULTS = DEFAULTS;
/**
* @public
* @const
* @type {number}
*/
countdown.ALL = MILLENNIA|CENTURIES|DECADES|YEARS|MONTHS|WEEKS|DAYS|HOURS|MINUTES|SECONDS|MILLISECONDS;
/**
* Override the unit labels
* @public
* @param {string|Array=} singular a pipe ('|') delimited list of singular unit name overrides
* @param {string|Array=} plural a pipe ('|') delimited list of plural unit name overrides
* @param {string=} last a delimiter before the last unit (default: ' and ')
* @param {string=} delim a delimiter to use between all other units (default: ', ')
* @param {string=} empty a label to use when all units are zero (default: '')
* @param {function(number):string=} formatter a function which formats numbers as a string
*/
countdown.setLabels = function(singular, plural, last, delim, empty, formatter) {
singular = singular || [];
if (singular.split) {
singular = singular.split('|');
}
plural = plural || [];
if (plural.split) {
plural = plural.split('|');
}
for (var i=LABEL_MILLISECONDS; i<=LABEL_MILLENNIA; i++) {
// override any specified units
LABELS_SINGLUAR[i] = singular[i] || LABELS_SINGLUAR[i];
LABELS_PLURAL[i] = plural[i] || LABELS_PLURAL[i];
}
LABEL_LAST = ('string' === typeof last) ? last : LABEL_LAST;
LABEL_DELIM = ('string' === typeof delim) ? delim : LABEL_DELIM;
LABEL_NOW = ('string' === typeof empty) ? empty : LABEL_NOW;
formatNumber = ('function' === typeof formatter) ? formatter : formatNumber;
};
/**
* Revert to the default unit labels
* @public
*/
var resetLabels = countdown.resetLabels = function() {
LABELS_SINGLUAR = ' millisecond| second| minute| hour| day| week| month| year| decade| century| millennium'.split('|');
LABELS_PLURAL = ' milliseconds| seconds| minutes| hours| days| weeks| months| years| decades| centuries| millennia'.split('|');
LABEL_LAST = ' and ';
LABEL_DELIM = ', ';
LABEL_NOW = '';
formatNumber = function(value) { return '<span class="contest_timedelta">' + value + "</span>"; };
};
resetLabels();
if (module && module.exports) {
module.exports = countdown;
} else if (typeof window.define === 'function' && typeof window.define.amd !== 'undefined') {
window.define('countdown', [], function() {
return countdown;
});
}
return countdown;
})(module);
|
file(REMOVE_RECURSE
"CMakeFiles/<API key>.dir/polymorphic.cpp.o"
"../../../coverage/<API key>.pdb"
"../../../coverage/<API key>"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/<API key>.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
|
var formMode="detail"; /*formMode detail add modify*/
var panelType="form"; /*panelType form search child */
var editIndex = undefined; /*datagrid */
var dg1EditIndex = undefined;
var objName=label.objName;
var lblDetailStr=label.detailStr;
var lblAddStr=label.addStr;
var lblEditStr=label.editStr;
var pageName=null; /*pageName*/
var pageHeight=0; /*pageHeight */
var topHeight=366; /*datagrid*/
var dgHeadHeight=28; /*datagrid */
var downHeight=30;
var paddingHeight=11; /* paddingTop+paddingBottom*/
var gridToolbar = null;
var dgConf=null; /*dgConf*/
var dg1Conf=null;
function initConf(){}
function initButton(){
for(var i=0;i<gridToolbar.length;i++){
var b=gridToolbar[i];/*disable*/
$("#"+b.id).linkbutton({iconCls: b.iconCls,text:b.text,disabled:true,handler:b.handler,plain:1});
}
}
function initBtnDisabled() {
var btnDisabled=[{"id":"btn_refresh"},{"id":"btn_search"}];
for(var i=0;i<btnDisabled.length;i++) {
$('#'+btnDisabled[i].id).linkbutton('enable');
}
}
function component() {
initConf();
if(window.innerHeight) pageHeight=window.innerHeight;
else pageHeight=document.documentElement.clientHeight;
$('#middle').css("height",<API key>);
$('#tab').tabs({
onSelect:tab_select,
fit:true
});
/*key domdom id*/
installKey("btn_collapse",Keys.f1,null,null,null);
installKey("btn_edit",Keys.f2,null,null,null);
installKey("btn_search",Keys.f3,null,null,null);
installKey("btn_add",Keys.f4,null,null,null);
installKey("btn_delete",Keys.del,null,null,null);
installKey("btn2_save",Keys.s,true,null,null);
installKey("btn2_search",Keys.q,true,null,null);
installKey("btn2_edit",Keys.e,true,null,null);
document.onhelp=function(){return false}; /*IEF1*/
window.onhelp=function(){return false}; /*IEF1*/
$('#btn2_save').linkbutton({iconCls: 'icon-save'}).click(btn2_save);
$('#btn2_edit').linkbutton({iconCls: 'icon-save'}).click(btn2_update),
$('#btn2_search').linkbutton({iconCls: 'icon-search'}).click(btn2_search);
$('#btn2_addItem').linkbutton({iconCls: 'icon-add'}).click(btn2_addItem);
$('#btn2_editItem').linkbutton({iconCls: 'icon-edit'}).click(btn2_editItem);
$('#btn2_rmItem').linkbutton({iconCls: 'icon-remove'}).click(btn2_rmItem);
$('#btn2_ok').linkbutton({iconCls: 'icon-ok'}).click(btn2_ok);
dgConf.toolbar='
dgConf.onCollapse=dg_collapse;
dgConf.onSelect=dg_select;
dgConf.singleSelect=true;
dgConf.onLoadSuccess=dg_load;
dgConf.onClickRow=dg_click;
dgConf.onDblClickRow=dg_dbl;
dgConf.onExpand=dg_expand;
dgConf.collapsible=true;
dgConf.collapseID="btn_collapse";
dgConf.pagination=true;
dgConf.fit=true;
dgConf.rownumbers=true;
dgConf.singleSelect=true;
dg1Conf.onClickRow=dg1_click;
dg1Conf.onDblClickRow=dg1_dbl;
$("#dg").datagrid(dgConf);
initButton();
initBtnDisabled();
$('#top').css("height","auto");
lov_init();
$(".formChild").height(<API key>);
//$("#ff1 input").attr("readonly",1);
}
function showChildGrid(param){
$("#dg1").datagrid(dg1Conf);
}
function showForm(row){
//$("#ff1").form("load",row);
//$("#ff2").form("load",row);;
}
function dg_collapse(){/* tabs tab_select panelselectedtrue*/
var panel=$("#tab").tabs("getSelected"); /*selected*/
if(panel!=null) panel.panel({selected:1});
$('#middle').css("height",<API key>);
$(".formChild").height(<API key>);
$("#tab").tabs({fit:true,stopSelect:true});/*tab tab_select */
if(panel!=null) panel.panel({selected:0});
}
function dg_expand(){
var panel=$("#tab").tabs("getSelected");
if(panel!=null) panel.panel({selected:1});
$('#middle').css("height",<API key>);
$(".formChild").height(<API key>);
$("#tab").tabs({fit:true,stopSelect:true});
if(panel!=null) panel.panel({selected:0});
}
function dg_load(){
$('#mask').css('display', "none");
$('#dg').datagrid('selectRow', 0);
}
function dg_select(rowIndex, rowData){/* ff1 ff2 dg1*/
showChildGrid(rowData);
showForm(rowData,"add");
useDetailMode();
}
function dg_add(){
useAddMode();
}
function dg_edit(){
var row=$('#dg').datagrid('getSelected');
if(row){
useEditMode();
}
else $.messager.alert('', '!',"info");
}
function dg_delete(){
var confirmBack=function(r){
if(!r) return;
var p=$('#dg').datagrid('getRowIndex',$('#dg').datagrid('getSelected'));
if (p == undefined){return}
$('#dg').datagrid('cancelEdit', p)
.datagrid('deleteRow', p);
var currRows=$('#dg').datagrid('getRows').length;
if(p>=currRows) p
if(p>=0) $('#dg').datagrid('selectRow', p);
}
var row=$('#dg').datagrid('getSelected');
if(row) $.messager.confirm('', '?', confirmBack);
else $.messager.alert('', '!',"info");
}
function dg_refresh(){
}
function dg_search(){/* search*/
panelType="search";
$('#tab').tabs("select",1);
}
function dg_click(index){
/* tab*/
if(panelType=="search"){
$('#tab').tabs("select",0);
}
}
function dg_dbl(){
document.getElementById("btn_edit").click();
}
function tab_select(title,index){
$('#down a').css("display","none");
if(index==0){/*grid add edit*/
$('#btn2_addItem').css("display","inline-block");
$('#btn2_editItem').css("display","inline-block");
$('#btn2_rmItem').css("display","inline-block");
$('#btn2_ok').css("display","inline-block");/*commit*/
}
else if(index==1){/* search*/
panelType="search";
$('#btn2_search').css("display","inline-block");
}
}
function useDetailMode(row){
//formMode="detail";
//$('#ff2').css("display","none");
//$('#ff1').css("display","block");
//if(panelType=="search") $('#tab').tabs("select",0);
//else tab_select();
}
function btn2_addItem(){
if(dg1_endEditing()){
var p=$('#dg1').datagrid('getRowIndex',$('#dg1').datagrid('getSelected'));
if (p == undefined){return}
$('#dg1').datagrid('unselectAll');
$('#dg1').datagrid('insertRow',{index:p+1,row:{}})
.datagrid('beginEdit', p+1)
.datagrid('selectRow', p+1);
dg1EditIndex=p+1;
}
else{
$('#dg1').datagrid('selectRow', dg1EditIndex);
}
}
function btn2_editItem(){
var index=$('#dg1').datagrid('getRowIndex', $('#dg1').datagrid('getSelected'));
if (dg1EditIndex != index){
if (dg1_endEditing()){
$('#dg1').datagrid('selectRow', index)
.datagrid('beginEdit', index);
dg1EditIndex = index;
} else {
$('#dg1').datagrid('selectRow', dg1EditIndex);
}
}
}
function btn2_rmItem(){
var confirmBack=function(r){
if(!r) return;
var p=$('#dg1').datagrid('getRowIndex',$('#dg1').datagrid('getSelected'));
if (p == undefined){return}
$('#dg1').datagrid('cancelEdit', p)
.datagrid('deleteRow', p);
var currRows=$('#dg1').datagrid('getRows').length;
if(p>=currRows) p
if(p>=0) $('#dg1').datagrid('selectRow', p);
}
var row=$('#dg1').datagrid('getSelected');
if(row) $.messager.confirm('', '?', confirmBack);
else $.messager.alert('', '!',"info");
}
function dg1_endEditing(){
if (dg1EditIndex == undefined){return true}
var flag=$('#dg1').datagrid('validateRow',dg1EditIndex);
if(flag){
$('#dg1').datagrid('endEdit', dg1EditIndex);
dg1EditIndex = undefined;
return true;
}
return false;
}
function dg1_click(index){
if (dg1EditIndex != index){
dg1_endEditing();
}
}
function dg1_dbl(index){
document.getElementById("btn2_editItem").click();
}
function useAddMode(){};
function useEditMode(){};
function form_change(type){}/*type= add|edit*/
function removeValidate(){}/*type= enable|remove*/
function btn2_save(){}
function btn2_update(){}
function btn2_search(){}
function btn2_ok(){}
function lov_init(){}
|
FROM ruby:2.3.3
RUN apt-get update && apt-get install -y \
#Packages
net-tools \
nodejs
#Install phantomjs
RUN apt-get update \
&& apt-get install -y --<API key> \
ca-certificates \
bzip2 \
libfontconfig \
&& apt-get clean \
|
## Capistrano
[) that allows you to define _tasks_, which may
be applied to machines in certain roles. It also supports tunneling connections
via some gateway machine to allow operations to be performed behind VPN's and
firewalls.
Capistrano was originally designed to simplify and automate deployment of web
applications to distributed environments, and originally came bundled with a set
of tasks designed for deploying Rails applications.
## Documentation
* [https:
## DEPENDENCIES
* [Net::SSH](http://net-ssh.rubyforge.org)
* [Net::SFTP](http://net-ssh.rubyforge.org)
* [Net::SCP](http://net-ssh.rubyforge.org)
* [Net::SSH::Gateway](http://net-ssh.rubyforge.org)
* [HighLine](http://highline.rubyforge.org)
* [Ruby](http://www.ruby-lang.org/en/) ≥ 1.8.7
If you want to run the tests, you'll also need to install the dependencies with
Bundler, see the `Gemfile` within .
## ASSUMPTIONS
Capistrano is "opinionated software", which means it has very firm ideas about
how things ought to be done, and tries to force those ideas on you. Some of the
assumptions behind these opinions are:
* You are using SSH to access the remote servers.
* You either have the same password to all target machines, or you have public
keys in place to allow passwordless access to them.
Do not expect these assumptions to change.
## USAGE
In general, you'll use Capistrano as follows:
* Create a recipe file ("capfile" or "Capfile").
* Use the `cap` script to execute your recipe.
Use the `cap` script as follows:
cap sometask
By default, the script will look for a file called one of `capfile` or
`Capfile`. The `sometask` text indicates which task to execute. You can do
"cap -h" to see all the available options and "cap -T" to see all the available
tasks.
## CONTRIBUTING:
* Fork Capistrano
* Create a topic branch - `git checkout -b my_branch`
* Rebase your branch so that all your changes are reflected in one
commit
* Push to your branch - `git push origin my_branch`
* Create a Pull Request from your branch, include as much documentation
as you can in the commit message/pull request, following these
[guidelines on writing a good commit message](http://tbaggery.com/2008/04/19/<API key>.html)
* That's it!
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 jermit.protocol.zmodem;
/**
* ZEofHeader represents the end of a file.
*/
class ZEofHeader extends Header {
/**
* Public constructor.
*/
public ZEofHeader() {
this(0);
}
/**
* Public constructor.
*
* @param data the data field for this header
*/
public ZEofHeader(final int data) {
super(Type.ZEOF, (byte) 0x0B, "ZEOF", data);
}
/**
* Get the file size value.
*
* @return the value
*/
public int getFileSize() {
return data;
}
}
|
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class FormLoader {
public static String connectionString = "jdbc:hsqldb:file:db-data/teamsandplayers";
static Connection con;
public static void main(String[] args) throws Exception {
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
} catch (<API key> e) {
throw e;
}
MainTeamForm form = new MainTeamForm();
form.setVisible(true);
try {
// will create DB if does not exist
// "SA" is default user with hypersql
con = DriverManager.getConnection(connectionString, "SA", "");
} catch (SQLException e) {
throw e;
} finally {
con.close();
System.out.println("Program complete");
}
}
}
|
<?php
namespace Memento\Test;
use Memento;
class SingleTest extends Harness
{
/** @dataProvider provideClients */
public function testStoreMethod(Memento\Client $client)
{
$success = $client->store($this->getKey(), array('foo' => 'bar'), $this->getExpires());
$this->assertTrue($success);
$this->assertEquals($this->getExpires(), $client->getExpires($this->getKey()));
$this->assertEquals($this->getExpires(), $client->getTtl($this->getKey())); // default should be the same as expires
// store with ttl
$success = $client->store($this->getKey(), array('foo' => 'bar'), $this->getExpires(), $this->getTtl());
$this->assertTrue($success);
$this-><API key>($this->getExpires(), $client->getExpires($this->getKey()));
$this-><API key>($this->getTtl(), $client->getTtl($this->getKey()));
}
/** @dataProvider provideClients */
public function testExists(Memento\Client $client)
{
$client->store($this->getKey(), true);
$exists = $client->exists($this->getKey());
$this->assertTrue($exists);
}
/** @dataProvider provideClients */
public function testRetrieve(Memento\Client $client)
{
$client->store($this->getKey(), array('foo' => 'bar'));
$data = $client->retrieve($this->getKey());
$this->assertEquals($data, array('foo' => 'bar'));
}
/** @dataProvider provideClients */
public function testInvalidRetrieve(Memento\Client $client)
{
$data = $client->retrieve(new Memento\Key(md5(time() . rand(0, 1000))));
$this->assertEquals($data, null);
}
/** @dataProvider provideClients */
public function testInvalidate(Memento\Client $client)
{
$client->store($this->getKey(), true);
$invalid = $client->invalidate($this->getKey());
$this->assertTrue($invalid);
$exists = $client->exists($this->getKey());
$this->assertFalse($exists);
}
/** @dataProvider provideClients */
public function testTerminate(Memento\Client $client)
{
$client->store($this->getKey(), true);
$terminated = $client->terminate($this->getKey());
$this->assertTrue($terminated);
$exists = $client->exists($this->getKey());
$this->assertFalse($exists);
}
/** @dataProvider provideClients */
public function testExpires(Memento\Client $client)
{
$client->store($this->getKey(), array('foo' => 'bar'), 1, $ttl = 5);
sleep(3);
$exists = $client->exists($this->getKey());
$this->assertFalse($exists);
// check if cache exists but include expired caches
$exists = $client->exists($this->getKey(), true);
$this->assertTrue($exists);
$client->store($this->getKey(), array('foo' => 'bar'), $this->getExpires(), $this->getTtl());
$this->assertTrue($client->exists($this->getKey()));
$client->expire($this->getKey());
sleep(1);
$this->assertFalse($client->exists($this->getKey()));
// check if cache exists but include expired caches
$exists = $client->exists($this->getKey(), true);
$this->assertTrue($exists);
}
}
|
@import UIKit;
#import "SPXDataView.h"
/**
* Provides collectionView specific definitions of a dataView
*/
@interface UITableView (<API key>) <SPXDataView>
/**
* Gets/sets the block to execute when the collectionView requests a cell
*/
@property (nonatomic, copy) UITableViewCell *(^<API key>)(UITableView *tableView, id object, NSIndexPath *indexPath);
/**
* Gets/sets the block to execute when the collectionView requests the cell to be configured
*/
@property (nonatomic, copy) void (^<API key>)(UITableView *tableView, UITableViewCell *cell, id object, NSIndexPath *indexPath);
/**
* Gets/sets the block to execute when the collectionView requests a section header
*/
@property (nonatomic, copy) NSString *(^<API key>)(UITableView *tableView, NSUInteger section);
/**
* Gets/sets the block to execute when the collectionView requests a section footer
*/
@property (nonatomic, copy) NSString *(^<API key>)(UITableView *tableView, NSUInteger section);
/**
* Gets/sets the block to execute when the collectionView requests whether or not a cell can be moved
*/
@property (nonatomic, copy) BOOL (^<API key>)(UITableView *tableView, UITableViewCell *cell, id object, NSIndexPath *indexPath);
/**
* Gets/sets the block to execute when the collectionView requests whether or not a cell can be edited
*/
@property (nonatomic, copy) BOOL (^<API key>)(UITableView *tableView, UITableViewCell *cell, id object, NSIndexPath *indexPath);
/**
* Gets/sets the block to execute when the collectionView commits an editing action for a cell
*/
@property (nonatomic, copy) void (^<API key>)(UITableView *tableView, UITableViewCell *cell, id object, NSIndexPath *indexPath);
/**
* Gets/sets the block to execute when the collectionView moves a cell
*/
@property (nonatomic, copy) void (^<API key>)(UITableView *tableView, NSIndexPath *sourceIndexPath, NSIndexPath *<API key>);
@end
|
// Generated by class-dump 3.5 (64 bit).
#import "CDStructures.h"
@interface <API key> : NSObject
{
}
@end
|
<html lang="en">
<head>
<title>C - Debugging with GDB</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Debugging with GDB">
<meta name="generator" content="makeinfo 4.8">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Supported-Languages.html#Supported-Languages" title="Supported Languages">
<link rel="next" href="D.html#D" title="D">
<link href="http:
<!
Copyright (C) 1988-2017 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with the
Invariant Sections being ``Free Software'' and ``Free Software Needs
Free Documentation'', with the Front-Cover Texts being ``A GNU Manual,''
and with the Back-Cover Texts as in (a) below.
(a) The FSF's Back-Cover Text is: ``You are free to copy and modify
this GNU Manual. Buying copies from GNU Press supports the FSF in
developing GNU and promoting software freedom.''
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
--></style>
</head>
<body>
<div class="node">
<p>
<a name="C"></a>
Next: <a rel="next" accesskey="n" href="D.html#D">D</a>,
Up: <a rel="up" accesskey="u" href="Supported-Languages.html#Supported-Languages">Supported Languages</a>
<hr>
</div>
<h4 class="subsection">15.4.1 C and C<tt>++</tt></h4>
<p><a name="<API key>"></a><a name="<API key>"></a>
Since C and C<tt>++</tt> are so closely related, many features of <span class="sc">gdb</span> apply
to both languages. Whenever this is the case, we discuss those languages
together.
<p><a name="<API key>"></a><a name="<API key><API key>"></a><a name="<API key>"></a>The C<tt>++</tt> debugging facilities are jointly implemented by the C<tt>++</tt>
compiler and <span class="sc">gdb</span>. Therefore, to debug your C<tt>++</tt> code
effectively, you must compile your C<tt>++</tt> programs with a supported
C<tt>++</tt> compiler, such as <span class="sc">gnu</span> <code>g++</code>, or the HP ANSI C<tt>++</tt>
compiler (<code>aCC</code>).
<ul class="menu">
<li><a accesskey="1" href="C-Operators.html#C-Operators">C Operators</a>: C and C<tt>++</tt> operators
<li><a accesskey="2" href="C-Constants.html#C-Constants">C Constants</a>: C and C<tt>++</tt> constants
<li><a accesskey="3" href="<API key>.html#<API key>">C Plus Plus Expressions</a>: C<tt>++</tt> expressions
<li><a accesskey="4" href="C-Defaults.html#C-Defaults">C Defaults</a>: Default settings for C and C<tt>++</tt>
<li><a accesskey="5" href="C-Checks.html#C-Checks">C Checks</a>: C and C<tt>++</tt> type and range checks
<li><a accesskey="6" href="Debugging-C.html#Debugging-C">Debugging C</a>: <span class="sc">gdb</span> and C
<li><a accesskey="7" href="<API key>.html#<API key>">Debugging C Plus Plus</a>: <span class="sc">gdb</span> features for C<tt>++</tt>
<li><a accesskey="8" href="<API key>.html#<API key>">Decimal Floating Point</a>: Numbers in Decimal Floating Point format
</ul>
</body></html>
|
Answer these questions in your reflection:
What git concepts were you struggling with prior to the GPS session?
- Prior to the GPS session I was having trouble navigating between branches. I also was completely confused on remote and fetch. I thought that you could just use the command git pull which would fetch/merge in one.
What concepts were clarified during the GPS?
- Using git checkout moves between branches.
What questions did you ask your pair and the guide?
- I asked them questions on what was troubling me and that cleared things up. I am still a little fuzzy on fetch / remote but I know that will come with more practice. Git pull is also a compact way to fetch and merge in one.
What still confuses you about git?
- When using the remote I am still not completely sure on what it does. I will need to do more research and practice while I work on the HTML this week.
How was your first experience of pairing in a GPS?
- My first experience was great! I really enjoyed working with my partner and the guide had some great pointers. Once again my feelings toward DBC are getting better and better as the days go on. I am having a great time learning things that interest me.
|
#!/usr/bin/env python3
"""
Categorize and analyze user sessions.
Read in <API key>.gz file, output some fancy results.
"""
from collections import defaultdict
from collections import Counter
import sys
import time
import os
import resource
import json
import fnmatch
from pipes import Pipes
import operator
from operation import Operation
KB = 1024
MB = KB * 1024
GB = MB * 1024
TB = GB * 1024
PB = TB * 1024
MONITOR_LINES = 100000
class UserSession():
def __init__(self, user_id):
self.user_id = user_id
self.from_ts = 0
self.till_ts = 0
self.get_requests = 0
self.reget_requests = 0
self.put_requests = 0
self.get_bytes = 0
self.put_bytes = 0
self.rename_requests = 0
self.del_requests = 0
self.get_dirs = 0
self.put_dirs = 0
self.put_files_per_dir = 0.0
self.get_files_per_dir = 0.0
self.window_seconds = 0
self.file_cnt_gets = Counter()
self.file_cnt_puts = Counter()
self.dir_cnt_gets = Counter()
self.dir_cnt_puts = Counter()
self.num_ops = 0
self.last_ts = 0
def add_op(self, op):
self.num_ops += 1
if op.ts < self.last_ts:
raise Exception("Timestamp too old")
else:
self.last_ts = op.ts
if op.optype == 'g':
self.get_requests += 1
self.get_bytes += op.size
self.file_cnt_gets[op.obj_id] += 1
self.dir_cnt_gets[op.parent_dir_id] += 1
elif op.optype == 'p':
self.put_requests += 1
self.put_bytes += op.size
self.file_cnt_puts[op.obj_id] += 1
self.dir_cnt_puts[op.parent_dir_id] += 1
elif op.optype == 'd':
self.del_requests += 1
elif op.optype == 'r':
self.rename_requests += 1
#update last time stamp in the session
self.till_ts = op.ts + op.execution_time
def finish(self):
self.get_dirs = len(self.dir_cnt_gets)
if self.get_dirs > 0:
self.get_files_per_dir = float(self.get_requests) / self.get_dirs
self.put_dirs = len(self.dir_cnt_puts)
if self.put_dirs > 0:
self.put_files_per_dir = float(self.put_requests) / self.put_dirs
"""
set reget_counter
:param counter: contains [ 1, 1, 5] counts of objects. value > 1 is a re-retrieval.
:return:
"""
for c in self.file_cnt_gets.values():
if c > 1:
self.reget_requests += (c - 1)
# self.announce()
return ";".join([str(x) for x in [
self.user_id,
self.from_ts,
self.till_ts,
self.till_ts - self.from_ts,
self.get_requests,
self.reget_requests,
self.put_requests,
self.get_bytes,
self.put_bytes,
self.rename_requests,
self.del_requests,
self.get_dirs,
self.put_dirs,
self.put_files_per_dir,
self.get_files_per_dir,
self.window_seconds
]]
)
def announce(self):
print("closed session. gets: %r, regets: %r, puts: %r, dels: %r, renames: %r get_dirs: %r, put_dirs: %r, get_bytes: %r put_bytes: %r window_seconds: %d" % \
(self.get_requests, self.reget_requests, self.put_requests, self.del_requests, self.rename_requests, self.get_dirs, self.put_dirs, self.get_bytes, self.put_bytes, self.window_seconds))
def find_clusters(atimes):
foo = Counter()
bar = dict()
for i in xrange(120, 3660, 10):
clusters = get_clusters(atimes, i)
cs = len(clusters)
foo[cs] += 1
# note first occurance of this cluster size.
if cs not in bar:
bar[cs] = i
# print(len(atimes), i, cs)
return bar[foo.most_common()[0][0]]
def get_clusters(data, maxgap):
'''Arrange data into groups where successive elements
differ by no more than *maxgap*
cluster([1, 6, 9, 100, 102, 105, 109, 134, 139], maxgap=10)
[[1, 6, 9], [100, 102, 105, 109], [134, 139]]
cluster([1, 6, 9, 99, 100, 102, 105, 134, 139, 141], maxgap=10)
[[1, 6, 9], [99, 100, 102, 105], [134, 139, 141]]
'''
data.sort()
groups = [[data[0]]]
for x in data[1:]:
if abs(x - groups[-1][-1]) <= maxgap:
groups[-1].append(x)
else:
groups.append([x])
return groups
def <API key>(user_session_file, out_pipeline, target_file_name):
with open(user_session_file, 'r') as sf:
ops = list()
atimes = list()
for line in sf:
op = Operation()
op.init(line.strip())
ops.append(op)
atimes.append(op.ts)
ops.sort(key=operator.attrgetter('ts'))
atimes.sort()
window_seconds = find_clusters(atimes)
session_counter = 1
uf = os.path.basename(user_session_file)
user_id = uf[:uf.find(".user_session.csv")]
session = UserSession(user_id)
session.window_seconds = window_seconds
for op in ops:
if session.from_ts == 0:
session.from_ts = op.ts
session.till_ts = op.ts + op.execution_time
if (session.till_ts + window_seconds) < op.ts:
# this session is over, so archive it.
out_pipeline.write_to(target_file_name, session.finish())
del session
session = UserSession(user_id)
session.window_seconds = window_seconds
session_counter += 1
session.add_op(op)
if session.num_ops > 0:
out_pipeline.write_to(target_file_name, session.finish())
print("sessions: %d with window_seconds: %d" %(session_counter, window_seconds))
if __name__ == "__main__":
source_dir = os.path.abspath(sys.argv[1])
result = os.path.abspath(sys.argv[2])
results_dir = os.path.dirname(result)
target_file_name = os.path.basename(result)
users_session_files = [os.path.join(dirpath, f)
for dirpath, dirnames, files in os.walk(source_dir)
for f in fnmatch.filter(files, '*.user_session.csv')]
#remove the old log file, as outpipe is append only.
if os.path.exists(os.path.join(results_dir, target_file_name)):
os.remove(os.path.join(results_dir, target_file_name))
out_pipe = Pipes(results_dir)
csv_header = ";".join(["user_id",
"from_ts",
"till_ts",
"session_lifetime",
"get_requests",
"reget_requests",
"put_requests",
"get_bytes",
"put_bytes",
"rename_requests",
"del_requests",
"get_dirs",
"put_dirs",
"put_files_per_dir",
"get_files_per_dir",
"window_seconds"
])
out_pipe.write_to(target_file_name, csv_header)
cnt = 0
for sf in users_session_files:
cnt += 1
print ("working on %d/%d" % (cnt, len(users_session_files)))
<API key>(sf, out_pipe, target_file_name)
# if cnt >=20:
# break
out_pipe.close()
print("wrote results to %s: " % (os.path.join(results_dir, target_file_name)))
|
package esl
import (
"io"
"errors"
"unicode/utf8"
)
// Buffer ...
type buffer []byte
// MemoryReader ...
type memReader [ ]byte
// MemoryWriter ...
type memWriter [ ]byte
// ErrBufferSize indicates that memory cannot be allocated to store data in a buffer.
var ErrBufferSize = errors.New(`could not allocate memory`)
func newBuffer( size int ) *buffer {
buf := make([ ]byte, 0, size )
return (*buffer)(&buf)
}
func ( buf *buffer ) reader( ) *memReader {
n := len( *buf )
rbuf := ( *buf )[:n:n]
return ( *memReader )( &rbuf )
}
func ( buf *buffer ) writer( ) *memWriter {
return ( *memWriter )( buf )
}
func ( buf *buffer ) grow( n int ) error {
if ( len( *buf )+ n ) > cap( *buf ) {
// Not enough space to store [:+(n)]byte(s)
mbuf, err := makebuf( cap( *buf )+ n )
if ( err != nil ) {
return ( err )
}
copy( mbuf, *buf )
*( buf ) = mbuf
}
return nil
}
// allocates a byte slice of size.
// If the allocation fails, returns error
// indicating that memory cannot be allocated to store data in a buffer.
func makebuf( size int ) ( buf [ ]byte, memerr error ) {
defer func( ) {
// If the make fails, give a known error.
if ( recover( ) != nil ) {
( memerr ) = ErrBufferSize
}
}( )
return make( [ ]byte, 0, size ), nil
}
func ( buf *memReader ) Read( b [ ]byte ) ( n int, err error ) {
if len( *buf ) == 0 {
return ( 0 ), io.EOF
}
n, *buf = copy( b, *buf ), ( *buf )[ n: ]
return // n, nil
}
func ( buf *memReader ) ReadByte( ) ( c byte, err error ) {
if len(*buf) == 0 {
return ( 0 ), io.EOF
}
c, *buf = (*buf)[0], (*buf)[1:]
return // c, nil
}
func ( buf *memReader ) ReadRune( ) ( r rune, size int, err error ) {
if len(*buf) == 0 {
return 0, 0, io.EOF
}
r, size = utf8.DecodeRune(*buf)
*buf = (*buf)[size:]
return // r, size, nil
}
func ( buf *memReader ) WriteTo( w io.Writer ) ( n int64, err error ) {
for len( *buf ) > 0 {
rw, err := w.Write( *buf )
if ( rw > 0 ) {
n, *buf = n + int64( rw ), (*buf)[rw:]
}
if ( err != nil ) {
return n, err
}
}
return ( 0 ), io.EOF
}
func ( buf *memWriter ) Write( b []byte ) ( n int, err error ) {
*buf = append( *buf, b...)
return len( b ), nil
}
func ( buf *memWriter ) WriteByte( c byte ) error {
*buf = append( *buf, c )
return ( nil )
}
func ( buf *memWriter ) WriteRune( r rune ) error {
if ( r < utf8.RuneSelf ) {
return buf.WriteByte( byte( r ))
}
b := *buf
n := len( b )
if ( n + utf8.UTFMax ) > cap( b ) {
b = make( []byte, ( n + utf8.UTFMax ))
copy( b, *buf )
}
w := utf8.EncodeRune( b[ n:( n + utf8.UTFMax )], r )
*buf = b[ :( n + w )]
return nil
}
func ( buf *memWriter ) WriteString( s string ) ( n int, err error ) {
*buf = append( *buf, s...)
return len( s ), nil
}
// func (buf *memWriter) ReadFrom(r io.Reader) (n int64, err error) {
// // NOTE: indefinite allocation! Try to use io.WriterTo interface!
|
package com.zimbra.cs.versioncheck;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Date;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import com.zimbra.common.util.ZimbraLog;
import com.zimbra.common.account.Key;
import com.zimbra.common.account.Key.ServerBy;
import com.zimbra.common.service.ServiceException;
import com.zimbra.common.soap.AdminConstants;
import com.zimbra.common.soap.SoapFaultException;
import com.zimbra.common.soap.SoapTransport;
import com.zimbra.common.util.CliUtil;
import com.zimbra.cs.account.Config;
import com.zimbra.cs.account.Provisioning;
import com.zimbra.cs.account.Server;
import com.zimbra.cs.client.LmcSession;
import com.zimbra.cs.client.soap.<API key>;
import com.zimbra.cs.client.soap.<API key>;
import com.zimbra.cs.client.soap.<API key>;
import com.zimbra.cs.util.BuildInfo;
import com.zimbra.cs.util.SoapCLI;
import com.zimbra.common.util.DateUtil;
/**
* @author Greg Solovyev
*/
public class VersionCheckUtil extends SoapCLI {
private static final String OPT_CHECK_VERSION = "c";
private static final String <API key> = "m";
private static final String SHOW_LAST_STATUS = "r";
protected VersionCheckUtil() throws ServiceException {
super();
}
public static void main(String[] args) {
CliUtil.toolSetup();
SoapTransport.setDefaultUserAgent("zmcheckversion", BuildInfo.VERSION);
VersionCheckUtil util = null;
try {
util = new VersionCheckUtil();
} catch (ServiceException e) {
System.err.println(e.getMessage());
System.exit(1);
}
try {
util.<API key>();
CommandLine cl = null;
try {
cl = util.getCommandLine(args);
} catch (ParseException e) {
System.out.println(e.getMessage());
util.usage();
System.exit(1);
}
if (cl == null) {
System.exit(1);
}
if (cl.hasOption(OPT_CHECK_VERSION)) {
//check schedule
Provisioning prov = Provisioning.getInstance();
Config config;
config = prov.getConfig();
String updaterServerId = config.getAttr(Provisioning.<API key>);
if (updaterServerId != null) {
Server server = prov.get(Key.ServerBy.id, updaterServerId);
if (server != null) {
Server localServer = prov.getLocalServer();
if (localServer!=null) {
if(!localServer.getId().equalsIgnoreCase(server.getId())) {
System.out.println("Wrong server");
System.exit(0);
}
}
}
}
String versionInterval = config.getAttr(Provisioning.<API key>);
if(versionInterval == null || versionInterval.length()==0 || versionInterval.equalsIgnoreCase("0")) {
System.out.println("Automatic updates are disabled");
System.exit(0);
} else {
long checkInterval = DateUtil.getTimeIntervalSecs(versionInterval,0);
String lastAttempt = config.getAttr(Provisioning.<API key>);
if(lastAttempt != null) {
Date lastChecked = DateUtil.<API key>(config.getAttr(Provisioning.<API key>));
Date now = new Date();
if (now.getTime()/1000- lastChecked.getTime()/1000 >= checkInterval) {
util.doVersionCheck();
} else {
System.out.println("Too early");
System.exit(0);
}
} else {
util.doVersionCheck();
}
}
} else if (cl.hasOption(<API key>)) {
util.doVersionCheck();
} else if (cl.hasOption(SHOW_LAST_STATUS)) {
util.doResult();
System.exit(0);
} else {
util.usage();
System.exit(1);
}
} catch (Exception e) {
System.err.println(e.getMessage());
ZimbraLog.extensions.error("Error in versioncheck util", e);
util.usage(null);
System.exit(1);
}
}
private void doVersionCheck() throws SoapFaultException, IOException, ServiceException, <API key> {
LmcSession session = auth();
<API key> req = new <API key>();
req.setAction(AdminConstants.VERSION_CHECK_CHECK);
req.setSession(session);
req.invoke(getServerUrl());
}
private void doResult() throws SoapFaultException, IOException, ServiceException, <API key> {
try {
LmcSession session = auth();
<API key> req = new <API key>();
req.setAction(AdminConstants.<API key>);
req.setSession(session);
<API key> res = (<API key>) req.invoke(getServerUrl());
List <VersionUpdate> updates = res.getUpdates();
for(Iterator <VersionUpdate> iter = updates.iterator();iter.hasNext();){
VersionUpdate update = iter.next();
String critical;
if(update.isCritical()) {
critical = "critical";
} else {
critical = "not critical";
}
System.out.println(
String.format("Found a %s update. Update is %s . Update version: %s. For more info visit: %s",
update.getType(),critical,update.getVersion(),update.getUpdateURL())
);
}
} catch (SoapFaultException soape) {
System.out.println("Cought SoapFaultException");
System.out.println(soape.getStackTrace().toString());
throw (soape);
} catch (<API key> lmce) {
System.out.println("Cought <API key>");
System.out.println(lmce.getStackTrace().toString());
throw (lmce);
} catch (ServiceException se) {
System.out.println("Cought ServiceException");
System.out.println(se.getStackTrace().toString());
throw (se);
} catch (IOException ioe) {
System.out.println("Cought IOException");
System.out.println(ioe.getStackTrace().toString());
throw (ioe);
}
}
protected void <API key>() {
// super.<API key>();
Options options = getOptions();
Options hiddenOptions = getHiddenOptions();
hiddenOptions.addOption(OPT_CHECK_VERSION, "autocheck", false, "Initiate version check request (exits if <API key>==0)");
options.addOption(SHOW_LAST_STATUS, "result", false, "Show results of last version check.");
options.addOption(<API key>, "manual", false, "Initiate version check request.");
}
protected String getCommandUsage() {
return "zmcheckversion <options>";
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EmployeeFinder.Models
{
public enum Position
{
Bartender,
Waiter,
Bellboy,
Receptionist,
Manager,
Housekeeper,
Chef,
Manintanace
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Domain
{
public class Meeting
{
public int ConsultantId { get; set; }
public Consultant Consultant { get; set; }
public int UserId { get; set; }
public User User { get; set; }
public DateTime BeginTime { get; set; }
public DateTime EndTime { get; set; }
public override string ToString()
{
return $"{BeginTime} -> {EndTime}";
}
}
}
|
module PiwikAnalytics
module Helpers
def piwik_tracking_tag
config = PiwikAnalytics.configuration
return if config.disabled?
if config.use_async?
file = "piwik_analytics/<API key>"
else
file = "piwik_analytics/piwik_tracking_tag"
end
render({
:file => file,
:locals => {:url => config.url, :id_site => config.id_site}
})
end
end
end
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author Stephan Reith
@date 31.08.2016
This is a simple example to demonstrate how the ROS Spinnaker Interface can be used.
You will also need a ROS Listener and a ROS Talker to send and receive data.
Make sure they communicate over the same ROS topics and std_msgs.Int64 ROS Messages used in here.
"""
import spynnaker.pyNN as pynn
from <API key> import <API key>
# import transfer_functions as tf
from <API key> import SpikeSourcePoisson
from <API key> import SpikeSinkSmoothing
ts = 0.1
n_neurons = 1
simulation_time = 10000
pynn.setup(timestep=ts, min_delay=ts, max_delay=2.0*ts)
pop = pynn.Population(size=n_neurons, cellclass=pynn.IF_curr_exp, cellparams={}, label='pop')
# The <API key> just needs to be initialised. The following parameters are possible:
ros_interface = <API key>(
n_neurons_source=n_neurons, # number of neurons of the injector population
Spike_Source_Class=SpikeSourcePoisson, # the transfer function ROS Input -> Spikes you want to use.
Spike_Sink_Class=SpikeSinkSmoothing, # the transfer function Spikes -> ROS Output you want to use.
# You can choose from the transfer_functions module
# or write one yourself.
output_population=pop, # the pynn population you wish to receive the
# live spikes from.
ros_topic_send='to_spinnaker', # the ROS topic used for the incoming ROS values.
ros_topic_recv='from_spinnaker', # the ROS topic used for the outgoing ROS values.
clk_rate=1000, # mainloop clock (update) rate in Hz.
ros_output_rate=10) # number of ROS messages send out per second.
# Build your network, run the simulation and optionally record the spikes and voltages.
pynn.Projection(ros_interface, pop, pynn.OneToOneConnector(weights=5, delays=1))
pop.record()
pop.record_v()
pynn.run(simulation_time)
spikes = pop.getSpikes()
pynn.end()
# Plot
import pylab
spike_times = [spike[1] for spike in spikes]
spike_ids = [spike[0] for spike in spikes]
pylab.plot(spike_times, spike_ids, ".")
pylab.xlabel('Time (ms)')
pylab.ylabel('Neuron ID')
pylab.title('Spike Plot')
pylab.xlim(xmin=0)
pylab.show()
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>area-method: Not compatible </title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.13.1 / area-method - 8.5.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
area-method
<small>
8.5.0
<span class="label label-info">Not compatible </span>
</small>
</h1>
<p> <em><script>document.write(moment("2022-02-04 18:52:19 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-04 18:52:19 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.13.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.07.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.07.1 Official release 4.07.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "matej.kosik@inria.fr"
homepage: "https://github.com/coq-contribs/area-method"
license: "Proprietary"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/AreaMethod"]
depends: [
"ocaml"
"coq" {>= "8.5" & < "8.6~"}
]
tags: [ "keyword:geometry" "keyword:chou gao zhang area method" "keyword:decision procedure" "category:Mathematics/Geometry/AutomatedDeduction" "date:2004-2010" ]
authors: [ "Julien Narboux <>" ]
bug-reports: "https://github.com/coq-contribs/area-method/issues"
dev-repo: "git+https://github.com/coq-contribs/area-method.git"
synopsis: "The Chou, Gao and Zhang area method"
description: """
This contribution is the implementation of the Chou, Gao and Zhang's area method decision procedure for euclidean plane geometry.
This development contains a partial formalization of the book "Machine Proofs in Geometry, Automated Production of Readable Proofs for Geometry Theorems" by Chou, Gao and Zhang.
The examples shown automatically (there are more than 100 examples) includes the Ceva, Desargues, Menelaus, Pascal, Centroïd, Pappus, Gauss line, Euler line, Napoleon theorems.
Changelog
2.1 : remove some not needed assumptions in some elimination lemmas (2010)
2.0 : extension implementation to Euclidean geometry (2009-2010)
1.0 : first implementation for affine geometry (2004)"""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/area-method/archive/v8.5.0.tar.gz"
checksum: "md5=<API key>"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install </h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-area-method.8.5.0 coq.8.13.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.13.1).
The following dependencies couldn't be met:
- coq-area-method -> coq < 8.6~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-area-method.8.5.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install </h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https:
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ieee754: Not compatible</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.9.1 / ieee754 - 8.7.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
ieee754
<small>
8.7.0
<span class="label label-info">Not compatible</span>
</small>
</h1>
<p><em><script>document.write(moment("2020-08-24 17:47:06 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-08-24 17:47:06 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.12 <API key> of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-m4 1 Virtual package relying on m4
coq 8.9.1 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.05.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.05.0 Official 4.05.0 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/ieee754"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/IEEE754"]
depends: [
"ocaml"
"coq" {>= "8.7" & < "8.8~"}
]
tags: [ "keyword: floating-point arithmetic" "keyword: floats" "keyword: IEEE" "category: Computer Science/Data Types and Data Structures" "category: Computer Science/Semantics and Compilation/Semantics" "date: 1997" ]
authors: [ "Patrick Loiseleur" ]
bug-reports: "https://github.com/coq-contribs/ieee754/issues"
dev-repo: "git+https://github.com/coq-contribs/ieee754.git"
synopsis: "A formalisation of the IEEE754 norm on floating-point arithmetic"
description: """
This library contains a non-verified implementation of
binary floating-point addition and multiplication operators inspired
by the IEEE-754 standard. It is today outdated.
See the attached 1997 report rapport-stage-dea.ps.gz for a discussion
(in French) of this work.
For the state of the art at the time of updating this notice, see
e.g. "Flocq: A Unified Library for Proving Floating-point Algorithms
in Coq" by S. Boldo and G. Melquiond, 2011."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/ieee754/archive/v8.7.0.tar.gz"
checksum: "md5=<API key>"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-ieee754.8.7.0 coq.8.9.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.9.1).
The following dependencies couldn't be met:
- coq-ieee754 -> coq < 8.8~ -> ocaml < 4.03.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-ieee754.8.7.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https:
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
|
import {<API key>, <API key>, <API key>, templateSourceUrl} from './compile_metadata';
import {CompilerConfig, <API key>} from './config';
import {ViewEncapsulation} from './core';
import * as html from './ml_parser/ast';
import {HtmlParser} from './ml_parser/html_parser';
import {InterpolationConfig} from './ml_parser/<API key>';
import {ParseTreeResult as HtmlParseTreeResult} from './ml_parser/parser';
import {ResourceLoader} from './resource_loader';
import {extractStyleUrls, <API key>} from './style_url_resolver';
import {<API key>, preparseElement} from './template_parser/template_preparser';
import {UrlResolver} from './url_resolver';
import {isDefined, stringify, SyncAsync, syntaxError} from './util';
export interface <API key> {
ngModuleType: any;
componentType: any;
moduleUrl: string;
template: string|null;
templateUrl: string|null;
styles: string[];
styleUrls: string[];
interpolation: [string, string]|null;
encapsulation: ViewEncapsulation|null;
animations: any[];
preserveWhitespaces: boolean|null;
}
export class DirectiveNormalizer {
private <API key> = new Map<string, SyncAsync<string>>();
constructor(
private _resourceLoader: ResourceLoader, private _urlResolver: UrlResolver,
private _htmlParser: HtmlParser, private _config: CompilerConfig) {}
clearCache(): void {
this.<API key>.clear();
}
clearCacheFor(normalizedDirective: <API key>): void {
if (!normalizedDirective.isComponent) {
return;
}
const template = normalizedDirective.template !;
this.<API key>.delete(template.templateUrl!);
template.externalStylesheets.forEach((stylesheet) => {
this.<API key>.delete(stylesheet.moduleUrl!);
});
}
private _fetch(url: string): SyncAsync<string> {
let result = this.<API key>.get(url);
if (!result) {
result = this._resourceLoader.get(url);
this.<API key>.set(url, result);
}
return result;
}
normalizeTemplate(prenormData: <API key>):
SyncAsync<<API key>> {
if (isDefined(prenormData.template)) {
if (isDefined(prenormData.templateUrl)) {
throw syntaxError(`'${
stringify(prenormData
.componentType)}' component cannot define both template and templateUrl`);
}
if (typeof prenormData.template !== 'string') {
throw syntaxError(`The template specified for component ${
stringify(prenormData.componentType)} is not a string`);
}
} else if (isDefined(prenormData.templateUrl)) {
if (typeof prenormData.templateUrl !== 'string') {
throw syntaxError(`The templateUrl specified for component ${
stringify(prenormData.componentType)} is not a string`);
}
} else {
throw syntaxError(
`No template specified for component ${stringify(prenormData.componentType)}`);
}
if (isDefined(prenormData.preserveWhitespaces) &&
typeof prenormData.preserveWhitespaces !== 'boolean') {
throw syntaxError(`The preserveWhitespaces option for component ${
stringify(prenormData.componentType)} must be a boolean`);
}
return SyncAsync.then(
this._preParseTemplate(prenormData),
(preparsedTemplate) => this.<API key>(prenormData, preparsedTemplate));
}
private _preParseTemplate(prenomData: <API key>):
SyncAsync<PreparsedTemplate> {
let template: SyncAsync<string>;
let templateUrl: string;
if (prenomData.template != null) {
template = prenomData.template;
templateUrl = prenomData.moduleUrl;
} else {
templateUrl = this._urlResolver.resolve(prenomData.moduleUrl, prenomData.templateUrl!);
template = this._fetch(templateUrl);
}
return SyncAsync.then(
template, (template) => this.<API key>(prenomData, template, templateUrl));
}
private <API key>(
prenormData: <API key>, template: string,
templateAbsUrl: string): PreparsedTemplate {
const isInline = !!prenormData.template;
const interpolationConfig = InterpolationConfig.fromArray(prenormData.interpolation!);
const templateUrl = templateSourceUrl(
{reference: prenormData.ngModuleType}, {type: {reference: prenormData.componentType}},
{isInline, templateUrl: templateAbsUrl});
const rootNodesAndErrors = this._htmlParser.parse(
template, templateUrl, {<API key>: true, interpolationConfig});
if (rootNodesAndErrors.errors.length > 0) {
const errorString = rootNodesAndErrors.errors.join('\n');
throw syntaxError(`Template parse errors:\n${errorString}`);
}
const <API key> = this.<API key>(new <API key>(
{styles: prenormData.styles, moduleUrl: prenormData.moduleUrl}));
const visitor = new <API key>();
html.visitAll(visitor, rootNodesAndErrors.rootNodes);
const templateStyles = this.<API key>(new <API key>(
{styles: visitor.styles, styleUrls: visitor.styleUrls, moduleUrl: templateAbsUrl}));
const styles = <API key>.styles.concat(templateStyles.styles);
const inlineStyleUrls = <API key>.styleUrls.concat(templateStyles.styleUrls);
const styleUrls = this
.<API key>(new <API key>(
{styleUrls: prenormData.styleUrls, moduleUrl: prenormData.moduleUrl}))
.styleUrls;
return {
template,
templateUrl: templateAbsUrl,
isInline,
htmlAst: rootNodesAndErrors,
styles,
inlineStyleUrls,
styleUrls,
ngContentSelectors: visitor.ngContentSelectors,
};
}
private <API key>(
prenormData: <API key>,
preparsedTemplate: PreparsedTemplate): SyncAsync<<API key>> {
return SyncAsync.then(
this.<API key>(
preparsedTemplate.styleUrls.concat(preparsedTemplate.inlineStyleUrls)),
(externalStylesheets) => this.<API key>(
prenormData, preparsedTemplate, externalStylesheets));
}
private <API key>(
prenormData: <API key>, preparsedTemplate: PreparsedTemplate,
stylesheets: Map<string, <API key>>): <API key> {
// Algorithm:
// - produce exactly 1 entry per original styleUrl in
// <API key>.externalStylesheets with all styles inlined
// - inline all styles that are referenced by the template into <API key>.styles.
// Reason: be able to determine how many stylesheets there are even without loading
// the template nor the stylesheets, so we can create a stub for TypeScript always synchronously
// (as resource loading may be async)
const styles = [...preparsedTemplate.styles];
this._inlineStyles(preparsedTemplate.inlineStyleUrls, stylesheets, styles);
const styleUrls = preparsedTemplate.styleUrls;
const externalStylesheets = styleUrls.map(styleUrl => {
const stylesheet = stylesheets.get(styleUrl)!;
const styles = [...stylesheet.styles];
this._inlineStyles(stylesheet.styleUrls, stylesheets, styles);
return new <API key>({moduleUrl: styleUrl, styles: styles});
});
let encapsulation = prenormData.encapsulation;
if (encapsulation == null) {
encapsulation = this._config.<API key>;
}
if (encapsulation === ViewEncapsulation.Emulated && styles.length === 0 &&
styleUrls.length === 0) {
encapsulation = ViewEncapsulation.None;
}
return new <API key>({
encapsulation,
template: preparsedTemplate.template,
templateUrl: preparsedTemplate.templateUrl,
htmlAst: preparsedTemplate.htmlAst,
styles,
styleUrls,
ngContentSelectors: preparsedTemplate.ngContentSelectors,
animations: prenormData.animations,
interpolation: prenormData.interpolation,
isInline: preparsedTemplate.isInline,
externalStylesheets,
preserveWhitespaces: <API key>(
prenormData.preserveWhitespaces, this._config.preserveWhitespaces),
});
}
private _inlineStyles(
styleUrls: string[], stylesheets: Map<string, <API key>>,
targetStyles: string[]) {
styleUrls.forEach(styleUrl => {
const stylesheet = stylesheets.get(styleUrl)!;
stylesheet.styles.forEach(style => targetStyles.push(style));
this._inlineStyles(stylesheet.styleUrls, stylesheets, targetStyles);
});
}
private <API key>(
styleUrls: string[],
loadedStylesheets:
Map<string, <API key>> = new Map<string, <API key>>()):
SyncAsync<Map<string, <API key>>> {
return SyncAsync.then(
SyncAsync.all(styleUrls.filter((styleUrl) => !loadedStylesheets.has(styleUrl))
.map(
styleUrl => SyncAsync.then(
this._fetch(styleUrl),
(loadedStyle) => {
const stylesheet =
this.<API key>(new <API key>(
{styles: [loadedStyle], moduleUrl: styleUrl}));
loadedStylesheets.set(styleUrl, stylesheet);
return this.<API key>(
stylesheet.styleUrls, loadedStylesheets);
}))),
(_) => loadedStylesheets);
}
private <API key>(stylesheet: <API key>): <API key> {
const moduleUrl = stylesheet.moduleUrl!;
const allStyleUrls = stylesheet.styleUrls.filter(<API key>)
.map(url => this._urlResolver.resolve(moduleUrl, url));
const allStyles = stylesheet.styles.map(style => {
const styleWithImports = extractStyleUrls(this._urlResolver, moduleUrl, style);
allStyleUrls.push(...styleWithImports.styleUrls);
return styleWithImports.style;
});
return new <API key>(
{styles: allStyles, styleUrls: allStyleUrls, moduleUrl: moduleUrl});
}
}
interface PreparsedTemplate {
template: string;
templateUrl: string;
isInline: boolean;
htmlAst: HtmlParseTreeResult;
styles: string[];
inlineStyleUrls: string[];
styleUrls: string[];
ngContentSelectors: string[];
}
class <API key> implements html.Visitor {
ngContentSelectors: string[] = [];
styles: string[] = [];
styleUrls: string[] = [];
<API key>: number = 0;
visitElement(ast: html.Element, context: any): any {
const preparsedElement = preparseElement(ast);
switch (preparsedElement.type) {
case <API key>.NG_CONTENT:
if (this.<API key> === 0) {
this.ngContentSelectors.push(preparsedElement.selectAttr);
}
break;
case <API key>.STYLE:
let textContent = '';
ast.children.forEach(child => {
if (child instanceof html.Text) {
textContent += child.value;
}
});
this.styles.push(textContent);
break;
case <API key>.STYLESHEET:
this.styleUrls.push(preparsedElement.hrefAttr);
break;
default:
break;
}
if (preparsedElement.nonBindable) {
this.<API key>++;
}
html.visitAll(this, ast.children);
if (preparsedElement.nonBindable) {
this.<API key>
}
return null;
}
visitExpansion(ast: html.Expansion, context: any): any {
html.visitAll(this, ast.cases);
}
visitExpansionCase(ast: html.ExpansionCase, context: any): any {
html.visitAll(this, ast.expression);
}
visitComment(ast: html.Comment, context: any): any {
return null;
}
visitAttribute(ast: html.Attribute, context: any): any {
return null;
}
visitText(ast: html.Text, context: any): any {
return null;
}
}
|
<?php
/* TwigBundle:Exception:error.atom.twig */
class <API key> extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
$this->env->loadTemplate("TwigBundle:Exception:error.xml.twig")->display(array_merge($context, array("exception" => (isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")))));
}
public function getTemplateName()
{
return "TwigBundle:Exception:error.atom.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 19 => 1, 79 => 21, 72 => 13, 69 => 12, 47 => 18, 40 => 11, 37 => 10, 22 => 1, 246 => 32, 157 => 56, 145 => 46, 139 => 45, 131 => 42, 123 => 41, 120 => 40, 115 => 39, 111 => 38, 108 => 37, 101 => 33, 98 => 32, 96 => 31, 83 => 25, 74 => 14, 66 => 11, 55 => 16, 52 => 21, 50 => 14, 43 => 9, 41 => 8, 35 => 9, 32 => 4, 29 => 6, 209 => 82, 203 => 78, 199 => 76, 193 => 73, 189 => 71, 187 => 70, 182 => 68, 176 => 64, 173 => 63, 168 => 62, 164 => 58, 162 => 57, 154 => 54, 149 => 51, 147 => 50, 144 => 49, 141 => 48, 133 => 42, 130 => 41, 125 => 38, 122 => 37, 116 => 36, 112 => 35, 109 => 34, 106 => 36, 103 => 32, 99 => 30, 95 => 28, 92 => 29, 86 => 24, 82 => 22, 80 => 24, 73 => 19, 64 => 19, 60 => 6, 57 => 12, 54 => 22, 51 => 10, 48 => 9, 45 => 17, 42 => 16, 39 => 6, 36 => 5, 33 => 4, 30 => 3,);
}
}
|
<HTML>
<!-- Mirrored from thevillagedanang.com/?p=62 by HTTrack Website Copier/3.x [XR&CO'2014], Thu, 02 Nov 2017 14:46:03 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8" /><!-- /Added by HTTrack -->
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html;charset=UTF-8"><META HTTP-EQUIV="Refresh" CONTENT="0; URL=about-us/index.html"><TITLE>Page has moved</TITLE>
</HEAD>
<BODY>
<A HREF="about-us/index.html"><h3>Click here...</h3></A>
</BODY>
<!-- Mirrored from thevillagedanang.com/?p=62 by HTTrack Website Copier/3.x [XR&CO'2014], Thu, 02 Nov 2017 14:46:03 GMT -->
</HTML>
|
/**
* HTTP.test
*/
"use strict";
/* Node modules */
/* Third-party modules */
var steeplejack = require("steeplejack");
/* Files */
describe("HTTPError test", function () {
var HTTPError;
beforeEach(function () {
injector(function (_HTTPError_) {
HTTPError = _HTTPError_;
});
});
describe("Instantation tests", function () {
it("should extend the steeplejack Fatal exception", function () {
var obj = new HTTPError("text");
expect(obj).to.be.instanceof(HTTPError)
.to.be.instanceof(steeplejack.Exceptions.Fatal);
expect(obj.type).to.be.equal("HTTPError");
expect(obj.message).to.be.equal("text");
expect(obj.httpCode).to.be.equal(500);
expect(obj.getHttpCode()).to.be.equal(500);
});
it("should set the HTTP code in the first input", function () {
var obj = new HTTPError(401);
expect(obj.httpCode).to.be.equal(401);
expect(obj.getHttpCode()).to.be.equal(401);
});
});
});
|
require File.join(File.dirname(__FILE__), './scribd-carrierwave/version')
require File.join(File.dirname(__FILE__), './scribd-carrierwave/config')
require 'carrierwave'
require 'rscribd'
require 'configatron'
module ScribdCarrierWave
class << self
def included(base)
base.extend ClassMethods
end
def upload uploader
file_path = full_path(uploader)
args = { file: file_path, access: ( uploader.class.public? ? 'public' : 'private' )}
type = File.extname(file_path)
if type
type = type.gsub(/^\./, '').gsub(/\?.*$/, '')
args.merge!(type: type) if type != ''
end
scribd_user.upload(args)
end
def destroy uploader
document = scribd_user.find_document(uploader.ipaper_id) rescue nil
document.destroy if !document.nil?
end
def <API key>(id)
scribd_user.find_document(id) rescue nil
end
def full_path uploader
if uploader.url =~ /^http(s?):\/\
uploader.url
else
uploader.root + uploader.url
end
end
module ClassMethods
def public?
@public
end
def has_ipaper(public = false)
include InstanceMethods
after :store, :upload_to_scribd
before :remove, :delete_from_scribd
@public = !!public
end
end
module InstanceMethods
def self.included(base)
base.extend ClassMethods
end
def upload_to_scribd files
res = ScribdCarrierWave::upload(self)
set_params res
end
def delete_from_scribd
ScribdCarrierWave::destroy(self)
end
def display_ipaper(options = {})
id = options.delete(:id)
<<-END
<script type="text/javascript" src="
<div id="embedded_doc#{id}">#{options.delete(:alt)}</div>
<script type="text/javascript">
var scribd_doc = scribd.Document.getDoc(#{ipaper_id}, '#{ipaper_access_key}');
scribd_doc.addParam( 'jsapi_version', 2 );
#{options.map do |k,v|
" scribd_doc.addParam('#{k.to_s}', #{v.is_a?(String) ? "'#{v.to_s}'" : v.to_s});"
end.join("\n")}
scribd_doc.write("embedded_doc
</script>
END
end
def fullscreen_url
"http://www.scribd.com/fullscreen/#{ipaper_id}?access_key=#{ipaper_access_key}"
end
def ipaper_id
self.model.send("#{self.mounted_as.to_s}_ipaper_id")
end
def ipaper_access_key
self.model.send("#{self.mounted_as.to_s}_ipaper_access_key")
end
# Responds the Scribd::Document associated with this model, or nil if it does not exist.
def ipaper_document
@document ||= ScribdCarrierWave::<API key>(ipaper_id)
end
private
def set_params res
self.model.update_attributes({"#{self.mounted_as}_ipaper_id" => res.doc_id,
"#{self.mounted_as}_ipaper_access_key" => res.access_key})
end
end
private
def scribd_user
Scribd::API.instance.key = ScribdCarrierWave.config.key
Scribd::API.instance.<API key>.config.secret
@scribd_user = Scribd::User.login(ScribdCarrierWave.config.username, ScribdCarrierWave.config.password)
end
end
end
CarrierWave::Uploader::Base.send(:include, ScribdCarrierWave) if Object.const_defined?("CarrierWave")
|
var gulp = require('gulp');
var babel = require('gulp-babel');
var concat = require('gulp-concat');
var merge = require('merge-stream');
var stylus = require('gulp-stylus');
var rename = require("gulp-rename");
var uglify = require("gulp-uglify");
var cssmin = require("gulp-cssmin");
var ngAnnotate = require('gulp-ng-annotate');
var nib = require("nib");
var watch = require('gulp-watch');
function compileJs(devOnly) {
var othersUmd = gulp.src(['src*.js', '!src/main.js'])
.pipe(babel({
modules: 'umdStrict',
moduleRoot: 'angular-chatbar',
moduleIds: true
})),
mainUmd = gulp.src('src/main.js')
.pipe(babel({
modules: 'umdStrict',
moduleIds: true,
moduleId: 'angular-chatbar'
})),
stream = merge(othersUmd, mainUmd)
.pipe(concat('angular-chatbar.umd.js'))
.pipe(gulp.dest('dist'))
;
if (!devOnly) {
stream = stream
.pipe(ngAnnotate())
.pipe(uglify())
.pipe(rename('angular-chatbar.umd.min.js'))
.pipe(gulp.dest('dist'));
}
return stream;
}
function compileCss(name, devOnly) {
var stream = gulp.src('styles/' + name + '.styl')
.pipe(stylus({use: nib()}))
.pipe(rename('angular-' + name + '.css'))
.pipe(gulp.dest('dist'))
;
if (!devOnly) {
stream = stream.pipe(cssmin())
.pipe(rename('angular-' + name + '.min.css'))
.pipe(gulp.dest('dist'));
}
return stream;
}
function compileAllCss(devOnly) {
var streams = [];
['chatbar', 'chatbar.default-theme', 'chatbar.default-animations'].forEach(function (name) {
streams.push(compileCss(name, devOnly));
});
return merge.apply(null, streams);
}
gulp.task('default', function() {
return merge.apply(compileJs(), compileAllCss());
});
gulp.task('_watch', function() {
watch('styles*.styl', function () {
compileAllCss(true);
});
watch('src*.js', function () {
compileJs(true);
});
});
gulp.task('watch', ['default', '_watch']);
|
package br.ufrj.g2matricula.domain;
import org.springframework.data.elasticsearch.annotations.Document;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.util.Objects;
import br.ufrj.g2matricula.domain.enumeration.MatriculaStatus;
/**
* A Matricula.
*/
@Entity
@Table(name = "matricula")
@Document(indexName = "matricula")
public class Matricula implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Enumerated(EnumType.STRING)
@Column(name = "status", nullable = false)
private MatriculaStatus status;
@ManyToOne
private Aluno dreAluno;
@ManyToOne
private Curso curso;
// <API key> - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public MatriculaStatus getStatus() {
return status;
}
public Matricula status(MatriculaStatus status) {
this.status = status;
return this;
}
public void setStatus(MatriculaStatus status) {
this.status = status;
}
public Aluno getDreAluno() {
return dreAluno;
}
public Matricula dreAluno(Aluno aluno) {
this.dreAluno = aluno;
return this;
}
public void setDreAluno(Aluno aluno) {
this.dreAluno = aluno;
}
public Curso getCurso() {
return curso;
}
public Matricula curso(Curso curso) {
this.curso = curso;
return this;
}
public void setCurso(Curso curso) {
this.curso = curso;
}
// <API key> - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Matricula matricula = (Matricula) o;
if (matricula.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), matricula.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "Matricula{" +
"id=" + getId() +
", status='" + getStatus() + "'" +
"}";
}
}
|
# <API key>
Docker container for RhodeCode Community Edition repository management platform
# WIP
|
<?php
class Admin_GeneralModel extends CI_Model {
public function <API key>()
{
$this->db->select('CID, CategoryName');
$this->db->from('<API key>');
$this->db->order_by('Ordering');
$query = $this->db->get();
if($query->num_rows())
return $query;
else
return FALSE;
}
public function GetAdminModuleList()
{
$this->db->select('MID, CID, ModuleName, DisplayName');
$this->db->from('admin_module');
$this->db->order_by('Ordering');
$query = $this->db->get();
if($query->num_rows())
return $query;
else
return FALSE;
}
public function <API key>($MID = NULL)
{
$this->db->select('AID, MID, Action');
$this->db->from('admin_module_action');
if($MID != NULL)
$this->db->where('MID', $MID);
$query = $this->db->get();
if($query->num_rows())
return $query->result();
else
return FALSE;
}
}
?>
|
#ifndef SYMTAB_H
#define SYMTAB_H
#include "symbol.h"
void symtab_init();
void push_scope();
void pop_scope();
symbol *bind_symbol(char *name);
symbol *lookup_symbol(char *name);
void print_symtab();
#endif
|
RSpec.describe("executables", skip_db_cleaner: true) do
include SharedSpecSetup
before do
#migrations don't work if we are still connected to the db
ActiveRecord::Base.remove_connection
end
it "extracts the schema" do
output = `bin/extract #{config_filename} production #{schema_filename} 2>&1`
expect(output).to match(/extracted to/)
expect(output).to match(/#{schema_filename}/)
end
it "transfers the schema" do
output = `bin/transfer-schema #{config_filename} production test config/include_tables.txt 2>&1`
expect(output).to match(/transferred schema from production to test/)
end
end
|
## S3proxy - serve S3 files simply
S3proxy is a simple flask-based REST web application which can expose files (keys) stored in the AWS Simple Storage Service (S3) via a simple REST api.
What does this do?
S3proxy takes a set of AWS credentials and an S3 bucket name and provides GET and HEAD endpoints on the files within the bucket. It uses the [boto][boto] library for internal access to S3. For example, if your bucket has the following file:
s3://mybucket/examples/path/to/myfile.txt
then running S3proxy on a localhost server (port 5000) would enable you read (GET) this file at:
http://localhost:5000/files/examples/path/to/myfile.txt
Support exists in S3proxy for the `byte-range` header in a GET request. This means that the API can provide arbitrary parts of S3 files if requested/supported by the application making the GET request.
Why do this?
S3proxy simplifies access to private S3 objects. While S3 already provides [a complete REST API][s3_api], this API requires signed authentication headers or parameters that are not always obtainable within existing applications (see below), or overly complex for simple development/debugging tasks.
In fact, however, S3proxy was specifically designed to provide a compatability layer for viewing DNA sequencing data in(`.bam` files) using [IGV][igv]. While IGV already includes an interface for reading bam files from an HTTP endpoint, it does not support creating signed requests as required by the AWS S3 API (IGV does support HTTP Basic Authentication, a feature that I would like to include in S3proxy in the near future). Though it is in principal possible to provide a signed AWS-compatible URL to IGV, IGV will still not be able to create its own signed URLs necessary for accessing `.bai` index files, usually located in the same directory as the `.bam` file. Using S3proxy you can expose the S3 objects via a simplified HTTP API which IGV can understand and access directly.
This project is in many ways similar to [S3Auth][s3auth], a hosted service which provides a much more complete API to a private S3 bucket. I wrote S3proxy as a faster, simpler solution-- and because S3Auth requires a domain name and access to the `CNAME` record in order to function. If you want a more complete API (read: more than just GET/HEAD at the moment) should check them out!
Features
- Serves S3 file objects via standard GET request, optionally providing only a part of a file using the `byte-range` header.
- Easy to configure via a the `config.yaml` file-- S3 keys and bucket name is all you need!
- Limited support for simple url-rewriting where necessary.
- Uses the werkzeug [`SimpleCache` module][simplecache] to cache S3 object identifiers (but not data) in order to reduce latency and lookup times.
Usage
# Requirements
To run S3proxy, you will need:
- [Flask][flask]
- [boto][boto]
- [PyYAML][pyyaml]
- An Amazon AWS account and keys with appropriate S3 access
# Installation/Configuration
At the moment, there is no installation. Simply put your AWS keys and bucket name into the config.yaml file:
yaml
AWS_ACCESS_KEY_ID: ''
<API key>: ''
bucket_name: ''
You may also optionally specify a number of "rewrite" rules. These are simple pairs of a regular expression and a replacement string which can be used to internally redirect (Note, the API does not actually currently send a REST 3XX redirect header) file paths. The example in the config.yaml file reads:
yaml
rewrite_rules:
bai_rule:
from: ".bam.bai$"
to: ".bai"
which will match all url/filenames ending with ".bam.bai" and rewrite this to ".bai".
If you do not wish to use any rewrite_rules, simply leave this commented out.
# Running S3cmd:
Once you have filled out the config.yaml file, you can test out S3proxy simply by running on the command line:
python app.py
*Note*: Running using the built-in flask server is not recommended for anything other than debugging. Refer to [these deployment options][wsgi_server] for instructions on how to set up a flask applicaiton in a WSGI framework.
# Options
If you wish to see more debug-level output (headers, etc.), use the `--debug` option. You may also specify a yaml configuration file to load using the `--config` parameter.
Important considerations and caveats
S3proxy should not be used in production-level or open/exposed servers! There is currently no security provided by S3proxy (though I may add basic HTTP authentication later). Once given the AWS credentials, S3proxy will serve any path available to it. And, although I restrict requests to GET and HEAD only, I cannot currently guarantee that a determined person would not be able to execute a PUT/UPDATE/DELETE request using this service. Finally, I highly recommend you create a separate [IAM role][iam_roles] in AWS with limited access and permisisons to S3 only for use with S3proxy.
Future development
- Implement HTTP Basic Authentication to provide some level of security.
- Implement other error codes and basic REST responses.
- Add ability to log to a file and specify a `--log-level` (use the Python logging module)
[boto]: http://boto.readthedocs.org/
[flask]: http://flask.pocoo.org/
[pyyaml]: http://pyyaml.org/wiki/PyYAML
[s3_api]: http://docs.aws.amazon.com/AmazonS3/latest/API/APIRest.html
[igv]: http:
[wsgi_server]: http://flask.pocoo.org/docs/deploying/
[iam_roles]: http://aws.amazon.com/iam/
[simplecache]: http://flask.pocoo.org/docs/patterns/caching/
[s3auth]: http:
|
Title: Survey data
Template: survey
Slug: survey/data
Github: True
The code to clean and process the survey data is available in the [GitHub repository](https:
<div class="row">
<div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">
<div class="github-widget" data-repo="andrewheiss/<API key>"></div>
</div>
</div>
The free response answers for respondents who requested anonymity have been
redacted.
- CSV file: [`<API key>.csv`](/files/data/<API key>.csv)
- R file: [`<API key>.rds`](/files/data/<API key>.rds)
|
// @flow
import { StyleSheet } from 'react-native';
import { colors } from '../../themes';
const styles = StyleSheet.create({
divider: {
height: 1,
marginHorizontal: 0,
backgroundColor: colors.darkDivider,
},
});
export default styles;
|
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_27) on Wed Nov 21 16:03:26 EST 2012 -->
<TITLE>
<API key>
</TITLE>
<META NAME="date" CONTENT="2012-11-21">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="<API key>";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/<API key>.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../org/pentaho/di/resource/ResourceUtil.html" title="class in org.pentaho.di.resource"><B>PREV CLASS</B></A>
<A HREF="../../../../org/pentaho/di/resource/<API key>.html" title="class in org.pentaho.di.resource"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/pentaho/di/resource/<API key>.html" target="_top"><B>FRAMES</B></A>
<A HREF="<API key>.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | CONSTR | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | CONSTR | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<H2>
<FONT SIZE="-1">
org.pentaho.di.resource</FONT>
<BR>
Interface <API key></H2>
<HR>
<DL>
<DT><PRE>public interface <B><API key></B></DL>
</PRE>
<P>
<HR>
<P>
<A NAME="method_summary"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/pentaho/di/resource/<API key>.html#<API key>(org.pentaho.di.resource.<API key>, int)"><API key></A></B>(<A HREF="../../../../org/pentaho/di/resource/<API key>.html" title="interface in org.pentaho.di.resource"><API key></A> ref,
int indention)</CODE>
<BR>
Allows injection of additional relevant properties in the
to-xml of the Resource Reference.</TD>
</TR>
</TABLE>
<P>
<A NAME="method_detail"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="<API key>(org.pentaho.di.resource.<API key>, int)"></A><H3>
<API key></H3>
<PRE>
<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> <B><API key></B>(<A HREF="../../../../org/pentaho/di/resource/<API key>.html" title="interface in org.pentaho.di.resource"><API key></A> ref,
int indention)</PRE>
<DL>
<DD>Allows injection of additional relevant properties in the
to-xml of the Resource Reference.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>ref</CODE> - The Resource Reference Holder (a step, or a job entry)<DD><CODE>indention</CODE> - If -1, then no indenting, otherwise, it's the indent level to indent the XML strings
<DT><B>Returns:</B><DD>String of injected XML</DL>
</DD>
</DL>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/<API key>.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../org/pentaho/di/resource/ResourceUtil.html" title="class in org.pentaho.di.resource"><B>PREV CLASS</B></A>
<A HREF="../../../../org/pentaho/di/resource/<API key>.html" title="class in org.pentaho.di.resource"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/pentaho/di/resource/<API key>.html" target="_top"><B>FRAMES</B></A>
<A HREF="<API key>.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | CONSTR | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | CONSTR | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
</BODY>
</HTML>
|
require 'ffi'
module ProcessShared
module Posix
module Errno
extend FFI::Library
ffi_lib FFI::Library::LIBC
attach_variable :errno, :int
# Replace methods in +syms+ with error checking wrappers that
# invoke the original method and raise a {SystemCallError} with
# the current errno if the return value is an error.
# Errors are detected if the block returns true when called with
# the original method's return value.
def error_check(*syms, &is_err)
unless block_given?
is_err = lambda { |v| (v == -1) }
end
syms.each do |sym|
method = self.method(sym)
new_method_body = proc do |*args|
ret = method.call(*args)
if is_err.call(ret)
raise SystemCallError.new("error in #{sym}", Errno.errno)
else
ret
end
end
<API key>(sym, &new_method_body)
define_method(sym, &new_method_body)
end
end
end
end
end
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http:
<!-- UASR: Unified Approach to Speech Synthesis and Recognition
< - Documentation home page
<
< AUTHOR : Matthias Wolff
< PACKAGE: n/a
<
< Copyright 2013 UASR contributors (see COPYRIGHT file)
< - Chair of System Theory and Speech Technology, TU Dresden
< - Chair of Communications Engineering, BTU Cottbus
<
< This file is part of UASR.
<
< UASR is free software: you can redistribute it and/or modify it under the
< terms of the GNU Lesser General Public License as published by the Free
< Software Foundation, either version 3 of the License, or (at your option)
< any later version.
<
< UASR is distributed in the hope that it will be useful, but WITHOUT ANY
< WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
< FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
< more details.
<
< You should have received a copy of the GNU Lesser General Public License
< along with UASR. If not, see [http:
<html>
<head>
<link rel=stylesheet type="text/css" href="toc.css">
</head>
<script type="text/javascript">
if (top==self)
top.location = "index.html";
</script>
<script type="text/javascript" src="default.js"></script>
<body onload="void(__tocInit('tocRoot'));">
<h2 class="CONT">Manual</h2>
<noscript><div class="noscript">
JavaScript is not enabled.
</div></noscript>
<div class="tocRoot" id="tocRoot">
<div class="tocLeaf"><a class="toc" href="home.html" target="contFrame" title="Database DocumentationHome Page">Home</a></div>
<div class="tocNode" id="<API key>">
<a class="toc" href="javascript:__tocToggle('<API key>');">[−]</a> <img src="resources/book_obj.gif" class="tocIcon"> Scripts
<!--{{ TOC -->
<div class="tocLeaf"><a href="automatic/vau.itp.html" target="contFrame" title="Voice authentication database plug-in. "
><img src="resources/blank_stc.gif" class="tocIcon"> <img src="resources/lib_obj.gif" class="tocIcon"> vau.itp</a></div>
<!--}} TOC -->
</div>
</div>
</body>
</html>
|
'use strict';
const _ = require('lodash');
const co = require('co');
const Promise = require('bluebird');
const AWS = require('aws-sdk');
AWS.config.region = 'us-east-1';
const cloudwatch = Promise.promisifyAll(new AWS.CloudWatch());
const Lambda = new AWS.Lambda();
const START_TIME = new Date('2017-06-07T01:00:00.000Z');
const DAYS = 2;
const ONE_DAY = 24 * 60 * 60 * 1000;
let addDays = (startDt, n) => new Date(startDt.getTime() + ONE_DAY * n);
let getFuncStats = co.wrap(function* (funcName) {
let getStats = co.wrap(function* (startTime, endTime) {
let req = {
MetricName: 'Duration',
Namespace: 'AWS/Lambda',
Period: 60,
Dimensions: [ { Name: 'FunctionName', Value: funcName } ],
Statistics: [ 'Maximum' ],
Unit: 'Milliseconds',
StartTime: startTime,
EndTime: endTime
};
let resp = yield cloudwatch.<API key>(req);
return resp.Datapoints.map(dp => {
return {
timestamp: dp.Timestamp,
value: dp.Maximum
};
});
});
let stats = [];
for (let i = 0; i < DAYS; i++) {
// CloudWatch only allows us to query 1440 data points per request, which
// at 1 min period is 24 hours
let startTime = addDays(START_TIME, i);
let endTime = addDays(startTime, 1);
let oneDayStats = yield getStats(startTime, endTime);
stats = stats.concat(oneDayStats);
}
return _.sortBy(stats, s => s.timestamp);
});
let listFunctions = co.wrap(function* (marker, acc) {
acc = acc || [];
let resp = yield Lambda.listFunctions({ Marker: marker, MaxItems: 100 }).promise();
let functions = resp.Functions
.map(f => f.FunctionName)
.filter(fn => fn.includes("aws-coldstart") && !fn.endsWith("run"));
acc = acc.concat(functions);
if (resp.NextMarker) {
return yield listFunctions(resp.NextMarker, acc);
} else {
return acc;
}
});
listFunctions()
.then(co.wrap(function* (funcs) {
for (let func of funcs) {
let stats = yield getFuncStats(func);
stats.forEach(stat => console.log(`${func},${stat.timestamp},${stat.value}`));
}
}));
|
from __future__ import absolute_import, division, print_function, unicode_literals
import string
import urllib
try:
from urllib.parse import urlparse, urlencode, urljoin, parse_qsl, urlunparse
from urllib.request import urlopen, Request
from urllib.error import HTTPError
except ImportError:
from urlparse import urlparse, urljoin, urlunparse, parse_qsl
from urllib import urlencode
from urllib2 import urlopen, Request, HTTPError
from random import SystemRandom
try:
<API key> = (string.ascii_letters +
string.digits)
except AttributeError:
<API key> = (string.ascii_letters.decode('ascii') +
string.digits.decode('ascii'))
def random_ascii_string(length):
random = SystemRandom()
return ''.join([random.choice(<API key>) for x in range(length)])
def url_query_params(url):
"""Return query parameters as a dict from the specified URL.
:param url: URL.
:type url: str
:rtype: dict
"""
return dict(parse_qsl(urlparse(url).query, True))
def url_dequery(url):
"""Return a URL with the query component removed.
:param url: URL to dequery.
:type url: str
:rtype: str
"""
url = urlparse(url)
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
'',
url.fragment))
def build_url(base, additional_params=None):
"""Construct a URL based off of base containing all parameters in
the query portion of base plus any additional parameters.
:param base: Base URL
:type base: str
::param additional_params: Additional query parameters to include.
:type additional_params: dict
:rtype: str
"""
url = urlparse(base)
query_params = {}
query_params.update(parse_qsl(url.query, True))
if additional_params is not None:
query_params.update(additional_params)
for k, v in additional_params.items():
if v is None:
query_params.pop(k)
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
urlencode(query_params),
url.fragment))
|
#!/bin/bash
# data in Empar_paper/data/<API key>
#length1000_b100.tar length1000_b150.tar length1000_b200.tar
#<API key>.fa
MOD=ssm
ITER=2 # number of data sets
bl=100
#prep output files
OUT_lik='<API key>'$bl'_'$MOD'_E.txt'
OUT_iter='<API key>'$bl'_'$MOD'_E.txt'
OUT_time='<API key>'$bl'_'$MOD'_E.txt'
OUT_nc='<API key>'$bl'_'$MOD'_E.txt'
[[ -f $OUT_lik ]] && rm -f $OUT_lik
[[ -f $OUT_iter ]] && rm -f $OUT_iter
[[ -f $OUT_time ]] && rm -f $OUT_time
[[ -f $OUT_nc ]] && rm -f $OUT_nc
touch $OUT_lik
touch $OUT_iter
touch $OUT_time
touch $OUT_nc
# run from within the scripts folder
for i in $(seq 0 1 $ITER)
do
#extract a single file from tar
tar -xvf ../data/<API key>/length1000_b$bl.tar length1000_b$bl\_num$i.fa
./main ../data/trees/treeE.tree length1000_b$bl\_num$i.fa $MOD > out.txt
cat out.txt | grep Likelihood | cut -d':' -f2 | xargs >> $OUT_lik
cat out.txt | grep Iter | cut -d':' -f2 | xargs >> $OUT_iter
cat out.txt | grep Time | cut -d':' -f2 | xargs >> $OUT_time
cat out.txt | grep "negative branches" | cut -d':' -f2 | xargs >> $OUT_nc
rm out.txt
# not poluting the folder with single files
rm length1000_b$bl\_num$i.fa
done
mv $OUT_time ../results/ssm/gennonh_data/balanc4GenNonh/.
mv $OUT_lik ../results/ssm/gennonh_data/balanc4GenNonh/.
mv $OUT_iter ../results/ssm/gennonh_data/balanc4GenNonh/.
mv $OUT_nc ../results/ssm/gennonh_data/balanc4GenNonh/.
|
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
using System.IO;
#endif
namespace SpritesAndBones.Editor
{
[CustomEditor(typeof(Skin2D))]
public class Skin2DEditor : UnityEditor.Editor
{
private Skin2D skin;
private float baseSelectDistance = 0.1f;
private float <API key> = 0.1f;
private int selectedIndex = -1;
private Color handleColor = Color.green;
private void OnEnable()
{
skin = (Skin2D)target;
}
public override void OnInspectorGUI()
{
<API key>();
EditorGUILayout.Separator();
if (GUILayout.Button("Toggle Mesh Outline"))
{
Skin2D.showMeshOutline = !Skin2D.showMeshOutline;
}
EditorGUILayout.Separator();
if (skin.GetComponent<SkinnedMeshRenderer>().sharedMesh != null && GUILayout.Button("Save as Prefab"))
{
skin.SaveAsPrefab();
}
EditorGUILayout.Separator();
if (skin.GetComponent<SkinnedMeshRenderer>().sharedMesh != null && GUILayout.Button("Recalculate Bone Weights"))
{
skin.<API key>();
}
EditorGUILayout.Separator();
handleColor = EditorGUILayout.ColorField("Handle Color", handleColor);
<API key> = EditorGUILayout.Slider("Handle Size", baseSelectDistance, 0, 1);
if (baseSelectDistance != <API key>)
{
baseSelectDistance = <API key>;
EditorUtility.SetDirty(this);
SceneView.RepaintAll();
}
if (skin.GetComponent<SkinnedMeshRenderer>().sharedMesh != null && GUILayout.Button("Create Control Points"))
{
skin.CreateControlPoints(skin.GetComponent<SkinnedMeshRenderer>());
}
if (skin.GetComponent<SkinnedMeshRenderer>().sharedMesh != null && GUILayout.Button("Reset Control Points"))
{
skin.<API key>();
}
if (skin.points != null && skin.controlPoints != null && skin.controlPoints.Length > 0
&& selectedIndex != -1 && GUILayout.Button("Reset Selected Control Point"))
{
if (skin.controlPoints[selectedIndex].originalPosition != skin.GetComponent<MeshFilter>().sharedMesh.vertices[selectedIndex])
{
skin.controlPoints[selectedIndex].originalPosition = skin.GetComponent<MeshFilter>().sharedMesh.vertices[selectedIndex];
}
skin.controlPoints[selectedIndex].ResetPosition();
skin.points.SetPoint(skin.controlPoints[selectedIndex]);
}
if (GUILayout.Button("Remove Control Points"))
{
skin.RemoveControlPoints();
}
EditorGUILayout.Separator();
if (skin.GetComponent<SkinnedMeshRenderer>().sharedMesh != null && GUILayout.Button("Generate Mesh Asset"))
{
#if UNITY_EDITOR
// Check if the Meshes directory exists, if not, create it.
if (!Directory.Exists("Assets/Meshes"))
{
AssetDatabase.CreateFolder("Assets", "Meshes");
AssetDatabase.Refresh();
}
Mesh mesh = new Mesh();
mesh.name = skin.GetComponent<SkinnedMeshRenderer>().sharedMesh.name.Replace(".SkinnedMesh", ".Mesh"); ;
mesh.vertices = skin.GetComponent<SkinnedMeshRenderer>().sharedMesh.vertices;
mesh.triangles = skin.GetComponent<SkinnedMeshRenderer>().sharedMesh.triangles;
mesh.normals = skin.GetComponent<SkinnedMeshRenderer>().sharedMesh.normals;
mesh.uv = skin.GetComponent<SkinnedMeshRenderer>().sharedMesh.uv;
mesh.uv2 = skin.GetComponent<SkinnedMeshRenderer>().sharedMesh.uv2;
mesh.bounds = skin.GetComponent<SkinnedMeshRenderer>().sharedMesh.bounds;
<API key>.CreateAsset(mesh, "Meshes/" + skin.gameObject.name + ".Mesh");
#endif
}
if (skin.GetComponent<SkinnedMeshRenderer>().sharedMaterial != null && GUILayout.Button("Generate Material Asset"))
{
#if UNITY_EDITOR
Material material = new Material(skin.GetComponent<SkinnedMeshRenderer>().sharedMaterial);
material.<API key>(skin.GetComponent<SkinnedMeshRenderer>().sharedMaterial);
skin.GetComponent<SkinnedMeshRenderer>().sharedMaterial = material;
if (!Directory.Exists("Assets/Materials"))
{
AssetDatabase.CreateFolder("Assets", "Materials");
AssetDatabase.Refresh();
}
AssetDatabase.CreateAsset(material, "Assets/Materials/" + material.mainTexture.name + ".mat");
Debug.Log("Created material " + material.mainTexture.name + " for " + skin.gameObject.name);
#endif
}
}
private void OnSceneGUI()
{
if (skin != null && skin.GetComponent<SkinnedMeshRenderer>().sharedMesh != null
&& skin.controlPoints != null && skin.controlPoints.Length > 0 && skin.points != null)
{
Event e = Event.current;
Handles.matrix = skin.transform.localToWorldMatrix;
EditorGUI.BeginChangeCheck();
Ray r = HandleUtility.GUIPointToWorldRay(e.mousePosition);
Vector2 mousePos = r.origin;
float selectDistance = HandleUtility.GetHandleSize(mousePos) * baseSelectDistance;
#region Draw vertex handles
Handles.color = handleColor;
for (int i = 0; i < skin.controlPoints.Length; i++)
{
if (Handles.Button(skin.points.GetPoint(skin.controlPoints[i]), Quaternion.identity, selectDistance, selectDistance, Handles.CircleCap))
{
selectedIndex = i;
}
if (selectedIndex == i)
{
EditorGUI.BeginChangeCheck();
skin.controlPoints[i].position = Handles.DoPositionHandle(skin.points.GetPoint(skin.controlPoints[i]), Quaternion.identity);
if (EditorGUI.EndChangeCheck())
{
skin.points.SetPoint(skin.controlPoints[i]);
Undo.RecordObject(skin, "Changed Control Point");
Undo.RecordObject(skin.points, "Changed Control Point");
EditorUtility.SetDirty(this);
}
}
}
#endregion Draw vertex handles
}
}
}
}
|
package com.thilko.springdoc;
@SuppressWarnings("all")
public class CredentialsCode {
Integer age;
double anotherValue;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public double getAnotherValue() {
return anotherValue;
}
public void setAnotherValue(double anotherValue) {
this.anotherValue = anotherValue;
}
}
|
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
/* @var $this yii\web\View */
/* @var $searchModel yii2learning\chartbuilder\models\DatasourceSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = Yii::t('app', 'Datasources');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="datasource-index">
<h1><?= Html::encode($this->title) ?></h1>
<?=$this->render('/_menus') ?>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('<i class="glyphicon glyphicon-plus"></i> '.Yii::t('app', 'Create Datasource'), ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php Pjax::begin(); ?> <?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'name',
// 'created_at',
// 'updated_at',
// 'created_by',
'updated_by:dateTime',
[
'class' => 'yii\grid\ActionColumn',
'options'=>['style'=>'width:150px;'],
'buttonOptions'=>['class'=>'btn btn-default'],
'template'=>'<div class="btn-group btn-group-sm text-center" role="group">{view} {update} {delete} </div>',
]
],
]); ?>
<?php Pjax::end(); ?></div>
|
module Web::Controllers::Books
class Create
include Web::Action
expose :book
params do
param :book do
param :title, presence: true
param :author, presence: true
end
end
def call(params)
if params.valid?
@book = BookRepository.create(Book.new(params[:book]))
redirect_to routes.books_path
end
end
end
end
|
;idta.asm sets up all the intterupt entry points
extern default_handler
extern idt_ftoi
;error interrupt entry point, we need to only push the error code details to stack
%macro error_interrupt 1
global interrupt_handler_%1
interrupt_handler_%1:
push dword %1
jmp common_handler
%endmacro
;regular interrupt entry point, need to push interrupt number and other data
%macro regular_interrupt 1
global interrupt_handler_%1
interrupt_handler_%1:
push dword 0
push dword %1
jmp common_handler
%endmacro
;common handler for all interrupts, saves all necessary stack data and calls our c intterupt handler
common_handler:
push dword ds
push dword es
push dword fs
push dword gs
pusha
call default_handler
popa
pop dword gs
pop dword fs
pop dword es
pop dword ds
add esp, 8
iret
regular_interrupt 0
regular_interrupt 1
regular_interrupt 2
regular_interrupt 3
regular_interrupt 4
regular_interrupt 5
regular_interrupt 6
regular_interrupt 7
error_interrupt 8
regular_interrupt 9
error_interrupt 10
error_interrupt 11
error_interrupt 12
error_interrupt 13
error_interrupt 14
regular_interrupt 15
regular_interrupt 16
error_interrupt 17
%assign i 18
%rep 12
regular_interrupt i
%assign i i+1
%endrep
error_interrupt 30
%assign i 31
%rep 225
regular_interrupt i
%assign i i+1
%endrep
;interrupt setup, adds all of out interrupt handlers to the idt
global idtsetup
idtsetup:
%assign i 0
%rep 256
push interrupt_handler_%[i]
push i
call idt_ftoi
add esp, 8
%assign i i+1
%endrep
ret
|
// @flow
(require('../../lib/git'): any).rebaseRepoMaster = jest.fn();
import {
<API key> as clearCustomCacheDir,
_setCustomCacheDir as setCustomCacheDir,
} from '../../lib/cacheRepoUtils';
import {copyDir, mkdirp} from '../../lib/fileUtils';
import {parseDirString as parseFlowDirString} from '../../lib/flowVersion';
import {
add as gitAdd,
commit as gitCommit,
init as gitInit,
setLocalConfig as gitConfig,
} from '../../lib/git';
import {fs, path, child_process} from '../../lib/node';
import {getNpmLibDefs} from '../../lib/npm/npmLibDefs';
import {testProject} from '../../lib/TEST_UTILS';
import {
<API key> as <API key>,
_installNpmLibDefs as installNpmLibDefs,
_installNpmLibDef as installNpmLibDef,
run,
} from '../install';
const BASE_FIXTURE_ROOT = path.join(__dirname, '<API key>');
function _mock(mockFn) {
return ((mockFn: any): JestMockFn<*, *>);
}
async function touchFile(filePath) {
await fs.close(await fs.open(filePath, 'w'));
}
async function writePkgJson(filePath, pkgJson) {
await fs.writeJson(filePath, pkgJson);
}
describe('install (command)', () => {
describe('<API key>', () => {
it('infers version from path if arg not passed', () => {
return testProject(async ROOT_DIR => {
const ARBITRARY_PATH = path.join(ROOT_DIR, 'some', 'arbitrary', 'path');
await Promise.all([
mkdirp(ARBITRARY_PATH),
touchFile(path.join(ROOT_DIR, '.flowconfig')),
writePkgJson(path.join(ROOT_DIR, 'package.json'), {
name: 'test',
devDependencies: {
'flow-bin': '^0.40.0',
},
}),
]);
const flowVer = await <API key>(ARBITRARY_PATH);
expect(flowVer).toEqual({
kind: 'specific',
ver: {
major: 0,
minor: 40,
patch: 0,
prerel: null,
},
});
});
});
it('uses explicitly specified version', async () => {
const explicitVer = await <API key>('/', '0.7.0');
expect(explicitVer).toEqual({
kind: 'specific',
ver: {
major: 0,
minor: 7,
patch: 0,
prerel: null,
},
});
});
it("uses 'v'-prefixed explicitly specified version", async () => {
const explicitVer = await <API key>('/', 'v0.7.0');
expect(explicitVer).toEqual({
kind: 'specific',
ver: {
major: 0,
minor: 7,
patch: 0,
prerel: null,
},
});
});
});
describe('installNpmLibDefs', () => {
const origConsoleError = console.error;
beforeEach(() => {
(console: any).error = jest.fn();
});
afterEach(() => {
(console: any).error = origConsoleError;
});
it('errors if unable to find a project root (.flowconfig)', () => {
return testProject(async ROOT_DIR => {
const result = await installNpmLibDefs({
cwd: ROOT_DIR,
flowVersion: parseFlowDirString('flow_v0.40.0'),
explicitLibDefs: [],
libdefDir: 'flow-typed',
verbose: false,
overwrite: false,
skip: false,
ignoreDeps: [],
useCacheUntil: 1000 * 60,
});
expect(result).toBe(1);
expect(_mock(console.error).mock.calls).toEqual([
[
'Error: Unable to find a flow project in the current dir or any of ' +
"it's parent dirs!\n" +
'Please run this command from within a Flow project.',
],
]);
});
});
it(
"errors if an explicitly specified libdef arg doesn't match npm " +
'pkgver format',
() => {
return testProject(async ROOT_DIR => {
await touchFile(path.join(ROOT_DIR, '.flowconfig'));
await writePkgJson(path.join(ROOT_DIR, 'package.json'), {
name: 'test',
devDependencies: {
'flow-bin': '^0.40.0',
},
});
const result = await installNpmLibDefs({
cwd: ROOT_DIR,
flowVersion: parseFlowDirString('flow_v0.40.0'),
explicitLibDefs: ['INVALID'],
libdefDir: 'flow-typed',
verbose: false,
overwrite: false,
skip: false,
ignoreDeps: [],
useCacheUntil: 1000 * 60,
});
expect(result).toBe(1);
expect(_mock(console.error).mock.calls).toEqual([
[
'ERROR: Package not found from package.json.\n' +
'Please specify version for the package in the format of `foo@1.2.3`',
],
]);
});
},
);
it('warns if 0 dependencies are found in package.json', () => {
return testProject(async ROOT_DIR => {
await Promise.all([
touchFile(path.join(ROOT_DIR, '.flowconfig')),
writePkgJson(path.join(ROOT_DIR, 'package.json'), {
name: 'test',
}),
]);
const result = await installNpmLibDefs({
cwd: ROOT_DIR,
flowVersion: parseFlowDirString('flow_v0.40.0'),
explicitLibDefs: [],
libdefDir: 'flow-typed',
verbose: false,
overwrite: false,
skip: false,
ignoreDeps: [],
useCacheUntil: 1000 * 60,
});
expect(result).toBe(0);
expect(_mock(console.error).mock.calls).toEqual([
["No dependencies were found in this project's package.json!"],
]);
});
});
});
describe('installNpmLibDef', () => {
const FIXTURE_ROOT = path.join(BASE_FIXTURE_ROOT, 'installNpmLibDef');
const <API key> = path.join(
FIXTURE_ROOT,
'fakeCacheRepo',
);
const origConsoleLog = console.log;
beforeEach(() => {
(console: any).log = jest.fn();
});
afterEach(() => {
(console: any).log = origConsoleLog;
});
it('installs scoped libdefs within a scoped directory', () => {
return testProject(async ROOT_DIR => {
const FAKE_CACHE_DIR = path.join(ROOT_DIR, 'fakeCache');
const FAKE_CACHE_REPO_DIR = path.join(FAKE_CACHE_DIR, 'repo');
const FLOWPROJ_DIR = path.join(ROOT_DIR, 'flowProj');
const FLOWTYPED_DIR = path.join(FLOWPROJ_DIR, 'flow-typed', 'npm');
await Promise.all([mkdirp(FAKE_CACHE_REPO_DIR), mkdirp(FLOWTYPED_DIR)]);
await Promise.all([
copyDir(<API key>, FAKE_CACHE_REPO_DIR),
touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')),
writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), {
name: 'test',
devDependencies: {
'flow-bin': '^0.40.0',
},
}),
]);
await gitInit(FAKE_CACHE_REPO_DIR),
await gitAdd(FAKE_CACHE_REPO_DIR, 'definitions');
await gitCommit(FAKE_CACHE_REPO_DIR, 'FIRST');
setCustomCacheDir(FAKE_CACHE_DIR);
const availableLibDefs = await getNpmLibDefs(
path.join(FAKE_CACHE_REPO_DIR, 'definitions'),
);
await installNpmLibDef(availableLibDefs[0], FLOWTYPED_DIR, false);
});
});
});
describe('end-to-end tests', () => {
const FIXTURE_ROOT = path.join(BASE_FIXTURE_ROOT, 'end-to-end');
const <API key> = path.join(
FIXTURE_ROOT,
'fakeCacheRepo',
);
const origConsoleLog = console.log;
const origConsoleError = console.error;
beforeEach(() => {
(console: any).log = jest.fn();
(console: any).error = jest.fn();
});
afterEach(() => {
(console: any).log = origConsoleLog;
(console: any).error = origConsoleError;
});
async function fakeProjectEnv(runTest) {
return await testProject(async ROOT_DIR => {
const FAKE_CACHE_DIR = path.join(ROOT_DIR, 'fakeCache');
const FAKE_CACHE_REPO_DIR = path.join(FAKE_CACHE_DIR, 'repo');
const FLOWPROJ_DIR = path.join(ROOT_DIR, 'flowProj');
const FLOWTYPED_DIR = path.join(FLOWPROJ_DIR, 'flow-typed', 'npm');
await Promise.all([mkdirp(FAKE_CACHE_REPO_DIR), mkdirp(FLOWTYPED_DIR)]);
await copyDir(<API key>, FAKE_CACHE_REPO_DIR);
await gitInit(FAKE_CACHE_REPO_DIR),
await Promise.all([
gitConfig(FAKE_CACHE_REPO_DIR, 'user.name', 'Test Author'),
gitConfig(FAKE_CACHE_REPO_DIR, 'user.email', 'test@flow-typed.org'),
]);
await gitAdd(FAKE_CACHE_REPO_DIR, 'definitions');
await gitCommit(FAKE_CACHE_REPO_DIR, 'FIRST');
setCustomCacheDir(FAKE_CACHE_DIR);
const origCWD = process.cwd;
(process: any).cwd = () => FLOWPROJ_DIR;
try {
await runTest(FLOWPROJ_DIR);
} finally {
(process: any).cwd = origCWD;
clearCustomCacheDir();
}
});
}
it('installs available libdefs', () => {
return fakeProjectEnv(async FLOWPROJ_DIR => {
// Create some dependencies
await Promise.all([
touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')),
writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), {
name: 'test',
devDependencies: {
'flow-bin': '^0.43.0',
},
dependencies: {
foo: '1.2.3',
},
}),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')),
]);
// Run the install command
await run({
overwrite: false,
verbose: false,
skip: false,
ignoreDeps: [],
explicitLibDefs: [],
});
// Installs libdefs
expect(
await Promise.all([
fs.exists(
path.join(
FLOWPROJ_DIR,
'flow-typed',
'npm',
'flow-bin_v0.x.x.js',
),
),
fs.exists(
path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'),
),
]),
).toEqual([true, true]);
// Signs installed libdefs
const fooLibDefContents = await fs.readFile(
path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'),
'utf8',
);
expect(fooLibDefContents).toContain('// flow-typed signature: ');
expect(fooLibDefContents).toContain('
});
});
it('installs available libdefs using PnP', () => {
return fakeProjectEnv(async FLOWPROJ_DIR => {
// Create some dependencies
await Promise.all([
touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')),
writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), {
name: 'test',
installConfig: {
pnp: true,
},
devDependencies: {
'flow-bin': '^0.43.0',
},
dependencies: {
// Use local foo for initial install
foo: 'file:./foo',
},
}),
mkdirp(path.join(FLOWPROJ_DIR, 'foo')),
]);
await writePkgJson(path.join(FLOWPROJ_DIR, 'foo/package.json'), {
name: 'foo',
version: '1.2.3',
});
// Yarn install so PnP file resolves to local foo
await child_process.execP('yarn install', {cwd: FLOWPROJ_DIR});
// Overwrite foo dep so it's like we installed from registry instead
writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), {
name: 'test',
installConfig: {
pnp: true,
},
devDependencies: {
'flow-bin': '^0.43.0',
},
dependencies: {
foo: '1.2.3',
},
});
// Run the install command
await run({
overwrite: false,
verbose: false,
skip: false,
ignoreDeps: [],
explicitLibDefs: [],
});
// Installs libdefs
expect(
await Promise.all([
fs.exists(
path.join(
FLOWPROJ_DIR,
'flow-typed',
'npm',
'flow-bin_v0.x.x.js',
),
),
fs.exists(
path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'),
),
]),
).toEqual([true, true]);
// Signs installed libdefs
const <API key> = await fs.readFile(
path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'),
);
const fooLibDefContents = <API key>.toString();
expect(fooLibDefContents).toContain('// flow-typed signature: ');
expect(fooLibDefContents).toContain('
});
});
it('ignores libdefs in dev, bundled, optional or peer dependencies when flagged', () => {
return fakeProjectEnv(async FLOWPROJ_DIR => {
// Create some dependencies
await Promise.all([
touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')),
writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), {
name: 'test',
devDependencies: {
foo: '1.2.3',
},
peerDependencies: {
'flow-bin': '^0.43.0',
},
<API key>: {
foo: '2.0.0',
},
bundledDependencies: {
bar: '^1.6.9',
},
dependencies: {
foo: '1.2.3',
},
}),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'bar')),
]);
// Run the install command
await run({
overwrite: false,
verbose: false,
skip: false,
ignoreDeps: ['dev', 'optional', 'bundled'],
explicitLibDefs: [],
});
// Installs libdefs
expect(
await Promise.all([
fs.exists(
path.join(
FLOWPROJ_DIR,
'flow-typed',
'npm',
'flow-bin_v0.x.x.js',
),
),
fs.exists(
path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'),
),
fs.exists(
path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'bar_v1.x.x.js'),
),
]),
).toEqual([true, true, false]);
});
});
it('stubs unavailable libdefs', () => {
return fakeProjectEnv(async FLOWPROJ_DIR => {
// Create some dependencies
await Promise.all([
touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')),
writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), {
name: 'test',
devDependencies: {
'flow-bin': '^0.43.0',
},
dependencies: {
someUntypedDep: '1.2.3',
},
}),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'someUntypedDep')),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')),
]);
// Run the install command
await run({
overwrite: false,
verbose: false,
skip: false,
explicitLibDefs: [],
});
// Installs a stub for someUntypedDep
expect(
await fs.exists(
path.join(
FLOWPROJ_DIR,
'flow-typed',
'npm',
'someUntypedDep_vx.x.x.js',
),
),
).toBe(true);
});
});
it("doesn't stub unavailable libdefs when --skip is passed", () => {
return fakeProjectEnv(async FLOWPROJ_DIR => {
// Create some dependencies
await Promise.all([
touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')),
writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), {
name: 'test',
devDependencies: {
'flow-bin': '^0.43.0',
},
dependencies: {
someUntypedDep: '1.2.3',
},
}),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'someUntypedDep')),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')),
]);
// Run the install command
await run({
overwrite: false,
verbose: false,
skip: true,
explicitLibDefs: [],
});
// Installs a stub for someUntypedDep
expect(
await fs.exists(path.join(FLOWPROJ_DIR, 'flow-typed', 'npm')),
).toBe(true);
});
});
it('overwrites stubs when libdef becomes available (with --overwrite)', () => {
return fakeProjectEnv(async FLOWPROJ_DIR => {
// Create some dependencies
await Promise.all([
touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')),
writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), {
name: 'test',
devDependencies: {
'flow-bin': '^0.43.0',
},
dependencies: {
foo: '1.2.3',
},
}),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')),
]);
await fs.writeFile(
path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_vx.x.x.js'),
'',
);
// Run the install command
await run({
overwrite: true,
verbose: false,
skip: false,
explicitLibDefs: [],
});
// Replaces the stub with the real typedef
expect(
await Promise.all([
fs.exists(
path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_vx.x.x.js'),
),
fs.exists(
path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'),
),
]),
).toEqual([false, true]);
});
});
it("doesn't overwrite tweaked libdefs (without --overwrite)", () => {
return fakeProjectEnv(async FLOWPROJ_DIR => {
// Create some dependencies
await Promise.all([
touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')),
writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), {
name: 'test',
devDependencies: {
'flow-bin': '^0.43.0',
},
dependencies: {
foo: '1.2.3',
},
}),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')),
]);
// Run the install command
await run({
overwrite: false,
verbose: false,
skip: false,
explicitLibDefs: [],
});
const libdefFilePath = path.join(
FLOWPROJ_DIR,
'flow-typed',
'npm',
'foo_v1.x.x.js',
);
// Tweak the libdef for foo
const libdefFileContent =
(await fs.readFile(libdefFilePath, 'utf8')) + '\n// TWEAKED!';
await fs.writeFile(libdefFilePath, libdefFileContent);
// Run install command again
await run({
overwrite: false,
verbose: false,
skip: false,
explicitLibDefs: [],
});
// Verify that the tweaked libdef file wasn't overwritten
expect(await fs.readFile(libdefFilePath, 'utf8')).toBe(
libdefFileContent,
);
});
});
it('overwrites tweaked libdefs when --overwrite is passed', () => {
return fakeProjectEnv(async FLOWPROJ_DIR => {
// Create some dependencies
await Promise.all([
touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')),
writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), {
name: 'test',
devDependencies: {
'flow-bin': '^0.43.0',
},
dependencies: {
foo: '1.2.3',
},
}),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')),
]);
// Run the install command
await run({
overwrite: false,
verbose: false,
skip: false,
explicitLibDefs: [],
});
const libdefFilePath = path.join(
FLOWPROJ_DIR,
'flow-typed',
'npm',
'foo_v1.x.x.js',
);
// Tweak the libdef for foo
const libdefFileContent = await fs.readFile(libdefFilePath, 'utf8');
await fs.writeFile(libdefFilePath, libdefFileContent + '\n// TWEAKED!');
// Run install command again
await run({
overwrite: true,
skip: false,
verbose: false,
explicitLibDefs: [],
});
// Verify that the tweaked libdef file wasn't overwritten
expect(await fs.readFile(libdefFilePath, 'utf8')).toBe(
libdefFileContent,
);
});
});
it('uses flow-bin defined in another package.json', () => {
return fakeProjectEnv(async FLOWPROJ_DIR => {
// Create some dependencies
await Promise.all([
touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')),
writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), {
name: 'test',
dependencies: {
foo: '1.2.3',
},
}),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')),
writePkgJson(path.join(FLOWPROJ_DIR, '..', 'package.json'), {
name: 'parent',
devDependencies: {
'flow-bin': '^0.45.0',
},
}),
mkdirp(path.join(FLOWPROJ_DIR, '..', 'node_modules', 'flow-bin')),
]);
// Run the install command
await run({
overwrite: false,
verbose: false,
skip: false,
packageDir: path.join(FLOWPROJ_DIR, '..'),
explicitLibDefs: [],
});
// Installs libdef
expect(
await fs.exists(
path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'),
),
).toEqual(true);
});
});
it('uses .flowconfig from specified root directory', () => {
return fakeProjectEnv(async FLOWPROJ_DIR => {
// Create some dependencies
await Promise.all([
mkdirp(path.join(FLOWPROJ_DIR, 'src')),
writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), {
name: 'test',
devDependencies: {
'flow-bin': '^0.43.0',
},
dependencies: {
foo: '1.2.3',
},
}),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')),
]);
await touchFile(path.join(FLOWPROJ_DIR, 'src', '.flowconfig'));
// Run the install command
await run({
overwrite: false,
verbose: false,
skip: false,
rootDir: path.join(FLOWPROJ_DIR, 'src'),
explicitLibDefs: [],
});
// Installs libdef
expect(
await fs.exists(
path.join(
FLOWPROJ_DIR,
'src',
'flow-typed',
'npm',
'foo_v1.x.x.js',
),
),
).toEqual(true);
});
});
});
});
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="refresh" content="0;URL=../../openssl_sys/fn.BN_exp.html">
</head>
<body>
<p>Redirecting to <a href="../../openssl_sys/fn.BN_exp.html">../../openssl_sys/fn.BN_exp.html</a>...</p>
<script>location.replace("../../openssl_sys/fn.BN_exp.html" + location.search + location.hash);</script>
</body>
</html>
|
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { assign } from 'lodash'
import autoBind from '../utils/autoBind'
const styles = {
'ClosedPanelWrapper': {
height: '40px'
},
'PanelWrapper': {
position: 'relative'
},
'Over': {
border: '1px dashed white',
overflowY: 'hidden'
},
'PanelTitle': {
width: '100%',
height: '40px',
lineHeight: '40px',
backgroundColor: '#000',
color: '#fff',
paddingLeft: '10px',
position: 'relative',
whiteSpace: 'nowrap',
overflowX: 'hidden',
textOverflow: 'ellipsis',
paddingRight: '8px',
cursor: 'pointer',
WebkitUserSelect: 'none',
userSelect: 'none'
},
'Handle': {
cursor: '-webkit-grab',
position: 'absolute',
zIndex: '2',
color: 'white',
right: '10px',
fontSize: '16px',
top: '12px'
},
'OpenPanel': {
position: 'relative',
zIndex: '2',
top: '0',
left: '0',
padding: '7px',
paddingTop: '5px',
maxHeight: '30%',
display: 'block'
},
'ClosedPanel': {
height: '0',
position: 'relative',
zIndex: '2',
top: '-1000px',
left: '0',
overflow: 'hidden',
maxHeight: '0',
display: 'none'
}
}
class Panel extends Component {
constructor() {
super()
this.state = {
dragIndex: null,
overIndex: null,
isOver: false
}
autoBind(this, [
'handleTitleClick', 'handleDragStart', 'handleDragOver', 'handleDragEnter',
'handleDragLeave', 'handleDrop', 'handleDragEnd'
])
}
handleTitleClick() {
const { index, isOpen, openPanel } = this.props
openPanel(isOpen ? -1 : index)
}
handleDragStart(e) {
// e.target.style.opacity = '0.4'; // this / e.target is the source node.
e.dataTransfer.setData('index', e.target.dataset.index)
}
handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault() // Necessary. Allows us to drop.
}
return false
}
handleDragEnter(e) {
const overIndex = e.target.dataset.index
if (e.dataTransfer.getData('index') !== overIndex) {
// e.target.classList.add('Over') // e.target is the current hover target.
this.setState({ isOver: true })
}
}
handleDragLeave() {
this.setState({ isOver: false })
// e.target.classList.remove('Over') // e.target is previous target element.
}
handleDrop(e) {
if (e.stopPropagation) {
e.stopPropagation() // stops the browser from redirecting.
}
const dragIndex = e.dataTransfer.getData('index')
const dropIndex = this.props.index.toString()
if (dragIndex !== dropIndex) {
this.props.reorder(dragIndex, dropIndex)
}
return false
}
handleDragEnd() {
this.setState({ isOver: false, dragIndex: null, overIndex: null })
}
render() {
const { isOpen, orderable } = this.props
const { isOver } = this.state
return (
<div
style={assign({}, styles.PanelWrapper, isOpen ? {} : styles.ClosedPanelWrapper, isOver ? styles.Over : {})}
onDragStart={this.handleDragStart}
onDragEnter={this.handleDragEnter}
onDragOver={this.handleDragOver}
onDragLeave={this.handleDragLeave}
onDrop={this.handleDrop}
onDragEnd={this.handleDragEnd}
>
<div
style={styles.PanelTitle}
onClick={this.handleTitleClick}
draggable={orderable}
data-index={this.props.index}
>
{this.props.header}
{orderable && (<i className="fa fa-th" style={styles.Handle}></i>)}
</div>
{
isOpen &&
(
<div style={isOpen ? styles.OpenPanel : styles.ClosedPanel}>
{this.props.children}
</div>
)
}
</div>
)
}
}
Panel.propTypes = {
children: PropTypes.any,
index: PropTypes.any,
openPanel: PropTypes.func,
isOpen: PropTypes.any,
header: PropTypes.any,
orderable: PropTypes.any,
reorder: PropTypes.func
}
Panel.defaultProps = {
isOpen: false,
header: '',
orderable: false
}
export default Panel
|
'use strict';
// src\services\message\hooks\timestamp.js
// Use this hook to manipulate incoming or outgoing data.
const defaults = {};
module.exports = function(options) {
options = Object.assign({}, defaults, options);
return function(hook) {
const usr = hook.params.user;
const txt = hook.data.text;
hook.data = {
text: txt,
createdBy: usr._id,
createdAt: Date.now()
}
};
};
|
package fr.lteconsulting.pomexplorer.commands;
import fr.lteconsulting.pomexplorer.AppFactory;
import fr.lteconsulting.pomexplorer.Client;
import fr.lteconsulting.pomexplorer.Log;
public class HelpCommand
{
@Help( "gives this message" )
public void main( Client client, Log log )
{
log.html( AppFactory.get().commands().help() );
}
}
|
// DORDoneHUD.h
// DORDoneHUD
#import <UIKit/UIKit.h>
@interface DORDoneHUD : NSObject
+ (void)show:(UIView *)view message:(NSString *)messageText completion:(void (^)(void))completionBlock;
+ (void)show:(UIView *)view message:(NSString *)messageText;
+ (void)show:(UIView *)view;
@end
|
namespace CAAssistant.Models
{
public class ClientFileViewModel
{
public ClientFileViewModel()
{
}
public ClientFileViewModel(ClientFile clientFile)
{
Id = clientFile.Id;
FileNumber = clientFile.FileNumber;
ClientName = clientFile.ClientName;
ClientContactPerson = clientFile.ClientContactPerson;
AssociateReponsible = clientFile.AssociateReponsible;
CaSign = clientFile.CaSign;
DscExpiryDate = clientFile.DscExpiryDate;
FileStatus = clientFile.FileStatus;
}
public string Id { get; set; }
public int FileNumber { get; set; }
public string ClientName { get; set; }
public string ClientContactPerson { get; set; }
public string AssociateReponsible { get; set; }
public string CaSign { get; set; }
public string DscExpiryDate { get; set; }
public string FileStatus { get; set; }
public string UserName { get; set; }
public <API key> InitialFileStatus { get; set; }
}
}
|
<?php
/**
* Task asset object
*
* @package Todoyu
* @subpackage Assets
*/
class <API key> extends TodoyuAssetsAsset {
/**
* Get task ID
*
* @return Integer
*/
public function getTaskID() {
return $this->getParentID();
}
/**
* Get task object
*
* @return Task
*/
public function getTask() {
return <API key>::getTask($this->getTaskID());
}
}
?>
|
// <auto-generated>
// This code was generated by a tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
namespace NewsSystem.Web.Admin
{
public partial class Edit
{
}
}
|
title: Stylesheets and JavaScript - Fabricator
layout: 2-column
section: Documentation
{{#markdown}}
# Stylesheets and JavaScript
> How to work with CSS and JS within Fabricator
Fabricator comes with little opinion about how you should architect your Stylesheets and JavaScript. Each use case is different, so it's up to you to define what works best.
Out of the box, you'll find a single `.scss` and `.js` file. These are the entry points for Sass compilation and Webpack respectively. It is recommended that you leverage the module importing features of each preprocessor to compile your toolkit down to a single `.css` and `.js` file. Practically speaking, you should be able to drop these two files into any application and have full access to your entire toolkit.
{{/markdown}}
|
<?php
namespace IdeHelper\Test\TestCase\Utility;
use Cake\Core\Configure;
use Cake\TestSuite\TestCase;
use IdeHelper\Utility\Plugin;
class PluginTest extends TestCase {
/**
* @return void
*/
protected function setUp(): void {
parent::setUp();
Configure::delete('IdeHelper.plugins');
}
/**
* @return void
*/
protected function tearDown(): void {
parent::tearDown();
Configure::delete('IdeHelper.plugins');
}
/**
* @return void
*/
public function testAll() {
$result = Plugin::all();
$this->assertArrayHasKey('IdeHelper', $result);
$this->assertArrayHasKey('Awesome', $result);
$this->assertArrayHasKey('MyNamespace/MyPlugin', $result);
$this-><API key>('FooBar', $result);
Configure::write('IdeHelper.plugins', ['FooBar', '-MyNamespace/MyPlugin']);
$result = Plugin::all();
$this->assertArrayHasKey('FooBar', $result);
$this-><API key>('MyNamespace/MyPlugin', $result);
}
}
|
# Hubot: hubot-loggly-slack
A hubot script to post alerts from Loggly into a Slack room as an attachment.
An attachment has additional formatting options.
See [`src/loggly-slack.coffee`](src/loggly-slack.coffee) for documentation.
# Installation
npm install hubot-loggly-slack
# Add "hubot-loggly-slack" to external-scripts.json
# Other hubot slack modules
https://github.com/spanishdict/hubot-awssns-slack
https://github.com/spanishdict/hubot-loggly-slack
https://github.com/spanishdict/<API key>
|
<?php
namespace Webvaloa;
use Libvaloa\Db;
use RuntimeException;
/**
* Manage and run plugins.
*/
class Plugin
{
private $db;
private $plugins;
private $runnablePlugins;
private $plugin;
// Objects that plugins can access
public $_properties;
public $ui;
public $controller;
public $request;
public $view;
public $xhtml;
public static $properties = array(
// Vendor tag
'vendor' => 'ValoaApplication',
// Events
'events' => array(
'<API key>',
'onBeforeController',
'onAfterController',
'onBeforeRender',
'onAfterRender',
),
// Skip plugins in these controllers
'skipControllers' => array(
'Setup',
),
);
public function __construct($plugin = false)
{
$this->plugin = $plugin;
$this->event = false;
$this->plugins = false;
$this->runnablePlugins = false;
// Plugins can access and modify these
$this->_properties = false;
$this->ui = false;
$this->controller = false;
$this->request = false;
$this->view = false;
$this->xhtml = false;
try {
$this->db = \Webvaloa\Webvaloa::DBConnection();
} catch (Exception $e) {
}
}
public function setEvent($e)
{
if (in_array($e, self::$properties['events'])) {
$this->event = $e;
}
}
public function plugins()
{
if (!method_exists($this->db, 'prepare')) {
// Just bail out
return false;
}
if (method_exists($this->request, 'getMainController') && (in_array($this->request->getMainController(), self::$properties['skipControllers']))) {
return false;
}
$query = '
SELECT id, plugin, system_plugin
FROM plugin
WHERE blocked = 0
ORDER BY ordering ASC';
try {
$stmt = $this->db->prepare($query);
$stmt->execute();
$this->plugins = $stmt->fetchAll();
return $this->plugins;
} catch (PDOException $e) {
}
}
public function pluginExists($name)
{
$name = trim($name);
foreach ($this->plugins as $k => $plugin) {
if ($plugin->plugin == $name) {
return true;
}
}
return false;
}
public function hasRunnablePlugins()
{
// Return runnable plugins if we already gathered them
if ($this->runnablePlugins) {
return $this->runnablePlugins;
}
if (!$this->request) {
throw new RuntimeException('Instance of request is required');
}
if (in_array($this->request->getMainController(), self::$properties['skipControllers'])) {
return false;
}
// Load plugins
if (!$this->plugins) {
$this->plugins();
}
if (!is_array($this->plugins)) {
return false;
}
$controller = $this->request->getMainController();
// Look for executable plugins
foreach ($this->plugins as $k => $plugin) {
if ($controller && strpos($plugin->plugin, $controller) === false
&& strpos($plugin->plugin, 'Plugin') === false) {
continue;
}
$this->runnablePlugins[] = $plugin;
}
return (bool) ($this->runnablePlugins && !empty($this->runnablePlugins)) ? $this->runnablePlugins : false;
}
public function runPlugins()
{
if (!$this->runnablePlugins || empty($this->runnablePlugins)) {
return false;
}
$e = $this->event;
foreach ($this->runnablePlugins as $k => $v) {
$p = '\\'.self::$properties['vendor'].'\Plugins\\'.$v->plugin.'Plugin';
$plugin = new $p();
$plugin->view = &$this->view;
$plugin->ui = &$this->ui;
$plugin->request = &$this->request;
$plugin->controller = &$this->controller;
$plugin->xhtml = &$this->xhtml;
$plugin->_properties = &$this->_properties;
if (method_exists($plugin, $e)) {
$plugin->{$e}();
}
}
}
public static function getPluginStatus($pluginID)
{
$query = '
SELECT blocked
FROM plugin
WHERE system_plugin = 0
AND id = ?';
try {
$db = \Webvaloa\Webvaloa::DBConnection();
$stmt = $db->prepare($query);
$stmt->set((int) $pluginID);
$stmt->execute();
$row = $stmt->fetch();
if (isset($row->blocked)) {
return $row->blocked;
}
return false;
} catch (PDOException $e) {
}
}
public static function setPluginStatus($pluginID, $status = 0)
{
$query = '
UPDATE plugin
SET blocked = ?
WHERE id = ?';
try {
$db = \Webvaloa\Webvaloa::DBConnection();
$stmt = $db->prepare($query);
$stmt->set((int) $status);
$stmt->set((int) $pluginID);
$stmt->execute();
} catch (PDOException $e) {
}
}
public static function setPluginOrder($pluginID, $ordering = 0)
{
$query = '
UPDATE plugin
SET ordering = ?
WHERE id = ?';
try {
$db = \Webvaloa\Webvaloa::DBConnection();
$stmt = $db->prepare($query);
$stmt->set((int) $ordering);
$stmt->set((int) $pluginID);
$stmt->execute();
} catch (PDOException $e) {
}
}
public function install()
{
if (!$this->plugin) {
return false;
}
$installable = $this->discover();
if (!in_array($this->plugin, $installable)) {
return false;
}
$db = \Webvaloa\Webvaloa::DBConnection();
// Install plugin
$object = new Db\Object('plugin', $db);
$object->plugin = $this->plugin;
$object->system_plugin = 0;
$object->blocked = 0;
$object->ordering = 1;
$id = $object->save();
return $id;
}
public function uninstall()
{
if (!$this->plugin) {
return false;
}
$db = \Webvaloa\Webvaloa::DBConnection();
$query = '
DELETE FROM plugin
WHERE system_plugin = 0
AND plugin = ?';
$stmt = $db->prepare($query);
try {
$stmt->set($this->plugin);
$stmt->execute();
return true;
} catch (Exception $e) {
}
return false;
}
public function discover()
{
// Installed plugins
$tmp = $this->plugins();
foreach ($tmp as $v => $plugin) {
$plugins[] = $plugin->plugin;
}
// Discovery paths
$paths[] = <API key>.DIRECTORY_SEPARATOR.self::$properties['vendor'].DIRECTORY_SEPARATOR.'Plugins';
$paths[] = <API key>.DIRECTORY_SEPARATOR.self::$properties['vendor'].DIRECTORY_SEPARATOR.'Plugins';
$skip = array(
'.',
'..',
);
$plugins = array_merge($plugins, $skip);
// Look for new plugins
foreach ($paths as $path) {
if ($handle = opendir($path)) {
while (false !== ($entry = readdir($handle))) {
if ($entry == '.' || $entry == '..') {
continue;
}
if (substr($entry, -3) != 'php') {
continue;
}
$pluginName = str_replace('Plugin.php', '', $entry);
if (!isset($installablePlugins)) {
$installablePlugins = array();
}
if (!in_array($pluginName, $plugins) && !in_array($pluginName, $installablePlugins)) {
$installablePlugins[] = $pluginName;
}
}
closedir($handle);
}
}
if (isset($installablePlugins)) {
return $installablePlugins;
}
return array();
}
}
|
const electron = window.require('electron');
const events = window.require('events');
const {
ipcRenderer
} = electron;
const {
EventEmitter
} = events;
class Emitter extends EventEmitter {}
window.Events = new Emitter();
module.exports = () => {
let settings = window.localStorage.getItem('settings');
if (settings === null) {
const defaultSettings = {
general: {
launch: true,
clipboard: true
},
images: {
copy: false,
delete: true
},
notifications: {
enabled: true
}
};
window.localStorage.setItem('settings', JSON.stringify(defaultSettings));
settings = defaultSettings;
}
ipcRenderer.send('settings', JSON.parse(settings));
};
|
using System;
using System.Collections.Generic;
using System.Linq;
using BohFoundation.<API key>.Repositories.Implementations;
using BohFoundation.AzureStorage.TableStorage.Implementations.Essay.Entities;
using BohFoundation.AzureStorage.TableStorage.Interfaces.Essay;
using BohFoundation.AzureStorage.TableStorage.Interfaces.Essay.Helpers;
using BohFoundation.Domain.Dtos.Applicant.Essay;
using BohFoundation.Domain.Dtos.Applicant.Notifications;
using BohFoundation.Domain.Dtos.Common.AzureQueuryObjects;
using BohFoundation.Domain.<API key>.Applicants;
using BohFoundation.Domain.<API key>.Common;
using BohFoundation.Domain.<API key>.Persons;
using BohFoundation.<API key>;
using BohFoundation.TestHelpers;
using EntityFramework.Extensions;
using FakeItEasy;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace BohFoundation.<API key>.Tests.IntegrationTests
{
[TestClass]
public class <API key>
{
private static <API key> _rowKeyGenerator;
private static <API key> <API key>;
private static <API key> <API key>;
private static <API key> <API key>;
[ClassInitialize]
public static void InitializeClass(TestContext ctx)
{
Setup();
<API key>();
FirstUpsert();
SecondUpsert();
<API key>();
}
#region SettingUp
private static void Setup()
{
<API key>.InitializeFields();
<API key>.InitializeFakes();
ApplicantsGuid = Guid.NewGuid();
Prompt = "prompt" + ApplicantsGuid;
TitleOfEssay = "title" + ApplicantsGuid;
<API key> = A.Fake<<API key>>();
_rowKeyGenerator = A.Fake<<API key>>();
<API key>();
SetupFakes();
<API key> = new <API key>(<API key>.DatabaseName,
<API key>.<API key>, <API key>.DeadlineUtilities);
<API key> = new <API key>(<API key>.DatabaseName,
<API key>.<API key>, <API key>, _rowKeyGenerator);
}
private static void <API key>()
{
var random = new Random();
GraduatingYear = random.Next();
var subject = new EssayTopic
{
EssayPrompt = Prompt,
TitleOfEssay = TitleOfEssay,
RevisionDateTime = DateTime.UtcNow
};
var subject2 = new EssayTopic
{
EssayPrompt = Prompt + 2,
TitleOfEssay = TitleOfEssay + 2,
RevisionDateTime = DateTime.UtcNow
};
var subject3 = new EssayTopic
{
EssayPrompt = "SHOULD NOT SHOW UP IN LIST",
TitleOfEssay = "REALLY SHOULDN't SHOW up",
RevisionDateTime = DateTime.UtcNow,
};
var graduatingYear = new GraduatingClass
{
GraduatingYear = GraduatingYear,
EssayTopics = new List<EssayTopic> { subject, subject2 }
};
var applicant = new Applicant
{
Person = new Person { Guid = ApplicantsGuid, DateCreated = DateTime.UtcNow },
<API key> =
new <API key>
{
GraduatingClass = graduatingYear,
Birthdate = DateTime.UtcNow,
LastUpdated = DateTime.UtcNow
}
};
using (var context = GetRootContext())
{
context.EssayTopics.Add(subject3);
context.GraduatingClasses.Add(graduatingYear);
context.Applicants.Add(applicant);
context.EssayTopics.Add(subject);
context.SaveChanges();
EssayTopicId = context.EssayTopics.First(topic => topic.EssayPrompt == Prompt).Id;
EssayTopicId2 = context.EssayTopics.First(topic => topic.EssayPrompt == Prompt + 2).Id;
}
}
private static int EssayTopicId2 { get; set; }
private static void SetupFakes()
{
RowKey = "<API key>";
A.CallTo(() => <API key>.<API key>.<API key>())
.Returns(GraduatingYear);
A.CallTo(() => <API key>.<API key>.GetUsersGuid()).Returns(ApplicantsGuid);
A.CallTo(() => _rowKeyGenerator.<API key>(ApplicantsGuid, EssayTopicId)).Returns(RowKey);
}
private static string RowKey { get; set; }
private static int GraduatingYear { get; set; }
private static string TitleOfEssay { get; set; }
private static string Prompt { get; set; }
private static Guid ApplicantsGuid { get; set; }
#endregion
#region FirstNotifications
private static void <API key>()
{
<API key> = <API key>.<API key>();
}
private static <API key> <API key> { get; set; }
[TestMethod, TestCategory("Integration")]
public void ApplicantsNotificationRepository_FirstGetNotifications_Should_Have_Two_EssayTopics()
{
Assert.AreEqual(2, <API key>.EssayNotifications.Count);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsNotificationRepository_FirstGetNotifications_EssayTopics_Should_Have_No_LastUpdated()
{
foreach (var essayTopic in <API key>.EssayNotifications)
{
Assert.IsNull(essayTopic.RevisionDateTime);
}
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsNotificationRepository_FirstGetNotifications_EssayTopics_Should_Have_Right_EssayTopic()
{
foreach (var essayTopic in <API key>.EssayNotifications)
{
if (essayTopic.EssayPrompt == Prompt)
{
Assert.AreEqual(TitleOfEssay, essayTopic.TitleOfEssay);
}
else
{
Assert.AreEqual(TitleOfEssay + 2, essayTopic.TitleOfEssay);
}
}
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsNotificationRepository_FirstGetNotifications_EssayTopics_Should_Have_Right_Ids()
{
foreach (var essayTopic in <API key>.EssayNotifications)
{
Assert.AreEqual(essayTopic.EssayPrompt == Prompt ? EssayTopicId : EssayTopicId2, essayTopic.EssayTopicId);
}
}
#endregion
#region FirstUpsert
private static void FirstUpsert()
{
Essay = "Essay";
var dto = new EssayDto {Essay = Essay + 1, EssayPrompt = Prompt, EssayTopicId = EssayTopicId};
<API key>.UpsertEssay(dto);
using (var context = GetRootContext())
{
EssayUpsertResult1 =
context.Essays.First(
essay => essay.EssayTopic.Id == EssayTopicId && essay.Applicant.Person.Guid == ApplicantsGuid);
}
}
private static Essay EssayUpsertResult1 { get; set; }
private static string Essay { get; set; }
[TestMethod, TestCategory("Integration")]
public void <API key>()
{
Assert.AreEqual(6, EssayUpsertResult1.CharacterLength);
}
[TestMethod, TestCategory("Integration")]
public void <API key>()
{
<API key>.RecentTime(EssayUpsertResult1.RevisionDateTime);
}
[TestMethod, TestCategory("Integration")]
public void <API key>()
{
Assert.AreEqual(RowKey, EssayUpsertResult1.RowKey);
}
[TestMethod, TestCategory("Integration")]
public void <API key>()
{
Assert.AreEqual(GraduatingYear.ToString(), EssayUpsertResult1.PartitionKey);
}
[TestMethod, TestCategory("Integration")]
public void <API key>()
{
<API key>.IsGreaterThanZero(EssayUpsertResult1.Id);
}
[TestMethod, TestCategory("Integration")]
public void <API key>()
{
A.CallTo(() => _rowKeyGenerator.<API key>(ApplicantsGuid, EssayTopicId)).MustHaveHappened();
}
[TestMethod, TestCategory("Integration")]
public void <API key>()
{
//Not checking time. It just isn't coming up. I did an in class check to see if it worked. It did.
A.CallTo(() => <API key>.UpsertEssay(A<<API key>>
.That.Matches(x =>
x.Essay == Essay + 1 &&
x.EssayPrompt == Prompt &&
x.EssayTopicId == EssayTopicId &&
x.PartitionKey == GraduatingYear.ToString() &&
x.RowKey == RowKey
))).MustHaveHappened();
}
#endregion
#region SecondUpsert
private static void SecondUpsert()
{
var dto = new EssayDto {Essay = Essay + Essay + Essay, EssayPrompt = Prompt, EssayTopicId = EssayTopicId};
<API key>.UpsertEssay(dto);
using (var context = GetRootContext())
{
EssayUpsertResult2 =
context.Essays.First(
essay => essay.EssayTopic.Id == EssayTopicId && essay.Applicant.Person.Guid == ApplicantsGuid);
}
}
private static Essay EssayUpsertResult2 { get; set; }
private static int EssayTopicId { get; set; }
[TestMethod, TestCategory("Integration")]
public void <API key>()
{
Assert.AreEqual(15, EssayUpsertResult2.CharacterLength);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_SecondUpsert_Should_Have_Have_RecentUpdated_More_Recent_Than_First()
{
<API key>.<API key>(EssayUpsertResult2.RevisionDateTime,
EssayUpsertResult1.RevisionDateTime);
}
[TestMethod, TestCategory("Integration")]
public void <API key>()
{
Assert.AreEqual(RowKey, EssayUpsertResult2.RowKey);
}
[TestMethod, TestCategory("Integration")]
public void <API key>()
{
Assert.AreEqual(GraduatingYear.ToString(), EssayUpsertResult2.PartitionKey);
}
[TestMethod, TestCategory("Integration")]
public void <API key>()
{
Assert.AreEqual(EssayUpsertResult1.Id, EssayUpsertResult2.Id);
}
[TestMethod, TestCategory("Integration")]
public void <API key>()
{
A.CallTo(() => _rowKeyGenerator.<API key>(ApplicantsGuid, EssayTopicId))
.MustHaveHappened(Repeated.AtLeast.Times(3));
}
[TestMethod, TestCategory("Integration")]
public void <API key>()
{
//Not checking time. It just isn't coming up. I did an in class check to see if it worked. It did.
A.CallTo(() => <API key>.UpsertEssay(A<<API key>>
.That.Matches(x =>
x.Essay == Essay + Essay + Essay &&
x.EssayPrompt == Prompt &&
x.EssayTopicId == EssayTopicId &&
x.PartitionKey == GraduatingYear.ToString() &&
x.RowKey == RowKey
))).MustHaveHappened();
}
#endregion
#region SecondNotifications
private static void <API key>()
{
<API key> = <API key>.<API key>();
}
private static <API key> <API key> { get; set; }
[TestMethod, TestCategory("Integration")]
public void ApplicantsNotificationRepository_SecondGetNotifications_Should_Have_Two_EssayTopics()
{
Assert.AreEqual(2, <API key>.EssayNotifications.Count);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsNotificationRepository_SecondGetNotifications_EssayTopics_Should_Have_No_LastUpdated()
{
foreach (var essayTopic in <API key>.EssayNotifications)
{
if (essayTopic.EssayPrompt == Prompt)
{
Assert.AreEqual(EssayUpsertResult2.RevisionDateTime, essayTopic.RevisionDateTime);
}
else
{
Assert.IsNull(essayTopic.RevisionDateTime);
}
}
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsNotificationRepository_SecondGetNotifications_EssayTopics_Should_Have_Right_EssayTopic()
{
foreach (var essayTopic in <API key>.EssayNotifications)
{
if (essayTopic.EssayPrompt == Prompt)
{
Assert.AreEqual(TitleOfEssay, essayTopic.TitleOfEssay);
}
else
{
Assert.AreEqual(TitleOfEssay + 2, essayTopic.TitleOfEssay);
}
}
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsNotificationRepository_SecondGetNotifications_EssayTopics_Should_Have_Right_Ids()
{
foreach (var essayTopic in <API key>.EssayNotifications)
{
Assert.AreEqual(essayTopic.EssayPrompt == Prompt ? EssayTopicId : EssayTopicId2, essayTopic.EssayTopicId);
}
}
#endregion
#region Utilities
private static DatabaseRootContext GetRootContext()
{
return new DatabaseRootContext(<API key>.DatabaseName);
}
[ClassCleanup]
public static void CleanDb()
{
using (var context = new DatabaseRootContext(<API key>.DatabaseName))
{
context.Essays.Where(essay => essay.Id > 0).Delete();
context.EssayTopics.Where(essayTopic => essayTopic.Id > 0).Delete();
context.<API key>.Where(info => info.Id > 0).Delete();
context.GraduatingClasses.Where(gradClass => gradClass.Id > 0).Delete();
}
}
#endregion
#region GetEssay
[TestMethod, TestCategory("Integration")]
public void <API key>()
{
GetEssay();
A.CallTo(() => _rowKeyGenerator.<API key>(ApplicantsGuid, EssayTopicId)).MustHaveHappened();
}
[TestMethod, TestCategory("Integration")]
public void <API key>()
{
GetEssay();
A.CallTo(
() =>
<API key>.GetEssay(
A<<API key>>.That.Matches(
x => x.PartitionKey == GraduatingYear.ToString() && x.RowKey == RowKey))).MustHaveHappened();
}
[TestMethod, TestCategory("Integration")]
public void <API key>()
{
var essayDto = new EssayDto();
A.CallTo(() => <API key>.GetEssay(A<<API key>>.Ignored))
.Returns(essayDto);
Assert.AreSame(essayDto, GetEssay());
}
private EssayDto GetEssay()
{
return <API key>.GetEssay(EssayTopicId);
}
#endregion
}
}
|
class Add<API key> < ActiveRecord::Migration[4.2]
def change
add_column :<API key>, :author_id, :integer
add_column :<API key>, :subject_id, :integer
end
end
|
# Using a compact OS
FROM registry.dataos.io/library/nginx
MAINTAINER Golfen Guo <golfen.guo@daocloud.io>
# Install Nginx
# Add 2048 stuff into Nginx server
COPY . /usr/share/nginx/html
EXPOSE 80
|
require 'test_helper'
require 'cache_value/util'
class UtilTest < Test::Unit::TestCase
include CacheValue::Util
context 'hex_digest' do
should 'return the same digest for identical hashes' do
hex_digest({ :ha => 'ha'}).should == hex_digest({ :ha => 'ha'})
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.